Python serial write doesn't work FIRST run - python

I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.
I'm having an issue where whenever I upload the arduino program and try to run the python the first time after I uploaded, it would be stuck on print ser.readline() which I'm assuming means for some reason python is not writing to the serial port. I would have to quit the python program and run it again to get it to get a reply from arduino. The program would continue to work until I re-upload the arduino then once again python wouldn't work on first run. Also if I open and close the serial monitor before I run the python program it will work the first run. Does anyone know what is the issue? This is on Ubuntu.
arduino
String str;
void setup() {
// Turn the Serial Protocol ON
Serial.begin(115200);
}
void loop() {
if (Serial.available()) {
str = Serial.readStringUntil('\n'); // Read the serial input
Serial.println(str); // sends ascii code
}
}
Python
import serial
ser = serial.Serial('/dev/ttyACM1', 115200)
for i in range(0,4):
str = "test string\n"
ser.write(str)
print ser.readline()

The issue is likely related to many Arduinos resetting when a new serial connection is made.
The solution is to either add a delay (about 2 seconds works) to the python program between the serial connection being created and the first data being sent or modifying the hardware to prevent a reset on serial connect.

By default python Serial might be blocking by default try removing the timeout:
ser = serial.Serial('/dev/ttyACM1', 115200,timeout=0)
additionally have a peek at the serial.threaded in the docs

I added
time.sleep(1)
ser.setDTR(level=0)
time.sleep(1)
after opening the serial port and the issue was fixed.

Related

Difficulty in python reading and writing to arduinos connected to serial ports

I'm working with a python program on a Windows PC running under Anaconda that is talking to multiple USB-attached arduino megas. I can create a string on the python side and successfully encode it as bytes and send it to the arduino where it is correctly interpreted. I can read a string from the arduino into the python program and correctly interpret it. The issue I'm having is when I try to read from one arduino and then send that message back out to another arduino. Example:
Python side code:
response = ser1.readline() #Read from arduino #1
ser2.write(response) #Write the response read from #1 out to #2
Arduino side (for serial 2):
if (Serial.available()>0) {
newStr = Serial.readString();
}
The Serial.readString() never completes; the arduino just hangs at that point.
I'm sure it's something stupidly simple, but python is a new language for me so I haven't been able to figure it out.

Troubleshooting serial communication from Python to Arduino

I'm using software which has Python scripting capabilities. I want to use it to move a Clearpath servo and run internal software commands intermittently.
Using an Arduino, I can control the servo, but it starts going wrong once I start using serial communication. After reading through other post, I'm thinking the problems are arising because serial communication is 8bit and I'm wanting to send large int.
For example, a section of the Arduino code shows:
void loop(){
if(Serial.available()){
inByte = Serial.readStringUntil('\n');
ser = inByte.toInt();
X.move(ser);
while(!X.commandDone()||!X.readHLFB())
{ }
Serial.print (inByte);
delay(1000);
}
}
Before I started using serial communication, I'd utilize integers in X.move(ser) and get flawless results. Now that I'm using the serial port, I can tell there's something wrong with this code. Even though it seems to work using the Serial Monitor, the more I try it (especially using larger numbers) the more I realize its probably not doing what it did before I used serial.
Then add Python into the mix and it gets even worse.
To give you an idea of what I'm trying to do, here was an example of Python code:
ser = serial.Serial('COM3', 9600, timeout=1)
ser.close()
ser.open()
while True:
var = "1000"
ser.write(var.encode())
time.sleep(1)'
Using this code, the servo moves but it's not right at all.
How can I send large integers (for example, 50502) from Python to Arduino through serial without it getting mangled during serial communication?

How to write commands to a serial port using NodeJs?

Good day everyone,
I am having issues writing commands to a lock connected to a USB controller which is connected to the laptop port using NodeJs. I have successfully achieved this in python, but is having issues in nodejs.
The reason why I am converting to nodejs is because the entire application is written in nodejs and runs has a desktop app via electron, and opening/closing port is just a small component of it.
The python equivalent and which works fine
ser = serial.Serial()
ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program MUST be at same rate
// COMPORT is a variable that stores an integer such as 6
ser.port = "COM{}".format(COMPORT)
ser.timeout = 10
ser.open()
command = "open1"
#call the serial_connection() function
ser.write(("%s\r\n"%command).encode('ascii')) #Southco locks receives and sends commands in ASCII
Now in NodeJs, I am using the library serialport and I am trying to achieve this via nodejs that runs under the electron app.
var SerialPort = require('serialport');
var port = new SerialPort("COM6", {
baudRate: 38400
});
port.on('open', function() {
port.write(Buffer.from('open1', 'ascii'), function(err) {
if (err)
return sendData(500, err.message);
console.log('message written');
});
});
I know nodejs is able to interact with the port because when I run serialport-list in command prompt or when i run it within the code
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName, port.pnpId, port.manufacturer); // or console.log(port)
});
});
it shows the port information. Hence, nodejs is able to read the port, and issue information about the specific port, but I cant seem to issue command succesfully to it. It seems to get execute since no error message is thrown and it does display message written in console, but the lock does not react, whereas with the python code the lock does react by opening or closing demanding on the command that is written.
Any help would be appreciated.
If you look in the SerialPort docs you'll see that the port is immediately opened when a new instance is instantiated, unless you pass the option AutoOn=false.
So, in your case, the port is already open by the time you set the listener .on('open'), so it never receives an event. Remove the listener and just call .write() immediately.

Arduino Serial programming issue

I'm sending an integer from python using pySerial.
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600);
ser.write(b'5');
When i compile,the receiver LED on arduino blinks.However I want to cross check if the integer is received by arduino. I cannot use Serial.println() because the port is busy. I cannot run serial monitor first on arduino and then run the python script because the port is busy. How can i achieve this?
You could listen for the Arduino's reply with some additional code.
import serial
ser = serial.Serial('/dev/cu.usbmodem1421', 9600); # timeout after a second
while ser.isOpen():
try:
ser.write(b'5');
while not ser.inWaiting(): # wait till something's received
pass
print(str(ser.read(), encoding='ascii')) #decode and print
except KeyboardInterrupt: # close the port with ctrl+c
ser.close()
Use Serial.print() to print what the Arduino receives to the serial port, where your Python code is also listening.
You can upload an arduino program that listens for that specific integer and only blinks the light if it gets that int.

pySerial program doesn't read serial correctly

I have a problem using pySerial, and I don´t know from where to start looking for.
I have a 64 bits Windows Seven OS, with Python 2.7.5 (32 bits), and pySerial and Arduino (Arduino working correctly) already installed.
My Arduino code is the following:
// the setup routine runs once when you press reset:
void setup() {
// initialize the serial in 19200 baud rate
Serial.begin(19200);
}
// the loop routine runs over and over again forever:
void loop() {
delay(1000); // wait for a second
Serial.print("hello");
}
(Arduino conected in COM8, when using Serial Monitor I can see it saluting)
And my PySerial code looks like this:
import serial
import time
arduino = serial.Serial("COM8", 19200)
time.sleep(2)
while True:
print arduino.readline()
When I start this script, the program runs, but I can´t see the serial output (I think the configuration in the Python script is OK because if something - e.g. the port - is wrong, it crashes).
I don´t know what to do to find a solution.
Can you help me?
You might try using println instead of print on the Arduino/C side, and/or set a timeout for the serial read on the Python side.
Since serial.readline() waits for a \n, and you never send one using print, the serial read will just wait for a timeout. (But it's a bit more complicated than this, and it's worth reading the docs on readline and EOL.)
If this doesn't work, at least switch readline to just read and print out each character you may (or may not) be reading, but don't make it more complicated by waiting for the \n that readline requires.
From the demo docs:
Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received. Also note that readlines() only works with a timeout. readlines() depends on having a timeout and interprets that as EOF (end of file). It raises an exception if the port is not opened correctly.

Categories

Resources