Pages: [1]   Go Down
Author Topic: Generate tone without tone library  (Read 751 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 33
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.
Logged

Offline Offline
Edison Member
*
Karma: 49
Posts: 1666
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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

Pete
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 33
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Montreal
Offline Offline
Faraday Member
**
Karma: 30
Posts: 2602
Per aspera ad astra.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 33
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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

Pages: [1]   Go Up
Jump to: