I am quite enthusiastic about the new Raspberry Pico. However I find the C SDK not very friendly and I prefer to have something as simple as the Arduino API. I did not want to wait for the official Arduino support – so I started my own project.

In order to implement the Arduino tone() I first provided an version which was based on the PWM functionality.
After some more thoughts I decided that it is much more elegant to use the Timer Alarm:

#pragma once

#include "PicoTimer.h"

// generate sound by toggling the pin state in the frequency of the tone
bool generateSound(repeating_timer_t *rt) {
    PicoTone *pt = (PicoTone*)rt->user_data
    pt->state = !pt->state; // toggle state
    digitalWrite(pt->pin, pt->state); 
}

/**
 * @brief We use the TimerAlarm to generate tones.
 */
class PicoTone {
    public:
        PicoTone(){
        }
        ~PicoTone(){
            stop();
        }
        void tone(uint8_t pinNumber, unsigned int frequency) {
            pin = pinNumber;
            int delay = 1000 / frequency / 2;
            alarm.start(generateSound, delay, MS, this);
        }
        void noTone(uint8_t pinNumber) {
            alarm.stop();
        }
    protected:
        TimerAlarmRepeating alarm;
        int pin;
        bool state;
};

I love the fact that we can pass an argument to the timer function. This is much more elegant then the version that I implemented for the ESP32.


2 Comments

Anonymous · 6. December 2022 at 4:44

How did you set up your circuit?

    pschatzmann · 6. December 2022 at 8:15

    Just connect a passive buzzer, some earphones or some Piezo Elements. One cable goes to the indicated pin, the other to ground…

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *