0
votes

I want to send serial data ('a') to my arduino using python.

The receiving code on the arduino is the following:

char inChar = (char)Serial.read();
if(inChar=='a'){
    //do stuff
}

When sending the charachter 'a' from the arduino serial terminal, it works. However, when sending from python 2.7 (code see below), the rx led flashes but to stuff is not executed (i.e. inChar=='a' is false). I tried everything but I can't solve this problem.

Pyhton code:

import serial
ser = serial.Serial('/dev/ttyUSB0',9600)
ser.write('a')

EDIT: ser.write(b'a') doesn't work neither

4
similar question is answered here see if this helpswarl0ck
@warl0ck I read the post already but it didn't helpblack
add ser.flush() at the end or ser.close() reference from link to make sure the data is sentwarl0ck
@black next time provide a minimal, reproducible example of your problem, because sometimes the context in which certain lines of code appear is important to reproduce and identifythe issue, and this holds also when there is no context at all.Patrick Trentin

4 Answers

2
votes

When you see the Rx light blinking but the arduino does not seem to receive data, I would check two things:

1) Make sure that the arduino has plenty of time to set up and start serial communications before sending data from the python host. You could include code that causes the onboard LED to blink with a distinctive pattern after the Serial.begin statement, and then start the python code after that. (LED details: how to make the LED blink)

2) Make sure that the communication settings are correct. You may want to explicitly set all of the parameters so that you know what they are and make sure they are the same on both ends of the cable. For example, on the arduino:

// set up Serial comm with standard settings
Serial.begin(9600,SERIAL_8N1);
Serial.flush();

And then in the python code:

bytesize=8
parity='N'
stopbits=1
timeout=3

ser = serial.Serial(port_name, baudrate=9600, bytesize=bytesize, parity=parity, stopbits=stopbits, timeout=timeout)

Also, if you can send data from the arduino to the python host, then you know that your communication set up is correct.

1
votes

add

ser.flush()

at the end after ser.write('a')

or

ser.close()

reference from link to make sure the data is sent to the port.

0
votes

Thank you for your replies. However, it did not solve my problem.

After trying nearly every imaginable solution, I fix it. Between opening the port and sending/reading, a delay is required - at least with my raspberry.

So this works:

import serial
import time

ser = serial.Serial('/dev/ttyUSB0',9600) #opening the port
time.sleep(1) #wait 1s
ser.write('a') #write to the port
-1
votes

You can see my decision here => https://github.com/thisroot/firebox

import firebox as fb

serPort = fb.findDevice('stimulator')
if(serPort):
    data = []
    data.append("<fire,200,5>")
    fb.sendMessage(serPort,data)