I got a system where I would send a command from my host computer using Python Socket (the computer is the server) and the MKR1000 (client) would send back information depends on the command sent.
Unfortunately, the bidirectional communication is unstable. I can guarantee the MKR1000 received the command and (maybe) sending information back, but for some reason, my host computer would not receive the command.
Anyway, this is my first time trying out socket, so I would like some guru to review my code and maybe spot the mistake in here? Thanks a lot.
Python:
import socket
import time
def coor2bytes(coor_fnc):
coorByte = [0, 0, 0, 0, 0, 0]
if (coor_fnc[0] >= 0):
coorByte[0] = (coor_fnc[0] >> 8) & 0xFF # High byte of X
coorByte[1] = coor_fnc[0] & 0xFF # Low byte of X
else:
coor_fnc[0] = coor_fnc[0]*(-1)
coorByte[0] = (coor_fnc[0] >> 8) & 0xFF # High byte of X
coorByte[0] = coorByte[0] ^ 0x80
coorByte[1] = coor_fnc[0] & 0xFF # Low byte of X
if (coor_fnc[1] >= 0):
coorByte[2] = (coor_fnc[1] >> 8) & 0xFF # High byte of Y
coorByte[3] = coor_fnc[1] & 0xFF # Low byte of Y
else:
coor_fnc[1] = coor_fnc[1]*(-1)
coorByte[2] = (coor_fnc[1] >> 8) & 0xFF # High byte of X
coorByte[2] = coorByte[2] ^ 0x80
coorByte[3] = coor_fnc[1] & 0xFF # Low byte of X
if (coor_fnc[2] >= 0):
coorByte[4] = (coor_fnc[2] >> 8) & 0xFF # High byte of Phi
coorByte[5] = coor_fnc[2] & 0xFF # Low byte of Phi
else:
coor_fnc[2] = coor_fnc[2]*(-1)
coorByte[4] = (coor_fnc[2] >> 8) & 0xFF # High byte of Phi
coorByte[4] = coorByte[4] ^ 0x80
coorByte[5] = coor_fnc[2] & 0xFF # Low byte of Phi
return coorByte
def bytes2coor(byte_fnc):
receivedCoor_fnc = [0, 0, 0]
receivedCoor_fnc[0] = ((-1)**(byte_fnc[0]>>7)) * ((byte_fnc[1]) | (((byte_fnc[0]&0x7f)<<8)))
receivedCoor_fnc[1] = ((-1)**(byte_fnc[2]>>7)) * ((byte_fnc[3]) | (((byte_fnc[2]&0x7f)<<8)))
receivedCoor_fnc[2] = ((-1)**(byte_fnc[4]>>7)) * ((byte_fnc[5]) | (((byte_fnc[4]&0x7f)<<8)))
return receivedCoor_fnc
if __name__ == '__main__':
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234)) # bind(ip, port)
print("Done binding.")
s.listen(2)
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
clientsocket.settimeout(1)
while True:
print();
print("What you want to do?")
print("0. Send target")
print("1. Get current coordinate")
print("2. Set current coordinate (not yet implement)")
try:
a = int(input("I choose: "))
except Exception:
print("Error.")
a = -1;
if (a == 0):
coor = [0, 0, 0]
try:
coor[0] = int(input("X: "))
coor[1] = -int(input("y: "))
coor[2] = int(input("phi: "))
coorByte = coor2bytes(coor)
clientsocket.send(bytes([0]))
clientsocket.send(bytes(coorByte))
print("I already sent the target.")
except Exception:
print("Error.")
elif (a == 1):
receive = 0
while (not receive):
try:
clientsocket.send(bytes([1]))
bytesReceived = []
full_msg = []
while (len(full_msg) < 8):
bytesReceived = clientsocket.recv(8)
for x in range(len(bytesReceived)):
full_msg.append(bytesReceived[x])
receivedCoor = bytes2coor(full_msg)
print("coordinate received: " + str(receivedCoor))
receive = 1
except socket.timeout:
print("Time out. Will try again.")
elif (a == 2):
setCoor = [0, 0, 0]
try:
setCoor[0] = int(input("X: "))
setCoor[1] = -int(input("y: "))
setCoor[2] = int(input("phi: "))
setcoorByte = coor2bytes(setCoor)
clientsocket.send(bytes([2]))
clientsocket.send(bytes(setcoorByte))
print("I already sent the new coordinate.")
except Exception:
print("Error.")
else:
print("Not yet implement.")
Arduino:
#include <WiFi101.h>
#include <SPI.h>
// To connect to the server on laptop
char ssid[] = "iPhone";
char pass[] = "00000000";
int status = WL_IDLE_STATUS;
IPAddress server(172,20,10,3);
WiFiClient client;
// Random variable
int a, i, j, k, m;
byte buf0[7];
byte buf1[7];
byte buf2[7];
long start = millis();
int elapsedTime = 0;
int timeout = 0;
void setup() {
// put your setup code here, to run once:
// Serial.begin(115200);
Serial.begin(115200);
Serial1.begin(115200);
// status = WiFi.begin(ssid, pass);
while (status != WL_CONNECTED) {
status = WiFi.begin(ssid, pass);
}
j = client.connect(server, 1234);
while (j != 1) {
j = client.connect(server, 1234);
}
}
void loop()
{
if (client.available()) {
a = client.read();
Serial.print("I got: ");
Serial.println(a);
if (a == 0) { // Send new target to Due
Serial.println("I send target.");
j = 0;
start = millis();
while(j<6) {
elapsedTime = millis() - start;
if (elapsedTime > 1000) {
timeout = 1;
break;
}
if (client.available()>0) {
buf0[j] = client.read();
Serial.println(buf0[j]);
j++;
}
}
if (timeout != 1) {
Serial1.write((byte) 0);
// Send coordinate back to Due
for (i = 0; i<6; i++) {
Serial1.write(buf0[i]);
}
} else {
timeout = 0;
}
} else if (a == 1) {
// Get the coordinate from the Due
Serial.println("I receive coordinate.");
Serial1.write((byte) 1);
k = 0;
start = millis();
while(k < 6) {
elapsedTime = millis() - start;
if (elapsedTime > 1000) {
timeout = 1;
break;
}
if (Serial1.available() > 0) {
buf1[k] = Serial1.read();
Serial.println(buf1[k]);
k++;
}
}
if (timeout != 1) {
for (i=0;i<6;i++) {
client.write(buf1[i]);
delay(10);
}
client.write((byte) 0); // fill in the blank size
delay(10);
client.write((byte) 0);
} else {
timeout = 0;
}
// for (int i = 0; i<8; i++) {
// client.write((byte) 0);
// }
} else if (a == 2) { // set the current coordinnate to be something else.
Serial.println("I set coordinate.");
m = 0;
while(m<6) {
if (client.available()>0) {
buf2[m] = client.read();
Serial.println(buf2[m]);
m++;
}
}
Serial1.write((byte) 2);
// Send coordinate back to Due
for (i = 0; i<6; i++) {
Serial1.write(buf2[i]);
}
} else if (a == 3) { // identify yourself
Serial.println("Identify myself.");
client.write((byte) 1);
}
}
}
If you have time to read through the Arduino code, then you would see that I actually have serial communication between my MKR and Due too. I also can guarantee that the MKR can receive all those data from the Due and not stuck in some infinite loop.
Thank you!
Ok so for some reason if I added a delay right after the MKR connecting to WiFi, before connecting to the server, then everything just works.
Related
I have a piece of code in python. It is related to client Socket programming. I want to get the NTRIP data from "www.rtk2go.com". The code written in python works well and serves the purpose.
import socket
import base64
server = "www.rtk2go.com"
port = "2101"
mountpoint = "leedgps"
username = ""
password = ""
def getHTTPBasicAuthString(username, password):
inputstring = username + ':' + password
pwd_bytes = base64.standard_b64encode(inputstring.encode("utf-8"))
pwd = pwd_bytes.decode("utf-8").replace('\n', '')
return pwd
pwd = getHTTPBasicAuthString(username, password)
print(pwd)
header = "GET /{} HTTP/1.0\r\n".format(mountpoint) + \
"User-Agent: NTRIP u-blox\r\n" + \
"Accept: */*\r\n" + \
"Authorization: Basic {}\r\n".format(pwd) + \
"Connection: close\r\n\r\n"
print(header)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server, int(port)))
s.sendto(header.encode('utf-8'), (server, int(port)))
resp = s.recv(1024)
try:
while True:
try:
data = s.recv(2048)
except:
pass
finally:
s.close()
I wanted to implement the same thing in c++ code and after going through few online tutorials, I wrote the following code in C++ (I am very new to C++)
#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <netdb.h>
using namespace std;
#define SIZE 1000
#define PORT 2101
string base64Encoder(string input_str, int len_str) {
char char_set[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
char *res_str = (char *) malloc(SIZE * sizeof(char));
int index, no_of_bits = 0, padding = 0, val = 0, count = 0, temp;
int i, j, k = 0;
for (i = 0; i < len_str; i += 3) {
val = 0, count = 0, no_of_bits = 0;
for (j = i; j < len_str && j <= i + 2; j++) {
val = val << 8;
val = val | input_str[j];
count++;
}
no_of_bits = count * 8;
padding = no_of_bits % 3;
while (no_of_bits != 0) {
// retrieve the value of each block
if (no_of_bits >= 6) {
temp = no_of_bits - 6;
// binary of 63 is (111111) f
index = (val >> temp) & 63;
no_of_bits -= 6;
} else {
temp = 6 - no_of_bits;
// append zeros to right if bits are less than 6
index = (val << temp) & 63;
no_of_bits = 0;
}
res_str[k++] = char_set[index];
}
}
for (i = 1; i <= padding; i++) {
res_str[k++] = '=';
}
res_str[k] = '\0';
string a = res_str;
return a;
}
int main() {
string input_str = ":";
int len_str;
len_str = input_str.length();
string pwd = base64Encoder(input_str, len_str);
string mountpoint = "leedgps";
string header = "GET /" + mountpoint + " HTTP/1.0\r\n" + \
"User-Agent: NTRIP u-blox\r\n" + \
"Accept: */*\r\n" + \
"Authorization: Basic " + pwd + "\r\n" + \
"Connection: close\r\n\r\n";
struct hostent *h;
if ((h = gethostbyname("www.rtk2go.com")) == NULL) { // Lookup the hostname
cout << "cannot look up hostname" << endl;
}
struct sockaddr_in saddr;
int sockfd, connfd;
sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0;
if (sockfd) {
printf("Error creating socket\n");
}
saddr.sin_family = AF_INET;
saddr.sin_port = htons(2101);
if(inet_pton(AF_INET, "3.23.52.207", &saddr.sin_addr)<=0) //
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
cout << connect(sockfd, (struct sockaddr *)&saddr, sizeof(saddr)) << endl;
return 0;
}
But the connect method always returns -1 (in C++). Any idea what am I doing wrong?
sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0;
means that sockfd is either 0 or 1, which is not a valid socket.
Do this instead:
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error creating socket\n");
}
Hello there people of the internet, my team and I are running into an issue with this python code that sends a byte array of 37 characters to an arduino. The arduino controls 4 dc motors and 4 180 degree servos so we send the control data down to it via pyserial. We are using two logitech extreme 3d pro joysticks (reference link below) connected to the computer via usb. Using pygame the input is converted to PWM data that is sent to the arduino (already explained how that is done a few sentences ago). Our issue is that the code works perfectly on a MacOS machine, and when we attempt to run it on either a windows or linux machine (the laptop we will be using will have linux installed we just tested windows to see if it would work) it works for a few short seconds then freezes. When I test this code without the 4 dc motors and 4 servos attached (can't bring them home with me) it works perfectly on all os's, my colleague keeps telling me it's a programming issue but I can't seem to find it. I have attached all of the code below, if you have any questions please let me know.
Python Code
import pygame
import numpy as np
import serial
# function to map servo/motor data dependent on joystick input
def map(joy, min, max, omin, omax):
return float((((joy - min) * (omax - omin)) / (max - min)) + omin)
# same as above but used for the corner values of the joystick
def mapc(joy1, joy2, min1, max1, min2, max2, omin, omax):
return float((((((joy1 - min1) * (omax - omin)) / (max1 - min1)) + omin) + ((((joy2 - min2) * (omax - omin)) / (max2 - min2)) + omin)) / 2)
# dum1 = input("1: ")
class JoyStickClass:
# set up the joysticks and arduino
def __init__(self):
pygame.init()
pygame.joystick.init()
self.Joy1 = pygame.joystick.Joystick(0)
self.Joy2 = pygame.joystick.Joystick(1)
self.Joy1.init()
self.Joy2.init()
self.M1_Data = 1500
self.M2_Data = 1500
self.M3_Data = 1500
self.S1_Data = 1500
self.S2_Data = 1500
self.S3_Data = 1500
self.S4_Data = 1500
self.lights = 0
# port = str(input("Enter com port (Windows: COM, MacOS: usual crap:) : "))
self.ard1 = serial.Serial('/dev/cu.usbmodem1434201', 115200, timeout = 0.01)
self.startMarker = '<'
self.endMarker = '\n'
self.dividingmarker = ','
self.Timer = 0
# read the data from the joysticks and store them in their variables
def JoyRead(self):
for event in pygame.event.get():
self.Joy1X = self.Joy1.get_axis(0)
self.Joy1Y = self.Joy1.get_axis(1)
self.Joy1B1 = self.Joy1.get_button(0)
self.Joy1B6 = self.Joy1.get_button(5)
self.Joy1B7 = self.Joy1.get_button(6)
self.Joy1B8 = self.Joy1.get_button(7)
self.Joy1B3 = self.Joy1.get_button(2)
self.Joy2X = self.Joy2.get_axis(0)
self.Joy2Y = self.Joy2.get_axis(1)
self.Joy2B1 = self.Joy2.get_button(0)
self.Joy2B3 = self.Joy2.get_button(2)
self.Joy2B5 = self.Joy2.get_button(4)
self.Joy1H = self.Joy1.get_hat(0)
garbo = 1500
# Convert the data read from the joysticks to useful motor and servo data
def JoyConv(self):
self.Timer = self.Timer + 1
# Motor crap
x= self.Joy1X * 1
y=self.Joy1Y * 1
# Deadzones
if x > -.1 and x < .1:
x = 0
if y > -.1 and y < .1:
y = 0
tamp = map(abs(y),0,1,500,0)
# //preturn
pT = map(x,-1,1,-tamp,tamp)
lM = map(y, -1, 1, 1000, 2000)
rM = map(y, -1, 1, 1000, 2000)
# //Take the amplitude of the motors
lMAmp = round(1500-lM)
lMAmp -= pT
lM = 1500 - lMAmp
rMAmp = round(1500-rM)
rMAmp += pT
rM = 1500 - rMAmp
self.M1_Data = round(lM)
self.M2_Data = round(rM)
#Up Down
if self.Joy1B7 == 1 and self.Joy1B8 == 0:
self.M3_Data = 1000
elif self.Joy1B8 == 1 and self.Joy1B7 == 0:
self.M3_Data = 2000
else:
self.M3_Data = 1500
self.S2_Data = round(map(self.Joy2X, 1, -1, 800, 2200))
# ArmTIlt
if round(map(self.Joy2Y, -1, 1, 1000, 2000)) > 1600 and self.S1_Data < 2200 and self.Timer % 50 == 0:
self.S1_Data = self.S1_Data + 7
elif round(map(self.Joy2Y, -1, 1, 1000, 2000)) < 1400 and self.S1_Data > 1000 and self.Timer % 50 == 0:
self.S1_Data = self.S1_Data - 7
else:
self.S1_Data = self.S1_Data
if self.Joy2B1 == 1:
self.S3_Data = 2000
else:
self.S3_Data = 1000
# Camera
if self.Joy1H == (0, -1) and self.S4_Data <= 2200 and self.Timer % 100 == 0:
self.S4_Data = self.S4_Data + 15
elif self.Joy1H == (0, 1) and self.S4_Data >= 1000 and self.Timer % 100 == 0:
self.S4_Data = self.S4_Data - 15
else:
self.S4_Data = self.S4_Data
# lights
if self.Joy1H == (1, 0):
self.lights = 1
elif self.Joy1H == (-1, 0):
self.lights = 0
else:
self.lights = self.lights
# Send the data to the arduino
def send_to_arduino(self):
Sending_Data1 = str(self.M1_Data)
Sending_Data1 += self.dividingmarker
Sending_Data1 += str(self.M2_Data)
Sending_Data1 += self.dividingmarker
Sending_Data1 += str(self.M3_Data)
Sending_Data1 += self.dividingmarker
Sending_Data1 += str(self.S1_Data)
Sending_Data1 += self.dividingmarker
Sending_Data1 += str(self.S2_Data)
Sending_Data1 += self.dividingmarker
Sending_Data1 += str(self.S3_Data)
Sending_Data1 += self.dividingmarker
Sending_Data1 += str(self.S4_Data)
Sending_Data1 += self.dividingmarker
Sending_Data1 += str(self.lights)
Sending_Data1 += self.endMarker
Sending_Data_ByteArray1 = bytearray(Sending_Data1, 'ascii')
# print()
if self.ard1.inWaiting():
self.ard1.flush()
self.ard1.write(Sending_Data_ByteArray1)
data = self.ard1.readline()
print(data, len(Sending_Data_ByteArray1))
# self.ard1.flush()
class MainClass:
def __init__(self):
self.joy = JoyStickClass()
def run(self):
self.joy.JoyRead()
self.joy.JoyConv()
self.joy.send_to_arduino()
main = MainClass()
while 1==1:
main.run()
Arduino Code:
#include <Servo.h>
Servo M1;
Servo M2;
Servo M3;
Servo M4;
Servo S1;
Servo S2;
Servo S3;
Servo S4;
int VA = 0; //1000-2000
int VB = 0; //1000-2000
int VC = 0; //1000-2000
int VD = 0; //1000-2000
int VE = 0; //1000-2000
int VF = 0; //1000-2000
int VG = 0; //1000-2000
int VH = 0; //1000-2000
int VI = 0; //1 or 0
int Lights = 13;
void setup()
{
Serial.begin(115200);
Serial.println();
pinMode(Lights, OUTPUT);
M1.attach(22);
M2.attach(23);
M3.attach(24);
M4.attach(25);
S1.attach(30);
S2.attach(34);
S3.attach(38);
S4.attach(42);
}
void SerialEvent()
{
char characterBuf[39]; //stores incoming
int incomingLength = 0; //stores incoming length
char *token; //token for converting byte array to string array
int counterNum = 1;
//1503,1503,1500,1503,1523,1000,1500,0
if (Serial.available()) {
// Serial.println("1");
incomingLength = Serial.readBytesUntil('\n', characterBuf, 50); //calculate length of byte array
token = strtok(characterBuf, ","); //convert to string
VA = atoi(token);
// Serial.println(token);
while (token != NULL) { //if token doesnt find another comma it goes back to beginning
token = strtok(NULL, ","); //changes token to a string def of NULL
// Serial.println(token);
switch (counterNum) {
case 1:
VB = atoi(token);
break;
case 2:
VC = atoi(token);
break;
case 3:
VD = atoi(token);
break;
case 4:
VE = atoi(token);
break;
case 5:
VF = atoi(token);
break;
case 6:
VG = atoi(token);
break;
case 7:
VH = atoi(token);
break;
case 8:
VI = atoi(token);
break;
}
counterNum++;
}
}
}
void loop()
{
if (Serial.available()) {
SerialEvent();
M1.writeMicroseconds(VA);
M2.writeMicroseconds(VB);
M3.writeMicroseconds(VC);
M4.writeMicroseconds(VD);
S1.writeMicroseconds(VE);
S2.writeMicroseconds(VF);
S3.writeMicroseconds(VG);
S4.writeMicroseconds(VH);
if (VI == 1) {
digitalWrite(Lights, HIGH);
}
else {
digitalWrite(Lights, LOW);
}
}
Serial.print("M1: ");
Serial.print(VA);
Serial.print(" ");
Serial.print("M2: ");
Serial.print(VB);
Serial.print(" ");
Serial.print("M3: ");
Serial.print(VC);
Serial.print(" ");
Serial.print("M4: ");
Serial.print(VC);
Serial.print(" ");
Serial.print("S1: ");
Serial.print(VD);
Serial.print(" ");
Serial.print("S2: ");
Serial.print(VE);
Serial.print(" ");
Serial.print("S3: ");
Serial.print(VF);
Serial.print(" ");
Serial.print("S4: ");
Serial.print(VG);
Serial.print(" ");
Serial.print("Lights: ");
Serial.print(VH);
Serial.println();
}
please excuse any formatting errors, I have been working on this problem for the last 48 hours and I didn't have time to check it for those.
Also reference link to the joysticks:
https://www.amazon.com/Extreme-3D-Pro-Joystick-Windows/dp/B00009OY9U/ref=sr_1_1?crid=1MQ474EU5M3KK&dchild=1&keywords=logitech+extreme+3d+pro+joystick&qid=1615092807&sprefix=logitech+extreme+%2Caps%2C164&sr=8-1
reference links to both the servos and the motors:
Servos:
https://www.savoxusa.com/products/savsw1210sg-waterproof-coreless-digital
Motors:
http://aquaphoton.net/aquaphoton/?product=seabotix-thruster-btd150
Any other questions let me know
By switching the serial.flush to the arduino side it fixed the problem.
I am trying to make a resource monitor with an arduino and it is working great for almost 20 seconds before it almost stops running.
When it slows down, it takes almost 5 seconds between updates.
I have tried to comment out everything with psutil and giving it a permanent value.
and have tried the same with GPUtil.
Here is the python code
import serial.tools.list_ports
import serial
import psutil
import GPUtil
import time
import serial
ports = list(serial.tools.list_ports.comports())
baud = 9600
for p in ports:
if "Arduino" in p[1]:
port = p[0]
ser=serial.Serial(port, baud, timeout=1)
try:
while True:
cpuUsage = psutil.cpu_percent()
ramUsage = psutil.virtual_memory()
cpuUsage = str(cpuUsage)
GPUs = GPUtil.getGPUs()
gpuUsage = GPUs[0].load
gpuUsage = str(gpuUsage)
gpuUsage = gpuUsage[2:]
ramUsage = str(ramUsage.percent)
toSend = cpuUsage + "," + gpuUsage + ","+ ramUsage
print (toSend)
ser.write(toSend.encode())
#print("20.5".encode())
#line = ser.readline()[:-2]
#line.decode()
#print ("Read : " , line);
time.sleep(0.1)
except:
print ("error")
Here is the Arduino code
#include <FastLED.h>
#define NUM_LEDS 15
#define DATA_PIN 6
float Cpu = 40;
float Gpu = 99;
float Ram = 60;
String Cpu_Read;
String Gpu_Read;
String Ram_Read;
int RXLED = 17;
String StrNumbers = "";
int numbers;
int Received = 0;
int Separrator = 0;
String Text = "";
CRGB leds[NUM_LEDS];
void setup() {
// put your setup code here, to run once:
FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(5);
Serial.begin(115200);
pinMode(LED_BUILTIN_TX,INPUT);
pinMode(LED_BUILTIN_RX,INPUT);
}
void loop() {
// put your main code here, to run repeatedly:
char inByte = ' ';
StrNumbers = "";
Text = "";
Separrator = 0;
Cpu_Read = "";
Gpu_Read = "";
Ram_Read = "";
Received = 0;
pinMode(LED_BUILTIN_TX,INPUT);
while(Serial.available() > 0){ // only send data back if data has been sent
pinMode(LED_BUILTIN_TX,OUTPUT);
inByte = Serial.read(); // read the incoming data
if (inByte == ','){
Separrator += 1;
}
else if (Separrator == 0){
Cpu_Read += (char) inByte;
}
else if (Separrator == 1){
Gpu_Read += (char) inByte;
}
else if (Separrator == 2){
Ram_Read += (char) inByte;
Serial.print("Ram : ");
Serial.println(Ram_Read);
}
else{
Serial.println("Error");
}
/*
inByte = Serial.read(); // read the incoming data
if (isDigit(inByte)) { // tests if inByte is a digit
StrNumbers += (char) inByte;
Serial.println(inByte); // send the data back in a new line so that it is not all one long line
//Serial.println(numbers); // send the data back in a new line so that it is not all one long line
}
else if (inByte == ".")
{
abortLoop = 1;
}
else{
Text +=(char) inByte;
}
*/
Received = 1;
}
if (Received == 1){
Cpu = Cpu_Read.toInt();
Gpu = Gpu_Read.toInt();
Ram = Ram_Read.toInt();
UpdateMonitor(Cpu ,Gpu ,Ram);
}
Text.trim();
if (StrNumbers != ""){
numbers = StrNumbers.toInt();
Serial.println(numbers);
if (numbers > 100) numbers = 100;
UpdateMonitor(Cpu,numbers,Ram);
}
if(Text!= ""){
//Serial.println(Text); // send the data back in a new line so that it is not all one long line
}
if (Text == "ResourceMonitor"){
Serial.println("Yes");
}
else if (Text != ""){
Serial.println(Text);
numbers = Text.toInt();
if (numbers > 100) numbers = 100;
UpdateMonitor(Cpu, numbers, Ram);
}
}
void UpdateMonitor(int cpu,int gpu, int ram){
int Cpu_Usage = map(cpu, 0, 100, 0, 5);
int Gpu_Usage = map(gpu, 0, 100, 0, 5);
int Ram_Usage = map(ram, 0, 100, 0, 5);
FastLED.clear();
for(int led = 0; led < Ram_Usage; led++) {
leds[led] = CRGB::Blue;
}
for(int led = 0; led < Gpu_Usage; led++) {
leds[9 - led] = CRGB::Green;
}
for(int led = 0; led < Cpu_Usage; led++) {
leds[led+10] = CRGB::Red;
}
FastLED.show();
}
it is fixed now not sure what fixet it but it works atleast :)
thansk to all that have tried to helt
I would like to trigger data acquisition on my Arduino UNO with connected accelerometer (MPU 6050) by using Python.
The idea is that when the command is given in Python, the Arduino would start saving data on its SRAM and when a certain number of measurements would be saved, the data would be sent in a package back to Python.
This is my current Arduino code:
#include<Wire.h>
#define MPU6050_DLPF_94HZ MPU6050_DLPF_CFG_2
const int MPU_addr_1 = 0x68; // I2C address of the first MPU-6050
const int baudrate = 19200;
int16_t AcX1; // definition of variables
const int len = 200; // Buffer size
float analogDataArray[len];
int count = 0;
void setup() {
Wire.begin();
Wire.beginTransmission(MPU_addr_1);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(baudrate);
}
void loop() {
Wire.beginTransmission(MPU_addr_1);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr_1, 8, true); // request a total of 14 registers
float AcX1 = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
if (Serial.available())
{
if (Serial.read() == 'Y') {
analogDataArray[count] = AcX1;
count = count + 1;
if (count >= len) {
for (int i; i <= len; i = i + 1) {
Serial.println(analogDataArray[i] / 16384);
}
}
count = 0;
}
}
delay(5);
}
and this is my Python code:
import serial
arduinoData = serial.Serial('COM3', 19200)
com = input('Press "Y":' )
arduinoData.write(bytes(com, 'utf-8'))
vec = []
run = True
while run is True:
while (arduinoData.inWaiting() == 0):
pass
arduinoString = arduinoData.readline()
vec.append(float(arduinoString))
if len(vec) >= 100:
run = False
print(vec)
I've managed to get it working for 1 measurement but as soon as I defined an array inside Arduino to save multiple measurements, the code doesn't work. I'm sure that it is close to working, but I can't find the detail that is stopping me from that.
Thank you for any provided help.
Kind regards,
L
I got it working, the problem was in my Arduino code, as expected.
#include<Wire.h>
#define MPU6050_DLPF_94HZ MPU6050_DLPF_CFG_2
const int MPU_addr_1 = 0x68; // I2C address of the first MPU-6050
const int baudrate = 9600;
int16_t AcX1; // definition of variables
const int len = 200; // Buffer size
float analogDataArray[len];
int count = 0;
int ans;
void setup() {
Wire.begin();
Wire.beginTransmission(MPU_addr_1);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(baudrate);
}
void loop() {
Wire.beginTransmission(MPU_addr_1);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr_1, 8, true); // request a total of 14 registers
float AcX1 = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
if (Serial.available() && Serial.read() == 'Y') {
ans = 1;
}
if (ans == 1) {
analogDataArray[count] = AcX1;
count = count + 1;
if (count >= len) {
for (int i; i <= len; i = i + 1) {
Serial.println(analogDataArray[i] / 16384);
}
ans = 0;
}
}
delay(5);
}
I'm trying to create a python websocket class that can connect to a websocket server and I need help writing a function that can mask and unmask data. I have an similar websocket class in PHP that looks like this:
function unmask($text) {
$length = ord($text[1]) & 127;
if($length == 126) {
$masks = substr($text, 4, 4);
$data = substr($text, 8);
}
elseif($length == 127) {
$masks = substr($text, 10, 4);
$data = substr($text, 14);
}
else {
$masks = substr($text, 2, 4);
$data = substr($text, 6);
}
$text = "";
for ($i = 0; $i < strlen($data); ++$i) {
$text .= $data[$i] ^ $masks[$i%4];
}
return $text;
}
function mask($text){
$b1 = 0x80 | (0x1 & 0x0f);
$length = strlen($text);
if($length <= 125)
$header = pack('CC', $b1, $length);
elseif($length > 125 && $length < 65536)
$header = pack('CCn', $b1, 126, $length);
elseif($length >= 65536)
$header = pack('CCNN', $b1, 127, $length);
return $header.$text;
}
So I tried to create the same thing in Python:
def mask(text):
b1 = 0x80 | (0x1 & 0x0f)
length = len(text)
if length <= 125:
header = struct.pack('CC', b1, length)
if length > 125 & length < 65536:
header = struct.pack('CCn', b1, 126, length)
if length <= 65536:
header = struct.pack('CCNN', b1, 127, length)
return header + text
And it returns an error:
Bad char in struct format
If anyone could help me write the function that would be great. Thanks!
I found an really helpful script that did exactly what i needed.
http://sidekick.windforwings.com/2013/03/minimal-websocket-broadcast-server-in.html