black
black

Reputation: 1263

Serial python to arduino

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.

Python code:

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

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

Upvotes: 0

Views: 1206

Answers (4)

black
black

Reputation: 1263

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

Upvotes: 0

warl0ck
warl0ck

Reputation: 3464

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.

Upvotes: 1

mhopeng
mhopeng

Reputation: 1081

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.

Upvotes: 2

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)

Upvotes: -1

Related Questions