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
Related
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time
def privacyfunc():
# Pin Definitions:
led_pin_1 = 7
led_pin_2 = 21
but_pin = 18
# blink LED 2 quickly 5 times when button pressed
def blink(channel):
x=GPIO.input(18)
print("blinked")
for i in range(1):
GPIO.output(led_pin_2, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(led_pin_2, GPIO.LOW)
time.sleep(0.5)
mqttBroker="mqtt.fluux.io"#connect mqtt broker
client=mqtt.Client("privacybtn") #create a client and give a name
client.connect_async(mqttBroker)#from the client -connect broker
while True:
client.publish("privacy", x)#publish this random number to the topic called temparature
print("Just published"+str(x)+"to Topc to privacy")#just print random no to topic temparature
break
def main():
# Pin Setup:
GPIO.setmode(GPIO.BOARD) # BOARD pin-numbering scheme
GPIO.setup([led_pin_1, led_pin_2], GPIO.OUT) # LED pins set as output
GPIO.setup(but_pin, GPIO.IN) # button pin set as input
# Initial state for LEDs:
GPIO.output(led_pin_1, GPIO.LOW)
GPIO.output(led_pin_2, GPIO.LOW)
GPIO.add_event_detect(but_pin, GPIO.FALLING, callback=blink, bouncetime=10)
print("Starting demo now! Press CTRL+C to exit")
try:
while True:
x=GPIO.input(18)
print(x)
# blink LED 1 slowly
GPIO.output(led_pin_1, GPIO.HIGH)
time.sleep(2)
finally:
GPIO.cleanup() # cleanup all GPIOs
if __name__ == '__main__':
main()
need to take this whole code into a function that can be accessed from another python file.plz, help me with this coding part.
In the new python file call import module where module is the name of the file. Like led_blink.py would be import led_blink
Then you can call the methods like so:
led_blink.blink(channel)
This is assuming the files are in the same folder.
Easiest way that I do this is to take a .py file and put it in the same directory you created the python script you are working with. From there you can do the following code from The_Python_File import *
Additionally note that the "The_Python_File" is the name of the .py file that contains the function you are trying to call, but you do not include .py when importing the file.
I have a raspberry pi and an RFID reader. I have a python script that uses RFID and spotipy to read RFID tags and plays a song/song when a certain RFID tag is scanned. I'm trying to make this python script run on startup using crontab -e so I don't have to run it everytime. I followed a tutorial online and used an example script. The example runs on start up. When I substitute it for the player script however it does not work. This is what I had in the crontab -e #reboot python3 /home/pi/Documents/rfidspotify/player.py. Here's the player python script I was using.(script works fine when I run it)
#!/usr/bin/env python
from mfrc522 import SimpleMFRC522
import RPi.GPIO as GPIO
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from time import sleep
DEVICE_ID="YOUR_DEVICE_ID"
CLIENT_ID="YOUR_CLIENT_ID"
CLIENT_SECRET="YOUR_CLIENT_SECRET"
while True:
try:
reader=SimpleMFRC522()
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri="http://localhost:8080",
scope="user-read-playback-state,user-modify-playback-state"))
# create an infinite while loop that will always be waiting for a new scan
while True:
print("Waiting for record scan...")
id= reader.read()[0]
print("Card Value is:",id)
sp.transfer_playback(device_id=DEVICE_ID, force_play=False)
# DONT include the quotation marks around the card's ID value, just paste the number
if (id=='RFID-CARDVALUE-1'):
# playing a song
sp.start_playback(device_id=DEVICE_ID, uris=['spotify:track:2vSLxBSZoK0eha4AuhZlXV'])
sleep(2)
elif (id=='RFID-CARDVALUE-2'):
# playing an album
sp.start_playback(device_id=DEVICE_ID, context_uri='spotify:album:0JGOiO34nwfUdDrD612dOp')
sleep(2)
# continue adding as many "elifs" for songs/albums that you want to play
# if there is an error, skip it and try the code again (i.e. timeout issues, no active device error, etc)
except Exception as e:
print(e)
pass
finally:
print("Cleaning up...")
GPIO.cleanup()
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)
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.
I build a keypad activated sensor with a Raspberry Pi and Python. Everything seems to go well but after a few minutes and several keypad entries, the Pi has a total crash and switches off immediately - no error messages pop up.
The script will continously wait for a keypad entry and if the code is correct, switch on a sensor, if it's not you have to try again. If the sensor is activated you have to put in the correct numbers to avoid an alarm being triggered after 30s)
Could anyone point me in the direction of what might be the problem? Here are the things I've tried so far without success
1) Exchange Pi to new Pi 2
2) Different OS, both NOOBS and Raspbian Wheezy
3) Different sensor (accelerometer vs IR sensor)
4) Disconnect monitor, keyboard and use SSH connection via Cygwin
5) Get log file until crash - log file was empty after reboot
python bad_script &> full_log.txt
6) Different log file command: causes instant crash and is also empty after reboot:
python script.py >> /logdir/script.py.log 2>&1
The question is: how am I able to crash Linux? If it's a memory problem, isn't there a prevention in linux to stop processed before they appear?
Here is the full script I am running:
import sys
from time import sleep
import threading
import signal
from matrix_keypad import RPi_GPIO1
import RPi.GPIO as GPIO
import smbus
import time
passcode = [1,2,3,4] # this is the correct code you have to enter
kp = RPi_GPIO1.keypad(columnCount = 3)
alarm_active = threading.Event() # shared variable used to control the sensor monitoring thread
alarm_active.clear() # Clear the alarm initially
monitor_thread = None # Global variable used to store the monitoring thread
#Set up all the pins correctio
GPIO.setmode(GPIO.BCM)
PINIR=7
GPIO.setup(7, GPIO.IN) # infrad-sensor
#Now activate the kaypad and listen for keypad inputs
def digit():
r = None
while r == None:
r = kp.getKey()
return r
def get_keycode():
# Function to loop around reading 4 keypresses in a row
# Compare against chosen code
# If match, switch the alarm state
entered = []
while len(entered) < 4:
key = digit()
sleep(0.5)
print key
entered.append( key )
if entered == passcode:
entered = []
print "Code correct"
switch_alarm_state()
else:
# Just clear the keypad buffer if the wrong code went in
# Could say "BAD CODE!" here, or even force immediate alarm perhaps
print "Wrong Code - Try again"
GPIO.output(27, True) # let red LED blink as indicator that code was wrong
time.sleep(1)
GPIO.output(27, False)
entered = []
def switch_alarm_state():
# Function to control the state of the alarm
# If the alarm should be on, run a thread monitoring the sensor
# If the alarm should be off, make sure the thread is stopped
global monitor_thread
if alarm_active.is_set():
# If the alarm is currently set, stop it
print "Alarm was abolished"
GPIO.output(17, False) #switch green LED off
alarm_active.clear() # Signals to the monitor thread that we wish to shut it down
monitor_thread.join() # Wait until the monitor thread has stopped
else:
# Alarm is not currently set, so start the sensor monitor thread going
print "Alarm was activated"
GPIO.output(17, True)
monitor_thread = threading.Thread( target=sensor_monitor )
alarm_active.set()
monitor_thread.start()
def sensor_monitor():
# Function to be run in a separate thread, monitoring the sensor
alarm_timer = None # Variable to hold a timer object that will fire the alarm
while alarm_active.is_set():
#print xrota
if GPIO.input(PINIR):
print "Alarm has been triggered"
if alarm_timer is None:
alarm_timer = threading.Timer( 30.0, fire_alarm )
alarm_timer.start()
sleep(0.5)
# The alarm must have been deactivated to get here
# Stop any outstanding alarms and shutdown
if alarm_timer is not None:
alarm_timer.cancel()
return
def fire_alarm():
# Here you implement the actions to be carried out by an alarm
print "Alarm is send to server"
msg = "Alarm"
publish.single("alarm/demo",msg, hostname="52.17.194.125")
def shutdown_handler( signum, frame ):
# Shut down the child thread nicely
alarm_active.clear()
monitor_thread.join()
if __name__ == '__main__': # This is the Python way to check you are being directly run, and not just imported by another script
signal.signal( signal.SIGINT, shutdown_handler ) # If you stop the script with ctrl+C, make sure it shuts down properly
signal.signal( signal.SIGTERM, shutdown_handler )
try:
while True:
get_keycode()
except KeyboardInterrupt:
GPIO.cleanup()
print "Quit program"