I'm working on a project with a coin acceptor and a raspberry. I have the following code to test the output from the coin acceptor:
import serial
from time import sleep
ser = serial.Serial('/dev/ttyUSB0', 4800, 8, 'N', 1, timeout=None)
while True:
line = ser.read(ser.inWaiting())
if len(line) > 0:
print ord(line)
ser.close()
everything works fine and i get output from the acceptor every time i drop a coin. But after a while it stops reading. In windows with a serial port monitor it works and I get output every time.
Thanks!
now i have modified the code, but there is the same behaviour as at the beginning. After a certain time it stops reading:
import serial
from time import sleep
ser = serial.Serial('/dev/ttyUSB0', 4800, bytesize=8, parity=serial.PARITY_EVEN, stopbits=1, timeout=0, rtscts=1)
sleep(3)
print("ready ..")
print(ser.isOpen())
while True:
line = ser.read()
if len(line) > 0:
print ser.isOpen()
print line
print ser.isOpen()
ser.close()
the output from ser.isOpen is always TRUE
Related
Im trying to read the signal strength/quality from gsm modems, so i used this AT+CSQ command.
from time import sleep
import serial
from curses import ascii
ser = serial.Serial()
ser.port = "COM10"
ser.baudrate = 9600
ser.open()
print(ser.write('AT+CSQ=?'.encode("ascii")))
ser.write returns the number of bytes written (on the port).
(https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.write)
You need to call ser.read afterward to read the answear.
Something like :
from time import sleep
import serial
ser = serial.Serial()
ser.port = "COM10"
ser.baudrate = 9600
ser.open()
try:
res_write = ser.write('AT+CSQ=?'.encode("ascii"))
sleep(0.01)
res_read = b""
while ser.inWaiting() > 0:
res_read += ser.read(1)
finally : # ensure you close the use of the port in case of crash
ser.close()
print(res_read.decode("ascii"))
I am using an accelerometer sensor in Node MCU to get 300 samples per second and store it for a week. My code below fails after some minutes.
import serial
ser = serial.Serial("COM5", 115200)
ser.flushInput()
i = 0
while True:
try:
i += 1
print (i)
ser_bytes = ser.readline()
print(ser_bytes)
except:
print("Keyboard Interrupt")
break
It failed after 4129 lines. I've attached the output
So I have 2 python scripts, one is reading serial port data and the other is receiving a list from that data, however once I run the second script I get a permission error and can no longer read from the serial port. These are my 2 scripts and I'm doing stuff with Arduino, I know that I can have all this in 1 file but for latency purposes I separated the logic from the read. Here are my scripts:
read.py:
import serial
from time import sleep
ser = serial.Serial('COM7', 9600)
while True:
ser_bytes = ser.readline()
decoded_bytes = ser_bytes[0:len(ser_bytes)-2].decode('utf-8')
if len(decoded_bytes) == 0:
ser.flushInput()
if len(decoded_bytes) != 0:
find1 = decoded_bytes.find('&')
find2 = decoded_bytes.find('|')
find3 = decoded_bytes.find('/')
left = decoded_bytes[0:find1]
right = decoded_bytes[find1+1:find2]
fire = decoded_bytes[find2+1: find3]
jump = decoded_bytes[find3+1:]
keypresses = [left, right, fire, jump]
ser.flushInput()
do.py:
from read import keypresses
import pyautogui as pg
while True:
if keypresses[0] == 1:
pg.keyDown('a')
else:
pg.keyUp('a')
if keypresses[1] == 1:
pg.keyDown('d')
else:
pg.keyUp('d')
if keypresses[2] == 1:
pg.mouseDown()
else:
pg.mouseUp()
if keypresses[3] == 1:
pg.keyDown('w')
else:
pg.keyUp('w')
If you could help that'd be nice, thanks.
I'm taking my first steps in Python programming. I'm using a TFMini Plus Lidar connected to a Windows 7 computer through a USB to TTL serial connection.
I'm getting readings through this code:
import time
import serial
import datetime
import struct
import matplotlib.pyplot as plt
ser = serial.Serial(
port="COM1",
baudrate = 115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
while 1:
x = ser.readline().decode("utf_8").rstrip('\n\r')
y=float(x)
print(y)
#time.sleep(0.1)
if y > 3:
print("too far!")
I want to have a single reading every X second (that can be set as per user choice), but I cannot find a way to do it. When I use time.sleep(), the readings get all the same:
Readings with time.sleep on
Basically i want to delay the frequency of readings or make it to selectively give me a single reading from the ones captured. How can I do it?
Thanks
You could use the schedule package. I.e.:
import time
import serial
import schedule
ser = serial.Serial(
port="COM1",
baudrate = 115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
def read_serial_port():
x = ser.readline().decode("utf_8").rstrip('\n\r')
y=float(x)
print(y)
if y > 3:
print("too far!")
rate_in_seconds = 10
schedule.every(rate_in_seconds).seconds.do(read_serial_port)
while True:
schedule.run_pending()
time.sleep(1)
I'm sending a list of values (e.g. 80,539,345,677) from Arduino to a Python app running on my RPi. I have not been successful in extracting the values and assigning them to respective variables or objects in the app.
Here's my code:
def read_values():
#if DEBUG:
print "reading arduino data"
ser = serial.Serial('/dev/ttyUSB0', 9600)
print "receiving arduino data"
ser_line = ser.readline()
print ser_line
ser.close()
ser_list = [int(x) for x in ser_line.split(',')]
ambientLight = ser_list[1]
print ambientLight
return ambientLight
What I'm getting from Python is:
reading arduino data
receiving arduino data
80,477,82,2
Traceback (most recent call last):
File "serialXivelyTest4c.py", line 77, in <module>
run()
File "serialXivelyTest4c.py", line 63, in run
ambientLight = read_values()
File "serialXivelyTest4c.py", line 27, in read_values
ser_list = [int(x) for x in ser_line.split(',')]
ValueError: invalid literal for int() with base 10: '8254\r80'
You can see that I'm getting values, but that they're being truncated. Can anyone please tell me where I'm going wrong here. Thanks so much.
I've never used an Arduino but here's how I read from serial with a different board. I used serial.
import streamUtils as su # see below
ser = su.connectPort("/dev/tty.SLAB_USBtoUART") # make sure you have the right port name
data = ""
while True:
try:
data = data + ser.read(1) # read one, blocking
time.sleep(1) # give it time to put more in waiting
n = ser.inWaiting() # look if there is more
if n:
data = data + ser.read(n) # get as much as possible
# I needed to save the data until I had complete
# output.
if data:
# make sure you have the whole line and format
else:
break
except serial.SerialException:
sys.stderr.write("Waiting for %s to be available" % (ser.name))
sys.exit(1)
sys.stderr.write("Closing port\n")
ser.close()
Here's the streamUtils.connectPort():
import serial
def connectPort(portname):
# connect to serial port
ser = serial.Serial()
ser.port = portname
ser.baudrate = 9600
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.bytesize = serial.EIGHTBITS
ser.timeout = 15 # need some value for timeout so the read will end
try:
ser.open()
except serial.SerialException:
sys.stderr.write("Could not open serial port %s\n" % (ser.name))
sys.exit(1)
return (ser)