Generating two completely independent tones


As you know it can't be done with the tone() procedure. But you can always read the time with the micros() function.

#define FILENAME "GEN2TONES"

const byte pin1 = 4;
const byte pin2 = 8;
int freq1 = 2000; // Hz
int freq2 = 4500; // Hz
long dt1 = 1000000 / freq1 / 2;
long dt2 = 1000000 / freq2 / 2;
boolean b1;
boolean b2;
long t, t0;
long t1 = micros() + dt1;
long t2 = micros() + dt2;

void setup() {
  Serial.begin(9600);
  Serial.println(FILENAME);
  t0 = 9; // experimental, should be something between 8 and 9
  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
}

void loop() {
  t = micros();
  if (t > t1) {
    t1 = micros() + dt1 - t0;
    b1 = !b1;
    digitalWrite(pin1, b1);
  }
  t = micros();
  if (t > t2) {
    t2 = micros() + dt2 - t0;
    b2 = !b2;
    digitalWrite(pin2, b2);
  }
}




contact: nji(at)gmx.de