Creating Two Buttons In Python And Controlling LED

Introduction

 
In this article, I am explaining about creating two buttons in Python for controlling the LED- LED ON and LED OFF.
 
List of Parts
 
Hardware Side
  • Arduino Uno
  • LED
Software Side
  • Arduino IDE
  • Python software
Connection
  • Connect the positive side of led to the 13 on the Arduino board.
  • Connect the negative side of led to the Gnd on the Arduino board.
Programming
 
Programming For Arduino Part
  1. int led = 13;  
  2. char mydata = 0;  
  3. voidsetup()   
  4. {  
  5.     pin Mode(led, OUTPUT);  
  6.     Serial begin(9600);  
  7. }  
  8. void loop()  
  9. {  
  10.     my data = int(serial.read());  
  11.     if (y data = = '1') digitalWrite(led, HIGH);  
  12.     if (mydata = = '0') digitalWrite(led, LOW);  
  13. }   
Now, connect to the Arduino part via USB cable and upload the program to the board.
 
Programming For Python Part
  1. import Serial    
  2. import time    
  3. from tkiner import*    
  4. def led_on();    
  5.     arduinoData.write(b '1')    
  6. def led_off( );    
  7.     arduinoData.Write(b '0')    
  8. led_control_Window=Tk( )    
  9. btn = Button(led_control_window,text = "led on",command = led_on)    
  10. btn2 = Button(led_control_window,text = "led off",command = led_off)    
  11. btn.pack( )    
  12. btn2.pack()    
  13. arduinoData= Serial.Serial("COM4",9600)   
Explanation
 
In the Python program, I have added the buttons. Now, the buttons will be displayed in the run window.
  1. btn = Button(led_control_window,text = "led on",command = led_on)    
  2. btn2 = Button(led_control_window,text = "led off",command = led_off)    
  3. btn.pack( )    
  4. btn2.pack()   
Now, when we click on the led on button, the LED will be ON and when we click led off, the LED will be off. (as shown in Figure 2).
 
 
Figure 1: Buttons in Run Window
 
Output
 
 
Figure 2: Output