run code every X seconds - python

I Have infinite loop that read bytes from serial port, I want to save the read data to firebase database every X seconds.
I used this code snippet but it's not helping:
import threading
def printit():
threading.Timer(5.0, printit).start()
print "Hello, World!"
printit()
This is my code
import serial
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "/dev/ttyUSB0"
ser.timeout = 30
try:
try:
while 1:
line = ser.readline().rstrip().decode('utf-8')
# print("save data here every X seconds)
except KeyboardInterrupt:
ser.close() # Close port
pass
except serial.serialutil.SerialException as e:
print(str(e))
I can't use sleep because it blocking the main thread,So how to let the code read continuously and print "data saved" every X seconds (I'll save to database in my case)

Thanks to Lutz Horn for the suggestion in the comment, I resolve the problem like that :
import schedule
import time
import serial
ser = serial.Serial()
ser.baudrate = 115200
ser.port = "/dev/ttyUSB0"
ser.timeout = 30
schedule.every(10).seconds.do(save_db)
try:
try:
while 1:
schedule.run_pending()
line = ser.readline().rstrip().decode('utf-8')
# here every 10 seconds the function save_db will be called
except KeyboardInterrupt:
ser.close() # Close port
pass
except serial.serialutil.SerialException as e:
print(str(e))

I hope i have understood you correctly. Use time.time() to set timer.
import time
def doEvery_X_Seconds():
print("I do it every X seconds")
time.sleep(1)
TIMER_LIMIT = 5
setTimer = time.time()
while(1):
print("hello world")
if(time.time() - setTimer >= TIMER_LIMIT):
doEvery_X_Seconds()
setTimer = time.time()
There is time.sleep(1) only to demonstrate, that it works.

Related

About "write()" change string to byte

i want to use "ser.write()" ,but error say a is not byte.
so ,what can i do?
import serial
from time import sleep
import sys
ser = serial.Serial('/dev/ttyS0',9600,timeout=1);
try:
whiel True:
a = input()
ser.write(a)
sleep(1)
except KeyboardInterrupt:
ser.close()

While loop is not terminating due to socket function

I am trying to run two while loops in this program. The first while loop needs to run up to 50 seconds but this loop does not exit after 50 seconds (Not terminating after 50 Seconds), it just continues. I verified the timer in a separate program, where timer works well,but in my program timer is not working.
import array
import time
import socket
import os,sys
import concurrent.futures
import struct
Nmax_Per_hop=100
hello_Broadcast_Period=40
NeighborDiscovery_Time_Interval=50
MyNeighborSet_ip=[]
all_ip=[]
a=10
b=0
start_time=time.time()
My_ip='192.168.1.1'
#############################################################################
def broadcast_hello(): # (send 'Hello message')
ip1 = "192.168.1.254"
print ("[tx]------>hello to:"+ ip1)
PORT = 12345
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)
s.sendto (b'Hello',('192.168.1.254',PORT))
##########################################################################
def received_hello():
PORT = 12345
ip=[]
recv_message_hello=[]
global a
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
s.bind(('',PORT))
message=s.recvfrom(4096)
print ("before the ip")
ip=message[1][0]
if (ip not in all_ip):
all_ip.append(ip)
print (all_ip)
recv_message=message[0]
if not recv_message in recv_message_hello:
recv_message_hello=recv_message
if (ip==My_ip):
pass
elif ip not in MyNeighborSet_ip :
MyNeighborSet_ip.append(ip)
else:
print ("Already in List")
print ("[N-Set]------------:",MyNeighborSet_ip)
##########################################################################
temp = concurrent.futures.ThreadPoolExecutor (max_workers=2)
Here this loop is not working well
while(((time.time()-start_time)<NeighborDiscovery_Time_Interval) and (len(MyNeighborSet_ip) <= Nmax_Per_hop)):
if (time.time()-start_time<hello_Broadcast_Period):
temp.submit(broadcast_hello)
try:
temp.submit(received_hello)
except:
print("###################")
print ("IP of this node is: ",My_ip)
print ("[N-Set]------------:",MyNeighborSet_ip)
while (b<10):
print ("dfdfdfdfdfdfdfdf")
b+=1
Can anybody help me how to fix this problem?

Python serial port read until it finishes

#!/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 "

Timer just runs the first time

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")

Finding string Python Arduino

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)

Categories