using python to make a power interface - python

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()

Related

Exit loop with KeyboardInterrupt then begin another loop in python

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.

Raspberry Pi: GPIO-pin gets high by GPIO.setup()

I currently have the problem that when I use the Gpio.setup(17, GPIO.OUT) function, the pin gets power. I have read a lot about this problem, but nothing has worked for me. I have even reinstalled Raspbian.
The script should work like this:
If I get a signal from the server the function messageDecoder() is called. If the message has the topic "rpi/gpio" the function setup_GPIO() should be called and then the function on(channel1) to supply the pin with power. But the pin already has power when setup_GPIO() is called! But I do not know why.
Does anyone have s solution?
Here is my code:
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import time
import datetime as datetime
def setup_GPIO(): # !!! when that function is called the pin gets power
GPIO.setmode(GPIO.BCM)
GPIO.setup(channel1, GPIO.OUT)
def on(pin):
print("ON", pin)
GPIO.output(pin, GPIO.HIGH) # !!! here the pin should get power, but it gets it already before
def off(pin):
print("OFF", pin)
GPIO.output(pin, GPIO.LOW)
GPIO.cleanup()
def connectionStatus(client, userdata, flags, rc):
mqttClient.subscribe("time")
mqttClient.subscribe("rpi/gpio")
def messageDecoder(client, userdata, msg):
print("topic: " , msg.topic, "payload: " , msg.payload,)
if msg.topic == "time":
...
elif msg.topic == "rpi/gpio":
messageActiv = str(msg.payload.decode(encoding='UTF-8'))
if messageActiv == "on":
setup_GPIO() # !!! here I call the setup_GPIO() function and the pin gets power
print("System is ON!")
on(channel1) # !!! I could leave out that function and the pin would have power
elif messageActiv == "off":
print("System is OFF!")
off(channel1)
else:
print("Unknown message!")
else:
print("Unknown topic!")
channel1 = 17
clientName = "RPI"
serverAddress = "192.168.8.138"
mqttClient = mqtt.Client(clientName)
mqttClient.connect(serverAddress)
if __name__ == '__main__':
i = 0
try:
now = datetime.datetime.today()
mqttClient.on_connect = connectionStatus
mqttClient.on_message = messageDecoder
mqttClient.loop_forever()
except KeyboardInterrupt:
print("Interrupt")
mqttClient.disconnect()
Thanks in advance :D
It appears the default output once setting the pin to be output is for the value to be high. Based on the docs, you can use the parameter initial=GPIO.HIGH to set the initial value.
GPIO.setup(channel1, GPIO.OUT,initial=GPIO.HIGH)
The code above sets the initial value to low according to the OP. Not sure why this happens. Please fill in if you know.
https://sourceforge.net/p/raspberry-gpio-python/wiki/BasicUsage/
Edited based on info provided in comment by OP

How do I run two while True statements in python?

I am trying to make a door swipe card system in Python for my Raspberry Pi. I broke the program into two: A Door Alarm and a Card Swipe Recording system. The two programs work individually but how do I combine the two programs into one python file? I've tried threading but it doesn't seem to work.
Below are the programs:
1.) Door Alarm: If door is left open for a certain duration, an led will blink, then an alarm will ring
import time
import RPi.GPIO as gpio
led = 37
buzzer = 11
door = 16
gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)
def blink(buzzer):
gpio.output(buzzer, True)
time.sleep(0.1)
gpio.output(buzzer, False)
time.sleep(0.1)
return
def blink(led):
gpio.output(led, True)
time.sleep(1)
gpio.output(led, False)
time.sleep(1)
return
while True:
if gpio.input(door):
time.sleep(3)
for i in range(0,5):
blink(led)
for i in range (0,5):
blink(buzzer)
else:
gpio.output(buzzer, False)
gpio.cleanup()
2.) Card Swipe Recording System: When someone swipes their card, the led blinks and a picture is taken
import datetime
import time
import os
import RPi.GPIO as gpio
led = 37
t = datetime.datetime.now()
gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(led, gpio.OUT)
def blink(led):
gpio.output(led, True)
time.sleep(0.1)
gpio.output(led, False)
time.sleep(0.1)
while True:
card = raw_input()
f = open("Laptop Sign Out" + '.txt', 'a')
f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
f.write('\n')
f.write(';')
f.write('\n')
f.close()
time.sleep(1)
for i in range(0,3):
blink(led)
os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
time.sleep(3)
gpio.cleanup()
(UPDATE) Also, below is my attempt at threading:
import time
import RPi.GPIO as gpio
import os
import datetime
from threading import Thread
led = 37
buzzer = 11
door = 16
t = datetime.datetime.now()
gpio.setmode(gpio.BOARD)
gpio.setwarnings(False)
gpio.setup(buzzer, gpio.OUT)
gpio.setup(led, gpio.OUT)
gpio.setup(door, gpio.IN, pull_up_down=gpio.PUD_UP)
def blink(buzzer):
gpio.output(buzzer, True)
time.sleep(0.1)
gpio.output(buzzer, False)
time.sleep(0.1)
return
def blink(led):
gpio.output(led, True)
time.sleep(1)
gpio.output(led, False)
time.sleep(1)
return
def doorsensor():
while True:
if gpio.input(door):
time.sleep(3)
for i in range(0,5):
blink(led)
for i in range (0,5):
blink(buzzer)
else:
gpio.output(buzzer, False)
def cardreader():
while True:
card = raw_input()
f = open("Laptop Sign Out" + '.txt', 'a')
f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
f.write('\n')
f.write(';')
f.write('\n')
f.close()
time.sleep(1)
for i in range(0,3):
blink(led)
os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
time.sleep(3)
f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())
f2.start()
f1.start()
gpio.cleanup()
You need to pass your thread functions as the target arguments, not their return values:
import sleep
f1 = Thread(target=doorsensor) # Remove parentheses after doorsensor
f1.daemon = True
f1.start()
f2 = Thread(target=cardreader) # Remove parentheses after cardreader
f2.daemon = True
f2.start()
# Use a try block to catch Ctrl+C
try:
# Use a while loop to keep the program from exiting and killing the threads
while True:
time.sleep(1.0)
except KeyboardInterrupt:
pass
gpio.cleanup()
The daemon property is set on each thread so that the program will exit when only the daemon threads are left:
A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.
I'm presenting a thread-less approach.
The idea is to turn your while bodies into update functions, and call them alternatively.
First off, your door loop becomes
def update_door():
if gpio.input(door):
time.sleep(3)
for i in range(0,5):
blink(led)
for i in range (0,5):
blink(buzzer)
else:
gpio.output(buzzer, False)
Then your card swipe recording system becomes
def update_card():
card = raw_input()
f = open("Laptop Sign Out" + '.txt', 'a')
f.write("OneCard Number: " + card[1:10] + " Time: " + t.strftime("%m-%d-%Y %H:%M:%S"))
f.write('\n')
f.write(';')
f.write('\n')
f.close()
time.sleep(1)
for i in range(0,3):
blink(led)
os.system('fswebcam ~/Desktop/Photos/%H%M%S.jpeg')
time.sleep(3)
Finally, your main loop becomes:
while True:
update_door()
update_card()
But a problem arises: time.sleep in update_card will delay update_door as well.
Here, you have three solutions:
1 - It's ok if update_door is delayed
Well, ok.
2 - It's not ok if update_door is delayed, but it's ok if update_card is not delayed
Then just remove time.sleep(3).
3 - You need update_door not to be delayed, and update_card to be delayed
Then you can set a manual timer, using the time module.
lastCardUpdate = time.time()
while True:
update_door()
now = time.time()
if now - lastCardUpdate >= 3:
update_card()
lastCardUpdate = now
But raw_input in update_card is a blocking method, waiting for a user input.
If you do need this user input to happen every three seconds, then this approach cannot be used.
If you can move it before the while, ie outside of the update_card function, then it's fine.
Else, you will indeed need to use threads.
If you are attempting to run these two programs simultaneously, then you will have to use either threading or multiprocessing, which you say you have attempted. If you have, may we see your attempt as we may be then able to help you with your issue there.
One other issue is that all of your methods are named Blink, which is not allowed in Python, in python all of your methods should have different names.
Edit: For threading make sure to type threading.Thread(target = target) as your code
Regardless of any other mistake, you need to join one of your threads once they have been started.
f1 = Thread(target = doorsensor())
f2 = Thread(target = cardreader())
f2.start()
f1.start()
f1.join()
What does f1.join() do?
Basically, it tells Python to wait until f1 has finished running.
If you don't do so, the program will start f1 and f2, then will exit.
Upon exiting, Python will release all the resources, including those two threads, whose execution will stop.

infinite while loop python

I am doing a parking sensor with raspberry pi and python
This is the code :
import RPi.GPIO as GPIO
import time
#from picamera import PiCamera
from time import sleep
from gpiozero import MotionSensor
import smtplib
sender = '*****#gmail.com'
reciever = '*****#gmail.com'
def BlueLED (): #Blue LED Function
GPIO.output(27, GPIO.HIGH)
time.sleep(3)
GPIO.output(27, GPIO.LOW)
def RedLED (): #Red LED Function
GPIO.output(22,GPIO.HIGH)
time.sleep(3)
GPIO.output(22, GPIO.LOW)
def Buzzer (): #Buzzer Function
GPIO.output(17, GPIO. HIGH)
time.sleep(3)
GPIO.output(17, GPIO.LOW)
def email(sender,reciever,msg):
try :
server = smtplib.SMTP('smtp.gmail.com',587)
server.ehlo()
server.starttls()
server.login(sender,'******')
server.sendmail(sender,reciever,msg)
server.close()
print('Email sent!')
except :
print('Error')
try :
GPIO.setmode(GPIO.BCM)
#camera = PiCamera()
pir = MotionSensor(4)
GPIO.setwarnings(False)
GPIO.setup(27, GPIO.OUT) #blueLED
GPIO.setup(22, GPIO.OUT) #redLED
GPIO.setup(17, GPIO.OUT) #buzzer
GPIO.setup(18, GPIO.OUT) #tempsensor
GPIO.setup(21, GPIO.IN, pull_up_down = GPIO.PUD_UP) #entry button
count = 0
while True :
if (pir.motion_detected):
print('Motion Detected')
#Calling the buzzer function
#Buzzer()
#The content that is going to be sent via email
msg = """Subject : Car Park
(Picture) """
email(sender,reciever,msg)
print('\nPlease press the button for the gate to open')
while True :
if(GPIO.input(21) == False):
if (count < 5):
BlueLED()
print('\nThere are ',(5-count), ' parking spaces empty ')
else :
RedLED()
print('\nSorry but the parking is full')
count = count + 1
except Exception as ex :
print('Error occured',ex)
My problem is that the first while loop is not working, i.e if the motion sensor is triggered nothing happens yet you can repress the button and the count is increased. I'm guessing there is an easy solution to this but non seem to come to mind. Would love your help, thanks
Your second while loop has no break point!!!
Your first while loop runs until it detects motion and then enters the second loop, and your second loop runs forever.
If you want both loops to work simultaneously then you should use threads!!!
If not then make a break point in second loop.
Simple example:
import time
count=0
count2=0
while True: #starting first loop
count+=1 # counting to 100 to start second loop
if count==100:
print("its 100 entering second loop")
time.sleep(1)
while True: # entering second loop
count2+=1 #counting to 100 to exit second loop
if count2==100:
print("its 100 exitin second loop")
time.sleep(1)
count=0
count2=0
break # exiting second loop this is the break point

GPIO pins won't work anymore halfway through my program

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

Categories

Resources