Jalal Mansoori
Published © GPL3+

Python3 and Arduino Communication

Easily send commands from Python3 versions to Arduino.

BeginnerFull instructions provided25,742
Python3 and Arduino Communication

Things used in this project

Story

Read more

Schematics

arduino_uno_nK1sUVJ7D8.jpg

For this project you just need arduino board and usb cable

Code

Arduino Code

Arduino
This code is for arduino and you need to upload this code before running python code
int datafromUser=0;
void setup() {
  // put your setup code here, to run once:
  pinMode( LED_BUILTIN , OUTPUT );
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  if(Serial.available() > 0)
  {
    datafromUser=Serial.read();
  }

  if(datafromUser == '1')
  {
    digitalWrite( LED_BUILTIN , HIGH );
  }
  else if(datafromUser == '0')
  {
    digitalWrite( LED_BUILTIN, LOW);
  }
  
}

Python3 Code

Python
import serial
import time

arduino=serial.Serial('COM1', 9600)
time.sleep(2)

print("Enter 1 to turn ON LED and 0 to turn OFF LED")

while 1:
    
    datafromUser=input()

    if datafromUser == '1':
        arduino.write(b'1')
        print("LED  turned ON")
    elif datafromUser == '0':
        arduino.write(b'0')
        print("LED turned OFF")

Credits

Jalal Mansoori

Jalal Mansoori

3 projects • 46 followers
BS Computer Science | Passionate blogger | Learn, Create, and Share

Comments