Rotary phone dial as a keypad
Decode a rotary telephone dial's pulses into digits and use them to enter a PIN.
Input · Intermediate
In a real product: Retro phone conversion (Telecom and networking): Dial pulses decode into digits.
Old telephones sent each digit as a train of pulses: dial a 5 and a contact opens five times as the dial returns. That is a tidy exercise in counting edges and in knowing when a sequence has ended.
What you'll learn
- Counting edges on a pin with a pull-up
- Using a second contact to know when a digit starts and ends
- A small state machine that collects a four-digit PIN
How it works
Both contacts join their pin to GND, so the sketch uses INPUT_PULLUP. While the dial turns, DIAL reads LOW. During that time PULSE opens once per count (it reads HIGH for each pulse), ten times for 0. When DIAL returns HIGH the count is the digit. Four digits make a PIN, which the sketch compares with the right one: the LED lights when it matches.
Try this
- Dial 1, 9, 8, 4 by clicking digits on the dial while it runs.
- Show each pulse on the LED as it arrives.
- Add a time-out: forget a half-entered PIN after five seconds.
sketch.ino
// A rotary dialer (DIAL on 2, PULSE on 3) entering a four-digit PIN; the LED on 13 lights when it is 1984.
const int DIAL = 2, PULSE = 3, LED = 13;
const char PIN_CODE[] = "1984";
char entered[5] = "";
int pulses = 0;
bool lastPulse = LOW, dialing = false;
void setup() {
Serial.begin(9600);
pinMode(DIAL, INPUT_PULLUP);
pinMode(PULSE, INPUT_PULLUP);
pinMode(LED, OUTPUT);
Serial.println("Dial the PIN");
}
void loop() {
bool turning = digitalRead(DIAL) == LOW;
bool pulse = digitalRead(PULSE) == HIGH;
if (turning) {
dialing = true;
if (pulse && !lastPulse) pulses++;
} else if (dialing) {
dialing = false;
int digit = pulses % 10;
pulses = 0;
size_t n = strlen(entered);
entered[n] = '0' + digit;
entered[n + 1] = '\0';
Serial.print("Digit ");
Serial.println(digit);
if (strlen(entered) == 4) {
bool ok = strcmp(entered, PIN_CODE) == 0;
Serial.println(ok ? "PIN accepted" : "Wrong PIN");
digitalWrite(LED, ok);
entered[0] = '\0';
}
}
lastPulse = pulse;
delay(2);
}