The Complete Beginner's Guide to Python for Arduino

In this article,I am going show you how to use python for arduino. For this I am going to use firmata library. First you need to upload standard firmata code which is available in arduino example in arduino IDE, into your arduino(I am using arduino uno).


1.Find firmata code in arduino examples in arduino IDE,

2.Then, upload standard firmata code into arduino,

3.Now, its time to download python library for firmata using command $ pip install pyfirmata and its documentation and full source code can be found on github.
Now we are all set lets get started,
Open up terminal and open python,
>>> from pyfirmata import Arduino, util #importing library for firmata
>>> board = Arduino('/dev/ttyACMA0') #'/dev/ttyACMA0' may be different for your OS, you can find that under tools tab of arduino IDE
>>> board.digital[10].write(1) #writing 1 or 'HIGH' to pin 10 of arduino
For using analog port, you need to use iterator thread otherwise board will keep sending data to your serial, until it overflows,it can be done as follow:
>>> it = util.Iterator(board) #making iterator object
>>> it.start() #starting iterator object
>>> board.analog[0].enable_reporting() #you need to enable reporting to read analog value
>>> board.analog[0].read() #reading value from channel zero of analog port
0.661440304938
Alternatively,you can use the get_pin method of the board. It let's you specify what pin you need by a string, composed of 'a' or 'd' (depending on wether you need an analog or digital pin), the pin number, and the mode ('i' for input, 'o' for output, 'p' for pwm). All seperated by :. Eg. a:0:i for analog 0 as input or d:3:p for digital pin 3 as pwm.:
>>> analog_0 = board.get_pin('a:0:i')
>>> analog_0.read()
0.661440304938
>>> pin3 = board.get_pin('d:3:p')
>>> pin3.write(0.6)
And that't it.Enjoy coding arduino in your favourite language python.Another article NodeJs and Arduino is comming soon.

2 comments: