RuntimeError: You must setup() the GPIO channel first - python

When i execute with sudo python3 program.py and press de switch 1 throws the next exception:
Taking picture...
Picture takeng...
Traceback (most recent call last):
File "main.py", line 21, in <module>
if GPIO.input(switch1):
RuntimeError: You must setup() the GPIO channel first
I use a raspberry cam library and rpi.gpio library for this project. Anyone knows what happend in my code ?
import RPi.GPIO as GPIO
import time
import picamera
# initial config for gpio ports
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
# input switches
switch1 = 22
switch2 = 23
switch3 = 24
# setup
GPIO.setup(switch1, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch2, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(switch3, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# main loop
while True:
if GPIO.input(switch1):
print ("Taking picture...")
with picamera.PiCamera() as camera:
camera.resolution = (1280, 720)
camera.start_preview()
time.sleep(0.5)
camera.capture("test.jpg")
print ("Picture takeng...")
elif GPIO.input(switch2):
print ("Taking video...")
elif GPIO.input(switch3):
print ("Poweroff...")
break
GPIO.cleanup()

The error is telling you that you have not set the pins to work as input and, when you try to access them as so, it fails. I had a similar problem and as far as I see it it should work (you are setting the pins after all).
Try changing GPIO.setmode(GPIO.BCM) to GPIO.setmode(GPIO.BOARD). You will also have to change the pin numbers to the physical ones (yours would be 15, 16 and 18).
I still don't know why, but it did the trick on my code.

You have to give access permission to the /dev/ folder and the mem file.
To do so open the raspberry terminal and enter the commands bellow
sudo chmod -R 777 /dev/ and hit enter
then
sudo chmod -R 777 /dev/mem and hit enter that's it

Related

How to use servoKit library and GPIO pins

I have been struggling because of the library adafruit_servokit has been stopping me from assigning pins. When I try to do this:
from adafruit_servokit import ServoKit # Servo library that works with Jetson
import RPi.GPIO as GPIO # Part of PWM DC motor control
GPIO.setmode(GPIO.BOARD) # Error here
It returns an error saying this:
Traceback (most recent call last):
File "brew.py", line 4, in <module>
GPIO.setmode(GPIO.BOARD)
File "/usr/lib/python3/dist-packages/Jetson/GPIO/gpio.py", line 317, in setmode
raise ValueError("A different mode has already been set!")
ValueError: A different mode has already been set!
I just need a way to control my servos and use my GPIO pins at the same time.
I'm open to buying new parts as well.
Turns out I just needed to use digitalio: https://learn.adafruit.com/circuitpython-on-raspberrypi-linux/digital-i-o

raspberry pi addEvent. Runtime error:Failed to add edge detection

I am writing python code on raspberry pi 3. I am registering an event on input channel 21, to check moisture detection. I am getting this error Runtime error:Failed to add edge detection.
My code is:
import RPi.GPIO as GPIO
import sys,os
import time
import datetime
channel = 21
led_output = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(led_output, GPIO.OUT)
def callback(channel):
filehandle = open("output.txt", "w") or die ("Could not write out")
if GPIO.input(channel) == 1:
print ("Water Detected!")
filehandle.write("1")
GPIO.output(led_output, GPIO.LOW)
else:
print ("Water Not Detected!")
filehandle.write("0")
GPIO.output(led_output, GPIO.HIGH)
filehandle.close()
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
print(GPIO.input(channel))
while True:
time.sleep(5)
When I reboot the Raspberry and run your code it works perfect.
Only after killing the process or CTRL-C keyboard interrupting and running it again the problem/error occurs. I think this has to do with the fact that you exit the program without cleaning up properly...
I got it working in case you exit the running the program with CTRL-C with the code below in which I included a GPIO.cleanup()
However...this unfortunately it does not cover the situation in which you simply kill the running programm...In that case you still need to reboot.
So there is room for improvement.
Please re-insert your own file management commands again.
import RPi.GPIO as GPIO
import sys,os
import time
import datetime
channel = 21
led_output = 18
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(channel, GPIO.IN)
GPIO.setup(led_output, GPIO.OUT)
def callback(channel):
if GPIO.input(channel) == 1:
print ("Water Detected!")
GPIO.output(led_output, GPIO.LOW)
else:
print ("Water Not Detected!")
GPIO.output(led_output, GPIO.HIGH)
GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300)
GPIO.add_event_callback(channel, callback)
print(GPIO.input(channel))
try:
while True:
#main loop here with some (dummy) code
eg_set_a_dummy_variable = 0
except KeyboardInterrupt:
# here you put any code you want to run before the program
# exits when you press CTRL+C
print ("Program interrupted by CTRL-C")
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:
# this ensures a clean exit and prevents your
# error "Runtime error:Failed to add edge detection"
# in case you run your code for the second time after a break
GPIO.cleanup()
# credits to:
# https://raspi.tv/2013/rpi-gpio-basics-3-how-to-exit-gpio-programs-cleanly-avoid-warnings-and-protect-your-pi
It is not very clean solution, but you can call GPIO.cleanup() at the start of your script too for case when your process was killed before and GPIO.cleanup() was not called.

Controlling RFID RC522 and servo motor in one program

I'm working on a project where I'm trying to turn a 5V servo motor (9g) when RFID RC522 detects a card. I'm using a Raspberry Pi 3 B+, Python RPi.GPIO lib and another lib: SimpleMFRC522 for the card reader.
I run into a problem where I can't set pins for the servo because of the SimpleMFRC522. I'm getting this error:
File "test.py", line 39, in <module>
unlock_cooler()
File "test.py", line 21, in unlock_cooler
GPIO.SETUP(7, GPIO.OUT)
AttributeError: 'module' object has no attribute 'SETUP'
Is there any ways to change the GPIO setup and using the servo together with the SimpleMFRC522 lib?
#!/usr/bin/env python
import RPi.GPIO as GPIO
import SimpleMFRC522
import re
rfid = 0
def read_RFID():
reader = SimpleMFRC522.SimpleMFRC522()
id, text = reader.read()
clean_text = re.findall('\d+', text)
match = int(clean_text[0])
rfid = match
GPIO.cleanup()
def unlock_cooler():
GPIO.SETUP(7, GPIO.OUT)
p = GPIO.PWM(7, 50)
p.start(2.5)
p.ChangeDutyCycle(7.5)
time.sleep(3)
p.ChangeDutyCycle(2.5)
time.sleep(1)
GPIO.cleanup()
read_RFID()
print(rfid)
if rfid == 6:
unlock_cooler()
GPIO.cleanup()
The setup method is named GPIO.setup() and not GPIO.SETUP() (note the lower-case characters!).
So changing the method unlock_cooler to this should solve the error that you got:
def unlock_cooler():
GPIO.setup(7, GPIO.OUT)
p = GPIO.PWM(7, 50)
p.start(2.5)
p.ChangeDutyCycle(7.5)
time.sleep(3)
p.ChangeDutyCycle(2.5)
time.sleep(1)
p.stop()
GPIO.cleanup()
Note that you would probably aslo want to call stop() on the PWM instance.

RuntimeError (in Raspberry Pi) produced at a defined variable

I have got the following RuntimeError in Python 2.7 with Raspberry Pi:
Traceback (most recent call last):
File "ldrmqtt.py", line 96, in <module>
main()
File "ldrmqtt.py", line 72, in main
ldrData= rc_time(pin_to_circuit)
File "ldrmqtt.py", line 53, in rc_time
GPIO.setup(pin_to_circuit, GPIO.OUT)
RuntimeError: Please set pin numbering mode using GPIO.setmode(GPIO.BOARD) or GPIO.setmode(GPIO.BCM)
I have connected an LDR to my Raspberry Pi and I am trying to send the values to Thingspeak using the MQTT broker. I am using Python 2.7.9
Here is a code snippet:
GPIO.setmode(GPIO.BOARD)
pin_to_circuit=7
def rc_time (pin_to_circuit):
count=0
GPIO.setup(pin_to_circuit, GPIO.OUT)
GPIO.output(pin_to_circuit, GPIO.LOW)
time.sleep(0.15)
GPIO.setup(pin_to_circuit, GPIO.IN)
while(GPIO.input(pin_to_circuit) == GPIO.LOW):
count +=1
return count
try:
while True:
print rc_time(pin_to_circuit)
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
def main():
print 'starting...'
ldrData= rc_time(pin_to_circuit)
tPayload= "field1=" % ldrData
while True:
try:
publish.single(topic, payload=tPayload, hostname=mqttHost,
port=tPort, tls=tTLS, transport= tTransport)
except KeyboardInterrupt:
break
except:
print: 'Error publishing the data'
#call main
if __name__=='__main__':
main()
You must set the numbering mode for GPIO ports:
GPIO.setmode(GPIO.BCM)
GPIO.BOARD – Board numbering scheme. The pin numbers follow the pin numbers on header P1.
GPIO.BCM – Broadcom chip-specific pin numbers. These pin numbers follow the lower-level numbering system defined by the Raspberry Pi’s Broadcom-chip brain.
From the error, it seems that you need to set GPIO.setmode.
import RPi.GPIO as GPIO
# for GPIO numbering, choose BCM
GPIO.setmode(GPIO.BCM)
# or, for pin numbering, choose BOARD
GPIO.setmode(GPIO.BOARD)
# but you can't have both, so only use one!!!
There is a nice write-up to be found here: http://raspi.tv/2013/rpi-gpio-basics-4-setting-up-rpi-gpio-numbering-systems-and-inputs

Relay RISING triggers GPIO event detect on another pin

I'm working on two separate projects on my RPi, a relay that drives a lamp (on GPIO 22) and a button that reboots the RPi (on GPIO 23). They both work fine when run alone but if I try to access the pin 22 while the 23 is being monitored the 23 reads a RISING although I have NOT pressed the button.
Here's the code of the program running on 23:
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import time
import os
import sys
def handler (signo):
print ("Rebooting\n")
GPIO.cleanup()
os.system("sudo reboot")
exit()
GPIO.setmode(GPIO.BCM)
pin = 23
GPIO.setup(pin, GPIO.IN,pull_up_down=GPIO.PUD_UP)
try:
GPIO.add_event_detect(pin, GPIO.RISING, callback=handler, bouncetime=800)
while (1):
time.sleep(10)
except KeyboardInterrupt:
print ("Quit")
GPIO.cleanup()
Here's a scheme of the circuit:
scheme.jpg
Does anyone know why this is happening?
I'm trying to access the gpio 22 (the relay) through:
/sys/class/gpio#...

Categories