Python script to control LED in Arduino
This project has been written to show how a Python script can communicate with Arduino and control devices such as LEDs. The following code can be used in either Linux or Windows environment. Please note to use one of the “serial” definition which is compatible with the corresponding OS.
Python code:
First, we need to import two required packages as follows:
import serial import time
Serial library let you communicate with the desire port which the Arduino board is connected to. Next make sure what are the port name and number in the desired operating system and define two variables to use it later.
In this case port name is ‘com6’ and the port number is 9600 in Windows so:
port_name = 'com6' port_num = 9600
If the environment is Linux these two variables would be as follows in our case:
port_name = '/dev/ttyACM0' port_num = 9600
Next by using serial library that is imported earlier, connection can be stablished as follows:
connection = serial.Serial(port_name, port_num, timeout=0)
Now by letting the program to sleep for a few second, in this case 2s, we let the connection to establish and print a message to user that the connection is ready to use.
time.sleep(2) print('{} is connected successfully.'.format(connection.name))
The following line is written to get any number from 1 to 3 from user. And finally send the numbers 1/2 to Arduino terminal port to turn LED on/off. 3 would result in exiting the program.
print("1-> on\n2-> off\n3-> exit") while 1: input_data = input('Enter:') if (input_data == '1'): ser.write(b'1') print("LED ON") if (input_data == '0'): ser.write(b'0') print("LED OFF") if (input_data == '3'): ser.close() else: print('Try again ...')
Finally save the whole code as any desired name with .py extension.
Arduino code:
Below shows the Arduino code which LED is attached to digital port 10. The communication port is set to 9600.
int LED = 10; void setup() { Serial.begin(9600); Serial.flush(); pinMode(LED, OUTPUT); digitalWrite(LED, LOW); } void loop() { if (Serial.available() > 0){ String userkey = Serial.readString(); if(userkey == '1'){ digitalWrite(LED, HIGH); } if(userkey == '0'){ digitalWrite(LED, LOW); } delay(300); } }
Description
10/20/2021
A Python script to communicate with Arduino and control an LED to switch on/off.
Language: Python, Arduino