'Pyserial only communicate to Arduino when there is a user input
My Python and Arduino code together are producing the most baffling behaviour. I am running a test to see if Pyserial is writing to and reading from my Arduino correctly, but it seems like Pyserial will only write to Arduino when a user input is taken. Note, this user input doesn't even need to be the message that is sent to the Arduino, but as long as such input is taken, whatever message that I meant to send to the Arduino will send. If no user input is taken, it seems that either Pyserial is not writing to Arduino, or Arduino is not responding to the serial input.
Here is my python code:
import serial
import time
arduino = serial.Serial(port='/dev/cu.usbmodem2101', baudrate=9600, timeout=.1)
def write_read(x):
#arduino.write(bytes(x, "utf-8"))
arduino.write(b'V6Com9P500zI0zO2zR50zG0zF8zT4zN1zC0r0zZ')
arduino.flush()
data1 = arduino.readline()
time.sleep(0.1)
data2 = arduino.readline()
return data1, data2
#num = input("Enter a number: ") # This is the trigger that allows the serial communication
message ="V6Com9P500zI0zO2zR50zG0zF8zT4zN1zC0r0zZ" # dummy message
value1, value2 = write_read(message)
value1 = value1.decode("utf-8").strip("\r\n")
print(value1) # printing the value
print(value2)
And here is my Arduino code:
int DAC = 1000;
int Velec = 300;
String dataread = "";
boolean readcomplete = false;
String inChar;
void setup() {
Serial.begin(9600);
Serial.setTimeout(1);
}
void serialEvent() {
while (Serial.available()) {
inChar = Serial.readString();
dataread += inChar;
if (inChar == "Z") {
readcomplete = true;
Serial.println(dataread); // a testing point
}
}
}
void loop() {
while (readcomplete) {
Serial.println(DAC);
Serial.println(dataread);
readcomplete = false;
}
}
Those are just testing code, I took out the lines that are irrelevant to this question. The Arduino code works fine by itself, if I manually enter the serial input in the serial monitor.
As I said earlier, it works fine if the 'num' input is not commented out in the Python code:
Enter a number: 8
V6Com9P500zI0zO2zR50zG0zF8zT4zN1zC0r0zZ
b'1000\r\n'
I don't even need to enter a number, I can basically enter anything, and it will work. But as soon as I comment out the 'num' line in the Python code, there will be no output, value1 and value2 in the python code will return empty, even though 'num' isn't even used anywhere else in the code:
b''
(first line is an empty line because it is decoded and stripped of \r\n)
I've tested this on both my Arduino Uno and Arduino Due, so it is not the board that is the problem. I am so confused, please accept my sincere gratitude for anyone that can shed even the tiniest of light on this problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
