Your code has a number of issues, which I'll address. I got the following to work:
Code: Select all
import pyb
import micropython
micropython.alloc_emergency_exception_buf(100)
adc = pyb.ADC(pyb.Pin('X1'))
dac = pyb.DAC(1)
def readAndWrite(timer):
value = adc.read()
value = value // 4095 * 255
dac.write(value)
pyb.LED(1).toggle()
timer = pyb.Timer(1)
timer.init(freq=1)
timer.callback(readAndWrite)
1 - Anytime you're writing code which uses callbacks, I recommend that you add the lines:
Code: Select all
import micropython
micropython.alloc_emergency_exception_buf(100)
2 - You weren't instantiating the ADC and DAC objects correctly. Before writing an IRQ you should probably verify that your code runs outside of a callback. For example, just call readAndWrite() from the REPL several times in a row and verify it works.
3 - You timer callback was missing the timer argument. Timer callbacks have to have a single argument which is the timer associated with the IRQ.
4 - You were using value / 4095 which needs to allocate a floating point number. Allocating floats isn't allowed inside an irq. If you use // instead, then it will do integer division.
5 - You need to have the definition of readAndWrite before you try to use it (so I had to reorder things to get it work).
6 - You called timer.callback(readAndWrite()) which passes what invoking the readAndWrite function. This is why your LED flashed once. The readAdnWrite() portion calls the function. There is no return value, so this means that the function returns None. This then passes None to the timer.callback routine which tells it to disable callbacks. What you wanted to do was: timer.callback(readAndWrite) Note there there are no parens after the readAndWrite. This passes the function to timer.callback, whereas adding the parens passes in the result of calling readAndWrite. A subtle, but very important difference.