I want to send some data to an Arduino through pyserial in Python. All I want to the Arduino to do is read the variable length string data from the serial port, and write it back so that Python can read it. Since I've been unable to do that, the code below only has Python sending on character. Here's the Python code:
import serial
import sys
import pywapi
import time
def main():
ser = serial.Serial(3, 9600, timeout=1)
print "Conn established"
print "Sending: %s" % "z".__repr__()
print ser.write('z'.encode("ascii"))
time.sleep(2)
print "Received: %s" % ser.read(10).__repr__()
ser.close()
Here's the Arduino code:
void setup(){
analogReference(DEFAULT);
Serial.begin(9600);
}
void loop(){
if(Serial.available() > 0)
Serial.println("x");
while(Serial.available() > 0){
Serial.print(Serial.read(), BYTE);
}
}
The output:
Conn established
Sending: 'z'
1
Received: ''
I know the code for the Arduino works because it works when data is being sent from the Arduino terminal. However, the moment I try to send anything from Python it fails. I've been struggling with this all day. Any help would be greatly appreciated.
Try increasing or removing the timeout, and set read's size to 1. You may also want to increase the sleep delay, or even implement a simple read loop.
Something like:
try:
while True:
data = ser.read(1).__repr__()
if data:
print "Received: %s." % data
else:
print "Looping."
except KeyboardInterrupt:
print "Done."
except:
raise
finally:
ser.close()
print "Closed port."
Then just use ctrl-c to stop it.
I would recommend verifying the two parts independently, using a separate serial port and serial comms software on the PC.
E.g. if your PC has two serial ports, then use a null-modem (loopback) cable to connect them. Or use com0com to make a pair of linked virtual serial ports. Run your Python software on one serial port, and a terminal program (Hyperterminal or RealTerm) on the other serial port. Manually verify the Python program's operation that way.
Then, connect your PC directly to the Arduino as usual, and use the terminal software to manually verify the Arduino software operation.
That process will allow you to narrow down the problem. Once you've verified them both, they should work well together.
Serial Port Monitor
Another method you can use is software that hooks into the PC's serial port driver, and allows you to monitor traffic on the serial port. I've used the Free Serial Port Monitor software from HHD Software in the past, and it worked well for our purposes. It allows you to monitor any of the PC's serial ports, and shows you a log (hex and text) of the serial data going over the port in both directions.
Do you need to flush the sent character out of any held serial buffer?
It may be that your character is not actually leaving the COM port and arriving at the Arduino. When you test this with the Arduino Terminal (I assume you mean the UI terminal in the development environment) you are actually sending your string + a carriage return I think, not just the character. (i.e. do you hit return after you type 'z' in your test?)
Try ser.flush() or perhaps also send a \r character. From your testing the Arduino works just fine, it's the python program that doesn't seem to be sending anything.
The reason you may have to send twice is that, if you're connecting via the USB, the first serial connection will reset the Arduino.
Related
I have a Python script to communicate with a measuring instrument over a RS232 serial port.
Everything works fine, but every time I turn on the PC (Windows 10) the communication doesn't work in the beginning. I have to open a serial terminal (for example hterm) press the "connect" and "disconnect" button. After that the Python script works as expected, reading and writing to and from the instrument is no problem.
Here is a short example of the code:
import serial, time
ser = serial.Serial(port='COM6', baudrate=19200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0, xonxoff=False, rtscts=False, dsrdtr=False)
time.sleep(1)
print(ser.isOpen()) #output: true
ser.write(b'READ:CH1\r\n')
time.sleep(1)
print("read:" + ser.read(18).decode('utf-8'))
ser.close()
print(ser.isOpen()) #output: false
The instrument doesn't receive the data "READ:CH1" or any other command. Because of this there isn't any transmitted data to the PC via ser.read().
I tried every possibility with hardware handshakes and very long sleep times. I guess there's a problem between Windows and Pyserial. In Python the port is open, but Windows doesn't send the data. Do you have any ideas what I could do?
Thanks for your help.
Best regards
Edit with solution:
Instead of or additional to "Serial.flushInput()" and "Serial.flushOutput()" you need "Serial.reset_input_buffer()" and "Serial.reset_output_buffer()".
If you are using a third-party tool and then the script works fine, then I think there is some garbage data present in the buffers of either side, flushing the serial port on the hardware device and on the python script too might work and verify the data being received on the hardware device it is possible garbage is being appended on the commands, also try to use some header bits which keep errors at bay in this kind of communication.
Use some serial port sniffer to verify what is being sent, like this
Look at https://github.com/pyserial/pyserial/issues/329
https://github.com/pyserial/pyserial/issues/329#issuecomment-400852426
https://github.com/pyserial/pyserial/issues/329#issuecomment-503059537
Do you see this?
Another issue that might be related:
https://github.com/pyserial/pyserial/issues/485
Another thing you could try is to open and close the port first.
That's the same thing you are doing with hterm for
ser = serial.Serial()
time.sleep(1)
print(ser.isOpen()) #output: true
ser.close()
ser = serial.Serial()
time.sleep(1)
print(ser.isOpen()) #output: true
...
Does this work?
I have a serial Python program, Linux environment (Raspbian / Raspberry Pi), that uses a serial port via a USB-to-serial adapter. I need to handle a situation when the user unplugs the USB adapter and then reinsert it.
The problem is that, on reconnect, the ttyUSB0 becomes ttyUSB1 and so the port is no longer found. However, if I stop the Python program (keyboard interrupt) and again unplug and reinsert the USB adapter, then the port goes back to ttyUSB0 (and so I can start over again). This can happen only when the Python program is stopped.
I tested the program in a flip-flop mode (and it seems to be working) in order to use ttyUSB1 when ttyUSB0 is no longer found and then vice versa, use ttyUSB0 back in case ttyUSB1 is no longer found, etc., but this looks like a weird solution to me.
Is there a better way to force pySerial to "forget" it has ever been connected to ttyUSB0 in case of error and release the current port to the system while the program is still running?
Here is a working flip-flop test program:
import serial
import time
p = "/dev/ttyUSB0"
while True:
error_flag = False
try:
s = serial.Serial(port=p, baudrate=9600, bytesize=8, parity="N", stopbits=1, timeout=None, xonxoff=False, rtscts=False, write_timeout=None, dsrdtr=False, inter_byte_timeout=None)
except Exception as e:
error_flag = True
if "ttyUSB0" in str(e):
p = "/dev/ttyUSB1"
print ("port is now", p)
elif "ttyUSB1" in str(e):
p = "/dev/ttyUSB0"
print ("port is now", p)
else:
print (e) # none of the above
# if not error_flag, do whatever, etc.
time.sleep(1)
You could try creating a udev rule that would create a symbolic link to that USB device and then you would be able to use something like /dev/myUSB that would always stay the same for that specific USB device.
First, you will need to find some identifying information for the USB drive. Typing in lsusb should display some information that looks like:
Bus 001 Device 004: ID 0403:6001 Future Technology Devices International
In this example 0403 is the Vendor Id and 6001 is the Product Id.
Create a file named 99_usbdevice.rules (I don't think the name matters, just the directory):
sudo nano /etc/udev/rules.d/99_usbdevices.rules
Note that the directory above may be specific to Raspbian.
Copy/paste the line below into the file and save it:
SUBSYSTEM=="tty", ATTRS{idVendor}=="0403", ATTRS{idProduct}=="6001", SYMLINK+="myUSB"
Restart your Raspberry Pi or unplug the USB and reinsert it. There should now be a /dev/myUSB entry that you can use the same way you would the ttyUSB# entry.
If the opened port file is closed when unplugged (or on error handler), then the port name will not change on subsequent connection of the USB device. If left open then it will create a different name each time.
Do not forget to close the file descriptor of /dev/ttyUSB0 as soon as you detect that the user unplugged the USB adapter (read or write with error), and before the reinsertion.
If you properly close the device, the ttyUSB1 device will never appear. On the other hand, you can see in some cases also ttyUSB2, ttyUSB3, and so on, if all the previous ttyUSBx's are blocked because not closed.
I am trying to establish communications via serial port between a PC with Ubuntu 14.04LTS and my RoMeo Arduino Board (Atmega 328). The used serial interface are 2 Xbee modules, one at PC and the other at the board.
Firstly, I am trying to develop a simple program to send messages to the board and receive them back. The code I use for the Arduino board is the following:
void loop(void)
{
char msg;
if (Serial.available()){
msg = Serial.read();
msg = Serial.print(msg);
}
}
When I send a unique character, the PC receives it back correctly. However, the problem I am facing is that for longer strings, the following characters are misspelled, as I obtain back strange hex numbers, as follows:
>>> import serial
>>> ser = serial.Serial(port='/dev/ttyUSB0', baudrate=57600, timeout=0.1)
>>> ser.write('H')
>>> ser.read(1)
'H'
>>> ser.write('Hello')
>>> ser.read(5)
'H\x8b\xbd'
Thanks in advance.
EDIT: Seems like there is an overflow problem with the XBee modules, but I can not figure it out completely: The problem is solved if I wait 0.01 seconds or more between sent characters, which is a huge amount of time. Namely, the code I use now for sending a word is:
for letter in word:
serial.write(letter)
time.sleep(0.01)
However, this waiting time is only needed when sending data from the PC to the Arduino. When the communication goes the other way (Arduino sends data to PC), I do not need to sleep and bytes are correctly sent all together at 57600 bauds.
The reason why the PC could not send more than 1 character to the Arduino board was that there was an XBee module configured with different port parameters than both the other module and the pyserial instance. In this case, the communication was established in Python with the following main parameters:
Baud rate: 57600
Bytesize: 8
Parity: None
Stop bits: 1
If one of this parameters is different in one of the XBee modules, the communication will be faulty (like this case) or even impossible.
To check the XBee configuration, the Digi XCTU application can be used: With the RF modules connected to the PC, open the program and read their configuration. Once opened, it has to be made sure that the 'Serial interfacing' options are equal to the previously listed.
At the image, it is shown the menu where these options can be changed. Note that the Stop bits and the Bytesize can not be configured. The first parameter was not adjustable until the XB24-ZB versions, and the last one seems to not be possible to change.
In the case of this question, the wrong parameter was the parity, as it was set to space parity in one of the modules, instead of no parity. Thus, the first byte was sent correctly, but after it the data was not coherent. After changing this parameter, the connection run OK.
I am attempting to receive data from the qu-bot at http://www.qu-bot.com. The robot has an ATML atmega16 microcontroller. I have written a program that runs on the robot which outputs data to its serial port. The program however stops whenever I connect to the controller. I tested this by adding a beep statement. The robot beeps as long as the program is running. The beeping stops when I connect to the robot. I tried qu-bo support and they suggested disabling the dtr flag on the serial port. I did that but no joy.
Is there anything else I can try?
[start of code running on the qu-bot]
Note:
This is written in some kind of proprietary variant of C which they call quick c.
// This code displays the uart functions.
int main(void)
{
INIT();
UART_INIT(57600);
UART_PRINT("HELLO!!\n");
DELAYS(1);
UART_PRINT("MY NAME IS QU-BOT.\n");
DELAYS(1);
UART_PRINT("HELLO!!\n");
UART_PRINT("YOU ARE USING UART SAMPLE CODES.\n");
while(1)
{
UART_PRINT("test\n");
BEEP();
DELAYS(60);
}
}
now for my python serial port reading program. I have tried this program both on raspbian and on windows 7 64bit. I am pasting the windows version. The raspbian version has a different name for the linux.
import serial
import time
ser=serial.Serial()
ser.port=8
ser.baudrate=57600
ser.setDsrDtr(False)
print 'initialized'
flag = ser.isOpen()
if flag:
print 'port already open.'
pass
else:
ser.open() # opening the port 'ser' that was just created to receive data
time.sleep(0.5)
print 'ready to read'
print ser
ser.write('a')
s=ser.read(4)
print s
ser.close()
Pranav
P.S. I have consulted the following links amongst others.
<https://learn.sparkfun.com/tutorials/terminal-basics/all>
<http://www.plainlystated.com/2013/06/raspberry-pi-serial-console/>
<http://elinux.org/RPi_Serial_Connection>
<https://learn.sparkfun.com/tutorials/terminal-basics/all>
Based on my experience in serial communications with microcontrollers the most likely cause of this problem is that when you connect the serial cable to the robot it causes a phantom byte (due to electrical noise that happens when you make the connection) to look like it's coming from the controller - either this or the controller is sending a legitimate byte to the robot. In either case it is likely that the arrival of a byte at the robot's serial port (even if it was only electrical noise mistaken to be a data byte - this is a very common occurrence) caused the robot's microcontroller to invoke the UART receive interrupt. If you don't have an appropriate UART receive handler (ISR - Interrupt Service Routine) written and linked into the correct interrupt vector then your robot's microcontroller can go off into "deep space" upon the detection of the first incoming serial data byte - and make your robot appear to "hang". If you intend to do "polled" serial communications (your code manually checks for received bytes in its main loop) instead of interrupt-driven (hardware detection of an incoming byte causes your UART Rx ISR to be invoked) then all you have to do is to disable UART interrupts and your problem should go away.
All right, so I am positive my Arduino circuit is correct and the code for it. I know this because when I use the serial monitor built into the Arduino IDE and send 'H' an LED lights up, when I send 'L' that LED turns off.
Now I made a Python program
import serial
ser = serial.Serial("COM4",9600)
ser.write("H")
When I run the code the LED blinks on for a second then goes back off.
However when I do each of these lines separately in the shell it works just like it is supposed to.
Any ideas?
When you open the serial port, this causes the Arduino to reset. Since the Arduino takes some time to bootup, all the input goes to the bitbucket (or probably to the bootloader which does god knows what with it). If you insert a sleep, you wait for the Arduino to come up so your serial code. This is why it works interactively; you were waiting the 1.5 seconds needed for the software to come up.
I confirmed that opening the serial port resets my Arduino Uno; I flashed a program which will blink the LED from the setup() routine -- calling open("/dev/ttyACM0") was sufficient to trigger the reset. This is IMHO a confusing and undocumented wrinkle in the serial support.
I had the same problem and it works if I add a delay of about 2 seconds from opening the serial connection to writing on it, 1 second was not enough.
Just to make it a bit more clear I'll modify the code so everyone can see what needs to be added!
import serial
import time
ser = serial.Serial("COM4",9600)
time.sleep(3)
ser.write("H")
Adding in a sleep statment helps to let the serial open up without any problems!
Assuming you are using an Arduino Uno
The USB port and the Uno serial bus exposed on pins 1 and 0 share the same RX/TX lines. I suggest getting a USB to TTL adapter like the one here so that you can communicate to the Arduino without using the USB port. The Arduino IDE has its own method for disengaging from the USB driver such that a virtual serial port can be created. Have your Ardunio use SoftwareSerial instead.
Here is an example I found on the internet where somebody had clashing bus issues.