I am attempting to make a simple python script that uses a moisture sensor on GOIP 21 and will output text on a display.
What I have:
Raspberry Pi 4 4GB
Arducam 1602 16x2 LCD Display Module Based on HD44780
KeeYees 5 Pcs High Sensitivity Soil Moisture Sensor Module with Female to Female Jump Wires, Sensor Module Watering System Manager for Arduino TE215
Breadboard 830
It's only a learning attempt, after I figure this out I plan on buying better sensors and actually having them display accurate percentages. For not a simple moisture detected vs no-detected is okay with me.
My code seems to work for outputting to the console, however when I try to output to the LCD, it gives some weird characters and stops. Not sure what to do as i'm not a python wiz (you'd think id be more like php, but nah lol).
Here is my code
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import sys
sys.path.append('/home/pi/lcd')
import lcd
#GPIO SETUP
moist1 = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(moist1, GPIO.OUT)
def callback(moist1):
if GPIO.input(moist1):
lcd.GPIO.cleanup()
lcd.lcd_init()
lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
lcd.lcd_string("Water Is Good", 2)
lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
lcd.lcd_string("Don't Add", 2)
lcd.GPIO.cleanup()
else:
lcd.GPIO.cleanup()
lcd.lcd_init()
lcd.lcd_byte(lcd.LCD_LINE_1, lcd.LCD_CMD)
lcd.lcd_string("Add Water Now!", 2)
lcd.lcd_byte(lcd.LCD_LINE_2, lcd.LCD_CMD)
lcd.lcd_string("!!!!!!!!!!!!!!", 2)
lcd.GPIO.cleanup()
GPIO.add_event_detect(moist1, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW
GPIO.add_event_callback(moist1, callback) # assign function to GPIO PIN, Run function on change
# infinite loop
while True:
time.sleep(1)
I can't figure out what I am doing wrong. Please let me know if you see it. Thanks
Related
I am trying to make wedding guest answer phone for my sister. The basic idea of these things is you pick up the handset, hear a message from the host, leave you own, replace the handset, and the recording stops and saves. I have set all of the hardware up fine, it works, but as I have essentially no experience with coding getting all of the individual aspects to work is my issue.
For the recording aspect scipy seems to work the best, I have been using this for 5 second test recordings.
import sounddevice as sd
from scipy.io.wavfile import write
import wavio as wv
import uuid
freq = 44100
duration = 5
recording = sd.rec(int(duration * freq),
samplerate=freq, channels=2)
sd.wait()
write("recording0_"+str(uuid.uuid4())+".wav", freq, recording)
The main issue is these messages are only 5 seconds, I don't know how to make them start recording after the host message and stop when the handset is replaced.
The following is the code that I have been using to play a test for the host message when the handset is picked up.
import RPi.GPIO as gpio
import pygame
gpio.setmode(gpio.BCM)
gpio.setup(23, gpio.IN, pull_up_down=gpio.PUD_UP)
gpio.setwarnings(False)
def rising(channel):
gpio.remove_event_detect(23)
print ('Button up')
pygame.mixer.init()
sound = pygame.mixer.Sound('/home/pi/Documents/E and R/test1.wav')
playing = sound.play()
while playing.get_busy():
pygame.time.delay(100)
gpio.add_event_detect(23, gpio.FALLING, callback=falling, bouncetime=10)
def falling(channel):
gpio.remove_event_detect(23)
print ('Button down')
gpio.add_event_detect(23, gpio.RISING, callback=rising, bouncetime=10)
gpio.add_event_detect(23, gpio.FALLING, callback=falling, bouncetime=10)
try:
raw_input()
except KeyboardInterrupt:
gpio.cleanup()
gpio.cleanup()
There are a few problems with this, I have tried changing the order of various aspects and either when you lift the handset and the audio is played it doesn't read if the handset is replaced while the audio is playing. Or in another version if you tap the handset switch a bunch of times it layers copies of the audio on top of each other.
Also I know that raw_input() is not used in python 3 but if I just use input() the code doesn't work and if I omit the whole section it doesn't work.
Basically, I'm illiterate and any help smashing this all together and showing me how to get audio recordings for an in-determinant length of time would be greatly appreciated.
Also if this helps I'm using a Raspberry pi 4 and Python 3.9.2.
I have a friend setting up an irrigation system at his house. He is telling me it won't detect moisture after the first run-through, regardless of whether there is moisture or not. In his own words:
"I’m trying to figure out how to make my program restarts the detection process. Like say my sensor is in soil and it detects water then after a certain period I need it to run again. My problems is that when I run it again and it’s sitting in a cup of water, it’s doesn’t detect the water. I read something about maybe checking the state of the sensor but I couldn’t get anywhere.
Also would I would the delay function to continuously run it in intervals."
He sent me his code today, and I would like to help him, although I am new to Python. Here is the code.
#!/usr/bin/python
import RPi.GPIO as GPIO
import time
#GPIO SETUP
channel = 20
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel, GPIO.IN)
def callback(channel):
if GPIO.input(channel)==0:
print (" Water Detected!")
else:
print ( 'NO Water Detected!')
GPIO.add_event_detect(channel, GPIO.FALLING, bouncetime=300) # 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
# infinite loop
while True:
time.sleep(1)
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
from time import sleep # Import the sleep function from the time module
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(3, GPIO.OUT, initial=GPIO.LOW) # Set pin 8 to be an outputpin and set initial value to low (off)
while True: # Run forever
GPIO.output(3, GPIO.HIGH) # Turn on
sleep(1) # Sleep for 1 second
GPIO.output(3, GPIO.LOW) # Turn off
sleep(1) # Sleep for 1 second
I have a setup in which I have a motor turning a 5cm diameter shaft at about 1 revolution a second. I need to stop the motor after a predetermined number of revolutions - lets say 10 for now.
The sensor mechanism I am using is simply a magnet and reed switch. The following script works well to record each time the switch is triggered.
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
button1=22
GPIO.setup(button1,GPIO.IN,pull_up_down=GPIO.PUD_UP)
while(1):
if GPIO.input(button1)==0:
print "Button 1 Pressed"
sleep(0.5)
Whilst this script runs the motor -
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
Motor1A = 19
Motor1B = 21
Motor1E = 23
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)
print "Going forwards"
GPIO.output(Motor1A,GPIO.LOW)
GPIO.output(Motor1B,GPIO.HIGH)
GPIO.output(Motor1E,GPIO.HIGH)
GPIO.cleanup()
In a nutshell then what I am seeking is a combined script which counts the number of event inputs on pin 22 and then turns pin 23 (the motor enable pin) to LOW on the count of 10.
Many thanks
Nick
So I'm trying to use a servo (Doman s0306d) with the pi camera, tried running this script I found to test the motor, it starts running but doesn't stop unless I manually unplug it from the breadboard.
import RPi.GPIO as IO # calling for header file for GPIO’s of PI
import time # calling for time to provide delays in program
IO.setwarnings(False) # do not show any warnings
IO.setmode (IO.BCM) # programming the GPIO by BCM pin numbers. (like PIN29 as‘GPIO5’)
IO.setup(19,IO.OUT) # initialize GPIO19 as an output
p = IO.PWM(19,50) # GPIO19 as PWM output, with 50Hz frequency
p.start(7.5) # generate PWM signal with 7.5% duty cycle
time.sleep(4)
for x in range(0,5): # execute loop forever
p.ChangeDutyCycle(7.5) # change duty cycle for getting the servo position to 90º
time.sleep(1) # sleep for 1 second
p.ChangeDutyCycle(12.5) # change duty cycle for getting the servo position to 180º
time.sleep(1) # sleep for 1 second
p.ChangeDutyCycle(2.5) # change duty cycle for getting the servo position to 0º
time.sleep(1) # sleep for 1 second
p.ChangeDutyCycle(0)
p.stop()
IO.cleanup()
Any ideas ? Thank you.
[EDIT] The servo you are using is a "continuous" servo - so you need to give it the zero speed or "STOP" setting pulse width of 1500us (according to the website http://www.domanrchobby.com/content/?150.html). I haven't used PWM on the pi but if the percentages are of the 50Hz pulse rate (20ms interval) then that should be your 7.5% centre value. You need to make sure the servo gets that pulse before your code exits.
[Original] You are setting the duty cycle to 0 when you exit, which will probably mean the servo doesn't get any pulses. Some servos will stop sometime after they don't get pulses, but some servos (particularly digital servos, but not all) will continue to try achieve the setting from the last pulse they received. Suggest you leave the setting at the mid range 7.5 which you know the servo can achieve and delay for a little while before cleaning up.
Hello i have been trying to work this one out by myself for over a week now but i think its time to ask the question.
This is my first program with python and i intend to control my aquarium with various functions.
The first function i am programming is a lighting schedule (shortened the code a bit for this post)
The code executes okay but the GPIO pin 2 isnt turning on and off properly. and im also getting a "runtimewarning this channel is already in use"
Can i please have a bit of guidance, im sure its something simple and noob :)
here is my code
#Lighting Program
import RPi.GPIO as GPIO
import datetime
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
#Declare Lighting On/Off Times
on_time_Monday = 600
off_time_Monday = 2330
rest of the days here
#Find out what day of the week it is
day = datetime.datetime.now()
day_of_week = day.isoweekday()
#find out what time it is
Current_time = datetime.datetime.strftime(datetime.datetime.now(),'%H%M')
#convert the time to an int so it can be compared
Current_time_INT = int(Current_time)
#Schedule on / off
if (day_of_week == 1) and (Current_time_INT > on_time_Monday and Current_time_INT < off_time_Monday) :
Light_on_off = 'on'
Using 'elif' for tues wed etc etc
else :
Light_on_off = 'off'
Now enable the outputs
#CALL OUTPUTS ON / OFF
GPIO.setup(2, GPIO.OUT)
if Light_on_off == 'on':
GPIO.output(2, GPIO.HIGH)
else:
GPIO.output(2, GPIO.LOW)
GPIO.cleanup()
In my experience "runtimewarning this channel is already in use" comes up when you have previously setup the GPIO pin, but haven't called
GPIO.cleanup().
I see that in your code, but I would suspect that for some reason it is not actually running.
Sometimes it is helpful to test out a GPIO pin in the terminal by running the python interpreter. It is especially useful to test if you have wired your circuit correctly.
>>>import RPi.GPIO as GPIO
>>>GPIO.setmode(GPIO.BCM)
>>>GPIO.setwarnings(False)
>>>GPIO.setup(2, GPIO.OUT)
>>>GPIO.output(2, GPIO.HIGH)
>>>GPIO.input(2)
True
>>>GPIO.output(2, GPIO.LOW)
>>>GPIO.input(2)
False
>>>GPIO.cleanup()
If your circuit is wired correctly you should be able to turn your light on and off this way. When you call GPIO.input(2) the interpreter responds with the current state of the pin. This enables you to make sure the pin is working even without a working external circuit. Once you know that it is working you can move on from there.
One simple way to flip a light switch on and off would be to use cron jobs. I have used this method successfully in the past.
You can write two short scripts, one that turns the light on, and one that turns it off.
Example: lightOn.py (replace 'HIGH' with 'LOW' for lightOff.py)
#!/usr/bin/env python
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(2, GPIO.OUT)
GPIO.output(2, GPIO.HIGH)
GPIO.cleanup()
Now you can create a crontab to automatically run the script at the times you want.
For example:
0 6 * * * /home/pi/lightOn.py
0 18 * * * /home/pi/lightOff.py
Would turn the light on everyday at 6AM and off at 6PM