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()
Related
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.
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?
I'm very new at Python scripting and am working on a script to turn on a fan when my Raspberry Pi3 reaches a specific temp. I've been trying to debug my code all day and found I can't figure out what's wrong. Here is my code:
import os
import sys
import signal
import subprocess
import atexit
import time
from time import sleep
import RPi.GPIO as GPIO
pin = 18
maxTMP = 60
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return()
def setPin(mode):
GPIO.output(pin, mode)
return()
def exit_handler():
GPIO.cleanup()
def FanON():
SetPin(True)
return()
def FanOFF():
SetPin(False)
return()
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
finally:
exit_handler()
Here is my error:
File "/home/pi/Scripts/run-fan.py", line 36
while True:
^
IndentationError: unexpected indent
I've tried to indent every way possible. I need help.
Thanks!
I want to preface this with, you should use four spaces for your indentation. If you do, it will be way, way easier to see problems like the one you have here. If you use an IDE like Spyder or PyCharm, there are settings that automatically highlight indentation problems for you (regardless of how many spaces you want to use).
That said, with your current indentation scheme of one-space-per-indent, you want to replace your bottom block with this:
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
If you used four spaces instead of one on your original code, it would have looked like this:
try:
setup()
while True:
process = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',stdout =
subprocess.PIPE,shell=True)
temp,err = process.communicate()
temp = str(temp).replace("temp=","")
temp = str(temp).replace("\'C\n","")
temp = float(temp)
if temp>maxTMP:
FanON()
else:
FanOFF()
sleep(5)
There's another problem here, which is that your while True block will currently never exit (maybe you want a break statement somewhere).
I am using pyhook to detect when user presses Control + C.
Then I get the data copied from the clipboard using win32clipboard api.
The problem I am facing is that the code returns the last copied data not the current one.
Is it because it takes time to save something in clipboard?
Here is my code:
from time import sleep
import win32clipboard
import win32api
import win32console
import win32gui
import pythoncom,pyHook
from threading import Thread
"""
win=win32console.GetConsoleWindow()
win32gui.ShowWindow(win,0)
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText('testing 123')
"""
data=''
def getcopied():
global data
while True:
try:
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()
break
except TypeError:
print "Copied Content Invalid"
break
if data.isalpha():
print data
def initkeystack():
global keystack
keystack=[ [i,-1] for i in ['','','','','']]
def ctrlc():
global keystack
ct=0
for i in range(5):
if ct==0:
if keystack[i]==['Lcontrol',0]:
ct=1
else:
if keystack[i]==['C',0]:
getcopied()
getcopied()
initkeystack()
def OnKeyboardEvent(event):
str=event.GetKey()
global keystack
if keystack[4]!=[str,0]:
del(keystack[0])
keystack.append([str,0])
ctrlc()
def OnKeyboardEventUp(event):
str=event.GetKey()
global keystack
if keystack[4]!=[str,1]:
del(keystack[0])
keystack.append([str,1])
ctrlc()
def klog():
keystack=[]
initkeystack()
while True:
try:
hm=pyHook.HookManager()
hm.KeyDown=OnKeyboardEvent
hm.KeyUp=OnKeyboardEventUp
hm.HookKeyboard()
while True:
pythoncom.PumpWaitingMessages()
except KeyboardInterrupt:
pass
a = Thread(target=klog)
a.start()
a.join()
You can use ctypes to get the clipboard.
Here's a simple function that will return the clipboard if it has a string in it.
import ctypes
user32 = ctypes.windll.user32
kernel32 = ctypes.windll.kernel32
def getClipboard(user32, kernel32):
user32.OpenClipboard(0)
if user32.IsClipboardFormatAvailable(1):
data = user32.GetClipboardData(1)
data_locked = kernel32.GlobalLock(data)
clipText = ctypes.c_char_p(data_locked)
kernel32.GlobalUnlock(data_locked)
text = clipText.value
else:
text = ""
user32.CloseClipboard()
return text
print(getClipboard(user32, kernel32))
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)