0
votes

I am sending integer value from arduino and reading it in Python using pyserial The arduino code is:

Serial.write(integer)

And the pyserial is:

ser=serial.Serial ('com3',9600,timeout =1)
X=ser.read(1)
print(X)

But it doesn't print anything except blank spaces Does anyone knows how to read this integer passed from arduino in Python?

3
What values does integer take? What's its type exactly? Could it be you're passing such bytes that may be interpreted as non-printable ASCII or space?Ilja Everilä

3 Answers

0
votes

You probably need to use a start bit.

The problem might be that the arduino has already written the integer by the time pyserial is running?

So write a character from pyserial to arduino to signal start like

    ser=serial.Serial ('com3',9600,timeout =1)
    ser.write(b'S')
    X=ser.read(1)
    print(X)

And write the integer from the arduino once you get this start bit.

0
votes

That is the not the right way to read an Integer from Arduino. Integer is a 32-bit type while your serial port would be set to EIGHTBITS (Both in pyserial and Arduino. Correct me if I'm wrong) in byte size, therefore you have to write the Character version of the Integer from Arduino while transmitting it through a Serial Port because a Character takes only EIGHTBITS in size which is also the convenient way to do the stuff that you need to, very easily.

Long story short, convert your Integer into a String or a Character Array before transmitting. (Chances are there are inbuilt functions available for the conversion).

On a side note here is the correct python code that you'd prefer to use:

ser = serial.Serial(
        port='COM3',
        baudrate=9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS
    )
    #RxTx
    ser.isOpen()
while 1:
    out = ''
    while ser.inWaiting() > 0:
        out += ser.read(1)
    if out != '':
        print ">>Received String: %s" % out
0
votes

An easy program which I tested:

Arduino:

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

void loop() {
  int f1=123;
  // print out the value you read:
  Serial.println(f1);
  delay(1000);    
}

Python:

import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.port = 'COM5'

ser.open()
while True:
  h1=ser.readline() 
  if h1:
    g3=int(h1); #if you want to convert to float you can use "float" instead of "int"
    g3=g3+5;
    print(g3)