GPIO pins won't work anymore halfway through my program - python

So, I am programming in python on my pi. Through a cwiid library I am connecting my wii controller. This works fine.
But, after my wii controller connects trough bluetooth, suddenly the leds won't work.
The same line of code works before connecting, but doesn't work anymore after connecting. How is this possible?
My complete code:
if __name__ == '__main__':
from sys import path
path.append("..")
import RPi.GPIO as GPIO
from time import sleep
import os
import cwiid
from MotorPwm2 import MotorPwm
from GPIOFuckUp import GPIOFuckUp
from Basis import Basis
GPIOFuckUp()
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
motor = MotorPwm([10, 9, 8, 7])
basis = Basis()
startbool = False
running = True
left_light = 21
right_light = 20
left_siren = 16
right_siren = 26
GPIO.setup(left_light, GPIO.OUT)
GPIO.setup(right_light, GPIO.OUT)
GPIO.setup(left_siren, GPIO.OUT)
GPIO.setup(right_siren, GPIO.OUT)
left_pin = GPIO.PWM(left_light, 1000)
right_pin = GPIO.PWM(right_light, 1000)
left_pin_s = GPIO.PWM(left_siren, 1000)
right_pin_s = GPIO.PWM(right_siren, 1000)
left_pin.start(100)
right_pin.start(100)
left_pin_s.start(0)
right_pin_s.start(0)
# Code above works. Leds turn on, with no problems.
def turn_on_left():
dim_left(100)
def turn_on_right():
dim_right(100)
def turn_on_lefts():
dim_lefts(100)
def turn_on_rights():
dim_rights(100)
def turn_on():
print 'aan'
dim_left(100)
dim_right(100)
def turn_off_lefts():
dim_lefts(0)
def turn_off_rights():
dim_rights(0)
def turn_off_left():
dim_left(0)
def turn_off_right():
dim_right(0)
def turn_off():
dim_left(0)
dim_right(0)
def dim(percentage):
dim_left(percentage)
dim_right(percentage)
def dim_left(percentage):
left_pin.ChangeDutyCycle(percentage)
print 'left'
def dim_right(percentage):
right_pin.ChangeDutyCycle(percentage)
print 'right'
def dim_lefts(percentage):
left_pin_s.ChangeDutyCycle(percentage)
def dim_rights(percentage):
right_pin_s.ChangeDutyCycle(percentage)
def siren_loop():
while running:
dim_lefts(100)
dim_rights(100)
sleep(0.05)
turn_off_lefts()
turn_off_rights()
sleep(0.05)
dim_rights(100)
sleep(0.05)
turn_on_rights()
sleep(0.05)
dim_lefts(100)
sleep(0.05)
dim_lefts(0)
sleep(0.05)
# Def things above also work. Copied the code in another file just to try
the leds, and that also worked.
button_delay = 0.1
print 'Press 1 + 2 on your Wii Remote now ...'
# Here the controller is connecting. After it is connected the leds turn of
# Before the following print lines are printed.
# Connect to the Wii Remote. If it times out
# then quit.
try:
wii = cwiid.Wiimote()
#GPIO.output(PIN_LED, 0)
except RuntimeError:
print "Error opening wiimote connection"
#GPIO.output(PIN_LED, 0)
# Uncomment this line to shutdown the Pi if pairing fails
os.system("sudo reboot")
quit()
print 'Wii Remote connected...\n'
print 'Press some buttons!\n'
print 'Press PLUS and MINUS together to disconnect and quit.\n'
wii.rpt_mode = cwiid.RPT_BTN
while True:
buttons = wii.state['buttons']
# If Plus and Minus buttons pressed
# together then rumble and quit.
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing connection ...'
wii.rumble = 1
#GPIO.output(PIN_LED, 1)
sleep(1)
wii.rumble = 0
#GPIO.output(PIN_LED, 0)
os.system("sudo reboot")
exit(wii)
# Button presses below work and print the correct lines. Just no leds :(
if (buttons & cwiid.BTN_LEFT):
print 'Left pressed'
motor.left_forward(50)
sleep(button_delay)
elif (buttons & cwiid.BTN_RIGHT):
print 'Right pressed'
motor.right_forward(50)
sleep(button_delay)
elif (buttons & cwiid.BTN_UP):
print 'Up pressed'
motor.forward(100)
sleep(button_delay)
elif (buttons & cwiid.BTN_DOWN):
print 'Down pressed'
motor.backward(100)
sleep(button_delay)
elif (buttons & cwiid.BTN_A):
print 'A'
if startbool == False:
print 'start aan'
startbool = True
sleep(0.5)
else:
print 'start uit'
startbool = False
sleep(0.5)
elif (buttons & cwiid.BTN_1):
if running:
turn_on()
sleep(5)
print '1'
print 'Licht 5 sec aan'
elif (buttons & cwiid.BTN_2):
print '2'
print 'sirene 5 sec aan'
siren_loop()
sleep(5)
else:
GPIO.cleanup()
So, for example, the start values turn the leds on when I run the program. This happens, the leds light up. But then, after the wii remote connects, they turn off and are impossible to turn on again.

After trying for another few hours, I finally found the problem.
The last line said:
else:
GPIO.cleanup()
Which resetted all the pins, hence they were not working. Deleting the else made everything work again.
Now I know the problem it seems so simple xD

Related

Freezing scripit Raspberry Pi4 GPIO omx player button triggered video

I used the script for triggered video by GPIO Rapsberry Pi4 buttons from github site Jesse Cake RPi Triggered video player https://github.com/JesseCake/RPi_Triggered_video_player
Mr. Cake did great job about it and the script with GPIO works great but I have two problems with it.
Main setup is: Raspberry Pi4, Rasbian Legacy Lite (Buster), working pins 26, 20, 16 which are shorten to the ground pin on rpi GPIO.
I have followed step by step with the readme note and do some small changes. Originaly the script is for two buttons and as per the script the video was store on the sd card folder. I add one more button and in my case all video is stored on USB pendrive.
The problems are:
When the default video starts everything is OK and the buttons on gpio work perfectly but when I Don't do anything and default video is playing on loop is doing great but when I want push any of three buttons I must push any of button twice because when I hit it once nothing happens. It looks like this script sleep and push button for the first time switch off this sleep.
When the script run 24h/day when the default video looping I must switch off raspberry power and then power on because the screen is freeze or I must push any pins button to switch of some kind of sleep.
My version of Mr. Cake code is as follow:
TriggeredVideoPlayer_GPIO_v9.py
#Copyright Jesse Stevens # Cake Industries 12/9/19
#icing#cake.net.au www.cake.net.au
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#GNU General Public License for more details.
#You should have received a copy of the GNU General Public License
#along with this program. If not, see <http://www.gnu.org/licenses/>.
#####################################################################
# BRAND NEW UDP PACKET TRIGGERED VIDEO PLAYER:
# -Removed console clearing from here, better to run on external shell script
# -Listens for A or B to trigger video 1 or 2 in order
# -Plays holding video whilst waiting to be triggered
# -Returns to main holding video after playing triggered videos
# -Listens on all interfaces on UDP port 5005
# -Ensure the packets you send are encoded to byte in utf-8 encoding
#####################################################################
import RPi.GPIO as GPIO
import sys
import os
import subprocess
import psutil
import time
import threading
import socket
##############################################################
# GPIO Pin in/out setup
##############################################################
GPIO.setmode(GPIO.BCM)
#Here we're using GPIO 17 and 18 as triggers, but these can be changed
#Be careful which pins you use, and do some reading on their functions
gpio1 = 26
gpio2 = 20
gpio3 = 16
#We're pulling up voltage on these, so short to ground to trigger:
GPIO.setup(gpio1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(gpio2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(gpio3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#Make sure your switches are pretty clean and your switching is simple
#The debounce amount below (in milliseconds) makes sure we don't get twitchy results
#from electrical noise or bad contacts. Increase this if you find multiple
#triggers are happening. Better yet, use small capacitors to help the switch
#This is intended for momentary trigger switches, not state-based switches
gpiobounce = 100
###############################################################
# file locations for media
###############################################################
startmovie = ("/mnt/USB/movies/1.mp4")
movie1 = ("/mnt/USB/movies/2.mp4")
movie2 = ("/mnt/USB/movies/3.mp4")
movie3 = ("/mnt/USB/movies/4.mp4")
##################################################################
#variables for making sure we only trigger each video player once:
##################################################################
needtostart = 1
running = 0
mode = 0
gpio1status = 0
gpio2status = 0
gpio3status = 0
################################################################################
#Redirecting console output to null so we don't litter the window with feedback
################################################################################
FNULL = open(os.devnull,'w')
#####################################################################
# threaded callbacks for interrupt driven button triggers
# also: resets so buttons must be release and pressed to re-trigger
#####################################################################
def pressedgpio1(channel):
global needtostart
global mode
global gpio1status
#check that the button was previously release before re-triggering
#remember, voltage low (zero) means pressed, due to our pull-ups
if (gpio1status == 0 and GPIO.input(gpio1) == 0):
print("GPIO#1 triggered")
mode = 1
needtostart = 1
gpio1status = 1
#the button was previously pressed, but is now released, let's reset
#remember, voltage high (1) means released, due to our pull-ups
elif (gpio1status == 1 and GPIO.input(gpio1) == 1):
print("GPIO#1 released and reset")
gpio1status = 0
#button is still being held down from last time, do nothing
elif (gpio1status == 1 and GPIO.input(gpio1) == 0):
print("GPIO#1 still held down, not triggered")
def pressedgpio2(channel):
global needtostart
global mode
global gpio2status
#check that the button was previously release before re-triggering
#remember, voltage low (zero) means pressed, due to our pull-ups
if (gpio2status == 0 and GPIO.input(gpio2) == 0):
print("GPIO#2 triggered")
mode = 2
needtostart = 1
gpio2status = 1
#the button was previously pressed, but is now released, let's reset
#remember, voltage high (1) means released, due to our pull-ups
elif (gpio2status == 1 and GPIO.input(gpio2) == 1):
print("GPIO#2 released and reset")
gpio2status = 0
#button is still being held down from last time, do nothing
elif (gpio2status == 1 and GPIO.input(gpio2) == 0):
print("GPIO#2 still held down, not triggered")
def pressedgpio3(channel):
global needtostart
global mode
global gpio3status
#check that the button was previously release before re-triggering
#remember, voltage low (zero) means pressed, due to our pull-ups
if (gpio3status == 0 and GPIO.input(gpio3) == 0):
print("GPIO#3 triggered")
mode = 3
needtostart = 1
gpio3status = 1
#the button was previously pressed, but is now released, let's reset
#remember, voltage high (1) means released, due to our pull-ups
elif (gpio3status == 1 and GPIO.input(gpio3) == 1):
print("GPIO#3 released and reset")
gpio3status = 0
#button is still being held down from last time, do nothing
elif (gpio3status == 1 and GPIO.input(gpio3) == 0):
print("GPIO#3 still held down, not triggered")
#########################################################################
# Definition of callback functions to physical button mapping
#########################################################################
#Interrupt driven callbacks with 100ms debounce in case of electrical noise
#Short to ground to trigger, release to reset (rise/fall detected in callbacks):
GPIO.add_event_detect(gpio1, GPIO.BOTH, callback=pressedgpio1, bouncetime=gpiobounce)
GPIO.add_event_detect(gpio2, GPIO.BOTH, callback=pressedgpio2, bouncetime=gpiobounce)
GPIO.add_event_detect(gpio3, GPIO.BOTH, callback=pressedgpio3, bouncetime=gpiobounce)
#########################################################################
#Main looping
#########################################################################
try:
while True:
###################################################################
#Base looping video
###################################################################
if (mode == 0):
if (needtostart == 1):
needtostart = 0
#for troubleshooting: uncomment
print("Starting main holding video")
m = subprocess.Popen(['omxplayer', '--loop', '-b', '--no-osd', startmovie], stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, close_fds=True)
#Set the current running to start video (for killing logic)
running = 0
else:
#Not needed on base loop, but in case of crash
#Check for end of video
if m.poll() is not None:
#Relaunch the process to start again
needtostart = 1
###################################################################
#Triggered video 1
###################################################################
elif (mode == 1):
if (needtostart == 1):
#kill off other videos first
if (running == 0):
print("Killing start video")
m.stdin.write(b'q')
m.stdin.flush()
#Let's sink the boot in
m.kill()
elif (running == 1):
print("Killing video 1 (restarting it)")
a.stdin.write(b'q')
a.stdin.flush()
#Let's sink the boot in
a.kill()
elif (running == 2):
print("Killing video 2")
b.stdin.write(b'q')
b.stdin.flush()
#Let's sink the boot in
b.kill()
elif (running == 3):
print("Killing video 3")
b.stdin.write(b'q')
b.stdin.flush()
#Let's sink the boot in
b.kill()
#for troubleshooting: uncomment
print("Starting first triggered video")
needtostart = 0
a = subprocess.Popen(['omxplayer', '-b', '--no-osd', movie1], stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, close_fds=True)
#Set the current running to video 1 (for killing logic)
running = 1
else:
#End checking:
#if process has quit
if a.poll() is not None:
#go back to start video/holding frame
mode = 0
needtostart = 1
#return back to start
if (needtostart == 1):
mode = 0
a.kill()
###################################################################
#Triggered video 2
###################################################################
elif (mode == 2):
if (needtostart == 1):
#kill off other videos first
if (running == 0):
print("Killing start video")
m.stdin.write(b'q')
m.stdin.flush()
#Let's sink the boot in
m.kill()
elif (running == 1):
print("Killing video 1")
a.stdin.write(b'q')
a.stdin.flush()
#Let's sink the boot in
a.kill()
elif (running == 2):
print("Killing video 2 (Restarting it)")
b.stdin.write(b'q')
b.stdin.flush()
#Let's sink the boot in
b.kill()
elif (running == 3):
print("Killing video 3")
b.stdin.write(b'q')
b.stdin.flush()
#Let's sink the boot in
b.kill()
#for troubleshooting: uncomment
print("Starting first triggered video")
needtostart = 0
b = subprocess.Popen(['omxplayer', '-b', '--no-osd', movie2], stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, close_fds=True)
#Set the current running to video 2 (for killing logic)
running = 2
else:
#End checking:
#if process has quit
if b.poll() is not None:
#go back to start video/holding frame
mode = 0
needtostart = 1
#return back to start
if (needtostart == 1):
mode = 0
b.kill()
###################################################################
#Triggered video 3
###################################################################
elif (mode == 3):
if (needtostart == 1):
#kill off other videos first
if (running == 0):
print("Killing start video")
m.stdin.write(b'q')
m.stdin.flush()
#Let's sink the boot in
m.kill()
elif (running == 1):
print("Killing video 1")
a.stdin.write(b'q')
a.stdin.flush()
#Let's sink the boot in
a.kill()
elif (running == 2):
print("Killing video 2")
b.stdin.write(b'q')
b.stdin.flush()
#Let's sink the boot in
b.kill()
elif (running == 3):
print("Killing video 3 (Restarting it)")
b.stdin.write(b'q')
b.stdin.flush()
#Let's sink the boot in
b.kill()
#for troubleshooting: uncomment
print("Starting first triggered video")
needtostart = 0
b = subprocess.Popen(['omxplayer', '-b', '--no-osd', movie3], stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE, close_fds=True)
#Set the current running to video 2 (for killing logic)
running = 3
else:
#End checking:
#if process has quit
if b.poll() is not None:
#go back to start video/holding frame
mode = 0
needtostart = 1
#return back to start
if (needtostart == 1):
mode = 0
b.kill()
#give the loop some breathing space (eases up on resources, but delays response by 100ms)
time.sleep(0.1)
#when killed, get rid of players and any other stuff that needs doing
finally:
#make sure all players are killed fully off
os.system('killall omxplayer.bin')
os.system('killall omxplayer')
#turn the blinking cursor back on in the terminal
#os.system("setterm -cursor on > /dev/tty1")
print("Quitting, Goodbye!")
TriggerPlayerLaunch_GPIO.sh
#!/bin/sh
#This script is to be put into /home/pi/
#This will wait 10 seconds for system startup to be completed,
#set permissions of the termainal to allow manipulation,
#clear the console, disable the blinking cursor, then launch
#the triggered video player as a forked background process with no
#console output to keep the screen clear
#wait 10 seconds for console messages to stop popping up
sleep 10
#ensure permissions allow changing of tty1 console properties
chmod 666 /dev/tty1
#disable console blinking cursor
setterm -cursor off > /dev/tty1
#wipe out the screen (cleared, black), redirect output to null
dd if=/dev/zero of=/dev/fb0 > /dev/null 2>&1
#start main python script in background and redirect output to null
python3 /home/pi/TriggeredVideoPlayer_GPIO_v9.py > /dev/null 2>&1 &

Python break out of poll when key pressed

Apologies for the newbie Python post, but a bit of Googling and I still can't find what I need.
I have the following Pi Hat; https://github.com/modmypi/Jam-HAT, ...and I'm using their docs to guide me; https://gpiozero.readthedocs.io/en/stable/recipes.html
My idea is pretty simple;
run script when button pressed
wait for it to run, showing flashy lights whilst running
if I press another button, stop/kill script
However, I'm stuck on the part where I need to stop the script with a button
#!/usr/bin/env python3
import gpiozero
import subprocess
from signal import pause
from time import sleep
button1 = gpiozero.Button(18)
button2 = gpiozero.Button(19)
green1 = gpiozero.LED(16)
green2 = gpiozero.LED(17)
red1 = gpiozero.LED(5)
red2 = gpiozero.LED(6)
script = ""
yellow1 = gpiozero.LED(12)
yellow2 = gpiozero.LED(13)
def kill_hello():
global script
script.kill()
print("Killed PID: ", script.pid)
red1.on()
sleep(.5)
red1.off()
red2.on()
sleep(.5)
red2.off()
def say_hello():
global script
green1.on()
sleep(.5)
green1.off()
green2.on()
sleep(.5)
green2.off()
script = subprocess.Popen(['/home/kali/hello.sh'])
print("Script PID: ", script.pid)
while script.poll() is None:
if not button2.when_pressed:
green1.on()
sleep(.5)
green1.off()
sleep(1)
button2.when_pressed = kill_hello
print("Press Ctrl & C to Quit")
try:
button1.when_pressed = say_hello
pause()
except KeyboardInterrupt:
print( "\n...Quit!")
I've tried a try/except where that while loop is, but that has also not worked (not like the KeyboardInterrupt). It doesn't recognise the button has been pressed, and I'm assuming because it's not within a valid catch/else/something block.
Any suggestions for a simple break out of loop, please?
It seems the issue is around a single process is hogging Python, thus creating multiple threads helped;
#!/usr/bin/env python3
import gpiozero
import subprocess
import time
import threading
from signal import pause
button1 = gpiozero.Button(18)
button2 = gpiozero.Button(19)
green1 = gpiozero.LED(16)
green2 = gpiozero.LED(17)
red1 = gpiozero.LED(5)
red2 = gpiozero.LED(6)
script = ""
yellow1 = gpiozero.LED(12)
yellow2 = gpiozero.LED(13)
switch = True
def blink():
def run():
while (switch == True):
green1.on()
time.sleep(.2)
green1.off()
time.sleep(.2)
if switch == False:
break
thread = threading.Thread(target=run)
thread.start()
def switchon():
global switch
global script
switch = True
print('switch on')
script = subprocess.Popen(['/home/kali/hello.sh'])
blink()
def switchoff():
global switch
global script
print('switch off')
script.kill()
switch = False
try:
button1.when_pressed = switchon
button2.when_pressed = switchoff
pause()
except KeyboardInterrupt:
print( "\n...Quit!")

raspberry pi 3 webbrowser controlled by buttons (Python)

hi I am trying to get 2 webcam outputs to be displayed in a webbrowser which runs in full screen mode.
So far it works aslong as I keep the fullscreen/kiosk disabled, once the full screen is on, my script pauses.
When I close the webbrowser the script continues and I can use my buttons which open a new browser and then the script pauses again (the purpose is that the script loops endlessly without pauses)
import RPi.GPIO as GPIO
from time import sleep
import os
url1 = 'http://10.0.0.31/mjpg/video.mjpg'
url2 = 'http://10.0.0.32/mjpg/video.mjpg'
GPIO.setmode(GPIO.BCM)
array = [4,17]
GPIO.setup(array, GPIO.IN, pull_up_down=GPIO.PUD_UP)
os.system('chromium-browser --app=http://10.0.0.31/mjpg/video.mjpg --kiosk')
while True:
if ( GPIO.input(17) == False ):
print('Button 1 Pressed')
os.system('date')
os.system('pkill chromium-browser')
print (GPIO.input(17))
os.system('chromium-browser --app=http://10.0.0.32/mjpg/video.mjpg --kiosk')
sleep(0.5)
if ( GPIO.input(4) == False ):
print('Button 2 Pressed')
os.system('date')
os.system('pkill chromium-browser')
print (GPIO.input(4))
os.system('chromium-browser --app=http://10.0.0.31/mjpg/video.mjpg --kiosk')
sleep(0.5)
else:
os.system('clear')
print ('Press a key')
sleep(0.1)
Is there a way to fix this without big changes (as I noticed a lot of people are fan of selenium, that's not an option) and using subprocess instead of os.system gives same result.
The reason this is happening is because os.system() waits for a process to finish, and won't continue your code until this happens. By using the "&" at the end of your command, the command does not have to finish, and your buttons should still be useable.
#Import libraries
import RPi.GPIO as GPIO
from time import sleep
import os
#Set up the URLs
url1 = 'http://10.0.0.31/mjpg/video.mjpg'
url2 = 'http://10.0.0.32/mjpg/video.mjpg'
#Set up GPIO pins
GPIO.setmode(GPIO.BCM)
array = [4,17]
GPIO.setup(array, GPIO.IN, pull_up_down=GPIO.PUD_UP)
#Open the first webpage
os.system('chromium-browser --app=http://10.0.0.31/mjpg/video.mjpg --kiosk & ')
while True:
if ( GPIO.input(17) == False ):
print('Button 1 Pressed')
os.system('date')
os.system('pkill chromium-browser')
print (GPIO.input(17))
os.system('chromium-browser --app=http://10.0.0.32/mjpg/video.mjpg --kiosk &')
sleep(0.5)
if ( GPIO.input(4) == False ):
print('Button 2 Pressed')
os.system('date')
os.system('pkill chromium-browser')
print (GPIO.input(4))
os.system('chromium-browser --app=http://10.0.0.31/mjpg/video.mjpg --kiosk &')
sleep(0.5)
else:
os.system('clear')
print ('Press a key')
sleep(0.1)

using python to make a power interface

First off, I'm very new to python. I have a raspberry pi connected via lan to a few nodes. I want the pi to be the power interface for the nodes. When a button is pressed, magic packets get sent to the nodes to wake them up. Once the nodes have been powered up, the same momentary switch will be able to power off the nodes, by ssh-ing into each and executing the "poweroff" command. While the machines are coming up, and while the machines are powering off, an LED should be blinking.
My attempt so far has most of the functionality I described, but the LED blinking is spotty, and I'm noticing that some of my threads are being redundantly executed.
My Question is, how do I get the led blinking to more accurately represent the state change of the machines.
Here is the script:
#!/usr/bin/python
import RPi.GPIO as GPIO
import threading
import time
import os
from subprocess import call
nodes = [
{
"name": "node-1",
"mac": "80:EE:73:AE:AA:7C",
"ip": "10.15.1.254",
},
#more nodes...
]
#function to blink the leds
def blink(pin,number):
try:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)
count =0
while count < number:
GPIO.output(pin,GPIO.HIGH)
time.sleep(.5)
GPIO.output(pin,GPIO.LOW)
time.sleep(.5)
count +=1
return
except Exception as inst:
print "error: could not blink"
#function to turn LED on or off based on power state
def led(pin, state):
try:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(pin, GPIO.OUT)
if state ==1:
GPIO.output(pin, GPIO.HIGH)
else:
GPIO.output(pin, GPIO.LOW)
except:
print "error: could not turn on LED"
#function to wake up a node
def wake(node, mac):
try:
print "waking" +node
call(["wakeonlan", mac])
except Exception as inst:
print "error: could not wake " + node
#function to power off nodes
def shutdown(node, ip):
try:
print "shutting down " +node
call(["ssh", "-o", "StrictHostKeyChecking=no", "root#"+ip, "poweroff"])
except Exception as inst:
print "error: could not shutdown " + node
#function to check the state of the nodes (if node can be pinged, it is up)
def checkstate(node,ip):
try:
response = os.system("ping -i 0.1 -c 1 -w2 " + ip + " > /dev/null 2>&1")
if response == 0:
state =1
else:
state =0
return state
except:
print "error could not ping"
#function checks if all node states are the same
def checksame(list):
try:
list = iter(list)
first = next(list)
return all(first == rest for rest in list)
except StopIteration:
return list[0]
def main():
while True:
state = []
for node in nodes:
node_name = node.get('name', '')
node_ip = node.get('ip', '')
state.append(checkstate(node_name,node_ip)) #write each node state to an array
power_state = state[1]
if power_state ==1:
led(40,1) #turn LED on because all the nodes are on
if not checksame(state): #checks that all values in state array are the same. If not, led should blink because there is a state change or an error in a node
t = threading.Thread(target=blink, args=(40,8) )
t.start()
else:
GPIO.setmode(GPIO.BOARD)
GPIO.setup(05, GPIO.IN, pull_up_down=GPIO.PUD_UP)
button_state = GPIO.input(05)
if button_state == False: #this is the button press detection
if power_state ==1:
#button has been pressed, and machines are on, need to be off
for node in nodes:
node_name = node.get('name', '')
node_ip = node.get('ip', '')
shutdown(node_name, node_ip)
print "Nodes have been shut down"
else:
#button has been pressed, machines are off, need to be on
for node in nodes:
node_name = node.get('name', '')
node_mac = node.get('mac', '')
wake(node_name,node_mac)
print "Nodes have been powered on"
t = threading.Thread(target=blink, args=(40, 180) )#this is a hack to show the LED blinking until the nodes can be pinged, otherwise, the LED would be off until the nodes were ping-able
t.start()
time.sleep(0.2)
if __name__ == "__main__":
main()

raspberry pi motion sensor input signal

I`m writing simple script for my home security system. it consist of button, led, buzzer, and sensor. It works like this:
- button pressed, - alarm function on, - it detects me ( everything is fine), - button pressed again, - alarm off(still fine) - button pressed again - and heres the problem: when a wave if front of the alarm when it was off, it still catches the movement, keeps this signal somehow, and the first thing after - alarm on is spotted signal, even if sensor didnt sent signal.
Hope i explain it clear enough. Here's the code:
import RPi.GPIO as GPIO
import time
import os
from itertools import cycle
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(04, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)#switch
GPIO.setup(17, GPIO.OUT)#led
GPIO.setup(18, GPIO.OUT)#buzzer
GPIO.setup(21, GPIO.IN)#sensor
#### definicje funkcji #####
############################
############################
def led_on(czas):
GPIO.output(17,1)
time.sleep(czas)
GPIO.output(17,0)
return;
#led_on(10)
############################
def buzzer_on(czas):
GPIO.output(18,1)
time.sleep(czas)
GPIO.output(18,0)
return;
#buzzer_on(0.1)
############################
def alarm_on():
print "alarm on"
while True:
if (GPIO.input(21)):
print "spotted!"
buzzer_on(0.1)
led_on(0.1)
time.sleep(1)
if (GPIO.input(04) == 1):
next(wlacznik)
alarm_off();
led_on(1)
break
return;
def alarm_off():
print "alarm off"
return;
############################
########################################### PROGRAM ###########################################
###############################################################################################
###############################################################################################
### WLACZNIK_ALARMU ######
wlacznik = cycle(range(2))
print "wartosc wlacznika:"
print next(wlacznik)
prev_input = 0 #toggle dla przycisku
while True:
input = GPIO.input(04)
#if the last reading was low and this one high, print
if ((not prev_input) and input):
print("Button pressed")
if (next(wlacznik) == 1):
led_on(0.1)
time.sleep(0.1)
led_on(0.1)
time.sleep(1)
alarm_on();
#update previous input
prev_input = input
#slight pause to debounce
time.sleep(0.05)
########################################### KONIEC ############################################
GPIO.cleanup()

Categories

Resources