I have a little script in Python which I am brand new to. I want to check if a certain word appears in ser.readline(). The syntax for the If statement is not right and I am not sure how to lay this out so it continuously reads the serial for the word "sound". I've attached an output image below so you can see how it is printing. I'd like to trigger an MP3 as it finds the word "sound" but as of yet I haven't even managed to get it to print a confirmation saying its found the word.
import serial
import time
ser = serial.Serial('COM6', 9600, timeout=0)
while 1:
try:
print (ser.readline())
time.sleep(1)
**if "sound" in ser.readline():
print("foundsound")**
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)
You may be reading from the port more often than you intend to. I would call ser.readline() just once per iteration of your main loop:
while True:
try:
data = ser.readline().decode("utf-8") # Read the data
if data == '': continue # skip empty data
print(data) # Display what was read
time.sleep(1)
if "sound" in data:
print('Found "sound"!')
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)
can you try:
import serial
import time
ser = serial.Serial('COM6', 9600, timeout=0)
while 1:
try:
line = ser.readline()
print line
time.sleep(1)
**if "sound" in line:
print("foundsound")**
except ser.SerialTimeoutException:
print('Data could not be read')
time.sleep(1)
Related
#!/usr/bin/python
I am struggling with quite the simple problem. I want to read some data from the serial port first than start writing the data. The data reading and writing works well. The problem is I need to read first around 7 lines like
X7_SEM_V3_6
ICAP OK
SA OK
IC OK
RBDK OK
status OK
S OK
Then send 'I' followed by N and C, then 9 hex digits from the text file. The code below read one line and went into the writing section and read the whole text file;
X7_SEM_V3_6
000062240
000062241
ICAP
000062240
000062241
so on
after doing this to all seven read lines than it send I. I want it read all seven lines once than send I and start working. this is in while loop. If I use something else it just read first line and stuck. Please some one help.
import serial, time
import binascii
ser = serial.Serial()
ser.port = "/dev/ttyUSB1"
ser.baudrate = 38400
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.xonxoff = False
ser.rtscts = False
ser.dsrdtr = False
number_address = 1341602
number_char = 9
timeout=1
f=open('lut.txt','r')
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput()
ser.flushOutput()
# reading
max_packet = 20
lines = 0
while True:
byteData = ser.read_until('\r',max_packet)
newdata=str(byteData)
print newdata.strip()
#ser.write('I')
ser.write('I')
time.sleep(0.01)
for line in f.readlines():
print line
ser.write('N')
time.sleep(0.01)
ser.write(' ')
time.sleep(0.01)
ser.write('C')
time.sleep(0.01)
for i in line:
newdata=i
ser.write(newdata)
time.sleep(0.01)
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
I have a python code to read some data from the serial port of the Artix-7 FPGA board it reads well. Then After read it suppose to write some data that is 9-digit hexadecimal number to the port it did well but the problem is after each write is read all the text file first then increment and the size of my text file is too big its about 1348065 lines .
here is the code please guide someone.
#!/usr/bin/python
import serial, time
from addresstable import *
import binascii
ser = serial.Serial()
ser.port = "/dev/ttyUSB1"
ser.baudrate = 38400
ser.bytesize = serial.EIGHTBITS
ser.parity = serial.PARITY_NONE
ser.stopbits = serial.STOPBITS_ONE
ser.xonxoff = False
ser.rtscts = False
ser.dsrdtr = False
number_address = 1341602
number_char = 9
timeout=1
#f=open('lut.txt','r')
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
exit()
if ser.isOpen():
try:
ser.flushInput()
ser.flushOutput()
# reading
max_packet = 20
lines = 0
while True:
byteData = ser.read_until('\r',max_packet)
newdata=str(byteData)
print newdata.strip()
ser.write('I')
time.sleep(0.01)
# writing
with open('adder-sem-address-sen0.txt', 'r') as f:
for line in f.readlines():
#print line
ser.write('N')
time.sleep(0.01)
ser.write(' ')
time.sleep(0.01)
ser.write('C')
time.sleep(0.01)
for i in line:
newdata=i
ser.write(newdata)
time.sleep(0.01)
time.sleep(1)
except Exception, e1:
print "error communicating...: " + str(e1)
else:
print "cannot open serial port "
My expected output is looks line
I>NC0000AABBF
I>NC0000AABBF
I>NC0000AABBA
and continue, it does same but after each line read it first it red the whole text file than read the next line
First of all I am a complete noobie when it comes to python. Actually I started reading about it this morning when I needed to use it, so sorry if the code is a disaster.
I'd like to get this done:
A communication via serial between two devices. The device where the python program is running has to be listening for some data being sent by the other device and storing it in a file. But every 30 seconds of received data it has to send a command to the other device to tell it to stop sending and begin a scan that takes 10 seconds.
This is the code I've written. It's printing continuously Opening connection..
from serial import Serial
from threading import Timer
import time
MOVE_TIME = 30.0
SCAN_TIME = 10.0
DEVICE_ADDRESS = '/dev/ttyACM0'
BAUD_RATE = 9600
while True:
try:
print("Opening connection...")
ser = Serial(DEVICE_ADDRESS, BAUD_RATE
break
except SerialException:
print("No device attached")
def scan():
print("Scanning...")
timeout = time.time() + SCAN_TIME
while True:
#Some code I haven't thought of yet
if time.time() > timeout:
ser.write(b'r') #command to start
break
def send_stop_command():
print("Sending stop command")
ser.write(b's') #command to stop
scan()
t = Timer(MOVE_TIME + SCAN_TIME, send_stop_command)
t.start()
filename = time.strftime("%d-%m-%Y_%H:%M:%S") + ".txt"
while True:
data = ser.readline()
try:
with open(filename, "ab") as outfile:
outfile.write(data)
outfile.close()
except IOError:
print("Data could not be written")
This is my current code, it does not seem to handle writes very well. It seems to be stuttering.
import serial
ser = serial.Serial(port='/dev/tty1', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1)
while True:
line = ser.readline()
print line,
if line == "":
var = raw_input()
if var != "":
ser.write(var)
I am trying to read several paragraphs of text, with a blank line separating each paragraph. when all the paragraphs are read, my pyserial script will then write a command to the serial channel, and then more paragraphs will be read, and so on.
How do I improve this?
---EDIT---------
Instead of raw_input(), I am now using select. Writing to the serial channel is ok now.
but for the reading, somehow it just refuses to read/print the last paragraph.
Can anyone help?
import serial
import select
import sys
ser = serial.Serial(port='/dev/tty1', baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, timeout=1)
while True:
line = ser.readline()
print line,
while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
lineIn = sys.stdin.readline()
if lineIn:
ser.write(lineIn)
else:
continue
Why not follow-up on Joran Beasley's suggestion?
import serial
ser = serial.Serial(
port='/dev/tty1',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
timeout=1)
while True:
line = ser.readline()
if not line.strip(): # evaluates to true when an "empty" line is received
var = raw_input()
if var:
ser.write(var)
else:
print line,
It's more pythonic and readable than binding sys.stdin in a while construct... O_o
I have a stupid python problem.
I'm trying to read a line from a file everytime i get a 'READY' message from a serial connection so i wrote this :
import serial
from time import sleep
port = "/dev/tty.usbserial-A400fYTT"
speed = 57600
polarfile = 'polarfile.pg'
f = open(polarfile, 'r')
ser = serial.Serial(port, speed, timeout=0)
while True:
data = ser.read(9999)
if len(data) > 0:
if(data == 'READY'):
f.readline()
else:
sleep(0.5)
sleep(1)
ser.close()
But it doesn't work, however if i replace the if(data == 'READY' block by print data. I get the READY message.
Also i can read my file with f.readline()...
Thanks to give advice to a py newbie
--
edit :
Important info, the serial doesn't receive only "READY" message, but a bunch of other, but i want just to react when the "READY" messsage is received.
I just replace
data = ser.read(9999)
by
data = ser.readline(9999) which gives me the message line by line instead of second by second of input data and then replace
if( data == 'READY' ):by
if (data.startswith('READY')):
and now it works :)