Reading multiple ultrasonic sensors with BBB using python - python

So i'm starting to use hc-sr04 ultrasonic sensors and ran into a problem. I want to read multiple sensors (two for starters) but I get the same distance value on both. Here is the code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Adafruit_BBIO.GPIO as GPIO
import time
def distanceMeasurement(TRIG,ECHO):
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulseStart = time.time()
while GPIO.input(ECHO) == 1:
pulseEnd = time.time()
pulseDuration = pulseEnd - pulseStart
distance = pulseDuration * 17150
distance = round(distance, 2)
return distance
#Configuration
GPIO.setup("P9_15",GPIO.OUT) #Trigger
GPIO.setup("P9_12",GPIO.IN) #Echo
GPIO.setup("P9_11",GPIO.OUT)
GPIO.setup("P9_13",GPIO.IN)
#Security
GPIO.output("P9_11", False)
GPIO.output("P9_15", False)
time.sleep(0.5)
#main Loop
try:
while True:
for i in range(2):
if i == 0:
recoveredDistance = distanceMeasurement("P9_11","P9_13")
print "Distance1: ",recoveredDistance,"cm"
elif i == 1:
recoveredDIstance = distanceMeasurement("P9_15","P9_12")
print "Distance2: ",recoveredDistance,"cm"
time.sleep(1)
except KeyboardInterrupt:
print "Measurement stopped by user"
GPIO.cleanup()
I get the same reading on both no matter the distance to the object on sensor2, the distance read in sensor1 is what both display; seems that sensor2 is ignored.
Doing some "manual debugging" (i.e. print TRIG, ECHO) I notice the function recives the correct parameters, here is the output to that "debugging":
P9_11
P9_13
Distance1: 20.79 cm
P9_15
P9_12
Distance2: 20.79 cm
P9_11
P9_13
Distance1: 20.13 cm
P9_15
P9_12
I want to use that one fucntion to read all the sensors. Thank you in advance

You print the same result twice, because the second measurement is saved as recoveredDIstance. So recoveredDistance is unchanged. Python is case sensitive.
while True:
recoveredDistance = distanceMeasurement("P9_11","P9_13")
print "Distance1: ", recoveredDistance, "cm"
recoveredDistance = distanceMeasurement("P9_15","P9_12")
print "Distance2: ", recoveredDistance, "cm"
time.sleep(1)

Related

How come when I try to run 2 python scripts that give and take data from another and one's reading serial port data I get a permission error?

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.

Error while Working with US-100 on Raspberry pi 3

I wrote the following code for my US-100 ultrasonic distance measurement sensor. But I am getting junk results everytime. when ever I am moving my sensor, I dont get any change in reading. Also, when I am connecting GND and VCC to sensor, input stops generating. Need help with Circuit diagram for connecting US-100 to Raspberry pi 3 and errors in this code which lead to junk results
import RPi.GPIO as GPIO
import time
import logging
LOG_FILENAME='US_100.log'
logging.basicConfig(format='%(asctime)s %(message)s',filename='US_100',
level=logging.DEBUG)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
while True:
GPIO.output(TRIG,False)
time.sleep(1.5)
print("Waiting for sensor to settle")
GPIO.output(TRIG,True)
time.sleep(0.0001)
GPIO.output(TRIG, False)
pulse_start=time.time()
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = (pulse_end-pulse_start)
print("Pulse duration =%1f " %pulse_duration)
distance = (pulse_duration*343/2)
if distance >0.5 and distance <400:
print("Distance = %1f" %distance)
else:
print("Out of Range")
logging.debug(distance)
Image of results which I am getting even though the object is 15-20cm apart.
Output Image

python program stops after wifi connection discontinuity

I started learning Python two months ago and I have written a code for a Raspberry pi project. My problem is that the program stucks after some hours of operation. I think that in all cases, it stopped after some wifi connection drops. But I don't understand why the whole program stops if there something wrong with the wifi connection. It stops uploading values and renew the lcd screen messages it prints (I removed this and other stuff from the code in order to be more easy to read.)
The code starts at the startup (sudo python /home/pi/test.py &) and contains two Threads:
The "Control" thread reads temperature and humidity by using an i2c bus and a sensor am2315 and according to a temperature threshold, controls a relay through GPIO.
The "Thingspeak" thread reads the temperature threshold from a 'Thingspeak' channel and then uploads the measurements from the previous thread to 'Thingspeak'.
I really don't know what to do and how to search for any solutions.
Any help will be much appreciated.
#! /usr/bin/env python
from time import sleep
import datetime
import urllib2
import RPi.GPIO as GPIO
import threading
import smbus
from tentacle_pi.AM2315 import AM2315
import smtplib
import contextlib
sleep(120)
# Lock
tLock = threading.Lock()
# Global variables
tem_global = 0; hum_global = 0
tem_hi = 35; relay = 21
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay, GPIO.OUT)
GPIO.output(relay, False)
sleep(1)
def Control():
global temg, humg, tem_hi, relay
# AM2315 setup
am = AM2315(0x5c,"/dev/i2c-1")
I2C_address = 0x70; I2C_bus_number = 1; i2c_channel_setup = 1
bus = smbus.SMBus(I2C_bus_number)
bus.write_byte(I2C_address, i2c_channel_setup)
sleep(1)
while True:
try:
tem_local, hum_local = am2315meas()
except:
tem_local = -1; hum_local = -1
tLock.acquire()
tem_global = tem_local; hum_global = hum_local
if tem_local < tem_hi:
GPIO.output(relay, True)
else:
GPIO.output(relay, False)
tLock.release()
sleep(150)
def Thingspeak():
global tem_global, hum_global, tem_hi
myAPI = "..."
channelID = "..."
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
sleep(30)
try:
# Reading value from thingspeak
tLock.acquire()
with contextlib.closing(urllib2.urlopen("https://api.thingspeak.com/channels/%s/fields/1/last?" % channelID)) as f_read:
tem_hi = float(fread.read())
t.Lock.release()
sleep(30)
# Uploading values to thingspeak
tLock.acquire()
with contextlib.closing(urllib2.urlopen(baseURL + "&field1=%s" % tem_global + "&field2=%s" % hum_global)) as f_upload:
pass
tLock.release()
except:
with open('/home/pi/errors.txt', mode='a') as file:
file.write('Network error recorded at %s.\n' % datetime.datetime.now())
file.close()
sleep(60)
continue
def Main():
t1 = threading.Thread(target=Thingspeak)
t2 = threading.Thread(target=Control)
t1.start()
t2.start()
t1.join()
t2.join()
GPIO.cleanup()
if __name__ == '__main__':
Main()
Problem solved. As James K Polk indicated, there was an error after the tLock.acquire(), every time the internet connection went off, causing deadlock of the program. Below is a corrected part of the code for anyone would be interested.
def Control():
global tem_global, hum_global, tem_hi, relay
# AM2315 setup
am = AM2315(0x5c,"/dev/i2c-1")
I2C_address = 0x70; I2C_bus_number = 1; i2c_channel_setup = 1
bus = smbus.SMBus(I2C_bus_number)
bus.write_byte(I2C_address, i2c_channel_setup)
sleep(1)
while True:
try:
tem_local, hum_local = am2315meas()
except:
tem_local = -1; hum_local = -1
with tLock:
tem_global = tem_local; hum_global = hum_local
if tem_local < tem_hi:
GPIO.output(relay, True)
else:
GPIO.output(relay, False)
sleep(150)
def Thingspeak():
global tem_global, hum_global, tem_hi
myAPI = "..."
channelID = "..."
baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI
while True:
sleep(30)
try:
# Reading value from thingspeak
with tLock:
with contextlib.closing(urllib2.urlopen("https://api.thingspeak.com/channels/%s/fields/1/last?" % channelID)) as f_read:
tem_hi = float(fread.read())
sleep(30)
# Uploading values to thingspeak
with tLock:
with contextlib.closing(urllib2.urlopen(baseURL + "&field1=%s" % tem_global + "&field2=%s" % hum_global)) as f_upload:
pass
except:
with open('/home/pi/errors.txt', mode='a') as file:
file.write('Network error recorded at %s.\n' % datetime.datetime.now())
sleep(60)
continue

Python: "while" is too slow, and sleep(0.25) becomes sleep(3) in actual execution

I am running a Python Program on a Raspberry Pi 3 which I want to log the temperature from a DS18B20 sensor once every 0.25 seconds.
Earlier, when the program was simple and displaying the temperature on shell, it was quite fast and not having issues. Unfortunately due to the program itself now which includes logging to a file, I am getting a log every 2 seconds or 3 seconds only.
How do I ensure the 0.25 second logging interval.
I have shared the code below:
#This program logs temperature from DS18B20 and records it
#Plots the temperature-time plot.
import os
import sys
#import matplotlib.pyplot as plt
from re import findall
from time import sleep, strftime, time
from datetime import *
#plt.ion()
#x = []
#y = []
ds18b20 = ''
def setup():
global ds18b20
for i in os.listdir('/sys/bus/w1/devices'):
if i != 'w1_bus_master1':
ds18b20 = i
# Reads temperature data from the Temp sensor
# This needs to be modified for use with max31855 and K-type thermocouples
def read():
# global ds18b20
location = '/sys/bus/w1/devices/' + ds18b20 + '/w1_slave'
tfile = open(location)
text = tfile.read()
tfile.close()
secondline = text.split("\n")[1]
temperaturedata = secondline.split(" ")[9]
temperature = float(temperaturedata[2:])
temperature = temperature / 1000
return temperature
#Loop for logging - sleep, and interrupt to be configured.
def loop():
while True:
if read() != None:
print "Current temperature : %0.3f C" % read()
#sleep(0.25)
func()
def write_temp(temperature,file_name):
with open(file_name, 'a') as log:
log.write("{0},{1}\n".format(datetime.now().strftime("%d-%m-%Y %H:%M:%S"),str(temperature)))
arg = sys.argv[1]
filename1 = str(arg) + "-" + datetime.now().strftime("%d-%m-%Y-%H-%M-%S")+".csv"
def func():
temperature = read()
#sleep(0.25)
write_temp(temperature,filename1)
#graph(temperature)
#For plotting graph using MatPlotLib
#Comment out this function during foundry trials to avoid system slowdown
#Check system resource usage and slowdown using TOP or HTOP
#def graph(temperature):
# y.append(temperature)
# x.append(time())
# plt.clf()
# plt.scatter(x,y)
# plt.plot(x,y)
# plt.draw()
#Interrupt from command-line
def destroy():
pass
if __name__ == '__main__':
try:
setup()
func()
loop()
except KeyboardInterrupt:
destroy()
I have commented out sections that I thought to be resource heavy, but still I can't manage anything less than 2 seconds. I am getting results as below:
Output:
27-09-2016 12:18:41,23.0
27-09-2016 12:18:43,23.062
27-09-2016 12:18:46,23.125
27-09-2016 12:18:48,23.187
27-09-2016 12:18:50,23.187
27-09-2016 12:18:53,23.562
27-09-2016 12:18:55,25.875
27-09-2016 12:18:58,27.187
27-09-2016 12:19:00,27.5
Only open the logfile once (and close it on program exit)
Don't always re-read the temperature from the sensor. You call read() way too often.
Reduce general overhead and simplify your calls.
I am not able to completely test this, but something like this sould work:
import os
import sys
import time
from datetime import datetime
def read_temp(dev):
'''Reads temperature from sensor and returns it as float.'''
loc = '/sys/bus/w1/devices/' + dev + '/w1_slave'
with open(loc) as tf:
return float(tf.read().split('\n')[1].split(' ')[9][2:]) / 1000.0
def write_temp(t, logfile):
'''Writes temperature as .3 float to open file handle.'''
logfile.write('{0},{1:.3f}\n'.format(datetime.now().strftime('%d-%m-%Y %H:%M:%S'), t))
def loop(dev, logfile):
'''Starts temperature logging until user interrupts.'''
while True:
t = read_temp(dev)
if t:
write_temp(t, logfile)
print('Current temperature: {0:.3f} °C'.format(t))
sys.stdout.flush() # Flush. Btw, print is time-consuming!
time.sleep(.25)
if __name__ == '__main__':
# Take the first match for a device that is not 'w1_bus_master1'
dev = [d for d in os.listdir('/sys/bus/w1/devices') if d != 'w1_bus_master1'][0]
# Prepare the log filename
fname = str(sys.argv[1]) + "-" + datetime.now().strftime("%d-%m-%Y-%H-%M-%S")+".csv"
# Immediately open the log in append mode and do not close it!
logfile = open(fname, 'a')
try:
# Only pass device and file handle, not the file name.
loop(dev, logfile)
except KeyboardInterrupt:
# Close log file on exit
logfile.close()

Python and gpio raspberry

I have a problem with my project, I have a little python script to read my gas meter.
Every revolution of digits a small magnet inside the gas meter close to the reed switch makes an input for my raspberry. The problem is when the magnet stops close to the sensor circuit leaving on a high level, which cause false inputs, here my script.
Any suggestion? thanks to all
#!/usr/bin/env python
import time
import datetime
import os.path
import pycurl
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.add_event_detect(10, GPIO.RISING, bouncetime = 5000)
def GetGas(arg):
time.sleep(0.01) # need to filter out the false positive of some power fluctuation
if GPIO.input(10) != GPIO.HIGH:
return
gastotale=0
if os.path.isfile('/var/www/myscripts/gas/gastotale.txt'):
file = open("/var/www/myscripts/gas/gastotale.txt","r")
gastotale = float(file.read())
file.close()
gastotale = gastotale+0.01
file = open("/var/www/myscripts/gas/gastotale.txt","w")
file.write(str(gastotale))
file.close()
now = datetime.datetime.now()
fileday = '/var/www/myscripts/gas/'+now.strftime("%Y-%m-%d")+'.txt'
gasday = 0
if os.path.isfile(fileday):
file = open(fileday,"r")
gasday = float(file.read())
file.close()
gasday = gasday+0.01
file = open(fileday,"w")
file.write(str(gasday))
file.close()
oem = pycurl.Curl()
oem.setopt(oem.URL, 'http://emoncms.org/input/post.json?node=0
csv=0,'+str(gasday)+',0,0,'+str(gastotale)+'&apikey=dfb6ccf')
oem.perform()
laststate = 0
while True:
if (GPIO.input(10) == 1 ):
if (laststate == 0):
gastotale = gastotale+0.01
laststate=1
else:
laststate=0
time.sleep(30)

Categories

Resources