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
Related
**I use this code.but it is not working. can someone help me?I got this type of error
raise IOError("{0} is set up as an INPUT and can therefore not be written to"
OSError: Digital pin 8 is set up as an INPUT and can therefore not be written to **
import pyfirmata
import time
board = pyfirmata.Arduino('/dev/ttyACM0')
start=0
end=0
trigpin = board.get_pin('d:7:o')
echopin= board.get_pin('d:8:i')
trigpin.write(0)
time.sleep(5)
while True:
trigpin.write(1)
time.sleep(3)
trigpin.write(0)
while echopin.write(0):
pass
start = time.time()
while echopin.write(1):
pass
end = time.time()
print((end - start)/58.0*1000000)
time.sleep(1)
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)
I have bought an Adafruit PCA9685 and completed the library installation, however, I have no clue of how to Program it. I want to base it on the following code I wrote:
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub
GPIO.setmode(GPIO.BCM)
PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27
GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)
FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 # flickering effect
# Duty Cycle (0 <= dc <=100)
living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)
porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)
fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)
# PubNub
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def _callback(m, channel):
print(m)
dc = m['brightness'] *10
if m['item'] == 'light-living':
living.ChangeDutyCycle(dc)
elif m['item'] == 'light-porch':
porch.ChangeDutyCycle(dc)
elif m['item'] == 'fireplace':
fire.ChangeDutyCycle(dc)
def _error(m):
print(m)
pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)
try:
while 1:
pass
except KeyboardInterrupt:
GPIO.cleanup()
sys.exit(1)
I dont know if on this its similar. I bought it because I wanted to be able to control more LED's with PWM from the Raspberry pi. I looked into it and found all kinds of weird commands and terms specific to this Chip.
Thanks!
First, If you look at page 29 of the data sheet (fig. 15) it shows that for Direct LED connection, you need to connect your LEDs inverted. i.e. connect the ground of the LED to the PWM line on the PCA9685 and the positive of the LED to the V+
Code is pretty simple (below is for an Arduino) And you use the function pwm.setPWM(uint8_t num, uint16_t on, uint16_t off) to turn the LEDs on and off and to different levels of brightness.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
void setup()
{
Serial.begin(9600);
pwm.begin();
pwm.setPWMFreq(1600); //This is the maximum PWM frequency
pwm.setPWM(1,0,4095); //this turns on the LED connected to channel one (I suspect the only line you're really looking for)
}
Hope that answers your question!
See below how to do this in python
import Adafruit_PCA9685
pwm = Adafruit_PCA9685.PCA9685()
pwm.set_pwm_freq(60)
# Demo using LED on Channel 12 of the PCA9685
# Wire up the LED on Channel 12 such that
# Shortleg of LED goes to GND and
# Long leg goes to PWM pin on channel 12
pwm.set_pwm(12,0,4095) # Full bright
time.sleep(5)
pwm.set_pwm(12,1024,3072) # half bright
time.sleep(5)
pwm.set_pwm(12,0,0) #off
time.sleep(5)
I just finished all of the prototyping of this project:, and I encountered 2 problems: https://www.pubnub.com/blog/2015-03-17-building-a-model-smart-home-with-raspberry-pi/
I cant run all of the programs at once(Humidity and Temperature, LEDs, Micro Servo motors, etc...)
I can't have more than three LED's (technically two)
What can I do to run everything at once, so it is all displayed in the WEB UI? How can I have more LED's, since the limit is 50mah which is about 2 LED's? (they can be three per 'room', so three per GPIO pin or just per GPIO). I dont see hoe it could work with such a power limit. Also, they need to be controlled with PWM. There simply isn't enough power on the Raspberry Pi!
the code for the DHT22 sensor is:
import time
import sys
from pubnub import Pubnub
import Adafruit_DHT as dht
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def callback(message):
print(message)
#published in this fashion to comply with Eon
while True:
h,t = dht.read_retry(dht.DHT22, 4)
temp='{0:0.1f}'.format(t)
hum='{0:0.1f}'.format(h)
message = {'temperature': temp, 'humidity': hum}
print 'Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(t, h)
pubnub.publish(channel=channel, message=message, callback=callback, error=callback)
the code for the led's is:
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub
GPIO.setmode(GPIO.BCM)
PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27
GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)
FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 # flickering effect
# Duty Cycle (0 <= dc <=100)
living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)
porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)
fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)
# PubNub
pubnub = Pubnub(publish_key='demo', subscribe_key='demo')
channel = 'pi-house'
def _callback(m, channel):
print(m)
dc = m['brightness'] *10
if m['item'] == 'light-living':
living.ChangeDutyCycle(dc)
elif m['item'] == 'light-porch':
porch.ChangeDutyCycle(dc)
elif m['item'] == 'fireplace':
fire.ChangeDutyCycle(dc)
def _error(m):
print(m)
pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)
try:
while 1:
pass
except KeyboardInterrupt:
GPIO.cleanup()
sys.exit(1)
Thanks!
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)