-1

From Arduino IDE the input is responding and bulb is glowing. However, the same thing from Python is not working.

What is the issue?

Desired Behavior

Arduino IDE serial input -> response behavior should match serial input -> response behavior with Python code.

LED bulb on Pin 13 should be set to ON / HIGH when serial port is written to with input 1.

Sample Code

Arduino code:

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    char serialListener = Serial.read();
    if (serialListener == 1) {
      digitalWrite(13, HIGH);
    } else if (serialListener == 0) {
      digitalWrite(13, LOW);
    }
  }
}

Python code:

import serial

ser = serial.Serial('COM3', baudrate=9600, timeout=1)
ser.close()
ser.open()
ser.write("1".encode())
1
  • 1
    I think you mean if (serialListener == '1') and else if (serialListener == '0'). What you have right now compares the ASCII value of the character it receives to 0 or 1, which is not what you want.
    – anonymoose
    Commented Dec 1, 2017 at 12:22

1 Answer 1

1

With if (serialListener == 1) you are expecting a byte with the value 1.
With ser.write("1".encode()) you are sending a character '1' with an ASCII code 49.

You need to fix your comparison in Arduino to match what you are sending, so you are comparing characters not byte values.

if (serialListener == '1') {
  digitalWrite(13, HIGH);
} else if (serialListener == '0') {
  digitalWrite(13, LOW);
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.