LED control using keyboard on Raspberry Pi 4 - Python - python

I am completely novice in Python and in Raspberry Pi. However, I have one, maybe easy to solve problem. I want to control LED diod on RPi4 with a keyboard.
If I press "1", I want the LED be active, and if I press "0" or any other key, I want to LED be inactive. I am running Python 3.7.3 on my Raspberry Pi4. The code below is working, but when I press "1" or "0", I have to run my code via command line again if I want to change status of LED.
Is there any solution, how to still read an input from keyboard and automatically based on it change the status of the LED?
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
user_input = input("Input value 0 or 1: ")
print(user_input)
while (True):
if user_input == "1":
GPIO.output(14,GPIO.HIGH)
time.sleep(1)
else:
GPIO.output(14,GPIO.LOW)
time.sleep(1)

You are only asking for the user input once. move the input(...) within the while loop.
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(14,GPIO.OUT)
while True:
user_input = input("Input value 0 or 1: ")
print(user_input)
if user_input == "1":
GPIO.output(14,GPIO.HIGH)
time.sleep(1)
else:
GPIO.output(14,GPIO.LOW)
time.sleep(1)

Related

Python Keyboard module executing keys to next line in CLI

I am creating a simple number only user input for CLI and also created it. But while using keyboard module when the user tries to press enter, the program closes perfectly, but the text that user enters gets executed in command line.
import keyboard
specials = "1234567890"
userinput = ""
no_of_presses = 0
print("Number to be doubled : ",end="",flush=True)
def show(e):
global no_of_presses, userinput
if(e.name in specials):
print(e.name,end="",flush=True)
no_of_presses+=1
userinput+=e.name
def output(e):
global userinput
print(f"\noutput : {int(userinput)*2}")
keyboard.on_press(show)
keyboard.on_press_key("enter",output)
keyboard.wait("enter")
Here is the image of sample error I am getting

Can't run file on boot-up with Raspberry Pi

I have tried multiple ways (crontab and rc.local) of going about this. I have triple checked my code and processes each time but to no avail.
I am making a father's day gift with a button that says his favorite word, "No!".
Every time I reboot, my program does not respond at all to the GPIO and the button attached.
Is it how I have things structured in my sloppy code?
I'm not native in Python so I beg of you to help me.
When ran from the terminal or through Thonny, it runs perfectly. But no matter what, doesn't boot at start-up!
Here is my rc.local
Here's my code for the program:
import pygame
from random import randint
import RPi.GPIO as GPIO
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
pygame.mixer.init()
#pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
proverbFile = 'proverbs/Pro1.mp3'
num = 5
def randNo ():
noFile = '/home/pi/Desktop/audio/no/No1.mp3'
print('Executed!')
default = 1
global num
pulled = 1
while num == pulled:
pulled = randint(1,4)
print('Same!')
num = pulled
print(num)
noFile = noFile.replace(str(default), str(num), 1)
print(noFile)
pygame.mixer.music.load(noFile)
pygame.mixer.music.play()
default = num
def button_callback(channel):
print("Button was pushed!")
randNo()
GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback)
#while True:
# keyPress = input('Press q to quit: ')
# if keyPress == 'q':
# break;
#GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) # Setup event on pin 10 rising edge
If you want a script to run when you boot into the LXDE environment, you could take a look at this Raspberry Pi forum post:
Navigate to ~/.config/lxsession/LXDE-pi
Open the autostart file in that folder:
$ sudo nano autostart
Add #midori on a new line. If you want to run something like a python script, put something like #python mypython.py on a new line. Running a script file would be #./superscript, but for some reason the script runs in an infinite loop (perhaps this will stop that).
Save and exit: Ctrl+X, Y, Enter
Restart your Raspberry Pi into the LXDE environment.
answer from here

to invert a GPIO input

This is my Code to start my other Code where i defined my Laser to start.
But in this Code i want to have a Button which starts my other script if i put press it.
But what this code does is it activate my code continuous.
What can i change in it ?
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import os
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO.setmode(GPIO.BOARD)
GPIO.setup(15,GPIO.IN) #GPIO17
#input = GPIO.input(27)
#print ("input",input)
while True :
#inputValue = GPIO.input(11)
#print ("input01",inputValue)
#time.sleep(1)
erg= GPIO.wait_for_edge(15,GPIO.RISING, bouncetime=20)
print ("Input",2)
#if (GPIO.input(11) == GPIO.HIGH):
#if erg==15:
print ("Input",1)
time.sleep(3)
#inputValue = 1
os.system("python /home/pi/gpio.py")
When you run os.system('python /home/pi/gpio.py') you start new process and your main process get back to work on its while loop.
As I understood your idea was to wait until button is pressed and then go to some other state waiting for something new to happen.
You don't need to start new process just import module (doc). When button was clicked break loop and run code from the imported module.
Also you may find it interesting to replace wait_for_edge with event_detected method. More about it here.

To check the status of relay using interrupt in raspberry pi

I am working with a raspberry pi with a relay with the incandescent bulb, buzzer, and button via SSH. The code is in a way that when I press a key from the keyboard the bulb and buzzer should be ON and when I press button both should get OFF. But my button code is not working properly.
And also I want to check the status of the relay using the interrupt and whenever the light on it should be sent a message to the database. But I don't know with interrupts. Below is my code. Please help me. Thanks in advance
import RPi.GPIO as GPIO
import time
in1 = 25 #GPIO25 pin22
buzzer=24 #GPIO24 PIN18
led=8 #GPIO8 PIN24
button=23 #GPIO23 PIN 16
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(in1, GPIO.OUT)
GPIO.setup(buzzer,GPIO.OUT)
GPIO.setup(led,GPIO.OUT)
#GPIO.setup(button,GPIO.IN,pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(button, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(in1, False)
GPIO.output(buzzer,False)
GPIO.output(led,False)
try:
GPIO.output(in1,False)
while True:
GPIO.output(in1,False)
# check from database whether it is effective or deffective .currently I have inputted from keyboard
variable=raw_input()
if variable=="a":
m=variable
for x in m:
GPIO.output(in1, True)
time.sleep(0.05)
GPIO.output(in1, False)
time.sleep(0.05)
GPIO.output(buzzer,True)
GPIO.output(led,True)
if in1==True || buzzer==True:
print "messge to database:pending"
#def my_callback(channel):
#if GPIO.input(button) == True:
GPIO.wait_for_edge(button, GPIO.FALLING)
#if variable=="b":
#while 1:
GPIO.output(in1,False)
GPIO.output(led,False)
GPIO.output(buzzer,False)
print "mesage to database:ack completed"
#else:
#pass
#else:
#pass
GPIO.output(in1,False)
except:
GPIO.cleanup()
GPIO.output(in1,False)
If there is any error in my code please help me to rectify that. Thanks

Waiting for Input without Interrupting with Loops

First of all, I use windows so i couldn't make curses work in windows.
I'm trying to make a login interface while an ASCII Animation is Looping.
def animation():
while True:
#something that do animation
def login_screen():
uname = str(input("Username : "))
passw = str(input("Password : "))
print("Welcome {}".format(uname))
so how do i do this in one console screen ? this is for example :

Categories