1

I am working a system which should make one of my raspberry pi GPIO pins to HIGH for about 2 seconds. I split this in 2 different files. The "website" file(named app.py) and the "GPIO" file(named test.ty). The test file is requested in this way:

from flask import Flask, render_template
from test import open_door

app = Flask(__name__)

@app.route('/opendoor')
def openDoor():
    open_door()


if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')

The test.py file looks like this:

import RPi.GPIO as GPIO
import time

testPin = 18

GPIO.setmode(GPIO.BCM)
GPIO.setup(testPin, GPIO.OUT)

counter =0

def open_door():
    try:
        print ("Everthing is fine")
        while counter < 900000:
             print ("Everything is good")
             GPIO.output(testPin, GPIO.HIGH)

             counter += 1

    except:
        print ("Everything is oke!")

    finally:
        GPIO.cleanup()

I get the messages "everything is fine" and "everything is oke!" but not the message "everything is good". This seems to me that the while loop does not execute. Anybody any idea why it does not work?

2
  • If you're getting the "oke" message, that means that there was an error. If the error happened before the "good" message, it won't print. Commented Dec 15, 2017 at 23:22
  • @Carcigenicate I ran it one more time, and what i got in my terminal was a little to long to write in this comment but is in the comment below Commented Dec 15, 2017 at 23:34

3 Answers 3

3

counter is not in the scope of your other file that invokes open_door() that's why you see "Everything is okie!" because unknown variable is an exception

Sign up to request clarification or add additional context in comments.

4 Comments

so i should include open_door(counter) to make it work?
It depends on what you want to do with the counter. If you want to always iterate 900000 times, then you can just do a for i in range(900000): why do you even need the counter? You can also move the declaration of the counter into your open_door() function.
I am connecting it to a relay which will make a shortcircuit to deactivate a lock. If i do this too short, the lock won't be deactivated so about 1 or 2 seconds will do. My entier project can be found here: stackoverflow.com/questions/47824519/…
Hmm interesting, yeah, then replace counter and the while loop with the for i in range(900000): although keep in mind what you're doing is "busy waiting" looping for no reason other than the fact that you need to "wait" 1-2 seconds. Something else you can consider is shortcircuiting the lock, "sleeping" for 1-2 seconds (leaving the system short circuited) and then waking up after 1-2 seconds to close the lock. Check out sleep here: docs.python.org/2/library/time.html#time.sleep
1

tl;dr - counter does not get initialized since only the method is invoked.

Python is an interpreter language. By importing open_door from test.py you are only including the code defined in the open_door function.

For example, take the following two programs:

bar.py:

counter = 0
def count():
    while (counter < 5):
        print(counter)
        counter += 1

foobar.py:

from bar import count
count()

The output received will be:

py foobar.py
Traceback (most recent call last):
  File "foobar.py", line 2, in <module>
    sayHey()
  File "C:\Temp\bar.py", line 3, in sayHey
    while (counter < 5):
UnboundLocalError: local variable 'counter' referenced before assignment

However, by moving the variable definition into the method we would get the following output:

py foobar.py
0
1
2
3
4

I would recommend creating a class which holds the variables as inner fields and contains the open_door method.

bar.py:

class MyClass:
    def __init__(self):
        self.__counter = 0
    def count(self, limit):
        while (self.__counter < limit):
            print(self.__counter)
            self.__counter += 1

foobar.py:

from bar import MyClass
driver = MyClass()
driver.count(3)

and now:

py foobar.py:
0
1
2    

Comments

-1

192.168.1.82 - - [15/Dec/2017 23:27:42] "GET /deur/open HTTP/1.1" 200 -

This works fine

Everything is oke!

192.168.1.82 - - [15/Dec/2017 23:27:44] "GET /opendoor HTTP/1.1" 500 - Traceback (most recent call last):

File "/usr/lib/python3/dist-packages/flask/app.py", line 1836, in call return self.wsgi_app(environ, start_response)

File "/usr/lib/python3/dist-packages/flask/app.py", line 1820, in wsgi_app response = self.make_response(self.handle_exception(e))

File "/usr/lib/python3/dist-packages/flask/app.py", line 1403, in handle_exception

reraise(exc_type, exc_value, tb)

File "/usr/lib/python3/dist-packages/flask/_compat.py", line 33, in reraise raise value

File "/usr/lib/python3/dist-packages/flask/app.py", line 1817, in wsgi_app response = self.full_dispatch_request()

File "/usr/lib/python3/dist-packages/flask/app.py", line 1477, in full_dispatch_request

rv = self.handle_user_exception(e)

File "/usr/lib/python3/dist-packages/flask/app.py", line 1381, in handle_user_exception

reraise(exc_type, exc_value, tb)

File "/usr/lib/python3/dist-packages/flask/_compat.py", line 33, in reraise raise value

File "/usr/lib/python3/dist-packages/flask/app.py", line 1475, in full_dispatch_request

rv = self.dispatch_request()

File "/usr/lib/python3/dist-packages/flask/app.py", line 1461, in dispatch_request

return self.view_functions[rule.endpoint](**req.view_args)

File "/home/pi/python/Deur/app.py", line 24, in openDeur return render_template('index')

File "/usr/lib/python3/dist-packages/flask/templating.py", line 127, in render_template

return 

_render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),

File "/usr/lib/python3/dist-packages/jinja2/environment.py", line 830, in get_or_select_template

return self.get_template(template_name_or_list, parent, globals)

File "/usr/lib/python3/dist-packages/jinja2/environment.py", line 791, in get_template

return self._load_template(name, self.make_globals(globals))

File "/usr/lib/python3/dist-packages/jinja2/environment.py", line 765, in _load_template

template = self.loader.load(self, name, globals)

File "/usr/lib/python3/dist-packages/jinja2/loaders.py", line 113, in load source, filename, uptodate = self.get_source(environment, name)

File "/usr/lib/python3/dist-packages/flask/templating.py", line 64, in get_source

raise TemplateNotFound(template)

jinja2.exceptions.TemplateNotFound: index

192.168.1.82 - - [15/Dec/2017 23:27:44] "GET /opendoor?

debugger=yes&cmd=resource&f=style.css HTTP/1.1" 200 -

192.168.1.82 - - [15/Dec/2017 23:27:45] "GET /opendoor?

debugger=yes&cmd=resource&f=jquery.js HTTP/1.1" 200 -

192.168.1.82 - - [15/Dec/2017 23:27:45] "GET /opendoor?

debugger=yes&cmd=resource&f=debugger.js HTTP/1.1" 200 -

192.168.1.82 - - [15/Dec/2017 23:27:45] "GET /opendoor?

debugger=yes&cmd=resource&f=console.png HTTP/1.1" 200 -

192.168.1.82 - - [15/Dec/2017 23:27:45] "GET /opendoor?

debugger=yes&cmd=resource&f=source.png HTTP/1.1" 200 -

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.