[PA-03] Python gives command to Arduino

This lesson will show you how to build a control form with 2 buttons to turn on and turn off Led on pin 13 of Arduino. How to do that? Simply Python send character ‘H’ and ‘L’ when pressing the corresponding button via COM port, then Arduino will read the sending character and do the corresponding command. I make a feedback response for Arduino when the command is done so the mechanism is more reliable.

Step 1: gui_command_toggle.ino


/*
 * Date: Tue, 02/05/2017
 * Desc: Receive command from Python
 * Do the command and give message feedback
 */
#define LED 13

void setup() {
 // Initial process
 pinMode(LED, OUTPUT);
 digitalWrite(LED, LOW);
 Serial.begin(9600);

Serial.println("Led is initially turn off. Staring ...");
 Serial.println("--------------------------------------");
}

void loop() {
 if (Serial.available()) {
 char c = Serial.read();
 if (c == 'H') {
 digitalWrite(LED, HIGH);
 Serial.println("Led is turn on");
 }
 else if (c == 'L') {
 digitalWrite(LED, LOW);
 Serial.println("Led is turn off");
 }
 }
}

Step 2: gui_toggle.py


from Tkinter import *
import serial
import time

def led_on():
 arduinoData.write(b'H') # Send with byte format, b

def led_off():
 arduinoData.write(b'L')

arduinoData = serial.Serial('com3', 9600)

# create form
led_control_window = Tk()
led_control_window.title("Control led 13 on Uno")
led_control_window.geometry("300x200") # Size of form

# create UI control
but_1 = Button(led_control_window, text="led_on", command=led_on)
but_1.place(x=100, y=140, width=90, height=30)
but_1.pack() # stick it to form
but_2 = Button(led_control_window, text="led_off", command=led_off)
but_2.place(x=300, y=340, width=190, height=130)
but_2.pack()

# run the GUI
led_control_window.mainloop()

while True:
 if (arduinoData.inWaiting()>0):
 myData = arduinoData.readline()
 print myData

The outcome is not as good as expected. Only when the GUI is closed, Arduino sends back the message. I should not use 2 buttons because there is a chance that I hit turn on when the Led is already turn on.

PA03_gui_totalPA03_gui_without_control

It is a not good result. Maybe I will build a text field to receive the feedback message from Arduino next time. The index of next section will be [PA-03a].

 

Note: Tkinter with capital "T"

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