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')
Related
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.
Please help me find problem in this code:
import serial
ser=serial.Serial("/dev/ttyACM0",9600)
ser.baudrate=9600
ser1=serial.Serial("/dev/ttyUSB0",9600)
ser1.baudrate=9600
ser2=serial.Serial("/dev/ttyUSB1",9600)
ser2.baudrate=9600
while True:
read_ser=ser.readline()
read_ser1=ser1.readline()
read_ser1=ser2.readline()
print(read_ser)
print(read_ser1)
print(read_ser2)
I expect that it will show me message from connected Arduino. Arduino send it when I apply card to RFID reader. But, it send only from first ser
This code works as I expected
import serial
ser=serial.Serial("/dev/ttyACM0",9600,timeout=1)
ser.baudrate=9600
ser1=serial.Serial("/dev/ttyUSB0",9600,timeout=1)
ser1.baudrate=9600
ser2=serial.Serial("/dev/ttyUSB1",9600,timeout=1)
ser2.baudrate=9600
while True: # Run forever
read_ser=ser.readline()
if (read_ser != ""):
print(read_ser)
read_ser1=ser1.readline()
if (read_ser1 != ""):
print(read_ser1)
read_ser2=ser2.readline()
if (read_ser2 != ""):
print(read_ser2)
Thank you #jasonharper
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()
I have ArduinoUNO, I use Python3. I want to make a single LED ON and OFF on command. But I get errors.
ON
TypeError: unicode strings are not supported, please encode to bytes: 'H'
OFF
TypeError: unicode strings are not supported, please encode to bytes: 'L'
What I am doing wrong?
Here's my code:
import serial
import time
arduino = serial.Serial("COM3", 9600)
def onOffFunction():
command = input("Type in something (on/off/bye): ");
if command == "on":
print ("The LED is ON")
time.sleep(1)
arduino.write('H')
onOffFunction()
elif command == "off":
print ("The LED is OFF")
time.sleep(1)
arduino.write('L')
onOffFunction()
elif command == "bye":
print ("Bye Bye!")
time.sleep(1)
arduino.close()
else:
print ("Sorry.. Try typing something else.")
onOffFunction()
time.sleep(2)
onOffFunction()
An explanation can be found here:
Writing data to Arduino is easy too (the following applies to Python
2.x):
import serial # if you have not already done so
ser = serial.Serial('/dev/tty.usbserial', 9600)
ser.write('5')
In Python 3.x the strings are Unicode by default. When sending data to
Arduino, they have to be converted to bytes. This can be done by
prefixing the string with b:
ser.write(b'5') # prefix b is required for Python 3.x, optional for Python 2.x
Adding prefix b' (byte conversion) has helped to make code errorless, however, ArduinoUNO does not respond to Python3 but responds to ArduinoIDE.
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.