Hello! I was working on a big project with an Arduino Mega (orangepip) when I realised serial communication was not working so I decided to test it with a simple Python script which would send a letter 'T' to the serial port, and the Arduino program would read and print it. I'm getting a mirrored question mark in the serial monitor. I've tried to send all the other characters on my keyboard and I've tried using an Arduino Uno instead. I still get the same result. The baud rate is set at 9600 for both, ports are the same, I uploaded test codes onto both Arduinos and they worked as expected so it's not a hardware issue. Please can someone please tell me if there's something I'm really missing here in the code or if you can figure out what's wrong? Thank you!
How can the Python script and serial monitor both be connected to the same serial port at the same time? If the Python script connects to the serial port first, you won't be able to open the serial monitor (at least for the same serial port).
This code will not work for echoing characters for two reasons. First, the read and print lines should be in loop(), not in setup(). Because setup() only runs once, only one character could ever get echoed back, and that character would have to be sent at exactly the right time after the Arduino is reset. Secondly, the code does not check if there is a character waiting to be read. So the Serial.read() will time out and return -1 which will probably appear as a strange character on serial monitor.
Try this
void setup()
{
Serial.begin(9600);
}
void loop()
{
if (Serial.available()) {
char c = Serial.read();
Serial.println(c);
}
}
import serial
import time
ser = serial.Serial('/dev/tty.usbmodem143301', baudrate=9600)
time.sleep(8)
ser.write(b'T')
Does it work?
Opening the serial port resets the Arduino. During the reset the serial interface isn't in a defined state so you may see some random bytes. After the time the Arduino waits for a sketch upload you can interact as you're used to.
On modern operating systems ( ) you can do that. A Un*x style OS lets you open a device several times. Locking is done in user space using best practice methods (lock files) but it seems that one of the two openers (at least) doesn't implement that.
Thanks! In my project I can't have the loop function going after the last line of data is sent so I was trying to find a way around using it - I followed your advice anyway and used loop function but with a condition to exit after receiving a specific character. Also, increasing both baud rate to 115200 helped get my letters for some reason. Thanks again!
Thanks pylon, implementing the delay was what I needed. I included handshake protocols to help with more complex processes as well. love the wink haha.