Go Down

Topic: Generate tone without tone library (Read 783 times) 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.



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

Quick Reply

With Quick-Reply you can write a post when viewing a topic without loading a new page. You can still use bulletin board code and smileys as you would in a normal post.

Warning: this topic has not been posted in for at least 120 days.
Unless you're sure you want to reply, please consider starting a new topic.

Note: this post will not display until it's been approved by a moderator.

shortcuts: alt+s submit/post or alt+p preview