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 &
Related
So I want to start a project that records my keyboard input and mouse movement for a sandbox PC games. I love farming, however whether I'm tired, and taking a short break to make a coffee or have a phone call. When I come back my farm gets annihilated.
I tried and made this one, but it seems not to work. Any way to make it better with the possibility to implement the recorded inputs in a loop function?
import pyautogui
def record_movement():
# Initialize variables to store mouse and keyboard events
mouse_events = []
keyboard_events = []
# Start recording mouse and keyboard events
pyautogui.PAUSE = 0.001 # Set a small pause to record events more accurately
pyautogui.FAILSAFE = False # Disable failsafe feature to allow for recording
recording = True
while recording:
event = pyautogui.getEvent()
if event.event_type == 'MouseMove':
mouse_events.append(event)
elif event.event_type == 'KeyDown':
keyboard_events.append(event)
elif event.event_type == 'KeyUp':
keyboard_events.append(event)
elif event.event_type == 'Quit':
recording = False
return mouse_events, keyboard_events
def replay_movement(mouse_events, keyboard_events):
# Replay recorded mouse and keyboard events
for event in mouse_events:
pyautogui.moveTo(event.x, event.y)
for event in keyboard_events:
if event.event_type == 'KeyDown':
pyautogui.press(event.name)
elif event.event_type == 'KeyUp':
pyautogui.keyUp(event.name)
# Test:
mouse_events, keyboard_events = record_movement()
replay_movement(mouse_events, keyboard_events)
could you please help me :
I want to make an LED ON by pressing a button it Should stays ON for 5 seconds, but I want it to, if I push the button while it's ON, it will stay ON as long as the time added up. for example: when the LED is On and I push the button another time, it will be ON for 10 seconds.
I'm using raspberry pi pico, with Thonny
Here is my code :
from machine import Pin, Timer
import time
White_LED = Pin(15, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_DOWN)
while True:
if button.value() == 1:
White_LED.on()
time.sleep(5)
White_LED.off()
At the moment when you sleep for 5 seconds, the code stops. So, it won't notice if you press the button again.
I think you'll need to make use of interrupt handlers (https://docs.micropython.org/en/v1.8.6/pyboard/reference/isr_rules.html) , or you could implement a simple event loop yourself.
An event loop keeps looking for things that happen and performs some action when it does. Here's a rough idea of how you might do it.
from machine import Pin, Timer
import time
White_LED = Pin(15, Pin.OUT)
button = Pin(14, Pin.IN, Pin.PULL_DOWN)
button_was = 0
light_on_until = 0
while True:
# See if the state of the button has changed
button_now = button.value()
if button_now != button_was:
button_was = button_now
if button_now == 1:
# button is down, but it was up.
# Increase light on time by 5 seconds
if light_on_until > time.ticks_ms():
# light is already on, increase the time by 5,000 ms
light_on_until += 5000
else:
# light isn't on, so set time to 5 seconds from now (5,000 ms)
light_on_until = time.ticks_ms() + 5000
if light_on_until > time.ticks_ms():
# light should be on, so if it's currently off, switch it on
if White_LED.value() == 0:
White_LED.on()
else:
# light should be off, so if it's currently on, switch it off
if White_LED.value() == 1:
White_LED.off()
I currently have a piece of code designed to communicate with two motors via a TCP Device Server which sends ASCII commands to them in order to trace sinusoidal paths. I wish to have the movement continue indefinitely and then immediately stop when KeyboardInterrupt is triggered, then have the motors move back to their defined home positions before the program ends.
This code can currently replicate sinusodial motion, but it currently does not stop immediately when KeyboardInterrupt is triggered, nor do the motors move back to their home positions. The sinusodial loop is designed such that when KeyboardInterrupt occurs, a global variable called move changes from True to False and this breaks the loop. The simplified code is given below:
import socket
import time
import numpy as np
import math
pi = math.pi
try:
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP Server Connection
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print("Failed to connect")
exit()
print("Sockets Created")
s1.connect(("192.168.177.200", 4001)) # Y motor
s2.connect(("192.168.177.200", 4002)) # X motor
# Disengage the motor to allow manual movement by wheel
s1.send("DI\n".encode("ASCII"))
message = s1.recv(1024).decode()
s2.send("DI\n".encode("ASCII"))
message = s1.recv(1024).decode()
homeposition = input("Are the motors centred? Press 'y' to confirm: ")
if homeposition == 'y':
s1.send("EN\n".encode("ASCII"))
s2.send("EN\n".encode("ASCII")) # energise the motors so they cannot be moved
print("Motors Engaged")
s1.send("HO\n".encode("ASCII")) # set current position as home position
s2.send("HO\n".encode("ASCII")) # set current position as home position
else:
print("Set home position and restart program")
exit()
#----ADD DATA FOR SAMPLING SINUSODIAL FUNCTIONS----
radius = input("Desired radius of movement (mm):")
radius = float(radius)
print("radius of circular path (mm): ", radius)
# need slightly different ratios for each motor due to different thread sizes
gearpositionlim_x = 20000 #one rotation equals 2.5mm (+ bearing ration on manipulator of 2:1)
gearpositionlim_y = 10000 #one rotation equals 2mm
# sample sine and cosine
step = 2*pi / 1000
time_range = np.arange(0,2*pi + step,step)
x_motorrange = gearpositionlim_x*np.cos(time_range)
y_motorrange = gearpositionlim_y*np.sin(time_range)
x_motorrange = ['la'+str(int(i)) for i in x_motorrange]
y_motorrange = ['la'+str(int(i)) for i in y_motorrange]
#print(x_motorrange)
x_motorrange_wcom = []
y_motorrange_wcom = []
{x_motorrange_wcom.extend([e, 'm', 'np']) for e in x_motorrange} # add movement prompts and wait for movement to complete
{y_motorrange_wcom.extend([e, 'm', 'np']) for e in y_motorrange} # add movement prompts and wait for movement to complete
# Set Acceleration and Deceleration of Motors
s1.send("AC10\n".encode("ASCII"))
message = s1.recv(1024).decode()
s2.send("AC10\n".encode("ASCII"))
message = s2.recv(1024).decode()
print("Acceleration set to 10 ")
s1.send("DEC10\n".encode("ASCII"))
message = s1.recv(1024).decode()
s2.send("DEC10\n".encode("ASCII"))
message = s2.recv(1024).decode()
print("Deceleration set to 10")
def setup(): #move to initial position before starting movement
s2.send(str(str(x_motorrange_wcom[0])+"\n").encode("ASCII"))
s2.send("m\n".encode("ASCII"))
s2.send("np\n".encode("ASCII"))
s2.send("delay200\n".encode("ASCII"))
def end():
print("Movement ended, return to home position")
s1.send("la0\n".encode("ASCII"))
s1.send("m\n".encode("ASCII"))
s1.send("np\n".encode("ASCII"))
s1.send("delay200\n".encode("ASCII"))
s1.send("DI\n".encode("ASCII"))
s1.send("delay200\n".encode("ASCII"))
time.sleep(2)
s2.send("la0\n".encode("ASCII"))
s2.send("m\n".encode("ASCII"))
s2.send("np\n".encode("ASCII"))
s2.send("delay200\n".encode("ASCII"))
s2.send("DI\n".encode("ASCII"))
s2.send("delay200\n".encode("ASCII"))
def motormove():
global move
try:
for i in np.arange(0,len(x_motorrange)):
if (move == True):
s1.send(str(str(x_motorrange[i])+"\n").encode("ASCII"))
s2.send(str(str(y_motorrange[i])+"\n").encode("ASCII"))
else:
break
except KeyboardInterrupt:
move = False
print(move)
end()
#-------------------------------------------
setup()
name = input("Code Ready, press enter to proceed: ")
if name == "":
print("Code Running: Press ctrl + c to end")
while (move == True):
motormove()
I believe my issue is with my function motormove(), but I am unsure of what I should do in order to achieve my desired operation. Does anyone know how this can be achieved?
Thanks in advance
Using library signal should be sufficient for your usecase. See code bellow.
import socket
import signal
import time
import numpy as np
import math
pi = math.pi
try:
s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #TCP Server Connection
s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except:
print("Failed to connect")
exit()
print("Sockets Created")
s1.send("HO\n".encode("ASCII")) # set current position as home position
s2.send("HO\n".encode("ASCII")) # set current position as home position
gearpositionlim = int(10000)
# sample sine and cosine
step = 2*pi / 2000
time_range = np.arange(0,2*pi + step,step)
x_motorrange = gearpositionlim*np.sin(time_range)
y_motorrange = gearpositionlim*np.cos(time_range)
def handler(signum, frame):
res = input("Ctrl-c was pressed. Do you really want to exit? y/n ")
if res == 'y':
exit(1)
else:
#Do STH
def setup():
s2.send(y_motorrange[0])+"\n").encode("ASCII"))
s2.send("m\n".encode("ASCII"))
s2.send("np\n".encode("ASCII"))
s2.send("delay200\n".encode("ASCII"))
def end():
print("Movement ended, return to home position")
s1.send("la0\n".encode("ASCII"))
s1.send("m\n".encode("ASCII"))
s1.send("np\n".encode("ASCII"))
s1.send("delay200\n".encode("ASCII"))
s1.send("DI\n".encode("ASCII"))
s1.send("delay200\n".encode("ASCII"))
time.sleep(2)
s2.send("la0\n".encode("ASCII"))
s2.send("m\n".encode("ASCII"))
s2.send("np\n".encode("ASCII"))
s2.send("delay200\n".encode("ASCII"))
s2.send("DI\n".encode("ASCII"))
s2.send("delay200\n".encode("ASCII"))
def motormove():
global move
try:
for i in np.arange(0,len(x_motorrange)):
if (move == True):
s1.send(str(str(x_motorrange[i])+"\n").encode("ASCII"))
s2.send(str(str(y_motorrange[i])+"\n").encode("ASCII"))
else:
break
except KeyboardInterrupt:
signal.signal(signal.SIGINT, handler)
#-------------------------------------------
setup()
name = input("Code Ready, press enter to proceed: ")
if name == "":
print("Code Running: Press ctrl + c to end")
while (move == True):
motormove()
This should be working just fine, note the signal function being called on KeyboardInterrupt, this redirects to signal function where, you can either exit or do something else.
I want to write a bot that will simulate mouse movements when user is away for more than 5 minutes and stay put when user takes control i.e. moves the mouse.
I have written following code as a part of the program.
Here is the link to my old program which clicks at given points periodically. The problem with this program is I have to start the program when I want to go somewhere and after returning close the program in order to resume working.
Here is the one of the module I wrote for the new program which detects whether mouse is moving or not.
import win32api
from time import sleep
print("starting engine.")
count = 0
while(True):
savedpos = win32api.GetCursorPos()
if count>20*5:
break
sleep(1)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady.")
else:
print("Mouse is moving.")
count += 1
I wont be writing the code but I have the Idea to solve the problem
you use pyautogui.position() to keep checking the position and if it doesnt change position for 300 seconds you move it
I wrote following code referring other Stackoverflow posts.
This code waits 4 minutes for mouse being steady. Whenever mouse is moved, timer is reset to zero.
import win32api
from time import sleep
import pyautogui as gui
print("starting engine.")
count = 0
savedpos = win32api.GetCursorPos()
def actions():
print(gui.size())
while True:
#toast.show_toast("ROBOT V2 !", "Robot is active.", threaded=False, icon_path=None, duration=2)
gui.click()
gui.press('home')
gui.moveTo(541, 142, 0.25) # Money Transfer dropdown
gui.click()
sleep(0.5)
gui.moveTo(541, 172, 0.25) # Money Transfer link
gui.click()
sleep(5)
cond()
def cond():
count = 0
while True:
savedpos = win32api.GetCursorPos()
sleep(0.5)
curpos = win32api.GetCursorPos()
if savedpos == curpos:
savedpos = curpos
print("Mouse is steady. Elapsed time: ", (count+1)/2, " seconds.")
count += 1
if count >= 480: # if count is greater than 60 it means timeout will occur after mouse is steady for more than
# 240 seconds i.e. 4 minutes. (approx.)
print("User away for more than 4 minutes, taking control of the system.")
actions()
break
else:
pass
else:
print("Mouse is moving.")
count = 0
cond()
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