# Experiment F: D Flip-Flop with Programmable Clock
import machine
import utime
# --- Pins for Monitoring ---
Q_PIN = machine.Pin(16, machine.Pin.IN) # Reads Q from flip-flop
Q_NOT_PIN = machine.Pin(17, machine.Pin.IN) # Reads Q̅ from flip-flop
# --- Pin for Generating Clock (GP18) ---
CLOCK_PIN = machine.PWM(machine.Pin(18))
CLOCK_FREQ = 100 # 100 Hz = 100 pulse per second
CLOCK_PIN.freq(CLOCK_FREQ)
CLOCK_PIN.duty_u16(32768) # 50% duty cycle
# --- Optional: Button to change Data input ---
# If you connected a button to GP19 for Data
# DATA_BUTTON = machine.Pin(19, machine.Pin.IN, machine.Pin.PULL_UP)
print("🧠 Experiment F: D Flip-Flop with Programmable Clock")
print("=" * 60)
print("SETUP:")
print("• Pico GP18 -> Flip-Flop CLK (Auto clock at 100 Hz)")
print("• Flip-Flop Q -> Pico GP16 (Monitor)")
print("• Flip-Flop Q̅ -> Pico GP17 (Monitor)")
print("• Data (D) pin: Connect to HIGH (3.3V) or LOW (GND)")
print("-" * 60)
print("ACTIONS:")
print("• Manually CHANGE the D input (HIGH/LOW)")
print("• Watch LEDs update on the next clock pulse")
print("-" * 60)
def monitor_flip_flop():
"""Reads and returns the state of the flip-flop."""
q_state = Q_PIN.value()
q_not_state = Q_NOT_PIN.value()
if q_state == q_not_state:
return "⚠️ ERROR: Q and Q̅ should be opposites!"
else:
bit_value = q_state
return f"Stored Bit: {bit_value} | Q: {'HIGH' if q_state else 'LOW'}, Q̅: {'HIGH' if q_not_state else 'LOW'}"
try:
counter = 0
while True:
status = monitor_flip_flop()
# Print with clock cycle counter
print(f"Clock Cycle: {counter:3d} | {status}", end='\r')
counter += 1
utime.sleep(1) # Wait 1 second per clock cycle
except KeyboardInterrupt:
CLOCK_PIN.deinit() # Turn off clock signal
print("\n\n✅ Experiment stopped. Clock halted.")
ERC Warnings
flop1:CLK: Clock driven by combinatorial logic