0
votes

I am using Python 3.2 trying to communicate with Arduino through the serial port. From the documentation, I understad that the Arduino Serial.Read() reads individual bytes. However, when I tried to implement this, the Serial.Read() reads all the numbers I sent. Here is the code for my Python and Arduino

For example, I have a the value 412 to send to Arduino.

Python:

xCoordint = 412
xCoordConverted = "%03d" % (xCoordint)
xCoord = [int(i) for i in str(xCoordConverted)]
xSingleDigit0 = chr(int(xCoord[0] + 48))
xSingleDigit1 = chr(int(xCoord[1] + 48))
xSingleDigit2 = chr(int(xCoord[2] + 48))
ser.write (bytes(xSingleDigit0, 'UTF-8'))
ser.write (bytes(xSingleDigit1, 'UTF-8'))
ser.write (bytes(xSingleDigit2, 'UTF-8'))

Arduino:

char joinCharX[3] ;
int n_avail = Serial.available();
  if(n_avail>0){ 
    for (int i=0;i<3; i++){
      joinCharX[i] = Serial.read();
    }
int xCoords = atoi(joinCharX);
Serial.print(joinCharX[0]);

The joinCharX[0] when returned is 412 and not 4. I was wondering why this is so and how do I get it back to read 1 individual byte at a time?

1

1 Answers

0
votes

Try:

char joinCharX[3] ;
int n_avail = Serial.available();
  if(n_avail>0){ 
    for (int i=0;i<3; i++){
      joinCharX[i] = Serial.read(1);  # Note the parameter
    }
int xCoords = atoi(joinCharX);
Serial.print(joinCharX[0]);

This should make it read one char at a time.

Correction:

You can't limit the no chars as above but your problem is that your print statement takes the first char as the start of a string: If you would like to see just the first char you need to use:

char forprint;
:
:
forprint = joinCharX[0];
Serial.print (forprint);