trouble w/ python interpreting serial output data

I'm trying to make the arduino send a word (or string) over the serial port and interpret that word with a python script. The python script will execute different functions based on what word the arduino sends over the serial port. I'm having trouble getting the python script to interpret the different words. This is for an alarm system. I have a door sensor hooked up to a digital pin and when it is high it sends the word "alert" over the serial port, when it is low it sends nothing. I want to add in different "alerts" like alert1 and alert2 and the python program will execute different functions based on the different alerts.

Arduino code (note: this is not my actual code, but the code that matters):

int inputPin = 2;
int val = 0;

void setup() {
     pinMode(inputPin, INPUT);

void loop() {
     val = digitalRead(inputPin);
     if (val == HIGH) {
          Serial.println("alert"); // Serial.print("alert"); doesn't work with python at all for me

And here is the python code that receives the alert (note: only the code that matters):

import serial

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

while 1:
   result = ser.readline()
   if result:   # This works but not if i want to do different stuff for different alerts
      print result

I know there is something stupid I'm not doing correctly, but I cant figure it out.. I have tried:

if result == "alert" if result == "alert\n"

I've tried changing this in the arduino code: Serial.println("alert"); to Serial.print("alert"); as well and no luck...

I've got a parallax pir sensor and rfid reader that I'm dying to hook up to the arduino, but I have to get the python code I've written to execute properly on these events... The python code also emails and text messages me when the alerts happen. Any suggestions would be greatly appreciated. I will post my whole project with schematics and source code once I am done.

Please help, and thanks in advance!

Try: if result[:5]=='alert'

One thing to keep in mind. Since you will be interpreting with PYTHON, you don't really need to send the whole word "ALERT". It's not like a HUMAN is reading and interpreting it.

Think along the lines of "A1" = ALERT 1, "Rx" report status change X.

Easier to interpret... shorter to send.

I would think that then you can interpret input like my quickie pseudo code example here:


if result == 'a1': print" ALARM 1"

elif result == 'r1': print "report 1


Wow, thanks for the fast replies!

I figured it out...

I tried: if result == "alert\n" if result == "alert" ...

but what worked was:

if result == "alert\r\n"


I had an issue getting a \r when I was expecting just \n.

FWIW I'd use .strip()

if result.strip() == "alert":