to invert a GPIO input - python

This is my Code to start my other Code where i defined my Laser to start.
But in this Code i want to have a Button which starts my other script if i put press it.
But what this code does is it activate my code continuous.
What can i change in it ?
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import os
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO.setmode(GPIO.BOARD)
GPIO.setup(15,GPIO.IN) #GPIO17
#input = GPIO.input(27)
#print ("input",input)
while True :
#inputValue = GPIO.input(11)
#print ("input01",inputValue)
#time.sleep(1)
erg= GPIO.wait_for_edge(15,GPIO.RISING, bouncetime=20)
print ("Input",2)
#if (GPIO.input(11) == GPIO.HIGH):
#if erg==15:
print ("Input",1)
time.sleep(3)
#inputValue = 1
os.system("python /home/pi/gpio.py")

When you run os.system('python /home/pi/gpio.py') you start new process and your main process get back to work on its while loop.
As I understood your idea was to wait until button is pressed and then go to some other state waiting for something new to happen.
You don't need to start new process just import module (doc). When button was clicked break loop and run code from the imported module.
Also you may find it interesting to replace wait_for_edge with event_detected method. More about it here.

Related

Need to take the whole python code into a function that can be access from another python file

import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time
def privacyfunc():
# Pin Definitions:
led_pin_1 = 7
led_pin_2 = 21
but_pin = 18
# blink LED 2 quickly 5 times when button pressed
def blink(channel):
x=GPIO.input(18)
print("blinked")
for i in range(1):
GPIO.output(led_pin_2, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(led_pin_2, GPIO.LOW)
time.sleep(0.5)
mqttBroker="mqtt.fluux.io"#connect mqtt broker
client=mqtt.Client("privacybtn") #create a client and give a name
client.connect_async(mqttBroker)#from the client -connect broker
while True:
client.publish("privacy", x)#publish this random number to the topic called temparature
print("Just published"+str(x)+"to Topc to privacy")#just print random no to topic temparature
break
def main():
# Pin Setup:
GPIO.setmode(GPIO.BOARD) # BOARD pin-numbering scheme
GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT) # LED pins set as output
GPIO.setup(but_pin, GPIO.IN) # button pin set as input
# Initial state for LEDs:
GPIO.output(led_pin_1, GPIO.LOW)
GPIO.output(led_pin_2, GPIO.LOW)
GPIO.add_event_detect(but_pin, GPIO.FALLING, callback=blink, bouncetime=10)
print("Starting demo now! Press CTRL+C to exit")
try:
while True:
x=GPIO.input(18)
print(x)
# blink LED 1 slowly
GPIO.output(led_pin_1, GPIO.HIGH)
time.sleep(2)
finally:
GPIO.cleanup() # cleanup all GPIOs
if __name__ == '__main__':
main()
need to take this whole code into a function that can be accessed from another python file.plz, help me with this coding part.
In the new python file call import module where module is the name of the file. Like led_blink.py would be import led_blink
Then you can call the methods like so:
led_blink.blink(channel)
This is assuming the files are in the same folder.
Easiest way that I do this is to take a .py file and put it in the same directory you created the python script you are working with. From there you can do the following code from The_Python_File import *
Additionally note that the "The_Python_File" is the name of the .py file that contains the function you are trying to call, but you do not include .py when importing the file.

correct way to handle GPIO interrupts when using time.sleep()

I have the following scenario. With a raspberry pi I have a main function which runs in a while loop and alternates tasks between calls to sleep. I would like a button press to interrupt the main loop and do another task for a certain amount of time before returning to the main loop. In reality I am displaying output on an LCD screen but I coded up this simpler example to illustrate the problem with my logic. I think things are getting crossed up because both functions seem to be active at the same time? I don't know the correct way to handle this scenario. Can someone suggest how to do this properly?
from time import sleep
import RPi.GPIO as GPIO
BUTTON_PIN = 2 # GPIO pin for mode button
def main():
print("mode1 part A")
sleep(4)
print("mode1 part B")
sleep(4)
def run_mode_two():
# I would like this function to full execute before retuning to main
print("mode2")
sleep(8)
# function to be called by interrupt
def button_released_callback(channel):
run_mode_two()
# intialize gpio for button
GPIO.setmode(GPIO.BCM)
GPIO.setup(
BUTTON_PIN,
GPIO.IN,
pull_up_down = GPIO.PUD_UP)
# interrupt to listen for button push
GPIO.add_event_detect(
BUTTON_PIN,
GPIO.RISING,
callback = button_released_callback,
bouncetime = 300)
while True:
main()
The following pseudo code for your reference. Only focus on the flow, please adapt it to your own needs.
mode = 1
def button_callback():
mode = 2
start_timer(5)
def timer_callback():
mode = 1
def loop():
if mode == 1:
# run code in mode 1
else:
# run code in mode 2
def main():
# init code here
# ...
while True:
loop()

Can't run file on boot-up with Raspberry Pi

I have tried multiple ways (crontab and rc.local) of going about this. I have triple checked my code and processes each time but to no avail.
I am making a father's day gift with a button that says his favorite word, "No!".
Every time I reboot, my program does not respond at all to the GPIO and the button attached.
Is it how I have things structured in my sloppy code?
I'm not native in Python so I beg of you to help me.
When ran from the terminal or through Thonny, it runs perfectly. But no matter what, doesn't boot at start-up!
Here is my rc.local
Here's my code for the program:
import pygame
from random import randint
import RPi.GPIO as GPIO
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
pygame.mixer.init()
#pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
proverbFile = 'proverbs/Pro1.mp3'
num = 5
def randNo ():
noFile = '/home/pi/Desktop/audio/no/No1.mp3'
print('Executed!')
default = 1
global num
pulled = 1
while num == pulled:
pulled = randint(1,4)
print('Same!')
num = pulled
print(num)
noFile = noFile.replace(str(default), str(num), 1)
print(noFile)
pygame.mixer.music.load(noFile)
pygame.mixer.music.play()
default = num
def button_callback(channel):
print("Button was pushed!")
randNo()
GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback)
#while True:
# keyPress = input('Press q to quit: ')
# if keyPress == 'q':
# break;
#GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) # Setup event on pin 10 rising edge
If you want a script to run when you boot into the LXDE environment, you could take a look at this Raspberry Pi forum post:
Navigate to ~/.config/lxsession/LXDE-pi
Open the autostart file in that folder:
$ sudo nano autostart
Add #midori on a new line. If you want to run something like a python script, put something like #python mypython.py on a new line. Running a script file would be #./superscript, but for some reason the script runs in an infinite loop (perhaps this will stop that).
Save and exit: Ctrl+X, Y, Enter
Restart your Raspberry Pi into the LXDE environment.
answer from here

Raspberry Pi crash during python program (OR how is it possible to kill Linux???)

I build a keypad activated sensor with a Raspberry Pi and Python. Everything seems to go well but after a few minutes and several keypad entries, the Pi has a total crash and switches off immediately - no error messages pop up.
The script will continously wait for a keypad entry and if the code is correct, switch on a sensor, if it's not you have to try again. If the sensor is activated you have to put in the correct numbers to avoid an alarm being triggered after 30s)
Could anyone point me in the direction of what might be the problem? Here are the things I've tried so far without success
1) Exchange Pi to new Pi 2
2) Different OS, both NOOBS and Raspbian Wheezy
3) Different sensor (accelerometer vs IR sensor)
4) Disconnect monitor, keyboard and use SSH connection via Cygwin
5) Get log file until crash - log file was empty after reboot
python bad_script &> full_log.txt
6) Different log file command: causes instant crash and is also empty after reboot:
python script.py >> /logdir/script.py.log 2>&1
The question is: how am I able to crash Linux? If it's a memory problem, isn't there a prevention in linux to stop processed before they appear?
Here is the full script I am running:
import sys
from time import sleep
import threading
import signal
from matrix_keypad import RPi_GPIO1
import RPi.GPIO as GPIO
import smbus
import time
passcode = [1,2,3,4] # this is the correct code you have to enter
kp = RPi_GPIO1.keypad(columnCount = 3)
alarm_active = threading.Event() # shared variable used to control the sensor monitoring thread
alarm_active.clear() # Clear the alarm initially
monitor_thread = None # Global variable used to store the monitoring thread
#Set up all the pins correctio
GPIO.setmode(GPIO.BCM)
PINIR=7
GPIO.setup(7, GPIO.IN) # infrad-sensor
#Now activate the kaypad and listen for keypad inputs
def digit():
r = None
while r == None:
r = kp.getKey()
return r
def get_keycode():
# Function to loop around reading 4 keypresses in a row
# Compare against chosen code
# If match, switch the alarm state
entered = []
while len(entered) < 4:
key = digit()
sleep(0.5)
print key
entered.append( key )
if entered == passcode:
entered = []
print "Code correct"
switch_alarm_state()
else:
# Just clear the keypad buffer if the wrong code went in
# Could say "BAD CODE!" here, or even force immediate alarm perhaps
print "Wrong Code - Try again"
GPIO.output(27, True) # let red LED blink as indicator that code was wrong
time.sleep(1)
GPIO.output(27, False)
entered = []
def switch_alarm_state():
# Function to control the state of the alarm
# If the alarm should be on, run a thread monitoring the sensor
# If the alarm should be off, make sure the thread is stopped
global monitor_thread
if alarm_active.is_set():
# If the alarm is currently set, stop it
print "Alarm was abolished"
GPIO.output(17, False) #switch green LED off
alarm_active.clear() # Signals to the monitor thread that we wish to shut it down
monitor_thread.join() # Wait until the monitor thread has stopped
else:
# Alarm is not currently set, so start the sensor monitor thread going
print "Alarm was activated"
GPIO.output(17, True)
monitor_thread = threading.Thread( target=sensor_monitor )
alarm_active.set()
monitor_thread.start()
def sensor_monitor():
# Function to be run in a separate thread, monitoring the sensor
alarm_timer = None # Variable to hold a timer object that will fire the alarm
while alarm_active.is_set():
#print xrota
if GPIO.input(PINIR):
print "Alarm has been triggered"
if alarm_timer is None:
alarm_timer = threading.Timer( 30.0, fire_alarm )
alarm_timer.start()
sleep(0.5)
# The alarm must have been deactivated to get here
# Stop any outstanding alarms and shutdown
if alarm_timer is not None:
alarm_timer.cancel()
return
def fire_alarm():
# Here you implement the actions to be carried out by an alarm
print "Alarm is send to server"
msg = "Alarm"
publish.single("alarm/demo",msg, hostname="52.17.194.125")
def shutdown_handler( signum, frame ):
# Shut down the child thread nicely
alarm_active.clear()
monitor_thread.join()
if __name__ == '__main__': # This is the Python way to check you are being directly run, and not just imported by another script
signal.signal( signal.SIGINT, shutdown_handler ) # If you stop the script with ctrl+C, make sure it shuts down properly
signal.signal( signal.SIGTERM, shutdown_handler )
try:
while True:
get_keycode()
except KeyboardInterrupt:
GPIO.cleanup()
print "Quit program"

Python "shutdown / reboot raspberry pi" script, using a single button

I got a piece of code in Python from here:
http://www.raspberry-pi-geek.com/Archive/2013/01/Adding-an-On-Off-switch-to-your-Raspberry-Pi
And I wanted to improve on it.
Since this is the first time I work with Python, I got stuck on understanding what actually happens.
Here is the code:
# Import the modules to send commands to the system and access GPIO pins
from subprocess import call
import RPi.GPIO as gpio
from time import sleep
gpio.setmode(gpio.BCM) # Set pin numbering to board numbering
gpio.setup(22, gpio.IN) # Set up pin 22 as an input
rebootBool = 0
# Define a function to keep script running
def main(pin):
while True:
#gpio.remove_event_detect(pin)
gpio.add_event_detect(22, gpio.RISING, callback=confirmation, bouncetime=200) # Set up an interrupt to look for button presses
sleep(5000000)
def confirmation(pin):
gpio.remove_event_detect(pin)
gpio.add_event_detect(22, gpio.RISING, callback=shutdown, bouncetime=200)
sleep(3) # if button has been pressed again within 3 seconds, shut down will happen
main(22)
def reboot(pin):
rebootBool = 1
call('reboot', shell=False)
exit(0)
# Define a function to run when an interrupt is called
def shutdown(pin):
gpio.remove_event_detect(pin)
gpio.add_event_detect(22, gpio.RISING, callback=reboot, bouncetime=200)
sleep(3) # if the button has been pressed for a third time, within 3 seconds, Pi will reboot
if rebootBool == 0: # Just to make sure a halt is not called after the 3 seconds have passed, if reboot is called
call('halt', shell=False)
exit(0)
main(22) # Run the loop function to keep script running
What I want to do is this:
If button is pressed once, a confirmation function is executed, in which it resets the button to call the shutdown function, if it's pressed within 3 seconds.
Else, resume with the main loop
In the shutdown function, if it's pressed again (within 3 seconds), it resets to call the reboot function.
Else go on, and shut down
What happens is this:
If I press the button twice or three times, it tells me that gpio.add_event_detect is already defined, when it tries to define it in main().
So it doesn't change it, and if I press it one more time, it calls the shutdown function.
What I don't understand is:
Why does it want to define the gpio event in main, when the actual function is either reboot or shutdown (and it should call either reboot or shutdown)?
Because a callback function is running in a separate thread. This means, for example, when you call any callback function in the main loop it still works(main loop), and thus it happens when you call a function gpio.add_event_detect from a callback function(thread #1) and from the main loop(thread #2) at the same time. It's typical race condition.
You can check it by running this code:
#!/usr/bin/python
# Import the modules to send commands to the system and access GPIO pins
from subprocess import call
import RPi.GPIO as gpio
from time import sleep
gpio.setmode(gpio.BCM) # Set pin numbering to board numbering
gpio.setup(22, gpio.IN, pull_up_down=gpio.PUD_DOWN) # Set up pin 22 as an input
rebootBool = 0
# Define a function to keep script running
def main(pin):
while True:
print "main loop"
gpio.remove_event_detect(22)
gpio.add_event_detect(22, gpio.RISING, callback=confirmation, bouncetime=200) # Set up an interrupt to look for button presses
sleep(1)
#raw_input()
def confirmation(pin):
print "confirmation1"
sleep(5)
print "confirmation2"
gpio.remove_event_detect(22)
gpio.add_event_detect(22, gpio.RISING, callback=shutdown, bouncetime=200)
sleep(5) # if button has been pressed again within 3 seconds, shut down will happen
gpio.remove_event_detect(22)
main(22)
def reboot(pin):
rebootBool = 1
print "reboot"
#call('reboot', shell=False)
exit(0)
# Define a function to run when an interrupt is called
def shutdown(pin):
print "shutdown"
gpio.remove_event_detect(pin)
gpio.add_event_detect(22, gpio.RISING, callback=reboot, bouncetime=200)
sleep(3) # if the button has been pressed for a third time, within 3 seconds, Pi will reboot
if rebootBool == 0: # Just to make sure a halt is not called after the 3 seconds have passed, if reboot is called
#call('halt', shell=False)
print "halt"
exit(0)
main(22) # Run the loop function to keep script running
So, after Anton Glukhov explained me what to look out for, I found out how to solve every issue, and now it's working flawlessly.
This is the link that better explains what I did:
http://sourceforge.net/p/raspberry-gpio-python/wiki/Inputs/
Unfortunately, I wasn't able to do it any other way than use a while loop in the main function.
But since there is nothing critical going on, a sleep of 1 second has been added to each loop, ensuring minimal CPU usage.
I am sharing the final code here, in hopes that it might help others:
# Import the modules to send commands to the system and access GPIO pins
from subprocess import call
import RPi.GPIO as gpio
from time import sleep
from os import system
gpio.setmode(gpio.BCM) # Set pin numbering to BCM numbering
gpio.setup(22, gpio.IN) # Set up pin 22 as an input
def confirmation(pin):
#print "Confirmation Function on pin %d" % pin
system('echo Press again to confirm Shut down menu! | wall -n') # let all logged in users know
gpio.remove_event_detect(pin)
gpio.add_event_detect(pin, gpio.RISING, bouncetime=200)
sleep(2) # if button has been pressed again within 2 seconds, shut down function is called
if gpio.event_detected(pin):
shutdown(pin)
else:
#print "canceled"
system('echo Shut down canceled! | wall -n') # let all logged in users know
main()
def resetPin(pin):
#print "Pin %d has been reset" % pin
gpio.remove_event_detect(pin)
gpio.add_event_detect(pin, gpio.RISING, bouncetime=200)
def reboot(pin):
#print "Reboot Function on pin %d" % pin
call('reboot', shell=False)
exit(0)
# Define a function to run when an interrupt is called
def shutdown(pin):
#print "ShutDown function on pin %d" % pin
system('echo Press again if you want to reboot instead of shut down! | wall -n') # let all logged in users know
gpio.remove_event_detect(pin)
gpio.add_event_detect(pin, gpio.RISING, bouncetime=200)
sleep(2) # if the button has been pressed for a third time, within 2 seconds, Pi will reboot
if gpio.event_detected(pin):
reboot(pin)
else:
call('halt', shell=False)
exit(0)
# Define a function to keep script running
def main():
#print "Main Function"
resetPin(22)
while True:
sleep(1)
if gpio.event_detected(22):
confirmation(22)
main() # Run the main function to keep script running

Categories