The LEDs dont blink and i get this error every time i run my python program.
blink.py:4: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(16,GPIO.OUT)
blink.py:5: RuntimeWarning: This channel is already in use, continuing anyway. Use GPIO.setwarnings(False) to disable warnings.
GPIO.setup(18,GPIO.OUT)
I've done some research into the problem but none of the solutions work
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)
while True:
GPIO.output(16, GPIO.HIGH)
GPIO.output(18, GPIO.LOW)
time.sleep(1)
GPIO.output(16, GPIO.LOW)
GPIO.output(18, GPIO.HIGH)
time.sleep(1)
Does anyone have a solution?
Have you tried using try/except/finally blocks in your while-loop for handling errors? (Let me know if try/except/finally is unfamiliar to you).
Here's an example you can take a look at
http://raspi.tv/2013/rpi-gpio-basics-3-how-to-exit-gpio-programs-cleanly-avoid-warnings-and-protect-your-pi
Good luck!
This is because the GPIO pins are already in use. Were they set up in another script before this? You should perform GPIO cleanup after every use. As #Tommi mentioned in their answer, a try/except/finally block is useful for triggering cleanup afterwards. Here is an example demonstrating this, adapted from this site.
import RPi.GPIO as GPIO
import time
# Consider calling GPIO.cleanup() first
GPIO.setmode(GPIO.BCM)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(18,GPIO.OUT)
try:
# Your code here
while True:
GPIO.output(16, GPIO.HIGH)
GPIO.output(18, GPIO.LOW)
time.sleep(1)
GPIO.output(16, GPIO.LOW)
GPIO.output(18, GPIO.HIGH)
time.sleep(1) # This line should be here so it is part of the while loop
except KeyboardInterrupt:
# Here you put any code you want to run before the program
# exits when you press CTRL+C
print("Keyboard interrupt")
except:
# This catches ALL other exceptions including errors.
# You won't get any error messages for debugging
# so only use it once your code is working
print("Other error or exception occurred!")
finally:
GPIO.cleanup() # This ensures a clean exit
I found out that the raspberry pi 3B GPIO pins are not in order, the place i was using them said it was in order but it was not. So after fixing one light blinks and one light continuously stays on but i need both to blink i shall look further.
Related
My question is: GPIO.add_event_detect() is detecting a false Rising edge continuously in an infinite loop and running the call_back function() infinitely even though I do not press the push-button connected to GPIO 25 even once But the call_back function() keeps executing.
Here is my code, where I want to call the call_back function x1() which contains the function WhatsApp(lat_o,long_o) only when the button is pressed but WhatsApp(lat_o,long_o) keeps executing without me pressing the button. Also, I put WhatsApp(lat_o,long_o) inside x1() to remove the problem of passing arguments to the call_back function.
# INTERRUPTS (NOT WORKING)
# Sample Coordinates
lat_o=33
long_o=72
# Import Libraries
import RPi.GPIO as GPIO
from time import sleep
def x1(channel):
WhatsApp(lat_o,long_o)
# Configure GPIO of Rpi
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BCM) # Use GPIO pin numbering
button1 = 25 # For WhatsApp
# Setup GPIO for Whatsapp
GPIO.setup(button1, GPIO.IN, pull_up_down = GPIO.PUD_DOWN) # Set GPIO 25 (pin 22) to be an input pin for WhatsApp
# Detect button1-press
GPIO.add_event_detect(button1 ,GPIO.RISING, callback = x1)
try:
while True : pass
except:
GPIO.cleanup()
Please help!
I don't want to execute WhatsApp(lat_o,long_o) using Polling (i.e., using if-else in a while loop) in my Final Code for my Final Year Project because I want GPIO to detect button press continuously and using Polling here will drain a lot of power of my Raspberry Pi 4.
According to this discussion on the raspsberrypi discussion
A rising edge will be detected at approx. 1.25V. However, when the
voltage lowers again and the input voltage drops below the 1.16V
level, a stream of interrupts will start, and continue until the level
is below 1.12V.
This is most dramatic when slower rising or falling edges are present,
as an example, when excessive anti-debounce measures have been taken.
This is the given solutuion
In software, I use two other techniques to get rid of the false hits.
First, after the edge has been recognized by the system, we don't know
if it is the one we expect. By waiting for 5mSec, and then reading the
input again but now with a Logic Level command, we can determine if
the edge is indeed what we expect and we then avoid and discard all
other (false) edges.
And finally the code for rising edge
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BCM)
Input_Sig = 23 # any plain GPIO pin
# if there is no external pull, use the internal one (pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(Input_Sig, GPIO.IN)
def interrupt_service_routine(Input_Sig):
sleep(0.005) # edge debounce of 5mSec
# only deal with valid edges
if GPIO.input(Input_Sig) == 1:
print("RISING")
return
# define the event; bountime of 5mSec means that subsequent edges will be ignored for 5mSec
GPIO.add_event_detect(Input_Sig, GPIO.RISING, callback=interrupt_service_routine, bouncetime=5)
def main():
try:
while True:
pass # your code
except KeyboardInterrupt:
pass
finally:
print("\nRelease the used pin(s)")
GPIO.cleanup([Input_Sig])
if __name__ == '__main__':
main()
import pygame
file = 'some.mp3'
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file)
pygame.mixer.music.play()
This outputs, "Process finished with exit code 0", but it doesn't play anything. How can I resolve this problem?
The play function starts the music playing, but returns immediately. Then your program reaches it's end, and the pygame object is automatically destroyed which causes the music to stop.
As you commented, it does play the music if you wait for it before exiting - because then the pygame object isn't destroyed until the while loop finishes.
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
The music stops because it's an asyncronous event, which means it'll keep going with the script. then, the script stops instantly, not giving the music a chance to start.
as stated before, you could use
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
however, even better is pygame.event.wait(), as it'll wait for all asynchronous events to end.
Here is a super easy way.
import pygame
file = 'some.mp3'
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(file)
pygame.mixer.music.play()
pygame.event.wait()
I've found a good solution from thepythongamebook.com:
pygame.mixer.pre_init(44100, -16, 2, 2048) # setup mixer to avoid sound lag
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load('music_01.mp3')
pygame.mixer.music.play(-1)
try this one.
import pygame
def pmusic(file):
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()
pygame.mixer.music.load(file)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
print("Playing...")
clock.tick(1000)
def stopmusic():
pygame.mixer.music.stop()
def getmixerargs():
pygame.mixer.init()
freq, size, chan = pygame.mixer.get_init()
return freq, size, chan
def initMixer():
BUFFER = 3072 # audio buffer size, number of samples since pygame 1.8.
FREQ, SIZE, CHAN = getmixerargs()
pygame.mixer.init(FREQ, SIZE, CHAN, BUFFER)
try:
initMixer()
file = 'C:\\data\\03.mp3'
pmusic(file)
except KeyboardInterrupt: # to stop playing, press "ctrl-c"
stopmusic()
print("\nPlay Stopped by user")
except Exception:
print("unknown error")
print("Done")
PyGame has 2 different modules for playing sound and music, the pygame.mixer module and the pygame.mixer.music module. This module contains classes for loading Sound objects and controlling playback. The difference is explained in the documentation:
The difference between the music playback and regular Sound playback is that the music is streamed, and never actually loaded all at once. The mixer system only supports a single music stream at once.
If you want to play a mp3 file, you need to initialize the module. Load the file with pygame.mixer.music.load. Invoke pygame.mixer.music.play() to start playback of the music stream. Finally, you have to wait for the file to play.
Use pygame.mixer.music.get_busy() to test if a sound is being mixed. Query the status of the mixer continuously in a loop.
In the loop, you need to delay the time by either pygame.time.delay or pygame.time.Clock.tick. In addition, you need to handle the events in the application loop. See pygame.event.get() respectively pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
import pygame
pygame.init()
pygame.mixer.music.load('my_music.mp3')
pygame.mixer.music.play()
clock = pygame.time.Clock()
while pygame.mixer.music.get_busy():
clock.tick(60)
pygame.event.poll()
It seems the audio does not play because of the way you have imported it. The code below plays the sound as expected. Nothing has changed here except that rather than import pygame it uses from pygame import mixer. This may be due to the fact Pygame is a package but I'm not sure.
from pygame import mixer
file = 'some.mp3'
mixer.init()
mixer.music.load(file)
mixer.music.play()
I have to make a player that can play two songs simultaneously.
The problem is that the only module that I could find that supports every sound manipulation method that I need to use is Pygame.mixer.music. Unfortunately it only supports a single music stream at once.
I tried to cheat the system using threads and multiprocessing but it didn't do the job.
My question is does anybody know a Python3 module that can play 2 songs at once and has the following possibilities: pause, stop, seek through the song, change volume and change speed of the song.
Or does anybody know how to do this with the Pygame module.
The multiprocessing code that I tried to use is down below if anybody can help with this I'd be grateful!
import pygame
import multiprocessing
pygame.mixer.init()
def play(arg):
pygame.mixer.init()
if arg:
print(arg)
pygame.mixer.music.load('song1.ogg')
pygame.mixer.music.play()
else:
print(arg)
pygame.mixer.music.load('song2.ogg')
pygame.mixer.music.play()
p1 = multiprocessing.Process(target=play, args=(True,))
p2 = multiprocessing.Process(target=play, args=(False,))
p1.start()
p2.start()
while True:
pass
You don't need any threading or multiprocessing. You can just paly 2 songs parallel using the pygame.mixer.Sound objects:
import pygame
pygame.mixer.init()
song_1 = pygame.mixer.Sound('song1.ogg')
song_2 = pygame.mixer.Sound('song2.ogg')
song_1.play(0)
song_2.play(0)
while pygame.mixer.get_busy():
pygame.time.delay(10)
I found a way to get the job done.
At the moment I am using 2 sound manipulation modules:
Pygame.mixer.music
python-vlc
They are working properly together and have the functions that I needed.
I have a simple watchdog in python 3 that reboots my server if something goes wrong:
import time, os
from multiprocessing import Pool
def watchdog(x):
time.sleep(x)
os.system('reboot')
return
def main():
while True:
p = Pool(processes=1)
p.apply_async(watchdog, (60, )) # start watchdog with 60s interval
# here some code thas has a little chance to block permanently...
# reboot is ok because of many other files running independently
# that will get problems too if this one blocks too long and
# this will reset all together and autostart everything back
# block is happening 1-2 time a month, mostly within a http-request
p.terminate()
p.join()
return
if __name__ == '__main__':
main()
p = Pool(processes=1) is declared every time the while loop starts.
Now here the question: Is there any smarter way?
If I p.terminate() to prevent the process from reboot, the Pool becomes closed for any other work. Or is there even nothing wrong with declaring a new Pool every time because of garbage collection.
Use a process. Processes support all of the features you are using, so you don't need to make a pool with size one. While processes do have a warning about using the terminate() method (since it can corrupt pipes, sockets, and locking primitives), you are not using any of those items and don't need to care. (In any event, Pool.terminate() probably has the same issues with pipes etc. even though it lacks a similar warning.)
I am trying to create a GUI with wxPython. After I create the GUI I want the code to continue to execute, so I have tried to throw the app.MainLoop() onto a new thread. This gives me issues. Also when I try to change the background color for example, it freezes up the GUI.
import wx
import threading
from threading import Thread
from multiprocessing import Process
class Display(wx.Frame):
def __init__(self, *args, **kwargs):
print 'here'
self.app = wx.App(False)
super(Display, self).__init__(*args, **kwargs)
self.SetTitle("Yo mama")
self.Show(True)
thread = Thread(target = self.app.MainLoop)
thread.start()
self.Close()
def DisplayGUI(self):
self.SetTitle("MyTitle")
self.Show(True)
def Changetitle(self):
self.SetTitle("Title2")
display = Display(None)
# do stuff
display.ChangeTitle()
# do stuff
So basically I want to be able to run a GUI, and control it later on within my program (not through the GUI itself with events). I plan on having pictures display at random times.
The GUI's MainLoop needs to run in the main thread. So do this, and if you want events at random times, you can use a timer, for example, wx.Timer.
Using this approach, all the changes you mention (displaying pictures, changing the titles, colors, etc) should be straightforward. Plus, you'll get a lot more control this way, where you can start and stop timers, change the interval, have multiple timers, setup timers that trigger each other, and many other options.
To learn more about wx.Timer, a good place to start is always the demo. There's also a tutorial here, and a video here.
(I've heard that there are ways to run the MainLoop in a separate thread, but nothing you mention requires that, and it will be much, much easier to just use a timer.)