I want to send some analog sensor data from a Teensy 3.2 to a mac running a python script (I am using the usual pyserial module and I send data using Serial.print() in the arduino sketch). I am using Teensy but I guess the same would be true for an Arduino Uno. The teensy is correctly sending on the serial port the data, as I can see it using the serial monitor. However, only the first time that I run the python script the data are handled by the script itself, if I stop the script then no data seem to be read in the serial buffer. To make the script work I necessarily have to re-launch the Arduino IDE and then upload the sketch.
Indeed the second time I run the script (after having stopped it), I can see that the pyserial function serial_port.inWaiting() does not give any data.
if (serial_port.inWaiting() > 0):
print("serial_port.inWaiting() > 0") # does not print anything the second time I launch the script
I have checked that the second time that I launch the script the serial connection is open (using self.serial_port.isOpen())
What is preventing the python script to get the serial data the second time? Why serial_port.inWaiting() is not seeing that there is data in the input buffer?
In the arduino sketch code I have added the line while(!Serial); in void setup()
EDIT: I post the code. This is the arduino code (I am testing on teensy so no initial handshaking is required as teensy will not reboot)
int sensor = 0;
void setup() {
Serial.begin(115200);
while(!Serial);
}
void loop() {
sensor = analogRead(0);
Serial.print(sensor);
}
And this is the python code:
#!/usr/bin/env python3
import serial
import time
import signal
import sys
def keyboard_interrupt(signal, frame):
serial_port.close()
time.sleep(2)
exit(0)
serial_port = serial.Serial("/dev/tty.usbmodem1225061", 115200)
signal.signal(signal.SIGINT, keyboard_interrupt)
signal.signal(signal.SIGTERM, keyboard_interrupt)
if serial_port.isOpen():
print(serial_port.name + ' is open...')
while True:
if (serial_port.inWaiting() > 0):
sensor = serial_port.read().decode("utf-8")
print('sensor: "{}" '.format(sensor))