Posts Tagged python

def Python meets Arduino:

I write this article as an introduction to how the Python language can be used to talk to the Arduino board. In essence, what I do here is simple serial communication.

There is a program that I ve written for the Arduino board that does two simple things:

  • Reads the serial input.
  • Constrains the input to an integer between 0 and 179 and writes it to the servo motor.

The point at which python comes into play is when we, as users, provide the input. Although the Arduino software has its own Serial monitor which can be used to accomplish the same task, I am using python just as an alternative (this can be done in any other language too…python is just the easiest one). It might so happen that later on the Serial monitor and its functionality¬† might not be enough. You might be writing a larger application of which the serial communication is only a small part. In which case Python to the rescue…

So here is the scenario in short..

There is a servo motor attached to one of the pwm digital output pins of the Arduino and i have the python interpreter running on my computer. If you don’t have python installed on your comp you can install it from http://www.python.org/getit/. You will also need to install the pySerial module if don’t already have it. Open the python interpreter and type “import serial”. If you get an error install it from here http://sourceforge.net/projects/pyserial/

Next I upload the following code to the board:

Serial available() : returns the number of characters still left to be read

One more thing to remember, in serial communication information is received in terms of character bytes. That means even if we give the input as the number 123. The microcontroller receives it as character ‘1’, character ‘2’ and character ‘3’ respectively

The next statement takes care of this problem. The expression ” incoming_byte – ‘0’ “, subtracts the character ‘0’ from the character received¬† giving us an integer for e.g. ‘1’ – ‘0’ = 1 (integer). and adds it to 10 * sum (as calculated in the previous iteration). The final sum is constrained between 0 & 179 and assigned to the variable “angle”. Finally, the value of “angle” is written to the Servo.

Once the program is uploaded, I move on to python. I open the interpreter and type the following commands which are quite self explanatory:

So…thats it. One of the simple ways in which python can be used with Arduino.

Advertisements

, , , , , , , ,

3 Comments