0

I was trying to send some Serial Data with python to my Arduino and light a led on/off, over the Serial monitor of the Arduino IDE it works fine but once I try to do it over the Python code, it won't work

Here is the Arduino Code:


int LED = 7;
char serialData;

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

void loop() {

  serialData = Serial.read();


if(serialData == '1'){
  digitalWrite(LED, HIGH);
}

if(serialData == '2'){
  digitalWrite(LED, LOW);
}

}

And this is the Python Code:

import serial
import time

ser = serial.Serial()
ser.baudrate = 9600
ser.port = 'COM5'

time.sleep(10)

ser.write("1")

Now what it should do when I start the python code, is to send the "1"over Serial to the Arduino, the Arduino should receive it and light on the led.

3
  • maybe you have to use ser.flush() to send it. Commented May 18, 2019 at 22:21
  • @furas nope, doesn't work either Commented May 19, 2019 at 10:14
  • can you try adding a delay (delay(10)) after digitalWrite(LED, HIGH) and digitalWrite(LED, LOW) inside their if statements ? Commented May 20, 2019 at 11:59

1 Answer 1

1

I think your Arduino code is fine, except that you just wait until you get some input in the serial port (line serialData = Serial.read();). If this is intended, that is fine, but if not you should consider checking Serial.available().

The main issue is in the Python code. As described in the pyserial documentation, you need to open the serial port. Also, you should consider closing this at the end of the code (you do not have to worry about if you use with to open the serial port as described here).

I added a for statement so that you can visualize the blinking on the Arduino.

import serial
import time

ser = serial.Serial()
ser.baudrate = 9600
ser.port = 'COM5'

ser.open()

for i in range(10):
    ser.write("1")
    time.sleep(1)
    ser.write("2")
    time.sleep(1)

ser.close()
Sign up to request clarification or add additional context in comments.

3 Comments

that didn't work for me either, for my understanding, the python could should look like this with "with" import serial import time with ser = serial.Serial('COM5', 9600) ser.open() ser.flush() ser.write("1") time.sleep(1000)
Nope, it should be with open(serial.Serial('COM5', 9600)) as ser: and no ser.open() after that. I ran this code on an Arduino Mega and it worked fine. What is your board? And can you report if you can just blink the LED on pin 7 from Arduino board, without Python communication?
That kinda works, I can now turn it off using the off python off code, but my other file that is exactly the same apart from the number does not affect it at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.