Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
1  
Write takes a byte not an int. You need to split your int into bytes then recombine them at the other end. – Majenko May 8 at 15:21
    
Beside what Majenko said, Pythons Serial.read also only reads one byte. What do you get when you use print("number: ", data);? 248? – Gerben May 8 at 16:02
    
@Gerben yes, i know Serial.read only reads one byte at a time but that statment is inside the loop. The output is mentioned above, i get 63736 as the output. Now i am trying to reassemble the bytes coming to python side but it seems not working. – Can May 8 at 17:00
    
By the way i edited the arduino code to send bytes in Serial.write(). How about now, can you take a look @Majenko ? – Can May 8 at 17:00

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.