I am trying to implement a system where outputs from an Arduino can be passed on to and printed in Python.
I have the following Arduino code snippet below:
void loop() {
if (Serial.available()) {
c = Serial.read();
if (c == '1') {
digitalWrite(pinLED1, HIGH);
digitalWrite(pinLED2, LOW);
//Serial.print("1 ON, 2 OFF\n");
}
My Python code snippet is as follow:
import serial
import time
arduino = serial.Serial('COM3', 9600, timeout=1)
msg = arduino.readline(arduino.inWaiting()) # read everything in the input buffer
time.sleep(3)
ASCIIdata = '121210'
for i in range(len(ASCIIdata)):
if ASCIIdata[i] == '1':
strin = '1'
arduino.write(strin.encode())
time.sleep(0.2)
#print(ASCIIdata[i])
try:
print ("Message from arduino: ")
print arduino.readline()
raise
except Exception as e:
print ("Fail to send!")
In the above example, I am trying to send inputs to Arduino via ASCIIdata, and when it matches the if-statement in Arduino, commands in the if-statement will be executed. I have purposely not do a print in Arduino and attempt to read something from Python by doing:
try:
print ("Message from arduino: ")
print arduino.readline()
raise
except:
print ("Fail to send!")
I observed that if I do not put raise in the try statement, the except statement will not be executed, but the program moves on after the specific timeout. Hence, I put raise in the try statement. May I ask if this is the correct approach to raising an exception?
I read that I should be doing except Exception as e instead of doing except because I would be catching all kinds of exception while the program is running. May I ask if this thought process is correct?
arduino.write(strin.encode()), no?