Answers for "serial python example"

3

serial communication python

//python

import serial

port = serial.Serial('COM5',9600)

while( port.isOpen()):
    comdata = int(input())

    if(comdata == 1):
        port.write(str.encode('1'))
    elif(comdata == 2):
        port.write(str.encode('2'))

    elif (comdata == 3):
        port.write(str.encode('3'))
    elif (comdata == 4):
        port.write(str.encode('4'))

    elif (comdata == 5):
        port.write(str.encode('5'))
    elif (comdata == 6):
        port.write(str.encode('6'))

    elif (comdata == 7):
        port.write(str.encode('7'))
    elif (comdata == 8):
        port.write(str.encode('8'))

    else:
        print('Invalid input!!!!')
        
// arduino

const int LED1 = 8;
const int LED2 = 9;
const int LED3 = 10;
const int LED4 = 11;
char comdata;

void setup() {

  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  Serial.begin(9600);
}

void loop() {

  if (Serial.available() > 0) {
      comdata =(Serial.read());
      
    if (comdata == '1') {
      Serial.println("LED1 is ON");
      digitalWrite(LED1, HIGH);
    }  
    else if (comdata == '2') {
      Serial.println("LED1 is OFF");
      digitalWrite(LED1, LOW);
    }
    
    
    else if (comdata == '3' ) {
      Serial.println("LED2 is ON");
      digitalWrite(LED2, HIGH);
    }
    else if (comdata == '4' ) {
      Serial.println("LED2 is OFF");
      digitalWrite(LED2, LOW);
    }
    
    else if (comdata == '5') {
      Serial.println("LED3 is ON");
      digitalWrite(LED3, HIGH);
    }
    else if (comdata == '6') {
      Serial.println("LED3 is OFF");
      digitalWrite(LED3, LOW);
    }
    
    else if (comdata == '7') {
      Serial.println("LED4 is ON");
      digitalWrite(LED4, HIGH);
    }
    
    else if (comdata == '8') {
      Serial.println("LED4 is OFF");
      digitalWrite(LED4, LOW);}


    
  }
}
Posted by: Guest on November-04-2020

Python Answers by Framework

Browse Popular Code Answers by Language