Reading Arduino serial ports in Windows 7 with Python + Pyserial

Here i am going to show you 3 working examples on how to read Arduino serial ports with windows. You are going to need following programs / tools:

Installing Python + Pyserial to Windows

First you have ton install Python on your computer. This is just typical install with no big deal. When you have installed Python you may want to restart your computer. If you are not sure if your install was succesfull you can open your command prompt and type python or go to location where you installed python and run Python.exe. If everything works correctly your command prompt should look something like this:

python command prompt

After installing Python you can download Pyserial. Unzip pyserial to folder where you installed python and says lib. For me example to location was:

c:\Python27\Lib\pyserial-2.6\

After you have unzipped pyserial, you should start command prompt and go to location above. In there you can find setup.py named file, which you cn run by typing:

python setup.py install

Now you have installed Python + Pyserial

Reading  Arduino serial ports with Pyserial

First code is basic ”Hello world” with arduino and python
Code for Arduino:

Hello world with serial ports

Arduino code:

void setup(){
// Open serial connection.
Serial.begin(9600);

}

void loop(){
Serial.print("Hello world");
delay(10); // ms

}

Next code for python: (Note that WordPress might break Pythons code blocks)

import serial
import time
ser = serial.Serial('COM3', 9600, timeout=0)

while 1:
 try:
  print ser.readline()
  time.sleep(1)
 except ser.SerialTimeoutException:
  print('Data could not be read')
  time.sleep(1)

Arduino read data from Python

Arduino read data when user type something and prints it out byte by byte.

Arduino code:


int incomingByte = 0;

void setup(){
// Open serial connection.
Serial.begin(9600);

}

void loop(){
if (Serial.available() > 0) {
 // read the incoming byte:
 incomingByte = Serial.read();

 // say what you got:
 Serial.print("I got: "); // ASCII printable characters
 Serial.println(incomingByte, DEC);
}

}

Python code:

import serial
import time
ser = serial.Serial('COM3', 9600, timeout=0)
var = raw_input("Enter something: ")
ser.write(var)
while 1:
	try:
		print ser.readline()
		time.sleep(1)
	except ser.SerialTimeoutException:
		print('Data could not be read')

Arduino control led

Controlling 1 led light with arduino and pyserial by typing 0 or 1 to turn led on and off

Code for arduino:

int incomingByte = 0;
int ledPin = 13;

void setup(){
pinMode(ledPin, OUTPUT);
}

void loop(){

if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();

// say what you got:
if(incomingByte == 49) { // ASCII printable characters: 49 means number 1
 digitalWrite(ledPin, HIGH);
} else if(incomingByte == 48) { // ASCII printable characters: 48 means number 0
 digitalWrite(ledPin, LOW);
}
}

}

Code for python:

import serial
ser = serial.Serial('COM3', 9600, timeout=0)
while 1:
	var = raw_input("Enter 0 or 1 to control led: ")
	ser.write(var)

Reading data from sensor and printing that to computer

In this code we are going to use unknown light sensor for arduino. You can basically use any type of sensor you want since the principle is the same.

Code for arduino:


int lightPin = 1;
float lightValue;

void setup(){
  pinMode(ledPin, OUTPUT);
}

void loop(){
  lightValue = analogRead(lightPin);
  Serial.println(lightValue);
  delay(1000);
  }

Code for python:

import serial
import time
ser = serial.Serial('COM3', 9600, timeout=0)
while 1:
	try:
		print ser.readline()
		time.sleep(1)
	except ser.SerialTimeoutException:
		print('Data could not be read')
	time.sleep(1)

Sources:

This page is licensed under a GNU General Public License v2
Advertisements

12 thoughts on “Reading Arduino serial ports in Windows 7 with Python + Pyserial

  1. Päivitysilmoitus: Arduino serial port | nisonen
  2. hello i have tried the codes for ”hello world”and reading a sensor with an ultrasonic sensor but my computer works for a while,for 2 minutes and then it gets stunned, witb both programs. Do you know what may be wrong?

    1. Hi,

      It’s really hard to say with that info what is wrong and best way for you to work is to start with the basics and move from there.

      1) Test Arduino with some code you know that work (also test that your ultrasonic sensor works without my codes)
      2) Test that your Python works correctly (simple hello world)
      3) Check your wirings in Arduino

      Usually if I have problem I return to point where it worked last time and start working from there again

  3. Does the port to comunicate from Python->to Arduino has to be the port that arduino uses by default or can it be any port?
    I mean, if arduino uses COM3 do I have necessarily to use COM3 on ”ser = serial.Serial(’COM3’, 9600, timeout=0)”.
    I want to make a both ways comunnication, is it possible?

  4. I get this error when I try the code for the Arduino to read from Python: ”Error opening serial port ’COM3’. (Port busy)”
    The only port I’m able to use with Arduino is ’COM3’, that means that I have to change the port in Python? and in that case, how do I know which port can I use?

  5. Thanks for this simple, but clear, examples!
    I found an error in the arduino code of ”Arduino control led” and ”Reading data from sensor and printing that to computer”. In the setup() the serial connection is not initialized. Copying ”Serial.begin(9600);” in setup() solves it.

    And for the people using python3.x:
    The print statement has become a function in python3 , so it needs arguments, e.g. ”print(ser.readline())”.
    And last one serial communication needs to be encoded. This can be done by writing ”.encode()” behind the variable, e.g. ”ser.write(var.encode())”

Vastaa

Täytä tietosi alle tai klikkaa kuvaketta kirjautuaksesi sisään:

WordPress.com-logo

Olet kommentoimassa WordPress.com -tilin nimissä. Log Out / Muuta )

Twitter-kuva

Olet kommentoimassa Twitter -tilin nimissä. Log Out / Muuta )

Facebook-kuva

Olet kommentoimassa Facebook -tilin nimissä. Log Out / Muuta )

Google+ photo

Olet kommentoimassa Google+ -tilin nimissä. Log Out / Muuta )

Muodostetaan yhteyttä palveluun %s