Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Newbie with Pi3
#41
I give up. I cannot understand what is going on
1. It triggers the callback function. That is good. It is supposed to start motor and enter infinite loop till respective switch is HIGH, stop motor print message that door IS open/close and quit that thread
2. However it intermediately exit the while True loop which is expected to work until pin 11/12 is True. It looks like it becomes True/HIGH immediately
3. I don't understand why it prints Day. Open door multiple times - i.e. light sensor is triggered multiple times in a row

Some thoughts - not sure that setting both 11 and 12 as 0 at the beginning is right. Isn't it expected that at the beginning the door is either open or closed, not in some interim state, thus you need to set one of them to UP and the respective switch should be pressed? When you cover the light sensor, you cover it and leave it like this, right - pretending it's night for a relatively long time? Are you sure everything with setup is OK?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#42
Can you run this script

I added a detailed logging to a file
import RPi.GPIO as GPIO
import time
from datetime import datetime
from twilio.rest import Client
import logging

debug = True

GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(7,GPIO.IN)   #LDR (Light Dependent Resistor)
   
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) #top switch
GPIO.setup(12, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # bottom switch
   
GPIO.setup(15,GPIO.OUT) # Door Open
GPIO.setup(13,GPIO.OUT) # Door Close

MY_PATH = os.path.dirname(sys.argv[0])
log = logging.getLogger("GPIO.LOGGER")

def setup_logger(*args):
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    formatter2 = logging.Formatter('%(message)s')

    # region file handler
    if 'fh' in args:
        # create the logging file handler
        fh = logging.FileHandler(os.path.join(MY_PATH, 'GPIO.log'), mode='w')
        fh.setLevel(logging.DEBUG)
        fh.setFormatter(formatter)
    # endregion

    # region console handler
    if 'ch' in args:
        ch = logging.StreamHandler()
        ch.setLevel(logging.INFO)
        ch.setFormatter(formatter2)
    # endregion

    # add handler to logger object
    for h in args:
        if h in locals():
            log.addHandler(locals().get(h))

   
   
def send_sms(sms_text="Hello from Python!"):
    twilio_client = Client("ACxxxxxxxxxxxxxx", "zzzzzzzzzzzzz")
    client.messages.create(to="+19732644152", 
                           from_="+12023351278", 
                           body=sms_text)
                           
def pin_status():
    pins = [7, 11, 12, 13, 15]
    pin_statuses = ['pin {}: {}'.format (pin, GPIO.input(pin)) for pin in pins]
    return ', '.join(pin_statuses)

 
def operate_door(channel):
    try:
        if channel == 7:
            log.debug('Callback1, {}'.format(pin_status()))
            if not GPIO.input(7) and not GPIO.input(11): # it's day and door is not open
                log.debug('Callback2, {}'.format(pin_status()))
                log.info("Day. Open door")
                log.info("Start motor. Time is {}".format(datetime.now().strftime('%d %b %Y %H:%M:%S.%f')))
                GPIO.output(15, True)
                log.debug('Callback3, {}'.format(pin_status()))
                while True:
                    log.debug('Callback4, {}'.format(pin_status()))
                    if GPIO.input(11):
                        GPIO.output(15,False)
                        log.debug('Callback5, {}'.format(pin_status()))
                        log.info("STOP. Door open. Time is {}".format(datetime.now().strftime('%d %b %Y %H:%M:%S.%f')))
                        break
                #send_sms("sms_text='Door opened'")
                     
            elif GPIO.input(7) and not GPIO.input(12): # it's night and door is not closed
                log.debug('Callback6, {}'.format(pin_status()))
                log.info("Night. Close door")
                log.debug("Start motor. Time is {}".format(datetime.now().strftime('%d %b %Y %H:%M:%S.%f')))
                GPIO.output(13, True)
                log.debug('Callback7, {}'.format(pin_status()))
                while True:
                    log.debug('Callback8, {}'.format(pin_status()))
                    if GPIO.input(12):
                        GPIO.output(13,False)
                        log.debug('Callback9, {}'.format(pin_status()))
                        log.info("STOP. Door closed. Time is {}".format(datetime.now().strftime('%d %b %Y %H:%M:%S.%f')))
                    break
            #send_sms("sms_text='Door opened'")
    except KeyboardInterrupt:
        pass

if debug:
    setup_logger('ch', 'fh')
    log.setLevel(logging.DEBUG)
else:
    setup_logger('ch')
    log.setLevel(logging.INFO)        
 
# add events detection, using separate thread
GPIO.add_event_detect(7, GPIO.BOTH, callback=operate_door, bouncetime=200)
delay = 1 # 1 sec. delay
log.info('Start monitoring')
log.debug('Main thread start, {}'.format(pin_status()))
try:
    while True:
        #time.sleep(delay) # you may change this or replace it with just pass
        #pass #uncomment this if you decide to remove time.sleep above
        log.debug('Main thread, {}'.format(pin_status()))
except KeyboardInterrupt:
    log.info('Stop monitoring and quit')
finally:
    GPIO.cleanup()
I hope I don't have syntax or typo errors.
It will create GPIO.log file in the same folder where the script is.

I also added GPIO.cleanup() based on http://raspi.tv/2013/rpi-gpio-basics-3-h...ct-your-pi
it's not related to our problem, but nevertheless....
I know it's frustrating, but you can always return to original script
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#43
(Apr-03-2018, 10:14 AM)buran Wrote: Some thoughts - not sure that setting both 11 and 12 as 0 at the beginning is right
When I start script I have the door open(no real door) photocell led on for open, door open switch set to open (on). Then i close door set open set to off, let it run short time then set door closed switch to on. I am working on running the other code now. Thanks Dualxeon
Reply
#44
(Apr-04-2018, 07:40 AM)Dualxeon Wrote: When I start script I have the door open(no real door) photocell led on for open, door open switch set to open (on).
In this case shouldn't you setup the switch 11 to PUD_UP?, e.g.
GPIO.setup(11, GPIO.IN, pull_up_down=GPIO.PUD_UP)

from wiki - - https://sourceforge.net/p/raspberry-gpio...ki/Inputs/
Quote:Pull up / Pull down resistors

If you do not have the input pin connected to anything, it will 'float'. In other words, the value that is read in is undefined because it is not connected to anything until you press a button or switch. It will probably change value a lot as a result of receiving mains interference.

To get round this, we use a pull up or a pull down resistor. In this way, the default value of the input can be set. It is possible to have pull up/down resistors in hardware and using software. In hardware, a 10K resistor between the input channel and 3.3V (pull-up) or 0V (pull-down) is commonly used. The RPi.GPIO module allows you to configure the Broadcom SOC to do this in software:

GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# or
GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

(where channel is the channel number based on the numbering system you have specified - BOARD or BCM).

Maybe I'm not correct - not sure
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#45
Not sure if this will help any but here is how I have it wired up. If you are tired of fooling with this I COMPLETELY understand. I stated at the beginning this is all new to me, but interesting. I have tried running the test script have some issues I will post that info in a minute. Thanks

Okay here is what I have
Error:
============= RESTART: /home/pi/Desktop/buran4-4-test switch.py ============= Traceback (most recent call last): File "/home/pi/Desktop/buran4-4-test switch.py", line 19, in <module> MY_PATH = os.path.dirname(sys.argv[0]) NameError: name 'os' is not defined


Not sure if I messed up or not , but I added
import os
then I get sys line 20 not defined so I
imported sys


now it ran this is what I got
Output:
============= RESTART: /home/pi/Desktop/buran4-4-test switch.py ============= Start monitoring Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door STOP. Door closed. Time is 04 Apr 2018 04:07:46.470615 Day. Open door Start motor. Time is 04 Apr 2018 04:08:31.712056 STOP. Door open. Time is 04 Apr 2018 04:08:33.181920 Day. Open door Start motor. Time is 04 Apr 2018 04:08:33.233796 STOP. Door open. Time is 04 Apr 2018 04:08:34.488290 Day. Open door Start motor. Time is 04 Apr 2018 04:08:34.543608 STOP. Door open. Time is 04 Apr 2018 04:08:35.079982 Day. Open door Start motor. Time is 04 Apr 2018 04:08:35.137366 STOP. Door open. Time is 04 Apr 2018 04:08:35.937013 Day. Open door Start motor. Time is 04 Apr 2018 04:08:36.022351 STOP. Door open. Time is 04 Apr 2018 04:08:37.494573 Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door Night. Close door STOP. Door closed. Time is 04 Apr 2018 04:10:46.583543 Day. Open door Start motor. Time is 04 Apr 2018 04:12:24.263203 STOP. Door open. Time is 04 Apr 2018 04:12:30.724498
I'm going to attach GPIO log

My internet stinks I am uploading GPIO log Attachment but only at 6 %.

Attached Files

.docx   Schematics.docx (Size: 145.89 KB / Downloads: 157)
Reply
#46
Missing imports were my mistake as I took some code from other script and didn't add the required imports.
it would be helpful to see the log file, so please attach it.
By the way on line 82
                log.debug("Start motor. Time is {}".format(datetime.now().strftime('%d %b %Y %H:%M:%S.%f')))
you may want to change log.debug to log.info in order to get this printed on console as well.

I am not tired of trying, but I'm completely out of ideas... And I feel a bit stupid making you to test so many things without success.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#47
I am working on GPIO log (19%). I am not tired of trying scripts I have learned from this. Just not much help you are in way over my pay grade. I have to leave for work in a bit I will try to get file loaded this morning. I will try to finish it from work if possible. Thanks again. Just trying to get a true Red Neck Chicken Coop LOL Thanks
Reply
#48
You can upload small portion from the begining of the log file. I can imagine it's quite big if you run the script long.
It's interesting for me too as I want to buy RPi myself :-)
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#49
Try this I got errors and could not do anything to it from work. this is just the top if you need more not a problem.

Attached Files

.txt   GPIO Top.log.txt (Size: 14.85 KB / Downloads: 161)
Reply
#50
Yes, please, upload a bigger file. This is less than a second of operation. If a problem to upload - you can share via dropbox link
Note that pin 11 (top switch is up, i.e. 1), right from the start
I will look at it in the morning as I'm going to sleep now
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020