import machine
import time
from machine import Pin
import time
import sys
import select
class InteractiveMemory:
def __init__(self):
"""
Interactive memory system using 74HC595
- Store values 1-8 in memory
- Display stored values on LEDs
- Show memory contents
"""
# 74HC595 connections to Pico GPIO pins
self.DS = machine.Pin(16, machine.Pin.OUT) # Serial data
self.SHCP = machine.Pin(17, machine.Pin.OUT) # Serial clock
self.STCP = machine.Pin(18, machine.Pin.OUT) # Storage/latch clock
# Initialize pins
self.DS.value(0)
self.SHCP.value(0)
self.STCP.value(0)
# Memory storage - 8 locations, each can store values 1-8
self.memory = [0] * 8 # Memory addresses 0-7
self.current_address = 0
# Turn off all LEDs initially
self.shift_out_8bit(0)
print("Interactive Memory System Initialized!")
print("Commands:")
print(" 'store <value>' - Store value 1-8 in current address")
print(" 'address <addr>' - Set current address (0-7)")
print(" 'show' - Display current memory value on LEDs")
print(" 'memory' - Show all memory contents")
print(" 'clear' - Clear all memory")
print(" 'help' - Show this help")
print(" 'quit' - Exit program")
print(f"\nCurrent address: {self.current_address}")
def shift_out_8bit(self, data_byte):
"""Send 8 bits to the 74HC595 chip"""
self.STCP.value(0) # Start shifting
# Send data byte (LSB first)
for i in range(8):
bit = (data_byte >> i) & 1
self.DS.value(bit)
self.SHCP.value(1)
self.SHCP.value(0)
self.STCP.value(1) # Latch the data to outputs
def store_value(self, value):
"""Store a value (1-8) in current memory address"""
if 1 <= value <= 8:
self.memory[self.current_address] = value
print(f"Stored {value} at address {self.current_address}")
# Convert value to binary pattern for LEDs
# Value 1-8 maps to bit patterns
if value == 1:
pattern = 0b00000001 # Bit 0
elif value == 2:
pattern = 0b00000011 # Bits 0-1
elif value == 3:
pattern = 0b00000111 # Bits 0-2
elif value == 4:
pattern = 0b00001111 # Bits 0-3
elif value == 5:
pattern = 0b00011111 # Bits 0-4
elif value == 6:
pattern = 0b00111111 # Bits 0-5
elif value == 7:
pattern = 0b01111111 # Bits 0-6
elif value == 8:
pattern = 0b11111111 # All bits
self.shift_out_8bit(pattern)
print(f"LEDs showing: {value} (0b{pattern:08b})")
else:
print("Error: Value must be between 1 and 8")
def set_address(self, address):
"""Set the current memory address"""
if 0 <= address <= 7:
self.current_address = address
print(f"Current address set to: {address}")
else:
print("Error: Address must be between 0 and 7")
def show_current(self):
"""Display the value at current address on LEDs"""
value = self.memory[self.current_address]
if value == 0:
pattern = 0b00000000
print(f"Address {self.current_address}: Empty (0)")
else:
# Convert stored value back to LED pattern
pattern = (1 << value) - 1 # Create pattern with 'value' number of bits
print(f"Address {self.current_address}: {value} (0b{pattern:08b})")
self.shift_out_8bit(pattern)
def show_memory(self):
"""Display all memory contents"""
print("\nMemory Contents:")
print("Addr | Value | Binary")
print("-----|-------|--------")
for addr in range(8):
value = self.memory[addr]
if value == 0:
binary = "00000000"
display = "Empty"
else:
pattern = (1 << value) - 1
binary = f"{pattern:08b}"
display = str(value)
print(f" {addr} | {display:3} | {binary}")
print()
def clear_memory(self):
"""Clear all memory locations"""
print("Clearing all memory...")
self.memory = [0] * 8
self.shift_out_8bit(0) # Turn off all LEDs
print("Memory cleared!")
def show_help(self):
"""Show available commands"""
print("\nAvailable Commands:")
print(" store <value> - Store value 1-8 at current address")
print(" Example: store 5")
print(" address <addr> - Set current address (0-7)")
print(" Example: address 3")
print(" show - Display current memory value on LEDs")
print(" memory - Show all memory contents")
print(" clear - Clear all memory")
print(" help - Show this help")
print(" quit - Exit program")
print(f"\nCurrent address: {self.current_address}")
def run_interactive(self):
"""Run the interactive memory system"""
print(f"\nInteractive Memory System Ready!")
print(f"Current address: {self.current_address}")
print("Type 'help' for commands")
while True:
try:
# Get user input
user_input = input("\n> ").strip().lower()
if user_input == "quit":
print("Goodbye!")
self.shift_out_8bit(0) # Turn off LEDs
break
elif user_input == "help":
self.show_help()
elif user_input == "show":
self.show_current()
elif user_input == "memory":
self.show_memory()
elif user_input == "clear":
self.clear_memory()
elif user_input.startswith("store "):
try:
value = int(user_input.split()[1])
self.store_value(value)
except (IndexError, ValueError):
print("Usage: store <value> (where value is 1-8)")
elif user_input.startswith("address "):
try:
address = int(user_input.split()[1])
self.set_address(address)
except (IndexError, ValueError):
print("Usage: address <addr> (where addr is 0-7)")
elif user_input == "":
continue # Empty input, just continue
else:
print("Unknown command. Type 'help' for available commands.")
except KeyboardInterrupt:
print("\nGoodbye!")
self.shift_out_8bit(0) # Turn off LEDs
break
except Exception as e:
print(f"Error: {e}")
# Main program
def main():
print("Interactive Memory System with 74HC595")
print("=====================================")
print("\nWiring Guide:")
print(" 74HC595 DS (Serial Data) -> GPIO 16")
print(" 74HC595 SHCP (Serial Clock) -> GPIO 17")
print(" 74HC595 STCP (Storage Clock) -> GPIO 18")
print(" 74HC595 OE -> GND")
print(" 74HC595 MR -> 3.3V")
print(" Connect Q0-Q7 to LEDs with appropriate resistors")
# Create and run interactive memory system
memory_system = InteractiveMemory()
memory_system.run_interactive()
# Run the program
if __name__ == "__main__":
main()