FTDI2232H mini module GPIO, LED not Blinking - python

I am trying to read and write in FTDI2232H mini module. I have 3 GPIO signal 1 input and 2 output. I tried to set the Pin to High and Low . But it is not working. I connected a LED to check and LED is not blinking.
import serial
class FTDI2232H:
# Define the bit masks for each pin
Signal1= 0x10 # AD4 (input)
Signal2= 0x20 # AD5 (output)
Signal3= 0x80 # AD6 (input)
def __init__(self, port="COM7", baudrate=6000000):
self.serial = serial.Serial(port=port, baudrate=baudrate)
# Configure the pins as inputs or outputs
# self.set_pin_direction(self.Signal1, 'in') # Set Signal1 pin as an input
self.set_pin_direction(self.Signal2, 'out') # Set Signal2 pin as an output
self.set_pin_direction(self.Signal3, 'out') # Set Signal3 pin as an output
'''RTS-Request to send; DTR (Data Terminal Ready);RI (Ring Indicator)
The set_pin_direction function sets the direction of a pin to either input or output.
If the pin is set to input, the function checks the state of the RI line to determine
whether to set the pin to RTS or DTR. If the pin is set to output, the function sets the
state of the RTS or DTR line depending on the pin and value parameters passed in.'''
def set_pin_direction(self, pin, direction):
if direction == 'in':
raise ValueError("Invalid pin direction. Pin must be set to 'out'.")
elif direction == 'out':
# Set pin as output if not already set
if pin == self.Signal1:
self.serial.setRTS(0)
else:
if pin == self.Signal3:
self.serial.setRTS(0)
else:
self.serial.setDTR(0)
else:
raise ValueError("Invalid pin direction. Must be 'in' or 'out'.")
'''The read_pin function reads the state of the RI line, which has been set to the
pin direction of input, and then sets the pin direction back to output
before returning the value.'''
def read_pin(self, pin):
# Set the pin direction to input
self.set_pin_direction(pin, 'in')
# Read the pin value
value = self.serial.getRI() # get the state of the RI line
# Set the pin direction back to output
self.set_pin_direction(pin, 'out')
return value
'''The write_pin function sets the pin direction to output, sets the state
of the RTS or DTR line based on the pin and value parameters passed in,
and then sets the pin direction back to output.'''
def write_pin(self, pin, value):
# Set the pin direction to output
self.set_pin_direction(pin, 'out')
# Set the pin value
if value:
if pin == self.Sgnal3:
self.serial.setRTS(1)
else:
self.serial.setDTR(1)
else:
if pin == self.Signal3:
self.serial.setRTS(0)
else:
self.serial.setDTR(0)
# Set the pin direction back to output
self.set_pin_direction(pin, 'out')
def close(self):
self.serial.close()
And the main code
import time
from lib_led import FTDI2232H
def main():
print("Creating FTDI2232H object")
ftdi = FTDI2232H()
ftdi.set_pin_direction(FTDI2232H.Signal2, 'out')
try:
ftdi.write_pin(FTDI2232H.Signal2, 0) # Set Signal2 pin to 0 (low)
while True:
ftdi.write_pin(FTDI2232H.Signal2, 1) # Set Signal 2 pin to 1 (high)
print("I am HIGH")
time.sleep(1) # Delay for half a second
ftdi.write_pin(FTDI2232H.Signal2, 0) # Remove this line
print("I am LOW")
time.sleep(1) # Delay for half a second
except KeyboardInterrupt:
pass
ftdi.close()
if __name__ == '__main__':
main()
Help me solve this. Here is the code. I connected my LED to CN2-13 pin of FTDI2232H mini module.
I expect the LED to glow when high and off when low. But for both the output pins, I don't see the LED blinking/glowing. But for the input pin of Signal1, The LED is glowing when its LOW and stops when its High

Related

PWM problem with importing motor module in python

I am having problems with a module that I am trying to import in python.
It is being run through a RPi 4b, driving 4 motors through 2 L298N h bridges.
When I run this code (FourMotorClassWithTurn) there is no problem and the motors perform as expected.
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)#setup the pin out to be board numbers not BCM
GPIO.setwarnings(False)#stops set warnings from showing
class Motor():
def __init__(self, EnFL, In1FL, In2FL, EnFR, In3FR, In4FR,
EnBR, In1BR, In2BR, EnBL, In3BL, In4BL):
self.EnFL = EnFL
self.In1FL = In1FL
self.In2FL = In2FL
#Front left motor
self.EnFR = EnFR
self.In3FR = In3FR
self.In4FR = In4FR
#Front right motor
self.EnBR = EnBR
self.In1BR = In1BR
self.In2BR = In2BR
#Back right motor
self.EnBL = EnBL
self.In3BL = In3BL
self.In4BL = In4BL
#Back left motor
GPIO.setup(self.EnFL,GPIO.OUT)
GPIO.setup(self.In1FL,GPIO.OUT)
GPIO.setup(self.In2FL,GPIO.OUT)
GPIO.setup(self.EnFR,GPIO.OUT)
GPIO.setup(self.In3FR,GPIO.OUT)
GPIO.setup(self.In4FR,GPIO.OUT)
GPIO.setup(self.EnBR,GPIO.OUT)
GPIO.setup(self.In1BR,GPIO.OUT)
GPIO.setup(self.In2BR,GPIO.OUT)
GPIO.setup(self.EnBL,GPIO.OUT)
GPIO.setup(self.In3BL,GPIO.OUT)
GPIO.setup(self.In4BL,GPIO.OUT)
self.pwmFL = GPIO.PWM(self.EnFL,100);
self.pwmFL.start(0);
self.pwmFR = GPIO.PWM(self.EnFR,100);
self.pwmFR.start(0);
self.pwmBR = GPIO.PWM(self.EnBR,100);
self.pwmBR.start(0);
self.pwmBL = GPIO.PWM(self.EnBL,100);
self.pwmBL.start(0);
#-------------------------------------------------------------------------
def move(self, speed=0.5, turn=0, time=0):
"""
Sets the motor to move
Parameters
----------
speed : TYPE, float
DESCRIPTION. Sets the speed of the motor 0 - 1. The default is 0.
turn : TYPE, float
DESCRIPTION. Sets the turn direction and rate of the
platform (-1) - 1. Full left = -1, full right = 1 The default is 0.
time : TYPE, float
DESCRIPTION. Sets the run time of the motor in seconds.
The default is 0.
Returns
-------
None.
"""
speed *= 100 #converts speed in PWM duty cycle value
turn *= 100 #converts turn in PWM duty cycle value
leftSpeed = speed + turn #adjusts the motor speed on each side for
#differential steering
rightSpeed = speed - turn
if leftSpeed>100: leftSpeed=100
elif leftSpeed<-100: leftSpeed=-100
if rightSpeed>100: rightSpeed=100
elif rightSpeed<-100: rightSpeed=-100 #PWM can only accept a maximum
#of 100 so values need limiting
self.pwmFL.ChangeDutyCycle(abs(leftSpeed))
self.pwmFR.ChangeDutyCycle(abs(rightSpeed))
self.pwmBR.ChangeDutyCycle(abs(rightSpeed))
self.pwmBL.ChangeDutyCycle(abs(leftSpeed))
#PWm can only accept positive values
if leftSpeed>0:
GPIO.output(self.In1FL, GPIO.LOW)
GPIO.output(self.In2FL, GPIO.HIGH)
GPIO.output(self.In3BL, GPIO.LOW)
GPIO.output(self.In4BL, GPIO.HIGH)
#left motor forward = In1_LOW & In3_LOW
# In2_HIGH & IN4_HIGH
else:
GPIO.output(self.In1FL, GPIO.HIGH)
GPIO.output(self.In2FL, GPIO.LOW)
GPIO.output(self.In3BL, GPIO.HIGH)
GPIO.output(self.In4BL, GPIO.LOW)
#left motor backwards = In1_HIGH & In3_HIGH
# In2_LOW & IN4_LOW
if rightSpeed>0:
GPIO.output(self.In3FR, GPIO.LOW)
GPIO.output(self.In4FR, GPIO.HIGH)
GPIO.output(self.In1BR, GPIO.LOW)
GPIO.output(self.In2BR, GPIO.HIGH)
#right motor forward = In1_LOW & In3_LOW
# In2_HIGH & IN4_HIGH
else:
GPIO.output(self.In3FR, GPIO.HIGH)
GPIO.output(self.In4FR, GPIO.LOW)
GPIO.output(self.In1BR, GPIO.HIGH)
GPIO.output(self.In2BR, GPIO.LOW)
#right motor backwards = In1_HIGH & In3_HIGH
# In2_LOW & IN4_LOW
print(f'Right speed is {rightSpeed}.')
print(f'Left speed is {leftSpeed}.')
sleep(time)
#-------------------------------------------------------------------------
def stop(self, time):
"""
Stops the motor
Parameters
----------
t : TYPE, optional
DESCRIPTION. Sets the stop time of the motor. The default is 0.
Returns
-------
None.
"""
self.pwmFL.ChangeDutyCycle(0)
self.pwmFR.ChangeDutyCycle(0)
self.pwmBR.ChangeDutyCycle(0)
self.pwmBL.ChangeDutyCycle(0)
sleep(time)
#----End of class--------------------------------------------------------------
def main():
"""
Test script if motor class is run in main
Returns
-------
None.
"""
motor1 = Motor(13,3,4,19,22,27,21,20,16,14,15,18)
motor1.stop(2)
motor1.move(0.4,-0.6,2)
GPIO.cleanup()
#-----------------------------------------------------------------------------
if __name__ == '__main__':
main()
However when I try to import the class into another module
from FourMotorClassWithTurn import Motor
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)#setup the pin out to be board numbers not BCM
GPIO.setwarnings(False)#stops set warnings from showing
motor1 = Motor(13,3,4,19,22,27,21,20,16,14,15,18)
motor1.stop(2)
motor1.move(0.4,-0.6,2)
GPIO.cleanup()
The motors will run once correctly but when I try to run it a second time I get a PWM fault
motor1 = Motor(13,3,4,19,22,27,21,20,16,14,15,18)
line 58, in init
self.pwmFL = GPIO.PWM(self.EnFL,100);
RuntimeError: A PWM object already exists for this GPIO channel
Anyone have an idea how to solve this?

Python code for multiple PIR motion sensors on Raspberry Pi

Connecting up to three 5v motion sensors on the raspberry pi for a project and I'm pretty new to python. I've successfully coded one motion sensor which lights up an LED and makes a buzzer sound when motion detected. How would I code multiple sensors that then light up different LEDs?
# Motion detected with buzzer and LED
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
#Refer pins by their sequence number on the board
GPIO.setmode(GPIO.BCM)
#Read output from PIR motion sensor
GPIO.setup(18, GPIO.IN)
#LED output pin
GPIO.setup(3, GPIO.OUT)
while True:
inp = GPIO.input(18)
#When output from motion sensor is HIGH
if inp == 1:
print("Motion detected!!")
GPIO.output(3, 1) #Turn on LED & Buzzer
time.sleep(1)
#When output from motion sensor in LOW
elif inp == 0:
print("No motion, all okay.")
GPIO.output(3, 0) #Turn off LED & Buzzer
time.sleep(1)
time.sleep(0.1)
You should create different instances for your sensors, for instance
inp_a = GPIO.input(18)
inp_b = GPIO.input(1x)
and so on.
then you can check with
if inp_b == 1
You can implement multithreading as well
Also, note that your last line of code, after the while loop, will never be executed.
If anyone in the future is looking to use a pair of PIR motion sensors on a raspberry 4, this code above helped me figured it out. The code below is how i used it.
motion_1 = GPIO.add_event_detect(pirPin, GPIO.RISING, callback=LIGHTS)
motion_2 = GPIO.add_event_detect(pirPin2, GPIO.RISING, callback=LIGHTS2)
try:
while True:
if motion_1 == 1:
motion_1
print('Test for BTC') # print in command line , not LCD
time.sleep(1)
elif motion_2 == 1:
motion_2
print('Test for eth') # print in command line, not LCD
time.sleep(1)
except KeyboardInterrupt:
print('Quit')
GPIO.cleanup()
## the lights function being called above, pulls data from binance API, and prints out the price to an LCD screen, so i can trigger a PIR motion on the left and it returns BTC, i can trigger PIR motion on the right and it returns ETH prices. Kind of fun to build.

Combining two python codes for raspberry pi with a servo and ldr sensor

I have Python code running on my raspberry pi 2b and a light sensor, which measures the amount of time it takes for the capacitor of the light sensor to charge and send the pin high:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
pin_to_circuit = 7
def rc_time (pin_to_circuit):
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1
if count > 1000000:
return True
else:
return count
#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
print rc_time(pin_to_circuit)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
I want when the count goes higher than 1000000, a MG90S, that I have also connected to the pi and a 4AA battery pack, moves about 90 degrees.
The code I was trying to integrate to move the servo:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p.ChangeDutyCycle(7.5) # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
GPIO.cleanup()
I want to combine these two Python codes. I tried for a bit, but I have almost no Python experience.
The code is now:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
pin_to_circuit = 7
def move_90_degrees():
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)
p = GPIO.PWM(12, 50)
p.start(7.5)
p.ChangeDutyCycle(7.5) # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
def rc_time (pin_to_circuit):
count = 0
#Output on the pin for
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.1)
#Change the pin back to input
GPIO.setup(pin_to_circuit, GPIO.IN)
#Count until the pin goes high
while (GPIO.input(pin_to_circuit) == GPIO.LOW):
count += 1
if count > 1000000:
return True
move_90_degrees()
else:
return count
#Catch when script is interrupted, cleanup correctly
try:
# Main loop
while True:
print rc_time(pin_to_circuit)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
The code does print True when the count exceeds 1000000, but the servo still doesn't move. The servo code on its own does however work correctly. (I forgot a bit of the servo code, that's why p wasn't defined, sorry.)
You could just integrate the code block you are using to move the MG90S into a function, insert it before or below your def rc_time (pin_to_circuit): (but first you have to define p inside, its not really clear what p refers to):
New Function from second code block:
def move_90_degrees():
p = '???'
GPIO.setup(12, GPIO.OUT)
p.ChangeDutyCycle(7.5) # turn towards 90 degree
time.sleep(1) # sleep 1 second
p.stop()
After defining this function, call it inside your first block like:
if count > 1000000:
move_90_degrees()
return True
else:
return count
That should work.
I've made a mistake in the code. I changed the order of the function call inside of the
if count > 1000000:
return True
move_90_degrees()
else:
return count
block to :
if count > 1000000:
move_90_degrees()
return True
else:
return count
otherwise, the code returns before the function call is executed. Is it working now?

else-like clause when PIR motion sensors not sensing using Raspberry Pi

I'm working on a Raspberry Pi project which displays a different video-loop depending on which of the 3 PIR motion sensors are "sensing motion". When no sensors are sensing anything, I want to display an additional video. So all in all there are 4 videos: left, middle, right, not-active.
Using Python 3.4.2 , I have managed to get videos playing when sensors are activated, but I am having difficulties getting a video to play when none of the sensors are active. I thought it would be a simple 'else' like clause, but apparently it is not. I've tried many different methods, but have ran out of ideas. Can someone help me integrate a "no motion detected" return to the code? The code is as below:
''' Import required stuff '''
import RPi.GPIO as GPIO #GPIO
import time #for delay
import subprocess #for omxplayer
''' GPIO setup '''
GPIO.setmode(GPIO.BCM) #GPIO setmode
PIR_PIN_L = 23 #define left pin
PIR_PIN_R = 24 #define right pin
PIR_PIN_M = 25 #define middle pin
GPIO.setup(PIR_PIN_L, GPIO.IN) #set left pin
GPIO.setup(PIR_PIN_R, GPIO.IN) #set right pin
GPIO.setup(PIR_PIN_M, GPIO.IN) #set middle pin
'''Definitions '''
def MOTIONL(PIR_PIN_L): #define motion on left
print("Motion Detected on Left!") #output if motion detected
def MOTIONR(PIR_PIN_R): #define motion on right
print("Motion Detected on Right!") #output if motion detected
def MOTIONM(PIR_PIN_M): #define motion in middle
print("Motion Detected at Middle!") #output if motion detected
''' Initiation '''
print("PIR Module Test (CTRL+C to exit)")
time.sleep(4)
print("Ready")
''' Sensing '''
try:
GPIO.add_event_detect(PIR_PIN_L, GPIO.RISING, callback=MOTIONL)
GPIO.add_event_detect(PIR_PIN_M, GPIO.RISING, callback=MOTIONM)
GPIO.add_event_detect(PIR_PIN_R, GPIO.RISING, callback=MOTIONR)
while 1:
time.sleep(100)
except KeyboardInterrupt:
print("Quit")
GPIO.cleanup()
I've replaced the video parts with print("Motion detected ...") for simplicity. If you can add a print("No motion detected") when no sensors are activated, it would be very helpful.
I managed to solve the issue, and thought I'll post it in case someone wants to use it. Note that the code has been changed quite considerably. It still uses very low CPU. The only difference is that this code is more efficient at picking up motions, but at the cost of higher false readings. That may be fixed by adjusting the knobs on the PIR sensor. The same concept can be applied to the code above.
''' Import required stuff '''
import RPi.GPIO as GPIO #GPIO
import time #for delay
''' GPIO setup '''
GPIO.setmode(GPIO.BCM) #GPIO setmode
PIR_PIN_L = 23 #define left pin
PIR_PIN_R = 24 #define right pin
PIR_PIN_M = 25 #define middle pin
GPIO.setup(PIR_PIN_L, GPIO.IN) #set left pin
GPIO.setup(PIR_PIN_R, GPIO.IN) #set right pin
GPIO.setup(PIR_PIN_M, GPIO.IN) #set middle pin
'''Definitions '''
def MOTIONL(): #define motion on left
if GPIO.input(PIR_PIN_L)==1 : #trigger condtion left being active
print("Motion Detected on Left") #output
time.sleep(3)
def MOTIONR(): #define motion on right
if GPIO.input(PIR_PIN_R)==1 : #trigger condtion right being active
print("Motion Detected on Right") #output
time.sleep(3)
def MOTIONM(): #define motion in middle
if GPIO.input(PIR_PIN_M)==1 : #trigger condtion middle being active
print("Motion Detected on Middle") #output
time.sleep(3)
def NOMOTION() :
if GPIO.input(PIR_PIN_L)==0 and GPIO.input(PIR_PIN_R)==0 and GPIO.input(PIR_PIN_M)==0 :
#above trigger condition is no sensor being active
print("No Motion Detected") #output
time.sleep(3)
''' Initiation '''
print("PIR Module Test (CTRL+C to exit)")
time.sleep(4)
print("Ready")
''' Sensing '''
try:
while 1: #calls defined functions simulatanously
NOMOTION()
MOTIONR()
MOTIONL()
MOTIONM()
except KeyboardInterrupt: #CTRL and C will reset shell
print("Quit")
GPIO.cleanup()
the print commands can be replaced with whatever function you wish to call.

Can someone tell me how I would modify this code to come on more than once a day?

Can someone please tell me how I would modify this code to come on more than once a day? I am very new to python and trying to get my pi to run this timer. I tried adding an additional variable to the array such as SatOn2 but it is ignored. Clearly I do not understand how this works in Python. This was originally intended to run xmas lights but I am modifying to run an irrigation drip timer.
Any help greatly appreciated. Thank You!
# Raspberry Pi custom Christmas light timer
# import GPIO module
import RPi.GPIO as GPIO
# set up GPIO pins as outputs
# This convention is for the "P1" header pin convention
# where the pins start with P1 in the upper left
# and go to P26 in the lower right, with odds in the
# left column and evens in the right column.
# So, pins P1-11 and P1-12 correspond to GPIO17 and
# GPIO18 respectively.
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
# import date and time modules
import datetime
import time
# Enter the times you want the lights to turn on and off for
# each day of the week. Default is for lights to turn on at
# 5:30pm and off at 10:30pm on weekdays, on at 5:00pm and off
# at 11:30pm on weekends. Note that this is using a 24-hour clock.
MonOn = datetime.time(hour=17,minute=30,second=0)
MonOff = datetime.time(hour=22,minute=30,second=0)
TueOn = datetime.time(hour=17,minute=30,second=0)
TueOff = datetime.time(hour=22,minute=30,second=0)
WedOn = datetime.time(hour=17,minute=30,second=0)
WedOff = datetime.time(hour=22,minute=30,second=0)
ThuOn = datetime.time(hour=17,minute=30,second=0)
ThuOff = datetime.time(hour=22,minute=30,second=0)
FriOn = datetime.time(hour=17,minute=30,second=0)
FriOff = datetime.time(hour=22,minute=30,second=0)
SatOn = datetime.time(hour=17,minute=0,second=0)
SatOff = datetime.time(hour=23,minute=30,second=0)
SunOn = datetime.time(hour=17,minute=0,second=0)
SunOff = datetime.time(hour=23,minute=30,second=0)
# Store these times in an array for easy access later.
OnTime = [MonOn, TueOn, WedOn, ThuOn, FriOn, SatOn, SunOn]
OffTime = [MonOff, TueOff, WedOff, ThuOff, FriOff, SatOff, SunOff]
# Set a "wait time" in seconds. This ensures that the program pauses
# briefly after it turns the lights on or off. Otherwise, since the
# loop will execute more than once a second, it will try to keep
# turning the lights on when they are already on (or off when they are
# already off.
waitTime = 3
# Start the loop that will run until you stop the program or turn
# off your Raspberry Pi.
while True:
# get the current time in hours, minutes and seconds
currTime = datetime.datetime.now()
# get the current day of the week (0=Monday, 1=Tuesday, 2=Wednesday...)
currDay = datetime.datetime.now().weekday()
#Check to see if it's time to turn the lights on
if (currTime.hour - OnTime[currDay].hour == 0 and
currTime.minute - OnTime[currDay].minute == 0 and
currTime.second - OnTime[currDay].second == 0):
# set the GPIO pin to HIGH, equivalent of
# pressing the ON button on the remote
GPIO.output(11, GPIO.HIGH)
# wait for a very short period of time then set
# the value to LOW, the equivalent of releasing the
# ON button
time.sleep(.5)
GPIO.output(11, GPIO.LOW)
# wait for a few seconds so the loop doesn't come
# back through and press the "on" button again
# while the lights ae already on
time.sleep(waitTime)
#check to see if it's time to turn the lights off
elif (currTime.hour - OffTime[currDay].hour == 0 and
currTime.minute - OffTime[currDay].minute == 0 and
currTime.second - OffTime[currDay].second == 0):
# set the GPIO pin to HIGH, equivalent of
# pressing the OFF button on the remote
GPIO.output(12, GPIO.HIGH)
# wait for a very short period of time then set
# the value to LOW, the equivalent of releasing the
# OFF button
time.sleep(.5)
GPIO.output(12, GPIO.LOW)
# wait for a few seconds so the loop doesn't come
# back through and press the "off" button again
# while the lights ae already off
time.sleep(waitTime)
Something like this should work:
# Raspberry Pi custom Christmas light timer
# import GPIO module
import RPi.GPIO as GPIO
# set up GPIO pins as outputs
# This convention is for the "P1" header pin convention
# where the pins start with P1 in the upper left
# and go to P26 in the lower right, with odds in the
# left column and evens in the right column.
# So, pins P1-11 and P1-12 correspond to GPIO17 and
# GPIO18 respectively.
GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
# import date and time modules
import datetime
import time
# Enter the times you want the lights to turn on and off for
# each day of the week. Default is for lights to turn on at
# 5:30pm and off at 10:30pm on weekdays, on at 5:00pm and off
# at 11:30pm on weekends. Note that this is using a 24-hour clock.
MonOn = datetime.time(hour=17,minute=30,second=0)
MonOff = datetime.time(hour=22,minute=30,second=0)
TueOn = datetime.time(hour=17,minute=30,second=0)
TueOff = datetime.time(hour=22,minute=30,second=0)
WedOn = datetime.time(hour=17,minute=30,second=0)
WedOff = datetime.time(hour=22,minute=30,second=0)
ThuOn = datetime.time(hour=17,minute=30,second=0)
ThuOff = datetime.time(hour=22,minute=30,second=0)
FriOn = datetime.time(hour=17,minute=30,second=0)
FriOff = datetime.time(hour=22,minute=30,second=0)
SatOn = datetime.time(hour=17,minute=0,second=0)
SatOff = datetime.time(hour=23,minute=30,second=0)
SunOn = datetime.time(hour=17,minute=0,second=0)
SunOff = datetime.time(hour=23,minute=30,second=0)
MonOnTwo = datetime.time(hour=12,minute=30,second=0)
MonOffTwo = datetime.time(hour=13,minute=30,second=0)
# Store these times in an array for easy access later.
OnTime = [[MonOn, MonOnTwo], [TueOn], [WedOn], [ThuOn], [FriOn], [SatOn], [SunOn]]
OffTime = [[MonOff, MonOffTwo], [TueOff], [WedOff], [ThuOff], [FriOff], [SatOff], [SunOff]]
# Set a "wait time" in seconds. This ensures that the program pauses
# briefly after it turns the lights on or off. Otherwise, since the
# loop will execute more than once a second, it will try to keep
# turning the lights on when they are already on (or off when they are
# already off.
waitTime = 3
halfWait = waitTime / 2
# Start the loop that will run until you stop the program or turn
# off your Raspberry Pi.
while True:
# get the current time in hours, minutes and seconds
currTime = datetime.datetime.now()
# get the current day of the week (0=Monday, 1=Tuesday, 2=Wednesday...)
currDay = datetime.datetime.now().weekday()
for dtimes in OnTime[currDay]:
#Check to see if it's time to turn the lights on
if (currTime.hour - dtimes.hour == 0 and
currTime.minute - dtimes.minute == 0 and
currTime.second - dtimes.second > -halfWait and
currTime.second - dtimes.second < halfWait):
# set the GPIO pin to HIGH, equivalent of
# pressing the ON button on the remote
GPIO.output(11, GPIO.HIGH)
# wait for a very short period of time then set
# the value to LOW, the equivalent of releasing the
# ON button
time.sleep(.5)
GPIO.output(11, GPIO.LOW)
for dtimes in OffTime[currDay]:
#check to see if it's time to turn the lights off
if (currTime.hour - dtimes.hour == 0 and
currTime.minute - dtimes.minute == 0 and
currTime.second - dtimes.second > -halfWait and
currTime.second - dtimes.second < halfWait):
# set the GPIO pin to HIGH, equivalent of
# pressing the OFF button on the remote
GPIO.output(12, GPIO.HIGH)
# wait for a very short period of time then set
# the value to LOW, the equivalent of releasing the
# OFF button
time.sleep(.5)
GPIO.output(12, GPIO.LOW)
# wait for a few seconds because it's pointless to burn energy
# with no benefit
time.sleep(waitTime)

Categories