Introduction: Arduino and Python

Picture of Arduino and Python

For a project (check out my blog for updates) I'm working on I needed to be able to communicate with my arduino, luckily the arduino can communicate though serial. It turns out almost any programming language can be used for serial communication but python seems to be the easiest so far.
I had some problems getting it all to work and finding a basic tutorial online proved very difficult. So hopefully this guide will explain the basics to anyone that is looking to start using the serial functions that the arduino provides.

I'm going to assume that if you're reading this you have some knowledge of how an arduino works and how to upload sketches and what not, however I will explain the arduino code when we get there. The python code is very basic but I will do my best to explain it as well. 

The code is not that hard to understand, the hard part is understanding how the serial communication works.

So, I'm going to show you how to tell your arduino to blink using your computer. Once you understand this you should be able to expand both the python code and the arduino code to fit your own projects. 

Step 1: Sorting Out Python

Picture of Sorting Out Python

Now, obviously, we're going to need python if we want to do anything so we better get that! If you don't have it installed, head over to the python website and download it! (

Once we have python installed were going to need a new library called PySerial. This is going to provide all the functions and methods we will need to talk to our arduino! 

If you're using a windows machince check out their source forge page for the windows installer.
If you're using MacOS/linux your going to have to look around the PySerial website. 

Also, if you're familiar with using Eclipse you might be intersted in the Python add-on for eclipse. Check it out if you would like to program in the eclipse environment.

Now if everything is installed we can actually start writing our Python program!

Step 2: Python Code!

Picture of Python Code!

Now we can actually start programming!

So, in order to actually use the PySerial methods we need to import the serial library before we try to use it.

Next I declare a variable that will act as a flag.When serial connections are opened with the arduino it takes a little while to sort things out. So we wont try to send anything to the arduino until it sends something to us.

Next we initialize a serial variable, "ser", that will be communicating with the arduino. Two parameters are sent when initializing a serial variable.
First you have to port that it will be communicating with. In my case It was COM11, but yours may differ. To find out what port your arduino is using, connect it to your computer and open up device manager. The arduino IDE will also tell you which port it is using.
The second parameter that is sent is the baud rate. The baud rate is the speed that the serial controller will send and receive at, the important thing is this baud rate matches the baud rate you use in the arduino sketch. I chose 9600 since it is a middle of the road speed and we don't need anything too fast for this example. If you want to use a faster or slower speed, use Google to figure out which speeds to use.

We want to tell the arduino to blink! So I have a write function that sends the number 1 to the arduino.
When the arduino sees this it's going to blink twice!

Now we want to wait until the arduino tells us that it has blinked twice. By having the while loop the program will loop (do nothing) until it receives a message. If we were to leave this while loop out, the program would close the serial port and the arduino wold stop blinking.

When we receive the message from the arduino we can close the serial port and end the program.

So that's all we need for the python program, just 10 lines of code!

Step 3: Setting Up the Arduino

Picture of Setting Up the Arduino

Im going to assume everyone has the adruino software installed and working.

Since we just want to make a light blink we can just use the light that is on the arduino or connect and LED to pin 13 and ground. 

Like the circuit the Code isn't too scary either.

In void setup () we start the serial monitor with a baud rate of 9600. The rate doesnt matter, just make sure it matches the baud rate in the python program.

Next, we make an output pin that out LED is connected to.

Lastly, we write something over serial so the python program knows we are ready.

In void loop() we have one big if statement. Basically this is waiting for the python program to send something over serial.
Once the arduino receives something the LED will blink twice.
After two blinks the arduino sends a message back saying it is finished blinking. The python program will see this and then stop.

Step 4: Test It Out!

Upload the sketch to your board and then run the python program. If everything was done properly you should see the light blink twice!!

If not make sure the programs are the same as mine or leave a comment here or message me, I'll be happy to help!

If you want start messing around this the code, try adding in another LED and make them alternate, try sending different things over serial. If you get stuck just remember Google is your friend!

Thanks for reading!


ajay07 (author)2016-08-09

can we write a python code on Arduino IDE.

please do reply.

thank you!

SebastiaanJansen (author)ajay072017-04-24

You can with microPython :

luigi.f.cerfeda (author)ajay072017-03-26

Not on Arduino IDE but you can use another IDE, Zerynth Studio:

With Zerynth you can program Arduino (32-bit MCU) boards directly in Python

Berkeley_Blue (author)ajay072016-10-21

currently, no. the only way is using pySerial (and compiling a .py script to .ino (not sure its possible))

eerimoq (author)ajay072016-09-26


have a look at the Pumbaa project. It is available in the Arduino IDE.

RoxetteMabellon (author)2017-04-02

The example give's errors

b.append(item) # this one handles int and str for our emulation and ints for Python 3.x
TypeError: an integer is required

sorry too difficult for me. thank you anyway

megapix (author)2016-07-09

The code that says "import" is the Python code. You run that on your PC using Python. The Arduino code is "sketch_SerialTest.ino"

skyhawk231 (author)megapix2016-07-11

Sorry I accidently deleted my first post :/ okay so i set it up as a python script and I ran it in the terminal and got this error:

Traceback (most recent call last):
File "", line 8, in <module>
import serial
File "/home/echo/Desktop/", line 5, in <module>
ser = serial.Serial("COM11", 9600)
AttributeError: 'module' object has no attribute 'Serial'

So is it a problem in the code?

MartinR95 (author)2016-03-21


I have tried to make this project using a Relay rather than an LED. I can get the relay to switch using Arduino and Python together, but then the Arduino continues to loop, switching the relay on and off, rather than ending once it has sent ‘0’ back to python to indicate it has done the loop. Any ideas why this may be?



russ_hensel (author)2016-01-23

I love the combination of Python and the Arduino. So I have created a collection about it. I have added your instructable, you can see the collection at: >>

luigi.f.cerfeda (author)2015-10-07

Hi guys, if you're looking for programming Arduino in Python, take a look at VIPER!website:

instructables profile:

zaaap (author)2012-10-02

At fiest I wanna thank you for submitting your tuotial here, its very nice and helpful however it has some flaws.
This Arduino code will blink for infinity UNLESS you 'clear' memory (which stores one value at a time). One way is to read from serial (eg. in Arduino software) and second one is replacing Serial.wite('0'); with;
After doing this it works like a charm!

poupsmaster (author)zaaap2015-09-06

Thx for the fix !

Harish AG (author)2015-08-04

Thanks!!!! it helped me a lot....

prappo.prince (author)2015-05-06

Thanks bra

Arduino4Me (author)2015-04-01

Thanks for the tutorial!

brodylittle011 (author)2014-01-12

when i run the python script it says access is denied...any ideas on how to fix? Thanks.

I'm late to mention it, but for future reference that usually means you have the COM port already open in the arduino IDE. or sometimes it can just be that you didn't close the window properly. It's annoying thing I used to have more problems with early on, the handling of the COM window is finicky. I sometimes would have to restart my computer to get it to clear.

Kinnishian (author)Kinnishian2014-12-30

To clarify, only 1 program can access the com port at a time.

for the COM port...

mccreamark (author)2014-11-08

Thank you, I was looking for a nice simple example:

I used it with python3.3 with these changes :

Change the comport string COMX to a single integer one below the port# you are using , example:

ser = serial.Serial(COM6, 9600) becomes ser = serial.Serial(5, 9600)

and add a b prefix for python3.3 serial write example:

ser.write( "1") becomes ser.write(b"1")

Thanks again

Kinnishian (author)mccreamark2014-12-30

Ah ,thanks! b"string" is simpler than bytearray("string") and explains to me better why I had to do that change ^_^

BradB1 (author)2014-09-07

Great introduction to communicating between an Arduino and a computer

Tbus (author)2014-02-25

I just finished a home-study Python programming course ( ) and this Instructable was an awesome test for my new programming skills. Thanks!

jsalam1 (author)2013-09-16

sorry not working

aatifof06 (author)2013-08-02

what does

means, exactly that 1..

and how to stop that blink using python.

amaituino (author)2013-07-21

I love what you did ! Thanks !!

tchen2 (author)2012-12-06

Im running python using mac. I have pyserial installed and was able to communicate with Arduino using terminal. However, when i tried to use eclipse, it stops me at import serial. Any idea how to over come this problem? Thanks!

RamirezTerrix (author)2012-11-22

Thanks works linke a charm!

Hustleer (author)2012-11-08


Can you post a mac version of the tutorial?
that would be nice. Good job on the tutorial though :)

renegadezombies (author)2012-09-17

I'm a bit confused. You say your "while" loop is meant to continue looping until the device is plugged in, yet it seems to me it will either throw an error or valuate "true" on the first iteration.

I believe "serin =" is meant to be your trigger here, that if it succeeds it will continue to go onto the next line "connected == "True"", and skip to the next iteration if it fails.

This however shouldn't work. If the device is not connected and you call "serin =", it will throw a "ValueError" exception. Even if this line of code passed fine through the prompt, the next line "connected == "True"" would run regardless of what happened in the previous line.

Your proper while loop should look like this:

while not connected:
       serin =
    except ValueError:
    connected = "True"

jbolt (author)2012-06-03

I also copied & pasted your code. I get the same error as krithimagic. I'm also a novice at this.

File "C:\Python32\lib\site-packages\serial\", line 236, in read
raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
serial.serialutil.SerialException: ReadFile failed ([Error 6] The handle is invalid.)

I am running Python 3.2 on Windows 7.

I believe this problem has something to do with Windows 7 being 64 bit. I have tried the various solutions I have found on the internet, but nothing seems to work.

Using a different sketch, I can see results that come back from the Arduino board in the Arduino Serial Monitor, so serial communication must be working. This leads me to think the problem is with Python or perhaps pySerial.

I'd appreciated any help or advice you might be able to provide.

jbolt (author)jbolt2012-06-04

As a follow-up for anyone who may be reading this in the future, my problem was due to improperly installing pySerial. After I got that problem straightened out, Bobbert72's software worked as described.

krithimagic (author)2012-03-16

Hey! I'm a real novice to python coding and I copied your Python code word to word. It works great until I have to write

while not connected:
serin =
connected = True

that's when I get an error:

Traceback (most recent call last):
File "", line 2, in
serin =
File "C:\Python27\lib\site-packages\serial\", line 236, in read
raise SerialException("ReadFile failed (%s)" % ctypes.WinError())
SerialException: ReadFile failed ([Error 6] The handle is invalid.)

Please help me out!

Bobbert72 (author)krithimagic2012-04-20

Sorry for the late reply!
At first glance it looks like your python code is trying to read from a file and not from the arduino's serial port. Make sure you have PySerial and your importing it properly. Although that really shouldn't be a problem since you aren't getting an error at the line above where you declare the variable ser.

Is your arduino plugged in to your computer? If it is, make sure the program is pointing to the right COM port. Ill edit the instructable to explain that process more clearly.

Check out the documentation for Python and PySerial on their website and mess around with the code a little.

About This Instructable




More by Bobbert72:Arduino and PythonHeart-Shaped Chocolate holder
Add instructable to: