I am trying to read the data from my Geiger Counter on my Beaglebone, but when I print the result, doesn't include my counter code:
import Adafruit_BBIO.UART as UART
import serial
import time
UART.setup("UART4")
ser = serial.Serial(port = "/dev/ttyO4", baudrate=9600)
r = 0
d = 0
z = 0
minutes = 0
while True:
timeout = time.time() + 60
while True:
x = ser.read()
if ser.isOpen():
print "Serial is open!"
r = r +1
print r
print x
elif x is '0':
d=d+1
#print '.'
elif x is '1':
d=d+1
#print '.'
time.sleep(1)
z=z+d
print "CPM %f " % d
print "total %f" % z
print "minutes %f" % minutes
My output came out as:
Serial is open!
1
1
Serial is open!
2
1
Serial is open!
3
0
There is no break in your inner while loop, so it will loop infinitely. Assuming counter code means the print statements at the end of your code sample, they will never be reached.
Related
I've two separate code bases for Tf-mini(Lidar) and servo motor. I want the both code to run at the same time. I tried to combine them in to a single code, But only one code runs at a time. Please help to rewrite or edit the code.
Code for servo motor here:
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.OUT)
p = GPIO.PWM(7, 100)
t = 0.007
r = 20
p.start(r)
while True:
for i in range(5,r):
p.ChangeDutyCycle(i)
print(i)
time.sleep(t)
for i in range(r,5,-1):
p.ChangeDutyCycle(i)
print(i)
time.sleep(t)`
Code for lidar here:
import time
import serial
ser = serial.Serial("/dev/ttyAMA0", 115200)
def read_data():
while True:
counter = ser.in_waiting
if counter > 8:
bytes_serial = ser.read(9)
ser.reset_input_buffer()
if bytes_serial[0] == 0x59 and bytes_serial[1] == 0x59: # this portion is for python3
print("Printing python3 portion")
distance = bytes_serial[2] + bytes_serial[3]*256 # multiplied by 256, because the binary
data is shifted by 8 to the left (equivalent to "<< 8").
# Dist_L, could simply be added resulting in 16-bit data of Dist_Total.
strength = bytes_serial[4] + bytes_serial[5]*256
temperature = bytes_serial[6] + bytes_serial[7]*256
temperature = (temperature/8) - 256
print("Distance:"+ str(distance))
print("Strength:" + str(strength))
if temperature != 0:
print("Temperature:" + str(temperature))
ser.reset_input_buffer()
if bytes_serial[0] == "Y" and bytes_serial[1] == "Y":
distL = int(bytes_serial[2].encode("hex"), 16)
distH = int(bytes_serial[3].encode("hex"), 16)
stL = int(bytes_serial[4].encode("hex"), 16)
stH = int(bytes_serial[5].encode("hex"), 16)
distance = distL + distH*256
strength = stL + stH*256
tempL = int(bytes_serial[6].encode("hex"), 16)
tempH = int(bytes_serial[7].encode("hex"), 16)
temperature = tempL + tempH*256
temperature = (temperature/8) - 256
print("Printing python2 portion")
print("Distance:"+ str(distance) + "\n")
print("Strength:" + str(strength) + "\n")
print("Temperature:" + str(temperature) + "\n")
ser.reset_input_buffer()
if __name__ == "__main__":
try:
if ser.isOpen() == False:
ser.open()
read_data()
except KeyboardInterrupt(): # ctrl + c in terminal.
if ser != None:
ser.close()
print("program interrupted by the user")
Please help me to combine these two code to run at the same time.
I think I see your problem. Both segments of code are sequentially driven and hence it will create problems. Here is what you need to do (pseudo code):
loop forever:
t1=start_time
change duty cycle #remove the wait code
poll the serial port #the ladar code
t2=end_time
if t2 - t1 < t:
wait (t - (t2-t1))
Being an old Arduino fan myself, I see the struggles of handling the servo motor. I have a simple library to do most of the dirty work for me. You are most welcome to use my library via any of the two links:
https://github.com/vikramdayal/RaspberryMotors or https://pypi.org/project/RaspberryMotors/#description
I'm writing a program which should add chars to strings in three different processes. If the resulting string matches a given one, the process which has the match, should send an "endflag" to process 0. After process 0 receives the "endflag" he should send a broadcast to all other processes (1 - 3) and exit. The other processes receive the broadcast and should exit too / stop working.
[...]
string_given = "abc"
magic_bytes = "0xDEA7C0DE"
chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !?#/\%&.-_:,;*+<>|(){}'
end_all = None
if rank == 0:
while(True):
recv_data = comm.recv(source=MPI.ANY_SOURCE)
print("0.recv: %s" % (recv_data))
if recv_data == magic_bytes:
end_all = magic_bytes
send_data = bcast(end_all, root=0)
sys.exit()
if rank == 1:
min, max = 1, 2
while(True):
for n in xrange(min, max):
for c in itertools.product(chars, repeat=n):
string = ''.join(c)
print("1.string: %s" % (string))
if string == string_given:
print("1.found: %s = %s" % (string, string_given))
end_all = magic_bytes
comm.send(end_all, dest=0)
recv_data = comm.bcast(end_all, root=0)
if recv_data == magic_bytes:
sys.exit()
if rank == 2:
min, max = 3, 4
while(True):
for n in xrange(min, max):
for c in itertools.product(chars, repeat=n):
string = ''.join(c)
print("2.string: %s" % (string))
if string == string_given:
print("2.found: %s = %s" % (string, string_given))
end_all = magic_bytes
comm.isend(end_all, dest=0)
recv_data = comm.bcast(end_all, root=0)
if recv_data == magic_bytes:
sys.exit()
[...]
The code above produces following output:
3.string: aaaaa
1.string: a
2.string: aaa
And then i think it deadlocks.
How can i prevent my code from the deadlock?
I'm really new to python and coding in general so i turn here for help. At work we need to test many cables with up to five DS18B20 sensors attached to them. We got this program and we've been using it for a while now to test cables with raspberry Pi. But there are few problems with it.
The program needs to detect the number of sensors attached and see if they're working, then list them by serial number lowest>highest (so we can warm them up, see which one gets highlighted, one by one and physically number them) and repeat.
It feels generally slow and crashes pretty often.
With the cables that have 5 sensors attached to them, it can find the sensors on max 2 cables(more if lucky), and when you attach 3rd cable it won't find them anymore or it will keep saying that there's 10 sensors attached. Rebooting the Pi fixes it but it takes time. Hot-swapping the cables is probably the main culprit here, but its the fastest way.
With 3 sensor cables you can check 4-5 of them until it hangs.
Any hints where the problem could be or how i could make things more efficient and faster are welcome.
Code:
import os,sys,time
import curses
stdscr = curses.initscr()
begin_x = 5; begin_y = 5
height = 40; width = 40
def temp_raw(sensor_str):
f = open(sensor_str, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp(sensor_str):
lines = temp_raw(sensor_str)
while lines[0].strip()[-3:] != 'YES':
lines = temp_raw(sensor_str)
temp_output = lines[1].find('t')
if temp_output != -1:
temp_string = lines[1].strip()[temp_output+2:]
temp_c = float(temp_string) / 1000.0
return temp_c
init = 1
timer = 0
search = 1
curses.noecho()
curses.curs_set(0)
subdirectories = []
old_nbr_of_subdirs = 1
nbr_of_subdirs = 1
old_subdirectories = []
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
while (1):
timer = timer + 1
while search == 1:
stdscr.addstr(10,30, "Searching for sensors");
subdirectories = os.listdir("/sys/bus/w1/devices/");
nbr_of_subdirs = len(subdirectories);
time.sleep(3)
if nbr_of_subdirs > old_nbr_of_subdirs:
stdscr.addstr(10,30, "Found %d new sensors " % (nbr_of_subdirs-old_nbr_of_subdirs));
stdscr.addstr(11,30, "Is this all sensors? (y/n)?");
stdscr.refresh()
c = -1;
while(c == -1):
c = stdscr.getch();
if c == ord('y'):
stdscr.addstr(10,30, " ");
stdscr.addstr(11,30, " ");
stdscr.refresh()
old_nbr_of_subdirs = nbr_of_subdirs;
init = 1;
search = 0;
timer = 0;
else:
stdscr.addstr(10,51 + timer, ". ");
timer = timer + 1;
timer = timer % 4;
stdscr.refresh()
if init == 1:
init = 0
alive_ticker = 0;
temp_list = [];
sensor_oldtemp = [0,0,0,0,0,0];
sensor_temp = [0,0,0,0,0,0];
active_sensor = [0,0,0,0,0,0];
sensors = 0;
alive_ticker = 0;
active = 2;
confirm = 0;
stdscr.addstr(17,0, "Number of subdirectories %d" % (len(subdirectories)));
removed = 0;
index = 0;
length_old_subdirs = len(old_subdirectories);
while (index < length_old_subdirs):
length_old_subdirs = len(old_subdirectories);
if old_subdirectories[index] in subdirectories:
subdirectories.remove(old_subdirectories[index]);
removed += 1;
index += 1;
else:
old_subdirectories.remove(old_subdirectories[index]);
index = 0;
stdscr.addstr(30,20, "Removed %d" % (removed))
stdscr.addstr(18,0, "Number of CUT subdirectories %d" % (len(subdirectories)));
stdscr.addstr(19,0, "Number of old_subdirectories %d" % (len(old_subdirectories)));
stdscr.addstr(13,20, "Press space to confirm active sensor!");
stdscr.addstr(14,20, "Press r to reset!");
for index in range(len(subdirectories)):
if subdirectories[index].find("28") != -1:
temp_list.append("/sys/bus/w1/devices/"+subdirectories[index]+"/w1_slave");
sensor_temp[sensors] = 0;
sensors = sensors + 1;
old_subdirectories = old_subdirectories + subdirectories;
temp_list.sort();
if confirm == 1:
stdscr.addstr(13,20, "Press space to confirm active sensor!");
stdscr.addstr(14,20, "Press r to restart!");
curses.halfdelay(1);
c = stdscr.getch();
if c == 32:
confirm = 0;
timer = 10
for z in range(sensors):
if active_sensor[z] > active:
stdscr.addstr(z+5,20, " " , curses.A_DIM)
active_sensor[z] = 100
stdscr.refresh()
elif c == ord('n'):
init = 1
continue
elif c == ord('r'):
for z in range(sensors):
active_sensor[z] = 1;
if (timer > 9):
timer = 0
nbr_active_sensors = 0
for y in range(sensors):
if 99 > active_sensor[y]:
nbr_active_sensors = nbr_active_sensors + 1;
sensor_temp[y] = read_temp(temp_list[y]);
if ((sensor_oldtemp[y] + 0.1) < sensor_temp[y]):
active_sensor[y] = active_sensor[y] + 1;
sensor_oldtemp[y] = sensor_temp[y]
stdscr.addstr(3,5, "nbr_active_sensors=%d" % (nbr_active_sensors))
stdscr.addstr(4,5, "sensors=%d" % (sensors))
if nbr_active_sensors == 0:
search = 1
timer = 0;
continue
for x in range(sensors):
if (99 > active_sensor[x] and active_sensor[x] > active):
confirm = 1
stdscr.addstr(x+5,20, "Sensor %d value %4.2f ID:%s : %d " % (x+1, sensor_temp[x], temp_list[x][20:-9], active_sensor[x]), curses.A_STANDOUT)
elif active_sensor[x] <= active:
stdscr.addstr(x+5,20, "Sensor %d value %4.2f ID:%s : %d " % (x+1, sensor_temp[x], temp_list[x][20:-9], active_sensor[x]))
stdscr.refresh()
alive_ticker = alive_ticker + 1
stdscr.addstr(2, 55, "Alive ticker: %6d" % (alive_ticker))
Question: when you insert the 3rd cable (with 2-3 temp sensor on them) it just won't find any new sensors anymore.
If I recall properly there is a Limit of 2 Cable. Have you verified your Hardware supports more Cable?
I suggest to rewrite the Code and separate the Code into UI, Sensor and Wire Parts.
For instance:
class DS18B20(object):
...
def read(self):
...
class One_Wire(object):
def search(self):
print("Searching sensors")
...
def read(self):
print('Reading sensors')
for key in self.sensors:
self.sensors[key].read()
def refresh(self):
print("Refreshing sensors")
...
def history(self, alive=True):
print('Reading History')
...
Usage:
if __name__ == '__main__':
oWire = One_Wire()
oWire.search()
print(oWire)
oWire.refresh()
print(oWire)
oWire.read()
print(oWire)
history = oWire.history()
print(history)
Output:
Searching sensors
Sensors:5, active:5
id:i2c-0 CONNECT temp:None, id:i2c-3 CONNECT temp:None, id:i2c-1 CONNECT temp:None, id:i2c-5 CONNECT temp:None, id:i2c-6 CONNECT temp:None
Refreshing sensors
NEW Sensor:i2c-2
NEW Sensor:i2c-4
Sensors:7, active:6
id:i2c-0 CONNECT temp:None, id:i2c-2 CONNECT temp:None, id:i2c-3 CONNECT temp:None, id:i2c-1 disconnect temp:None, id:i2c-5 CONNECT temp:None, id:i2c-6 CONNECT temp:None, id:i2c-4 CONNECT temp:None
Reading sensors
Reading sensors
Reading sensors
Sensors:7, active:6
id:i2c-0 CONNECT temp:19, id:i2c-2 CONNECT temp:25, id:i2c-3 CONNECT temp:26, id:i2c-1 disconnect temp:None, id:i2c-5 CONNECT temp:25, id:i2c-6 CONNECT temp:18, id:i2c-4 CONNECT temp:30
Reading History
[{'i2c-0': [20, 27, 19]}, {'i2c-2': [30, 21, 25]}, {'i2c-3': [23, 29, 26]}, {'i2c-5': [30, 18, 25]}, {'i2c-6': [30, 21, 18]}, {'i2c-4': [24, 18, 30]}]
This code works as expected. Output:
Loading
Loading.
Loading..
Loading...
Code:
done = False
count = 0
while not done:
print '{0}\r'.format("Loading"),
time.sleep(0.25)
print '{0}\r'.format("Loading."),
time.sleep(0.25)
print '{0}\r'.format("Loading.."),
time.sleep(0.25)
print '{0}\r'.format("Loading..."),
time.sleep(0.25)
count += 1
if count == 5:
done = True
And this code doesn't. Output:
Loading.
Loading...
Code:
done = False
count = 0
while not done:
print '{0}\r'.format("Loading"),
time.sleep(0.125)
print '{0}\r'.format("Loading."),
time.sleep(0.125)
print '{0}\r'.format("Loading.."),
time.sleep(0.125)
print '{0}\r'.format("Loading..."),
time.sleep(0.125)
count += 1
if count == 5:
done = True
Why does the time function seem to skip every second print statement if it is lower than 0.25?
Reason
Depending on the platform, Python buffers the output to different degrees.
For example, on Mac OSX there is no output at all even for your version with 0.25 seconds sleep.
Flushing manually
Flushing manually should work:
import sys
import time
done = False
count = 0
while not done:
for n in range(4):
print '{0}\r'.format("Loading" + n * '.'),
sys.stdout.flush()
time.sleep(0.125)
print ' ' * 20 + '\r',
count += 1
if count == 5:
done = True
You need to flush the output with sys.stdout.flush(). You also need to print empty spaces to make the dots "going back and forth":
print ' ' * 20 + '\r',
More minimal and cleaned up
This is shortened and a bit more general in terms of the shown text:
import sys
import time
text = 'Loading'
for _ in range(5):
for n in range(4):
print '{0}\r'.format(text + n * '.'),
sys.stdout.flush()
time.sleep(0.25)
nspaces = len(text) + n
print ' ' * nspaces + '\r',
Running unbuffered from the commandline
You can remove the line:
sys.stdout.flush()
if you run your script with the -u option:
python -u script_name.py
Note: This will have an effect on all print statements.
I have a simple question about socket programming. I've done to implement a server and two clients as following codes, but all of sudden it stops while it communicates each other. I have no idea why it happens all the time.
Would you give me advice, hint, or help?
Thank you for your time.
Client
# simple client
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
buf = 100
s.connect((host, port))
i = 0
timestep = 0
while(1):
k = '01'#+str(timestep)
#1
s.send(k)
print 'sending message is', k
#2
v = s.recv(buf)
print v
if v == 'hold 01':
print 'timestep is', timestep#'send the previous message'
if timestep == 0:
timestep == 0
else:
timestep -= 1
else:
print 'read data'
FILE = open("datainfo1.txt", "r+")
msg = FILE.read()
FILE.close()
#3
while(1):
tmp, msg = msg[:buf], msg[buf:]
s.send(tmp)
print len(tmp)
if len(tmp) < buf:
print 'break'
break
# send file
i+=1
timestep+=1
print 'end'
s.close()
Server
import socket, sys
# set up listening socket
lstn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = ""
port = 12345
# bind lstn socket to this port
lstn.bind(("", port))
lstn.listen(5)
# initialize buffer size
buf = 100
# initialize concatenate string, v
v = ''
# initialize client socket list
cs = []
check = [0, 0]
# a fixed number of clients
nc = 1
count = 0
status = [0,0]
j = 0
step = [0,0]
for i in range(nc):
(clnt,ap) = lstn.accept()
clnt.setblocking(0)
cs.append(clnt)
file = open("output_analysis.txt","w+")
while (len(cs) > 0):
clnt = cs.pop(0)
cs.append(clnt)
try:
#1
k = clnt.recv(buf)
print "k=",k,"\n"#[:2]
if k == '01':
print "1st client connected", status[0]
file.write("1st\t")
if status[0] == 0:
v = 'hold 01'
check[0] = 1
elif status[0] == 1:
v = 'go 01'
# status[0] = 0
print v, "the message\n"
file.write(v)
file.write("\t")
#2
clnt.send(v)
if status[0] == 1:
FILE = open("client1.txt","w+")
print 'receive 01'
#3
while(1):
status[0] = 0
print '1st : receiving'
msg = clnt.recv(buf)
print len(msg)
if len(msg) < buf:
print 'break'
#FILE.close()
break
elif k == '02':
print "2nd client connected", status[0]
file.write("2nd\t")
if status[1] == 0:
v = 'hold 02'
check[1] = 1
elif status[1] == 1:
v = 'go 02'
# status[0] = 0
print v, "the message\n"
file.write(v)
file.write("\t")
#2
clnt.send(v)
if status[1] == 1:
FILE = open("client2.txt","w+")
print 'receive 02'
#3
while(1):
status[1] = 0
print '2nd : receiving'
msg = clnt.recv(buf)
print len(msg)
if len(msg) < buf:
print 'break'
#FILE.close()
break
if check[0] == 1:# and check[1] == 1:
print j, 'here\n'
j += 1
for i in range(2):
check[i] = 0
status[i] = 1 # which means, all clients are connected
print check, status
else:
print 'hello'
except: pass
file.close()
lstn.close()
except: pass
You're ignoring all exceptions. This is a bad idea, because it doesn't let you know when things go wrong. You'll need to remove that except handler before you can reasonably debug your code.
One problem is you are setting non-blocking mode:
clnt.setblocking(0)
But never checking that it is safe to send or recv data. It turns out that since the code is ignoring all exceptions, it isn't seeing the following error that I got when I removed the try:
Exception [Errno 10035] A non-blocking socket operation could not be completed immediately
After removing the setblocking call, the code proceeded further, but still has problems.
Describing what problem you are trying to solve would help to understand what the code is trying to do.