- I think in this case the Timeout API is more suitable than the Ticker.
- To keep the ISR as short as possible I would recommend something as follows:
#include "mbed.h"
const uint32_t PWM_EVENT = (1UL << 0); // position 0
AnalogIn Meting(A0);
Timeout timeout;
DigitalOut myled(LED1);
EventFlags eventFlags;
void Pwm()
{
eventFlags.set(PWM_EVENT);
}
int main()
{
eventFlags.set(PWM_EVENT); // sets the flag for first time (you can replace it with Pwm(); if you like so)
while (1) {
eventFlags.wait_all(PWM_EVENT); // while blocking this thread, it waits for PWM_EVENT to become set
// then it clears the PWM_EVENT (by default)
chrono::microseconds chronoPer { long(Meting.read() * 100000 + 10000) };
printf("chronoPer = %lli us\r\n", chronoPer); // only for debugging, comment out to get accurate timing
myled = !myled;
timeout.attach(callback(&Pwm), chronoPer); // Pwm is called (only once) when chronoPer us elapsed
}
}
- For more info on how to use EventFlags see this thread.
Note: To format the source code on forum pages put a line with three back-ticks (like these ```) in front and after the code.