[PA-02] Send data from Arduino via pyserial

Step 1: install pyserial: go to https://pypi.python.org/pypi/pyserial/2.7 download version pyserial-2.7.win32.exe and install to your computer.

Step 2: load the following code to the Arduino, this code will send variable count to the computer via serial port and blink led on pin 13 (1 sec ON, 1 sec OFF to prove that Uno is still working)


/*
 * Arduino and Python Serial Port
 * Date: Thu, 27/04/2017
 * Desc: Serial port testing
 * Arduino counting and sending count via serial port COM3
 * Blink Led 13 to prove alive
 */
int cnt;
void setup() {
 // Initialize variable, procedure and state
 cnt = 0;
 Serial.begin(9600);
 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);
 // Foreword
 Serial.println("Counting demo");
 Serial.println("-------------");
}

void loop() { 
 // and sending count
 Serial.print("I am counting to ");
 Serial.print(cnt);
 Serial.println(" Mississippi.");
 // Counting
 cnt++;
 // Blink Led 13
 digitalWrite(13, HIGH);
 delay(1000);
 digitalWrite(13, LOW);
 delay(1000);
}

Now you can go to: Tools --> Serial Monitor to check the data that Arduino sent to PC.

Step 3: paste the following code in VIDLE VPython


import serial #Import Serial Library

arduinoSerialData = serial.Serial('COM3', 9600)

while(1==1):
 if (arduinoSerialData.inWaiting()>0):
 myData = arduinoSerialData.readline()
 print myData

Remember to change to COM port that is suitable in your computer (mine is 'COM3'). You can find your COM port at the bottom-right of your Arduino IDE.  The baud rate will be 9600 at default.

PA02_determine_COM_port

What happens if the variable int cnt reach the maximum positive value (in Arduino code I initiate variable cnt = 32760 in void setup)? Here comes the result:

PA02_integer_max_value

You can press Ctrl+C (corrupt) to terminal the running program. It will help for the next connection without prompting some alarm.

Beware of the variable type and its range and how microcontroller processes variable limit. You do not want to save too much money to bank account and then your account amount will be negative or zero.

 

That is one-way ticket, from Arduino to PC. Next time, I will show you the other way, from PC to Arduino.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s