开发者

How to "fake" multitasking on an 8-bit processor?

开发者 https://www.devze.com 2023-03-12 20:57 出处:网络
I have an Arduino with an Adafruit Motor Shield as part of my robot. I want to run the motors at the same time I play a tone on the piezo element.

I have an Arduino with an Adafruit Motor Shield as part of my robot. I want to run the motors at the same time I play a tone on the piezo element.

The problem is that I don't quite know how to fake/simulate multitasking in my code. I tried something like this:

void goForward(int duration) {

    for (int i; i<duration; i++) {
        tl.run(FORWARD);
        tr.run(BACKWARD);
        bl.run(FORWARD);
        br.run(BACKWARD);
        counter++;

        if (counter%4==0) {
            piezo != piezo;
        }

        delay(1);
    }
}

This runs the motors, however it doesn't create a tone on my piezo element. What would be a better way to program this so the piezo could be switched on/off at a frequency of 440 Hz while the motor commands开发者_Go百科 are running?


I don't know the Arduino board, but most microcontrollers have some timer interrupt. Have you tried to setup such a timer? In the timer interrupt handler you could enable/disable the piezo element, while the main loop could be used for controlling the motor.


Normal Arduino boards only have 3 timers. This limits "multitask" capability to 3 "threads". Arduino Mega has 16 timers. In other words, the Arduino Mega can be your solution. No?


Create scheduler to create parallel tasks, and use two timers for your motors, and if you have a third one use it for the buzzer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号