Using a serial byte sent from an Arduino to launch an application on the PC

One of my students is building an Arduino-based robotic system that needs to run a program on the PC to do some image capture. The Python script below bridges the gap. It opens a serial port (you need to specify the COM port that Windows has assigned to the Arduino), then processes incoming characters, waiting for a particular character (‘p’) to be received. When a ‘p’ is received, it launches an application using os.system. In this example, the application launched is Notepad, but it could be whatever you want.

import serial
import os

# Open whatever COM port is assigned to the Arduino
# at the same baudrate that the Arduino is using
with serial.Serial('COM5', 9600, timeout=1) as ser:
    # Now process incoming characters one at a time forever
    while 1:
        c = ser.read()          # read one byte
        print(c)                # print out the byte
        print('\n')             # print new line
        if c == b'p':
            # The received byte was a 'p' character
            # so launch an application on the PC
            os.system("notepad.exe")
            print("Got a P\n")
        else:
            # The received byte (if any) was not a 'p'
            print("Not a P\n")

To test the Python program, I uploaded the following tiny program to the Arduino to send a ‘p’ character once every ten seconds.

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  delay(10000);
  Serial.print("p");
}
Advertisement
This entry was posted in Uncategorized. Bookmark the permalink.

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 )

Connecting to %s