Using Python with Arduino

This page describes how to interact with an Arduino from Python code.

Getting Started

  1. If needed, install python.
  2. If needed, install pip.
  3. Install pyserial: pip install pyserial
  4. Install the Arduino IDE.
  5. Download the sample files.

Upload code your Arduino

  1. Determine your Arduino Sketchbook location. You can find this by opening preferences in the Arduino IDE (File > Preferences). The directory is listed near the top with the heading Sketchbook location.
  2. Close the Arduino IDE.
  3. Copy the SimpleSensor folder from the sample zip file into your sketchbook location.
  4. Re-open the Arduino IDE.
  5. Inside the Arduino IDE, open the SimpleSensor sketch.
  6. Select your Arduino type and serial port in the Tool menu. On a Mac the port will usually start with tty.usb. On Windows this will usually be the highest numbered COM port. The next time you plug-in this Arduino to this computer it will use the same port.
  7. Click the Upload button.

Log Data to CSV

  1. Edit simpleLogger.py so that the serial port matches the port identified by the Arduino IDE.
  2. If not already connected, connect your Arduino.
  3. Run python simpleLogger.py
  4. The program should display data and store it to a file called sensorLog.csv
  5. Press control-C or command-C to stop the program.

Real-time Plotting

  1. Install matplotlib
  2. Edit simplePlotter.py so that the serial port matches the port identified by the Arduino IDE.
  3. If not already connected, connect your Arduino.
  4. Run python simplePlotter.py
  5. The program should display a plot of the data.
  6. Press control-C or command-C to stop the program.

Feed Data to Xively

  1. Run pip install requests
  2. Download the Xively library for python
  3. In the downloaded folder, run python setup.py install
  4. Create a developer account on Xively.
  5. Log in to Xively and go to Web Tools > Develop > Add Device then create a new device. After you create it, you will see the device's API key (a long strong of letters and numbers) and feed ID.
  6. Create a new channel for the device.
  7. Edit simpleUpload.py to enter your API key, feed ID, channel name, and serial port.
  8. If not already connected, connect your Arduino.
  9. Run python simpleUpload.py
  10. The program should upload a data point to your Xively account once every 15 seconds.
  11. Press control-C or command-C to stop the program.

More information about feeding to online services: