0

I was developing small embedded system over arduino, and it was counting events using interrupts. The code was like that:

 volatile float count= 0;
 attachInterrupt(0, increaseCount, CHANGE); 

 void increaseCount(){
 ++count;
 }

the count variable should be volatile to access it inside an interrupt. Now, I am writing it over Raspberry pi using python. But, python has nothing called volatile. So, is there another technique to increase variable during thread/event. python give me that error when the event happens and the variable increases.

  File "MyApp.py", line 5, in my_callback
  count += 1
  UnboundedLocalError: local variable 'count' referenced before assignment

Any help ??

1 Answer 1

3

No, there's no such thing as volatile in Python, it's a much too low-level concept.

You should just make sure there is some shared context (like an object instance) in which the variable can reside, so that it can be shared between the two contexts. Python will do the rest.

class MyApp(object):
  def __init__(self):
    self._counter = 0
    registerInterrupt(self.interruptHandler)

  def interruptHandler(self):
    self._counter += 1

  def getCount(self):
    return self._counter

Something like that could be enough, of course you'd have to fill in the details and make the required call(s) to create an instance of MyApp and make sure there's a function registerInterrupt() that does the needed work to set up the callback into the instance.

Also, do note that a counter of events should almost never be float in C, that's incredibly strange design.

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

2 Comments

Thanks, i will try that solution, now
But, can u give me an example of shared context in python, i am a beginner

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.