I have to generate a given tone on a speaker, and for some requirements I can't use any of the existing tone libraries, so I'm going with a timer.
I'm trying to setup a timer that runs at 2x the desired frequency and simply togle the output pin high/low... I think this is what tone() do, isn't it?
This is my code:
#include <TimerOne.h>
#define FREQ 440
#define PIN 9
#define PERIOD 1000000/(FREQ*2)
volatile byte current = LOW;
void my_tone() {
current = ~current;
digitalWrite(PIN, current);
}
void setup() {
pinMode(PIN, OUTPUT);
Timer1.attachInterrupt(my_tone, PERIOD);
// tone(PIN, FREQ);
}
void loop() {
}
But this way I don't get expected output on the speaker. I supose the speaker is correctly wired, because tone() do work.
I wired the + wire on the speaker in series with a 100ohm resistor on the pin 9, and - wire of the speaker on arduino gnd.