How To: Control Arduino's Serial Monitor with Python

Arduino is an electronics platforming tool that is as fun as it is easy to get into. That doesn't mean it's weak either.
Arduino + Python

Arduino is amazing by itself but the entry level board, the Arduino Uno (pictured above, ~35$) has some limitations. Mainly, it has no native internet connectivity.

Enter the Python (and a computer like a Raspberry Pi)

Using Python and it's pySerial module we can control Arduino's serial port, and thus it's Serial Monitor (think I/O). The following Python script sends "on" or "off" through the Serial Monitor, which is then read by the Arduino to control an LED on PIN 13.
(If this all sounds foreign to you, please scroll down to bottom of the post for explanation.)

Python Code

import serial #pySerial  
import time  
ser = serial.Serial('/dev/ttyACM0', 9600)  
# If on Windows or "No such file '/dev/ttyACM0'" change
# to serial.Serial(9600)
time.sleep(2)  
ser.write("on") #can change to "off"  
print "Sent"  

Arduino Code

/*
 Simple LED Arduino sketch
 */

int led = 13; // Pin 13

void setup()  
{
    pinMode(led, OUTPUT); // Set pin 13 as digital out

    // Start serial connection
    Serial.begin(9600);
    Serial.flush();
}

void loop()  
{
    String input = "";

    // Read any serial input
    while (Serial.available() > 0)
    {
        input += (char) Serial.read(); // Read in one char at a time
        delay(5); // Delay for 5 ms so the next char has time to be received
    }

    if (input == "on")
    {
        if (digitalRead(13) == HIGH)
        {
          Serial.write("Led is already ON \n");
        }
        else
        {
          digitalWrite(led, HIGH); // on
          Serial.write("LED is on \n");
        }
    }
    else if (input == "off")
    {
        if (digitalRead(13) == LOW)
        {
          Serial.write("Led is already OFF \n");
        }
        else
        {
          digitalWrite(led, LOW); // on
          Serial.write("LED is off \n");
        }
    }
}

The Python code can be heavily modified and adapted to fit your needs. I adapted it to light up the LED when my web server is unreachable using urllib2.

Explanation: Arduino has a set of General Purpose Input/Output (GPIO) pins that have two settings, HIGH and LOW (1, and 0). When a pin is HIGH it can power an LED (or other electronics). Thus when our "on" command is sent PIN 13 is set to HIGH.

Raspberry Pi's also have GPIO pins!

»