[Tutor] counting function calls

Alan Gauld alan.gauld at yahoo.co.uk
Thu Apr 13 13:23:56 EDT 2017


On 13/04/17 17:10, marcus lütolf wrote:
> Dear experts, Mats
> I have found the solution, I put the counting variable at the wrong place: 

I don;t think so, what you have done now is count the times
through the loop, but thats not (always) the same as the
number of times the function gets called, which is what
you said you wanted to count..


>> #!/usr/bin/python3
>> import sys, time
>> import RPi.GPIO as gpio
>>
>> gpio.setmode(gpio.BOARD)
>> gpio.setup(23, gpio.IN)
>> count = 0
>> def mein_callback(pin):
>>     count += 1

This line will still give you an error.

>>     print('PIR 1 aktiviert', count)
>>     return
>>
>> try:
>        count = 0
>>     gpio.add_event_detect(23, gpio.RISING, callback = mein_callback)
>>     while True:
>>         time.sleep(2)
>            count += 1

This just counts how many times your while loop goes
round - once every 2 seconds. It says nothing about
how often the callback gets executed.

To do that you need to add the line

global count

to your callback function.

But then both the loop and function will increment
the global count variable so you need to remove
(or rename) the one in the loop.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list