I am trying to establish a communication between Arduino and Python. I want to write int values as bytes from arduino and read them in Python but i need some help to do that.
Here is my Arduino code:
long prev = millis();
int data = 255;
byte ar[4];
int index = 0;
union{
byte CBytes[2];
int Value;
}CovertItoB;
void setup(){
Serial.begin(115200);
}
void loop(){
long current = millis();
if(current - prev > 2000){
AddIntToByteArray(&data, ar, &index);
//Serial.write((byte*)&data, sizeof(data));
Serial.write(ar, 2);
data -= 1;
prev = millis();
}
}
void AddIntToByteArray(int *value, byte buffer[], int *ArrayIndex)
{
CovertItoB.Value=*value;
buffer[*ArrayIndex]=CovertItoB.CBytes[0];
ArrayIndex=*ArrayIndex+1;
buffer[*ArrayIndex]=CovertItoB.CBytes[1];
ArrayIndex=*ArrayIndex+1;
}
And here is my Python code:
import serial
import struct
ser = serial.Serial('/dev/ttyACM1', 115200)
while True:
data = ser.read(1)
bytesToRead = ser.inWaiting()
if bytesToRead:
data = data + ser.read(bytesToRead)
encodedData = data.encode('hex')
print(encodedData)
The output in Python side is, ('number: ', 63736)
which is not as expected.
I have tried to print it by using ord()
function but nothing worked.
Thanks in advance, any help would be appreciated.
print("number: ", data);
? 248? – Gerben May 8 at 16:02