CSE: Raw Tone

Make the loop() function generate and play an intermittent tone that bounces back and forth between the right and left channels:

// raw_tone - play a bouncing, intermittent tone in loop()

int oj_rc =  9;  // pin D9 drives the right channel
int oj_lc = 10;  // pin D10 drives the left channel

void setup() {
  pinMode(oj_rc, OUTPUT);
  pinMode(oj_lc, OUTPUT);

void loop() {

void raw_tone(int out_pin) {
  int len_delay  = 500;  // length of delay (ms)
  int len_state  = 500;  // length of state (us)
  int lim_cycles = 500;  // cycles per tone

  for (int i=0; i<lim_cycles; i++) {
    digitalWrite(out_pin, HIGH);  // set HIGH state

    digitalWrite(out_pin, LOW);   // set LOW  state



The tone() function uses a timer to tell it when to change the pin's state. It's quite possible (if a bit ugly) to generate tones using a for loop, digitalWrite(), and delayMicroseconds().

It would also be possible to give raw_tone() an API that is much closer to that of tone(). Alternatively, a sketch could use setup_alert() first and raw_tone() later. These changes are left as an exercise for the student...

This wiki page is maintained by Rich Morin, an independent consultant specializing in software design, development, and documentation. Please feel free to email comments, inquiries, suggestions, etc!

Topic revision: r16 - 05 Mar 2016, RichMorin
This site is powered by Foswiki Copyright © by the contributing authors. All material on this wiki is the property of the contributing authors.
Foswiki version v2.1.6, Release Foswiki-2.1.6, Plugin API version 2.4
Ideas, requests, problems regarding CFCL Wiki? Send us email