Python/Arduino Serial communication - python

We are trying to communicate from Python to our Arduino, but are encountering an issue when writing to the serial port from python
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)
user_input = 'L'
while user_input != 'q':
user_input = input('H = on, L = off, q = quit' )
byte_command = user_input.encode()
print(byte_command)
ser.writelines(byte_command) # This line gives us the error.
time.sleep(0.5) # wait 0.5 seconds
print('q entered. Exiting the program')
ser.close()
The following is the error that we receive:
return len(data)
TypeError: object of type 'int' has no len()

Your code works on my computer. I think the function you're trying to use (writelines) was added not that long ago to pyserial so maybe you are running on an outdated version.
In any case, as far as I know, writelines is inherited from the file handling class and you don't really need to use it for what you're trying to do. Actually I don't think it's even well documented
Just change it to:
ser.write(byte_command)
If you prefer you can see what version of pyserial you have and/or update.
To check your version run: pip3 list | grep serial
If you don't have version 3.4 you can update with: pip3 install pyserial --upgrade
Considering how writelines works for files (see, for instance here) your error might actually be related to the core Python you have (for your reference I'm running Python 3.7.3).

writelines accepts a list of strings so you can't use it to send a single string. Instead use write:
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)
user_input = 'L'
while user_input != 'q':
user_input = input('H = on, L = off, q = quit')
byte_command = user_input.encode()
print(byte_command)
ser.write(byte_command) # This line gives us the error.
time.sleep(0.5) # wait 0.5 seconds
print('q entered. Exiting the program')
ser.close()

Related

How to use pyserial with a device connected with a USB port?

I am currently trying to use pyserial to read the values from my handheld tachometer, the specific model is the DT-2100.
I am using python 3 and my current code looks like this:
# Imports
import serial
import time
import io
# Coding section
# Setting Parameters
port = "COM3"
baud = 38400
data = []
info = 0
# Setting the port location, baudrate, and timeout value
ser = serial.Serial(port, baud, timeout=2)
# Ensuring that the port is open
if ser.isOpen():
print(ser.name + ' is open...')
# trying to read a single value from the display
#input("Ensure that the DT-2100 is turned on...")
info = ser.write(b'CSD')
ser.write(b'CSD')
info_real = ser.readlines()
print()
print("The current value on the screen is: ", info)
print()
print("The real value on the screen is: ", info_real)
This is what I get back after running the code:
COM3 is open...
The current value on the screen is: 3
The real value on the screen is: []
Process finished with exit code 0
The main issue is that I should be getting the value that is displayed by the tachometer, which for this test was 0, but between my two attempted methods I got 3 and nothing.
Any help is greatly appreciated.
The zip file you linked to contained an xls file which seemed to detail all the commands.
All the commands seem to be wrapped in: <STX> cmd <CR>, so you are missing those.
The CSD command would need to be like this: ser.write(b'\x02CSD\r')
Similarly the reply is also wrapped in the same way and you would need to remove those bytes and interpret the rest.

"write_timeout" not working in Serial() in pyserial

I am trying to make a program which constantly reads data being sent from device using serial port to computer. In addition to this whenever I enter something it is sent to device.(My main aim is to make a serial terminal emulator).
I wrote following program but it waits for any input and does not constantly read data and display on screen sent by device as thought:
ser1 = serial.Serial(com_name_to_use, auto_baud, timeout=0, write_timeout=0)
while True:
try:
# Writing Section
inp_str1 = input() # + "\n"
str1 = inp_str1.encode(encoding="ascii")
ser1.write(str1)
time.sleep(0.03)
# Reading Section
bf = ser1.readline()
print(str(bf, encoding="utf-8"), end="")
except Exception as err1:
pass
Kindly, tell how to fix it.

Communicate an Arduino with python

I am trying to communicate an Arduino using python. I was able to connect it using the serial module. This is the code:
import serial
while True:
print "Opening port"
arduinoData = serial.Serial("com7", 9600)
print "The port is open"
while (arduinoData.inWaiting()==0): #I wait for data
print "There is no data"
print "Reading data"
arduinoString = arduinoData.readline()
print arduinoString
It seems that is hanging when I want to read the data, in the line that says arduinoString = arduino.readline().
What could be the problem?
instead using the while loop inside of the main while loop you can use an if else statement. Also, to read the data you can use the read function with arduinoData.inWaiting() as the paramater like this : arduinoData.read(arduinoData.inWaiting()). I hope this code will help you:
arduinoData = serial.Serial("com7", 9600)
while True:
if arduinoData.inWaiting() > 0: # check if there is data available
print "Reading data"
arduinoString = arduinoData.read(arduinoData.inWaiting()) '''read and decode data'''
print arduinoString
else:
print "There is no data"
The structure of your code is strange. I had a similar issue by creating the Serial object in a function without making it global. Maybe you should put this line outside the loop :
arduinoData = serial.Serial("com7", 9600)
Also, your initialization seems a bit light. I usually use more parameters but it depends of your hardware.
ser = serial.Serial(
port = 'com4', \
baudrate = 19200, \
parity=serial.PARITY_NONE, \
stopbits=serial.STOPBITS_ONE, \
bytesize = serial.EIGHTBITS, \
timeout = 0.25)
A workaround for your readline() issue coud be using the read() function instead and checking if it contains data.
Hope it will help !
Alright, you are getting the AttributeError: 'Serial' object has no attribute 'ser' error because in reality ser does not exist in the arduinoData object. It's my fault because I was thinking of the class that I created in my program containing ser which is just the another serial object. To fix this just replace arduinoData.ser with arduinoData
To add on, you should probably declare arduinoData outside of the while loop. you should do this because every time the you create a serial object it takes time to connect to the Arduino. For this, your program might not be able to read the data.
I hope this answer will help you.

Python Serial Read returning strange values

I have a small python example I got off another website. I am trying to understand how to read from serial using it.
I am sending a message from a FRDM K64f board over serial and the python program reads this but returns a strange values, below is an example of one of them:
YVkJ�ZC
My python code:
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyACM0',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
This is my code for the board:
int main(){
Serial pc(USBTX, USBRX);
pc.baud(9600);
while(1){
char c = pc.getc();
if((c == 'w')) {
pc.printf("Hello");
}
}
}
The exact return I get is this:
Enter your commands below.
Insert "exit" to leave the application.
>> w
>>YVkJ�ZC
>>
Managed to solve this.
My declaration of serial didn't seem to be working properly.
Went back to pyserial documentation and declaring my serial like below and using readline() solved the problem.
ser = serial.Serial('/dev/ttyACM0')

how to read command output from serial device using python

I have an embedded linux device and here's what I would like to do using python:
Get the device console over serial port. I can do it like this:
>>> ser = serial.Serial('/dev/ttyUSB-17', 115200, timeout=1)
Now I want to run a tail command on the embedded device command line, like this:
# tail -f /var/log/messages
and capture the o/p and display on my python >>> console.
How do I do that ?
Just open the file inside python and keep readign from it. If needed be, in another thread:
>>> ser = serial.Serial('/dev/ttyUSB-17', 115200, timeout=1)
>>> output = open("/var/log/messages", "rb")
And inside any program loop, just do:
data = output.read()
print(data)
If you want it to just go printing on the console as you keep doing other stuff, type
in something like:
from time import sleep
from threading import Thread
class Display(Thread):
def run(self):
while True:
data = self.output.read()
if data: print(data)
sleep(1)
t = Display()
t.output = output
t.start()
very first you need to get log-in into the device.
then you can run the specified command on that device.
note:command which you are going to run must be supported by that device.
Now after opening a serial port using open() you need to find the login prompt using Read() and then write the username using write(), same thing repeat for password.
once you have logged-in you can now run the commands you needed to execute

Categories

Resources