Divide a clock by two with a D flip-flop
Wire a D flip-flop's inverted output back to its input to halve a clock, and watch one bit of memory change only on the rising edge.
Logic · Intermediate
In a real product: Digital clock chip (Telecom and networking): Flip-flops divide a crystal's frequency down to the rates a system needs.
A flip-flop is one bit of memory. Its D input is only looked at at one instant: the rising edge of CLK. Between edges it ignores D completely and holds its output Q. Every register, counter and shift register in a chip is a row of these.
What you'll learn
- Edge-triggered memory: Q takes D on the rising edge of CLK and holds it
- Why feeding QN (the inverse of Q) back into D makes the output toggle on every clock
- That a toggling output has half the clock's frequency: a divide-by-two counter
- Telling a rising edge from a level in code
How it works
The Arduino makes the clock on pin 8: HIGH for half a second, then LOW for half a second. The flip-flop's QN output is wired to its own D input. On each rising edge it copies D, which is the opposite of what Q held, so Q flips. Two clock periods make one period of Q.
Q goes to pin 2, so the sketch can read what the flip-flop remembered, and through a resistor to the LED. The reset input R is left unconnected, so it never clears the bit.
Try this
- Hold the clock HIGH forever in the sketch and notice that Q stops changing: only edges count.
- Add a second flip-flop whose CLK is the first one's Q (a ripple counter) to divide by four.
- Reset the bit from the Arduino: wire pin 7 to R and pulse it HIGH.
sketch.ino
// Generates a clock on pin 8 and reads the D flip-flop's Q on pin 2. Q's inverse is wired back to D,
// so Q changes on every rising clock edge: it runs at half the clock's frequency.
const int CLOCK = 8;
const int Q = 2;
int edges = 0;
bool lastQ = false;
void setup() {
Serial.begin(9600);
pinMode(CLOCK, OUTPUT);
pinMode(Q, INPUT);
Serial.println("Clock edges -> Q");
}
void loop() {
digitalWrite(CLOCK, HIGH); // the rising edge: the flip-flop remembers D now
edges++;
delay(20); // let the output settle
bool q = digitalRead(Q);
if (q != lastQ) {
Serial.print("Rising edge ");
Serial.print(edges);
Serial.print(": Q is now ");
Serial.println(q ? "HIGH" : "LOW");
lastQ = q;
}
delay(480);
digitalWrite(CLOCK, LOW); // the falling edge changes nothing
delay(500);
}