Go Down

Topic: Generate tone without tone library (Read 1 time) previous topic - next topic


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.


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

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

Don't send me technical questions via Private Message.


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


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


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

Was just an shortcut for
Code: [Select]

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131