Python Forum
Pyserial ser.read() not working - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Pyserial ser.read() not working (/thread-15721.html)



Pyserial ser.read() not working - SpicyChef - Jan-28-2019

I'm new to Python and Pyserial.

I have this project that I'm working on where I need to have an Arduino communicate to my Python code through Pyserial.

Here is my Pyserial code.

import serial
import time
import sys

ser = serial.Serial('/dev/cu.usbserial-A505BRMT', 9600)  # open serial port
while True:
    print('write:',str.encode('90')) #print the sent value through the serial to check
    ser.write(str.encode('90'))#send the following value


    
    print('read:',ser.read(0))#read the same value back from the arduino

    time.sleep(1) 
Here is my Arduino code.
char data; //Holds incoming character

void setup()
{
Serial.begin(9600);   //Serial Port at 9600 baud
}

void loop() {
  if (Serial.available() > 0)   //Print only when data is received
  {
    data = Serial.read();   //Read byte of data
    Serial.print(data);   //Print byte of data
  }
}
Basically I'm sending a number (90) to the Arduino to read it in the serial monitor and then send it back to the Python code to read it again.
print('read:',ser.read(0)) This line doesn't seem to work no matter the value I use

Anyone has an idea to fix it?


RE: Pyserial ser.read() not working - buran - Jan-29-2019

Shouldn't it be non-zero value in ser.read(0)? it's the size (in bytes) to read