Go Down

Topic: Generate tone without tone library (Read 820 times) previous topic - next topic

magnomp

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.

el_supremo

Try this:
Code: [Select]
#define PERIOD (1000000L/(FREQ*2))

Also, read How to post code properly and do it.

Pete

magnomp

el_supremo,
I just tried your suggestion, but didn't get any change

Magician

Should it be like:
Code: [Select]
Timer1.initialize(T_PERIOD);           // Sampling with TimerOne library
Timer1.attachInterrupt(iProcess);


magnomp

Thanks! It worked
I thought
Code: [Select]
Timer1.attachInterrupt(function, period)

Was just an shortcut for
Code: [Select]
Timer1.initialize(period);
Timer1.attachInterrupt(function);

Go Up