0

I am new to async programming in Python and the internet has not helped me to solve my problem - does anyone of you have a solution?

I have an infinite loop, in which some sensor data is read. However, the sensor reading is quite slow, so I want so await the sensor signals.

My expectation of it looks like this (just the schematics):

    import bno055 #sensor library
    import asyncio
    
    aync def read_sensor():
           altitude=bno055.read()
           #..and some other unimportant lines which I hide here
           return altitude


    def main():

       while 1:
          await current_altitude= read_sensor() #??? how can I "await" the sensor signals?
          #....some other lines which I hide here, but they need to run syncronously
          print(current_altitude)

       
      

   main()      

Thank you in advance

haakla321
  • 11
  • 1
  • If `bno055.read` is not asynchronous you need to wrap it somehow in a thread or similar. – mkrieger1 Jun 23 '20 at 15:49
  • Does this answer your question? [How to use asyncio with existing blocking library?](https://stackoverflow.com/questions/41063331/how-to-use-asyncio-with-existing-blocking-library) – mkrieger1 Jun 23 '20 at 15:50

1 Answers1

0

To await function doing blocking IO you can run it by means of run_in_executor

def read_sensor():
    altitude=bno055.read()
    #..and some other unimportant lines which I hide here
    return altitude

loop = asyncio.get_running_loop()
altitude = await loop.run_in_executor(None, read_sensor)
alex_noname
  • 26,459
  • 5
  • 69
  • 86