Using Python with Arduino
This page describes how to interact with an Arduino from Python code.
Getting Started
- If needed, install python.
- If needed, install pip.
- Install pyserial:
pip install pyserial
- Install the Arduino IDE.
- Download the sample files.
Upload code your Arduino
- 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 headingSketchbook location
. - Close the Arduino IDE.
- Copy the
SimpleSensor
folder from the sample zip file into your sketchbook location. - Re-open the Arduino IDE.
- Inside the Arduino IDE, open the
SimpleSensor
sketch. - 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. - Click the
Upload
button.
Log Data to CSV
- Edit
simpleLogger.py
so that the serial port matches the port identified by the Arduino IDE. - If not already connected, connect your Arduino.
- Run
python simpleLogger.py
- The program should display data and store it to a file called
sensorLog.csv
- Press control-C or command-C to stop the program.
Real-time Plotting
- Install matplotlib
- Edit
simplePlotter.py
so that the serial port matches the port identified by the Arduino IDE. - If not already connected, connect your Arduino.
- Run
python simplePlotter.py
- The program should display a plot of the data.
- Press control-C or command-C to stop the program.
Feed Data to Xively
- Run
pip install requests
- Download the Xively library for python
- In the downloaded folder, run
python setup.py install
- Create a developer account on Xively.
- 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. - Create a new channel for the device.
- Edit
simpleUpload.py
to enter your API key, feed ID, channel name, and serial port. - If not already connected, connect your Arduino.
- Run
python simpleUpload.py
- The program should upload a data point to your Xively account once every 15 seconds.
- Press control-C or command-C to stop the program.
More information about feeding to online services:
- Xively
- Google Spreadsheets
- Others? Email support@manylabs.org with your recommendations.