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
Related
With this code I have connected a breadboard to a Raspberry pi 3. When a button on the breadboard is pressed a random audiofile from a specified folder is played.
import RPi.GPIO as GPIO
import vlc
import random
import os
def button_callback(channel):
print("Button was pushed!")
path = "/home/pi/Downloads/Slutprojekts_inspelningar_Kung-Fu_Panda"
files=os.listdir(path)
d = random.choice(files)
p = vlc.MediaPlayer(f"/home/pi/Downloads/Slutprojekts_inspelningar_Kung-Fu_Panda/{d}")
p.play()
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) # Set pin 10 to be an input pin and set initial value to be pulled low (off)
GPIO.add_event_detect(10,GPIO.RISING,callback=button_callback) # Setup event on pin 10 rising edge
message = input("Press enter to quit\n\n") # Run until someone presses enter
GPIO.cleanup() # Clean up
After pressing the button a couple of times, it stops working and I get these error messages:
Failed to create permanent mapping for memfd region with ID = 4052867084
Failed to regester memfd mempool. Reason: could not attach memfd SHM ID to pipe
Cannot send block reference with non-registered memfd ID = 4052867084
Fallig back to copying full block data over socket
mmap() failed: Cannot allocate memory
Expected output:
Button was pushed! #while playing the audiofile
Make sure that the previously started instances of VLC are actually terminating. Otherwise you're exhausting the memory available. That might also be a limit imposed by the OS, check with ulimit -a
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.
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
Anyone facing this issue when using raspberry-pi? The code below:
from gpiozero import MotionSensor
from picamera import PiCamera
camera = PiCamera()
pir = MotionSensor(4)
while True:
pir.wait_for_motion()
camera.start_preview()
pir.wait_for_no_motion()
camera.stop_preview()
Full trace:
traceback(most recent call last);
file "/home/pi/motion.py", line 11, in<module>
camera.start_preview()
typeError : unbound method start_preview() must be called with PiCamera instance as first argument (got nothing instead)
#owenbradstreet
Traceback(most recent call last):
File "/home/pi/motion.py",line 7,in<module>
with picamera.PiCamera()as camera:
File "/usr/lib/pyton2.7/dist-packages/picamera/camera`enter code here`.py",line 415, in_init_
self.init_camera(camera_num,sereo_mode,stereo_decimate)
File "/usr/lib/pyton2.7/dist-packages/picamera.py".line 444. in _init_camera
"Camera is not enabled.Try running 'sudo raspi-config'"
PiCameraError:Camera is not enabled.
Try running 'sudo raspi-config' and ensure that the camera has been enabled.
the thing is i have already enable camera :(
Raspberry Pi camera can be VERY finicky. Make sure the camera instantiation isn't throwing an error and that the sunny connector is really in there. But more likely the issue, the camera needs a couple seconds to start up on first preview. Try adding a time.sleep(2) after the first start_preview() (you might want to add one before your while loop)
Try instead:
from gpiozero import MotionSensor
import picamera
pir = MotionSensor(4)
while True:
with picamera.PiCamera() as camera:
camera.resolution = (*YOUR LENGTH HERE*, *YOUR WIDTH HERE*)
pir.wait_for_motion()
camera.start_preview()
pir.wait_for_no_motion()
camera.stop_preview()
All this does is import picamera separately, and execute the code after with the camera as 'camera'. This also means you don't need to close the stream.
Hope this helps!
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