Timer with sensor.snapshot

Hello everyone,My name is Tony ,I am a beginner in Python, I would like to ask a question.

I want to make a millisecond timer with camera,everything is normal until I put img=sensor.snapshot() into line18.

It’s working but counting very slowly.Timer with img=sensor.snapshot() - YouTube

And without the img=sensor.snapshot(),it really counting every 1 millisecond.Timer without img=sensor.snapshot() - YouTube

I put my code below,and sorry for my bad english.

import sensor,micropython
from pyb import Timer
micropython.alloc_emergency_exception_buf(100)
tick=0#1ms
ms=0
s=0
tim7 = Timer(7, freq=1000)#Timer(1ms)
sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QVGA)
#Timer
def systick(tim7):
    global tick
    tick=1
tim7.callback(systick)
#Loop
while(True):
    #img=sensor.snapshot()
    if tick==1:
        ms=ms+1.0
        if ms>=1000:
            ms=0
            s=s+1
        print(s,ms)
        tick=0

The snapshot function delays your code from running to update s, ms. If you move that logic to the timer callback it should work fine:

def systick(tim7):
    global s, ms
    ms=ms+1
    if ms>=1000:
        ms=0
        s=s+1
tim7.callback(systick)

#Loop
while(True):
    img=sensor.snapshot()
    print(s, ms)

Hi iabdalkader,thank you for your reply!

I have tried your suggestion,but it printed is not what I expected.print question - YouTube

I hope it can print every millisecond.

By the way, is there a way to calculate floating point numbers in the timer?

for example:

def systick(tim7):
    global s,ms
    ms=ms+1.0
    if ms>=1000:
        ms=0
        s=s+1
tim7.callback(systick)

It will show an error:MemoryError: memory allocation failed, heap is locked.

I believe MicroPython doesn’t allow the use of floats in interrupt handlers.

As for your code… the print statement isn’t in the callback so it can’t print every millisecond… If you want to do that then subtract using the camera. You can’t do print in a callback however as print blocks on I/O and this would make the callback stall causing the processor to lockup.

If you really need to modify the behavior to do this you’d have to edit our C code.

Hi kwagyeman, thank you for your reply.

So you mean that we can’t use the print function in the timer callback,unless we edit the C code.

How can i edit your C code?

And is that any way to avoid the delay of snapshot function in the while loop?

No you can’t call any function that allocates memory in a callback.

There’s no way to avoid the delay, the print function, in the while loop, needs a few milliseconds to return.