• Stars
    star
    406
  • Rank 105,766 (Top 3 %)
  • Language
    Python
  • Created about 12 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Python library for communicating with Arduino microcontroller boards

Python Arduino Command API

The Python Arduino Command API is a light-weight Python library for communicating with Arduino microcontroller boards from a connected computer using standard serial IO, either over a physical wire or wirelessly. It is written using a custom protocol, similar to Firmata.

This allows a user to quickly protoype programs for Arduino using Python code, or to simply read/control/troubleshoot/experiment with harware connected to an Arduino board without ever having to recompile and reload sketches to the board itself.

Method names within the Python Arduino Command API are designed to be as close as possible to their Arduino programming language counterparts

Simple usage example (LED blink)

#!/usr/bin/env python
"""
 Blinks an LED on digital pin 13
 in 1 second intervals
"""

from Arduino import Arduino
import time

board = Arduino('9600') #plugged in via USB, serial com at rate 9600
board.pinMode(13, "OUTPUT")

while True:
    board.digitalWrite(13, "LOW")
    time.sleep(1)
    board.digitalWrite(13, "HIGH")
    time.sleep(1)

Requirements:

Installation:

Either run pip install arduino-python from a command line, or run python setup.py build install from the source directory to install this library.

Setup:

  1. Verify that your Arduino board communicates at the baud rate specified in the setup() function (line 348) in prototype.ino. Change it there if necessary.
  2. Load the prototype.ino sketch onto your Arduino board, using the Arduino IDE.
  3. Set up some kind of serial I/O communication between the Arduino board and your computer (via physical USB cable, bluetooth, xbee, etc + associated drivers)
  4. Add from Arduino import Arduino into your python script to communicate with your Arduino

For a collection of examples, see examples.py. This file contains methods which replicate the functionality of many Arduino demo sketches.

Testing:

The tests directory contains some basic tests for the library. Extensive code coverage is a bit difficult to expect for every release, since a positive test involves actually connecting and issuing commands to a live Arduino, hosting any hardware required to test a particular function. But a core of basic communication tests should at least be maintained here and used before merging into the master branch.

After installation, the interactive tests can be run from the source directory:

$ python tests/test_main.py

Automated tests can be run from the source directory with:

$ python tests/test_arduino.py

Classes

  • Arduino(baud) - Set up communication with currently connected and powered Arduino.
board = Arduino("9600") #Example

The device name / COM port of the connected Arduino will be auto-detected. If there are more than one Arduino boards connected, the desired COM port can be also be passed as an optional argument:

board = Arduino("9600", port="COM3") #Windows example
board = Arduino("9600", port="/dev/tty.usbmodemfa141") #OSX example

A time-out for reading from the Arduino can also be specified as an optional argument:

board = Arduino("9600", timeout=2) #Serial reading functions will
#wait for no more than 2 seconds

Methods

Digital I/O

  • Arduino.digitalWrite(pin_number, state) turn digital pin on/off
  • Arduino.digitalRead(pin_number) read state of a digital pin
#Digital read / write example
board.digitalWrite(13, "HIGH") #Set digital pin 13 voltage
state_1 = board.digitalRead(13) #Will return integer 1
board.digitalWrite(13, "LOW") #Set digital pin 13 voltage
state_2 = board.digitalRead(13) #Will return integer 0
  • Arduino.pinMode(pin_number, io_mode) set pin I/O mode
  • Arduino.pulseIn(pin_number, state) measures a pulse
  • Arduino.pulseIn_set(pin_number, state) measures a pulse, with preconditioning
#Digital mode / pulse example
board.pinMode(7, "INPUT") #Set digital pin 7 mode to INPUT
duration = board.pulseIn(7, "HIGH") #Return pulse width measurement on pin 7

Analog I/O

  • Arduino.analogRead(pin_number) returns the analog value
  • Arduino.analogWrite(pin_number, value) sets the analog value
#Analog I/O examples
val=board.analogRead(5) #Read value on analog pin 5 (integer 0 to 1023)
val = val / 4 # scale to 0 - 255
board.analogWrite(11) #Set analog value (PWM) based on analog measurement

Shift Register

  • Arduino.shiftIn(dataPin, clockPin, bitOrder) shift a byte in and returns it
  • Arduino.shiftOut(dataPin, clockPin, bitOrder, value) shift the given byte out

bitOrder should be either "MSBFIRST" or "LSBFIRST"

Servo Library Functionality Support is included for up to 8 servos.

  • Arduino.Servos.attach(pin, min=544, max=2400) Create servo instance. Only 8 servos can be used at one time.
  • Arduino.Servos.read(pin) Returns the angle of the servo attached to the specified pin
  • Arduino.Servos.write(pin, angle) Move an attached servo on a pin to a specified angle
  • Arduino.Servos.writeMicroseconds(pin, uS) Write a value in microseconds to the servo on a specified pin
  • Arduino.Servos.detach(pin) Detaches the servo on the specified pin
#Servo example
board.Servos.attach(9) #declare servo on pin 9
board.Servos.write(9, 0) #move servo on pin 9 to 0 degrees
print board.Servos.read(9) # should be 0
board.Servos.detach(9) #free pin 9

Software Serial Functionality

  • Arduino.SoftwareSerial.begin(ss_rxPin, ss_txPin, ss_device_baud) initialize software serial device on specified pins. Only one sofware serial device can be used at a time. Existing software serial instance will be be overwritten by calling this method, both in Python and on the arduino board.
  • Arduino.SoftwareSerial.write(data) send data using the arduino 'write' function to the existing software serial connection.
  • Arduino.SoftwareSerial.read() returns one byte from the existing software serial connection
#Software serial example
board.SoftwareSerial.begin(0, 7, "19200") # Start software serial for transmit only (tx on pin 7)
board.SoftwareSerial.write(" test ") #Send some data
response_char = board.SoftwareSerial.read() #read response character

EEPROM

  • Arduino.EEPROM.read(address) reads a byte from the EEPROM
  • Arduino.EEPROM.write(address, value) writes a byte to the EEPROM
  • Arduino.EEPROM.size() returns size of the EEPROM
#EEPROM read and write examples
location = 42
value = 10 # 0-255(byte)

board.EEPROM.write(location, 10) 
print(board.EEPROM.read(location))
print('EEPROM size {size}'.format(size=board.EEPROM.size()))

Misc

  • Arduino.close() closes serial connection to the Arduino.

To-do list:

  • Expand software serial functionality (print() and println())
  • Add simple reset functionality that zeros out all pin values
  • Add I2C / TWI function support (Arduino Wire.h commands)
  • Include a wizard which generates 'prototype.ino' with selected serial baud rate and Arduino function support (to help reduce memory requirements).
  • Multi-serial support for Arduino mega (Serial1.read(), etc)

More Repositories

1

webcam-pulse-detector

A python application that detects and highlights the heart-rate of an individual (using only their own webcam) in real-time.
Python
3,093
star
2

stl_tools

Python code to produce STL geometry files from plain text, LaTeX code, and 2D numerical arrays (matrices)
Python
253
star
3

game-of-life

Simple Python implementation of Conway's game of life and other cellular automata, computed using numpy.fft
Python
172
star
4

simple-cython-example

A small project template that shows how to wrap C code into python using cython, along with other packaging concepts
Python
123
star
5

examgen

A Python class that can automatically generate mathematics exams, with solution keys, using Sympy and LaTeX.
Python
53
star
6

math-genealogy

A python script to collect data from the mathematics genealogy project and generate genealogy graphs, combine graphs, etc.
Python
34
star
7

magiceye-solver

A python code to automatically "solve" magic eye autostereograms
Python
30
star
8

pyemotiv

A Python library for data acquisition from the Emotiv Epoc EEG headset, using the research SDK.
Python
22
star
9

pygmaps-extended

Python wrapper for Google Maps JavaScript API V3 and Google Earth API.
Python
16
star
10

github-auto-tools

Python command line tool to clone all public repos and gists from a single github account, and populate empty new repos with a set of templated default files.
Python
15
star
11

pandemic

Python based dynamical optimization of a pandemic disease model
Python
11
star
12

python-screenshot

Python library to make screen captures and save the images to the cwd
Python
11
star
13

pyneulog

Python interface for Neulog GSR sensor
Python
8
star
14

maximum-submatrix-sum

Python code that implements an algorithm for finding the maximum submatrix sum of an M by N matrix
Python
5
star
15

pyrovio

Python code to interface with the Wowwee Rovio robotic webcam
Python
4
star
16

garage_door_control

Android, spark firmware, and fritzing file for garage door control project
Java
4
star
17

Rimworld_roof_editor

Tool for editing roof-types on Rimworld maps
Python
4
star
18

latex-homework-template

A multi-column, landscape-oriented LaTeX template for homework assignments
3
star
19

imresize

A replacement for scipy.misc.imresize that does not depend on PIL
Python
3
star
20

opencv-data-plotter

A python code for fast, real-time 2d data plotting for codes that already have opencv as a dependency.
Python
2
star
21

Atlas

OpenMDAO implementation of the Aerovelo Atlas human-powered helicopter design problem
C
2
star
22

data-store

Some python tools for doing key-value storing
Python
2
star
23

SGNDI

Separable Grid N-Dimensional Interpolator: A multi-dimensional interpolating class with based on 1D interpolation.
Python
2
star
24

CVtemplate

Template for a real time computer vision project using OpenCV
Python
2
star
25

talk_inverse_probs

A short talk on discrete ill-posed inverse problems
Python
2
star
26

arduino-sketch-demos

A collection of various arduino demo sketches
Processing
2
star
27

SwiftFiniteDifference.playground

experimentation with first class functions in Swift
Swift
2
star
28

quick_imshow

Python code to quickly display an image with matplotlib. Meant for debugging image processing code.
Python
2
star
29

CADRE-old

OpenMDAO implementation of the CADRE CubeSat design problem
Python
1
star
30

thearn.github.io

1
star
31

printable_ramps

IPython Notebook for generating hand-drawn 3D-printable candidate solutions to the Brachistochrone problem
JavaScript
1
star
32

pathfinding

Python
1
star
33

android_tutorial

Java
1
star
34

pickle-gzip

Small python library to save and load objects with pickle from disc, with gzip compression.
Python
1
star
35

solar

OpenMDAO solar energy model
Python
1
star