Menu
CoddyTech

Pitch From a Knob

Part of the Outputs section of Coddy's Arduino journey. Lesson 12 of 24.

A knob can play the buzzer like an instrument. The idea is the same as the dimmer: read the knob, convert the reading, use it.

This time the target range is a frequency. 200 Hz is a low hum and 2000 Hz a high whistle, so:

int reading = analogRead(A0);
int pitch = map(reading, 0, 1023, 200, 2000);
tone(8, pitch);

map() does not need the new range to start at 0: 0 becomes 200, 1023 becomes 2000, and the middle of the knob lands near 1100.

Calling tone() again with a new frequency changes the note straight away, so the pitch follows the knob as you turn it. A short delay(10) keeps the sketch from restarting the tone thousands of times a second.

challenge icon

Challenge

Easy

The knob is on A0 and the buzzer on pin 8. Make the knob set the pitch:

  • read the knob
  • convert the reading to a frequency from 200 to 2000 Hz with map()
  • play it with tone(), then wait 10 ms

Press Run and turn the knob, then Check.

Try it yourself

const int knobPin = A0;
const int buzzerPin = 8;

void setup() {
}

void loop() {
  // read the knob, map it to 200..2000 Hz and play it
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Outputs

Practice on your own: Arduino playground