import RPi.
GPIO as GPIO
import time
from rpi_lcd import LCD
# --- Constants ---
IR_SENSOR_PIN = 17 # GPIO pin for the IR sensor
I2C_ADDRESS = 0x27 # I2C address for the LCD
DEBOUNCE_TIME = 0.005 # 10 ms debounce time to filter out noise
# --- Initialization ---
[Link]([Link])
[Link](IR_SENSOR_PIN, [Link], pull_up_down=GPIO.PUD_UP)
lcd = None
try:
lcd = LCD(address=I2C_ADDRESS)
except Exception as e:
print(f"Error initializing LCD: {e}")
# --- Tachometer Variables ---
count = 0 # Initialize count
rpm = 0
last_pulse_time = [Link]() # Track the last pulse time for debounce logic
start_time = last_pulse_time # Timer for RPM calculation
# --- Functions ---
def calculate_rpm():
global count, start_time, rpm
elapsed_time = [Link]() - start_time
if elapsed_time >= 0.5: if elapsed_time > 0:
rpm = (count / elapsed_time) * 60 * 2
else:
rpm = 0
count = 0
start_time = [Link]()
def display_rpm():
if lcd:
try:
[Link](f"RPM: {int(rpm)}", 1)
[Link](" ", 2)
except Exception as e:
print(f"Error updating LCD: {e}")
def main():
global count, last_pulse_time
print("Tachometer Program Started")
try:
while True:
# Check if sensor is triggered (LOW state)
if [Link](IR_SENSOR_PIN) == [Link]: # Triggered by sensor (LOW state)
current_time = [Link]()
# Debounce logic
if current_time - last_pulse_time > DEBOUNCE_TIME:
count += 1
last_pulse_time = current_time
calculate_rpm() # Update RPM
display_rpm() # Update LCD display
[Link](0.0005) # Short delay for smoother updates
except KeyboardInterrupt:
print("Program interrupted by user.")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
# Cleanup GPIO and LCD
if lcd:
try:
[Link]()
except Exception as e:
print(f"Error clearing LCD: {e}")
[Link]()
print("GPIO cleanup completed. Exiting program.")
if __name__ == "__main__":
main()
import [Link] as GPIO
import time
# Pin configuration
SWITCH_PIN = 12 # GPIO pin connected to the switch
RELAY_PIN = 16 # GPIO pin connected to the relay
# GPIO setup
[Link]([Link]) # Use BCM pin numbering
[Link](SWITCH_PIN, [Link], pull_up_down=GPIO.PUD_DOWN) # Switch as input with pull-down
resistor
[Link](RELAY_PIN, [Link]) # Relay as output
try:
while True:
if [Link](SWITCH_PIN) == [Link]: # Check if the switch is ON
[Link](RELAY_PIN, [Link]) # Turn ON the relay
print("Relay ON")
else:
[Link](RELAY_PIN, [Link]) # Turn OFF the relay
print("Relay OFF")
[Link](0.1) # Small delay to avoid CPU overuse
except KeyboardInterrupt:
print("Exiting program...")
finally:
[Link]() # Reset GPIO settings