Controlling RFID RC522 and servo motor in one program - python

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.

Related

Need to take the whole python code into a function that can be access from another python file

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.

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.

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

Raspberry-pi - DHT11 + Relay trigger

I am a complete noob when it comes to Python and the Raspberry Pi unit but I am figuring it out.
I am working on a script to monitor the current temperature of my greenhouse that I am building. When the temp gets to 28C, I would like for it to activate my relay which will turn on the fan. At 26C the relay should turn off.
Build info:
Raspberry Pi 3
dht11 tempurature - GPIO pin 20
single relay board - GPIO pin 21
import RPi.GPIO as GPIO
import dht11
import time
import datetime
from time import sleep
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# Set relay pins as output
GPIO.setup(21, GPIO.OUT)
# read data using pin 20
instance = dht11.DHT11(pin=20)
while True:
result = instance.read()
tempHI = 28
tempLOW = 26
if result >= tempHI
GPIO.output(21, GPIO.HIGH) #turn GPIO pin 21 on
ifels result < tempLOW
GPIO.output(21, GPIO.LOW) #Turn GPIO pin 21 off
time.sleep(1)
The current errors I am getting:
python ghouse.py
File "ghouse.py", line 19
result = instance.read()
^
IndentationError: expected an indented block
For the current error you're facing, keep in mind that Python relies heavily on indentation. It's not like other languages such as C++ and Java that use curly braces to arrange statements.
To fix the indentation in your code, please see below:
import RPi.GPIO as GPIO
import dht11
import time
import datetime
from time import sleep
# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()
# Set relay pins as output
GPIO.setup(21, GPIO.OUT)
# read data using pin 20
instance = dht11.DHT11(pin=20)
while True:
result = instance.read()
tempHI = 28
tempLOW = 26
if result >= tempHI:
GPIO.output(21, GPIO.HIGH) #turn GPIO pin 21 on
ifels result < tempLOW:
GPIO.output(21, GPIO.LOW) #Turn GPIO pin 21 off
time.sleep(1)
In any if, else, elif, for, or while statement, the code that you want to execute must be indented within the statement in order for it to run, or else you will get the error that you are currently seeing.
There are a few more errors in your code but I'll let you figure out the rest! Welcome to programming in Python and using Raspberry Pi.

RuntimeError: You must setup() the GPIO channel first

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

Categories