Python


 [email protected] ’s features can be accessed from a compatible host, such as Raspberry Pi, using the Firmata protocol over serial (for more information see Programming Model).

Firmata provides a standardized mechanism to exchange information between a real-time processor such as  [email protected] and a host, useable by many programming languages.

Using Python Firmata with Ardhat

 [email protected] ships from the factory with Firmata already installed (but follow the instructions in Installation to make sure you have turned off kernel serial port use before proceeding). We need to install a couple of extra packages to allow the host to communicate over Firmata using Python.

To enter these commands more easily, connect to the Pi using `ssh`, so that you can copy and paste them into the terminal.

Setting up Python Firmata

~ $ sudo apt-get install python-pip python-serial

~ $ sudo pip install pyfirmata

~ $ python

# => You should now have a python prompt >>>

At the Python prompt we can then instantiate a board, and set and get values on  [email protected] .

To read the value on an analog pin, you have to first turn on the analog value reporting for that pin.

Note that

  • Analogue reads and PWM writes are normalized to a 0 .. 1 range, and not the standard Arduino 0 .. 255 and 0 .. 1023.

  • You should start a separate iterator thread to stop unread value reports clogging up the Firmata channel

As an example, the following Python commands let you perform a simple test of port D2.

At the Python Prompt...

>>> from pyfirmata import Arduino, util

>>> board = Arduino('/dev/ttyS0')

>>> board.digital[2].write(1)

>>> board.digital[2].read()

1

… or use this example for reading Analog port 0.

At the Python Prompt...

>>> from pyfirmata import Arduino, util

>>> board = Arduino('/dev/ttyS0')

>>> it = util.Iterator(board)

>>> it.start

>>> board.analog[0].enable_reporting()

>>> board.analog[0].read()

0.2727

# => You can repeat the above command to show the current output of Analog Port 0

More info on using Python Firmata can be found here.