I want to communicate between my Raspberry Pi and Arduino using Python. So far the Arduino successfully sends a serial message to the Raspberry Pi and the message is read with the ser.readline() function in Python. But when I want to blink a led connected to my Raspberry Pi with an IF statement it won't work
The blink() function and everything else works but the code won't go into the IF statement that checks the ser.readline() value with a string variable
This is the code of my Arduino:
String data="hello";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println(data);//data that is being Sent
delay(5000);
}
And this is the Python code wich runs on my Raspberry Pi:
import serial
import RPi.GPIO as GPIO
import time
LedPin = 11 # pin11
ser=serial.Serial("/dev/ttyUSB0",9600) #change ACM number as found from ls /dev/tty/ACM*
ser.baudrate=9600
def setup():
GPIO.setmode(GPIO.BOARD) # Set the board mode to numbers pins by physical location
GPIO.setup(LedPin, GPIO.OUT) # Set pin mode as output
GPIO.output(LedPin, GPIO.HIGH) # Set pin to high(+3.3V) to off the led
def blink():
print 'led on'
GPIO.output(LedPin, GPIO.LOW) # led on
time.sleep(1.0) # wait 1 sec
print 'led off'
GPIO.output(LedPin, GPIO.HIGH) # led off
time.sleep(1.0) # wait 1 sec
setup()
while True:
serialmessage = ser.readline()
print("serial message is " + serialmessage)
if serialmessage == "hello":
print("message recieved")
blink()
This is what I see in the terminal: terminal_image
I've been searching for hours trying to find a solution but with no luck. I've also just started programming in Python. Thank you for your time.
if
statement and call toblink()
aren't inside thewhile
loop. They need to be indented. – larsks