There has been similar questions all over the internet but none of them seem to answer my question, so can anybody tell me what is wrong with this code and how I can fix it?
Python code:
import serial
arduino_linux=serial.Serial("/dev/ttyACM0",9600)
while True:
print('write:',str.encode('90')) #print the sent value through the serial to check it with the readed value
arduino_linux.write(str.encode('90'))#send the following value
print('readed:',arduino_linux.read())#read the same value back from the arduino
my arduino code is as follows
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.write(Serial.read());
}
this is a simple sample of a project, my aim from this code is to send the integer number 90 from the pyserial and make sure the value the Arduino is reading is the same integer.
In case if necessary my project is an object follower with object detector and after calculating all the angles and everything it sends them to the Arduino so the Arduino can act up on the servo's.
This is the result I am getting:
But I would like something like:
write:b '90'
readed:b '90'
, not b'9'
or b'0'
I would also like to know how I can change these bytes to integers before I write them to a servo.
-
what version of python and the pySerial library you use?Juraj– Juraj ♦2018年11月05日 18:46:13 +00:00Commented Nov 5, 2018 at 18:46
1 Answer 1
Use Serial.write()
on Arduino to send raw bytes. print
converts them to text.
read
is not blocking, it doesn't wait for a byte and returns -1 if the receive buffer is empty. Check if read returned -1 or use Serial.available()
to get the number of bytes in the RX buffer.
Serial 'echo':
void loop() {
if (Serial.available()) {
Serial.write(Serial.read());
}
}
-
i have seen it and used Serial.write(). but i dont seem to quit understand what you said for the second problem. give me some specific example. ThanksEHM– EHM2018年11月05日 18:37:34 +00:00Commented Nov 5, 2018 at 18:37