I'm almost done with a project but when I give a value that is to high. I barely hear de buzzer playing because it only plays for a sec. Does someone know how to play the buzzer sound longer?
import pycom
import machine
import time
from machine import Pin
import socket
from network import LoRa
import binascii
import array
from machine import PWM
############### Weightsensor ###############
def main():
while True:
adc = machine.ADC() # create an ADC object
apin = adc.channel(pin='P16') # create an analog pin on P16
val = apin() # read an analog value
if val < 20:
print(val)
print("Weight is good")
binaryString = bin(val)
print(binaryString)
time.sleep(5)
if val > 20:
print(val)
print("Weight is to high")
binaryString = bin(val)
print(binaryString)
# 50% duty cycle at 38kHz.
pwm = PWM(3, frequency=78000) # use PWM timer 0, with a frequency of 5KHz
# create pwm channel on pin P12 with a duty cycle of 50%
pwm_c = pwm.channel(0, pin='P20', duty_cycle=1.0)
pwm_c.duty_cycle(0.3) # change the duty cycle to 30%
time.sleep(5)
if __name__ == "__main__":
main()
The buzzer plays in the second "if" statement.
Can someone help me out please?
Kind regards
I see multiple issues in your code: Why do you redefine again and again adc and apin in your while loop? move it before while True
Duty in your PWN should not influence pitch of your buzzer, so my advice would be omit all duty settings, or at least leave it to like 250 (experiment with it)
Pitch of buzzer is frequency value in your PWM declaration. You can change it with pwm.frequency(hertz) somewhere later. Or find best working setup in console by manualy entering commands.
How long will it sound is based on time.sleep()
In my opinion code should be something like that (have not tested on board):
import pycom
import machine
import time
from machine import Pin
import socket
from network import LoRa
import binascii
import array
from machine import PWM
############### Weightsensor ###############
def main():
adc = machine.ADC() # create an ADC object
apin = adc.channel(pin='P16') # create an analog pin on P16
# 50% duty cycle at 38kHz.
pwm = PWM(3, frequency=78000) # use PWM timer 0, with a frequency of 5KHz
# create pwm channel on pin P12 with a duty cycle of 50%
pwm_c = pwm.channel(0, pin='P20')
while True:
val = apin() # read an analog value
if val < 20:
print(val)
print("Weight is good")
binaryString = bin(val)
print(binaryString)
time.sleep(5)
if val > 20:
print(val)
print("Weight is to high")
binaryString = bin(val)
print(binaryString)
pwm_c.freq(500)
time.sleep(5)
pwm_c.freq(0)
if __name__ == "__main__":
main()
Related
I am trying to implement a sensor-based traffic light for a school project. By that I mean, there is a sound sensor LM393 that acts as a switch. When it detects a sound, it will change the sequence of the traffic lights. For example, the traffic light would be something like this: Red LED for 2 sec, turn off red, yellow LED for 2 sec, turn off yellow, green led for 2 sec, turn off green, then this cycle repeats itself. If a sound is detected, the sequence is interrupted and the green light immediately becomes green for 5 sec and then the normal cycle starts again.
This is what I have so far:
import RPi.GPIO as GPIO
from time import sleep
from threading import Thread
from gpiozero import LED
#GPIO SETUP
red = LED(17)
gre=LED(24)
yel = LED(27)
channel = 23
emer_detec = False
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN, pull_up_down = GPIO.PUD_UP)
def sound():
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=1000) # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(channel, callback) # assign function to GPIO PIN, Run function on change
def regular():
while True:
if not GPIO.input(channel):
red.on()
sleep(2)
red.off()
yel.on()
sleep(2)
yel.off()
gre.on()
sleep(2)
gre.off()
def callback(channel):
print('Emergency vehicle detected')
red.off()
yel.off()
gre.on()
sleep(5)
gre.off()
sound_thread= Thread(target=sound)
sound_thread.daemon= True
sound_thread.start()
regular_thread= Thread(target=regular)
regular_thread.daemon= True
regular_thread.start()
# infinite loop
while True:
pass
At first, the two threads are running in parallel when there is a sound and all lights go off as expected. However, when the green light is turned on, the normal cycle is also running. How can I stop the normal cycle thread when the other thread is working? Is there any way to do this without using threads?
One quick way to solve this might be to have some kind of global flag that handles the state of the system. For example,
IS_REGULAR = True
def regular():
while True:
if not GPIO.input(channel) and not IS_REGULAR:
for col in [red, yel, gre]:
col.on()
sleep(2)
col.off()
if not IS_REGULAR: break
def callback(channel):
global IS_REGULAR
IS_REGULAR = False
print('Emergency vehicle detected')
red.off()
yel.off()
gre.on()
sleep(5)
gre.off()
IS_REGULAR = True
I'm trying to collect sound data from a sound sensor connected to a raspberry pi 4. Right now I have it set up where it will print 1 every time sound is detected. However, when I try to add an else statement to print 0 when no sound is detected, it will only print 0 even if there is constant sound being played.
This is the code that works fine displaying 1 every time sound is detected.
import RPi.GPIO as GPIO
import time
SND_SNSR = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(SND_SNSR,GPIO.IN)
while True:
if (GPIO.input(SND_SNSR) == GPIO.LOW):
print("1")
time.sleep(0.1)
And this is the code I have for trying to get it to display every 6 seconds and display either 1 or 0 for sound or no sound but it's not working.
import RPi.GPIO as GPIO
import time
SND_SNSR = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(SND_SNSR,GPIO.IN)
while True:
if (GPIO.input(SND_SNSR) == GPIO.LOW):
print("1")
else:
print("0")
time.sleep(6)
Thanks for any help.
My task is to create a program, which will turn heater on if temperature in the house is less than 16°C or turning it off if it's more than 16°C. I decided to make it a bit useful and import the timer. I want to know how is it possible to repeat function, which allows to turn heater on or off, after "n" time inputted by user.
My current code is:
import time
import random
def main():
temp = random.randint(-15, 35)
print("Current temperature in the house:", temp,"°C")
time.sleep(1)
if temp <= 16:
print("It's cold in the house!")
t = input("How long should the heating work? Enter time in 1.00 (hours.minutes) format:")
print("Heating will work for:", t)
print("House Heating status: ON")
time.sleep() //The timer should start here for the time entered by the user
if temp > 16 and temp <= 25:
print("House Heating status: OFF")
if temp => 26:
print("House Cooler status: ON")
main()
Which technique should I use to add this timer?
Assuming your main function handles the call to time.sleep already, a simple way to repeat over and over would be to put your function in an infinite loop:
while True:
main()
Another way would be to have your main function return an integer of how long to wait until it should be called again. This decouples the waiting from the main logic.
def main():
...
t = input("How long should the heating work? Enter time in 1.00 (hours.minutes) format:")
...
return int(t)
while True:
wait_time = main()
time.sleep(wait_time)
I'm working on PIR sensor in order to detect the movement of human beings. Here is below the code that currently I am using and I just need to make a counter inside the loop in order to count the # of movements. Thanks in advance!!
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.IN) # PIR motion sensor
GPIO.setup(3, GPIO.OUT) #LED output pin
while True:
i=GPIO.input(11)
if i==0: #sensor is LOW
print "Not Occupied",i
GPIO.output(3, 0) #Turn OFF LED
time.sleep(0.1)
elif i==1: # sensor is HIGH
print "Occupied",i
GPIO.output(3, 1) #Turn ON LED
time.sleep(0.1)
When I was starting with Raspberry Pi, I was using only RPi.GPIO library, but now I am using only gpiozero library. I think, it is more clear than RPi.GPIO
Here is my solution of your problem using library gpiozero instead of RPi.GPIO:
from gpiozero import LED, MotionSensor
from signal import pause
pir = MotionSensor(11)
led = LED(3)
motion_counter = 0
def on_motion():
global motion_counter
led.on()
motion_counter += 1
print(motion_counter)
def on_no_motion():
led.off()
pir.when_motion = on_motion
pir.when_no_motion = on_no_motion
pause()
More about this great library: https://gpiozero.readthedocs.io/en/stable/
Your question is kind of confusing but here is how you would set a counter
counter = 0
while True:
counter += 1
i=GPIO.input(11)
if i==0: #sensor is LOW
print "Not Occupied",i
GPIO.output(3, 0) #Turn OFF LED
time.sleep(0.1)
elif i==1: # sensor is HIGH
print "Occupied",i
GPIO.output(3, 1) #Turn ON LED
time.sleep(0.1)`
print(counter)
Dear Stackoverflow Community!
I am currently on my first Project working with a Raspberry Pi. The task is to implement a TY-010 Photo Interruptor Sensor. What I want to do is following:
I want to count the interruptions in a given time (i.e 2 seconds). So something like that(not C, in Python):
d count how many Interruptions there are.
int i = 0
while(time != 3){
if(outputFunction == True)
i += 1;
}
You can find the whole Code beneath:
import RPi.GPIO as GPIO
import time
GPIO_PIN = 24
GPIO.setup(GPIO_PIN, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
print "Sensor-Test [Press STRG+C, to exit the Test]"
def outputFunction(null):
print("Signal detected")
GPIO.add_event_detect(GPIO_PIN, GPIO.RISING, callback=ausgabeFunktion, bouncetime=100)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()
I am thankful for any help or advise !
You have wrong defined ouputFunction, if you want a function without arguments just leave it empty, like this:
def outputFunction():
print("Signal detected")
You can add a statement to verify if have passed x seconds, if you do time.sleep() you are stopping your code and if you press the button it won't work, so do it this way:
try:
t_to_wait = 2 #Set to 2 secs
t1 = time.time() #Get the start time
while True:
if GPIO.input(GPIO_PIN) == 1:
outputFunction()
if t1-time.time() > t_to_wait:
break #Exit the loop if have passed t_to_wait seconds
except KeyboardInterrupt:
GPIO.cleanup()
I also would recommend you to read some examples because it seems that you don't know python very well and the use of the GPIO module