# ST-LAB

FIsica - Laboratorio III - Esperimentazioni di Elettronica

```mermaid
flowchart TD
    %% --- STILI ---
    classDef hw fill:#ffcccc,stroke:#333,stroke-width:2px;
    classDef memory fill:#e1f5fe,stroke:#333,stroke-width:1px;
    classDef logic fill:#fff9c4,stroke:#333,stroke-width:1px;
    
    Start((START)) --> Init
    
    %% --- BLOCCO INIZIALIZZAZIONE ---
    subgraph Init [1. Inizializzazione Bare Metal]
        direction TB
        RCC[RCC AHB4ENR & APB1ENR\nAbilita Clock GPIO & USART]:::hw
        GPIO[GPIO MODER & AFR\nButton=Input, LED=Output, TX=AF]:::hw
        UART[USART3 CR1 & BRR\nConfigura Baud & Abilita UE]:::hw
        NVIC[NVIC_EnableIRQ\nAbilita Interrupts al processore]:::hw
        
        RCC --> GPIO --> UART --> NVIC
    end

    Init --> MainLoop

    %% --- BLOCCO MAIN LOOP ---
    subgraph Main [2. Main Loop (Polling Button)]
        direction TB
        MainLoop(while 1)
        
        ReadIDR[Leggi GPIOC->IDR\n(Stato Bottone)]:::hw
        Debounce[Debounce Delay]:::logic
        
        EdgeCheck{Rising Edge?\n(Curr=1 && Prev=0)}:::logic
        
        ToggleOps[Toggle Logic]:::memory
        UpdatePrev[Prev = Curr]:::logic
        
        MainLoop --> ReadIDR --> EdgeCheck
        
        EdgeCheck -- NO --> UpdatePrev
        EdgeCheck -- SI --> ToggleOps
        
        subgraph Toggle [Logica XOR LED]
            ReadODR[Leggi GPIOB->ODR]:::hw
            XOR[Calcola: ODR ^ LED_MASK]:::logic
            WriteODR[Scrivi GPIOB->ODR]:::hw
            ReadODR --> XOR --> WriteODR
        end
        
        ToggleOps --> UpdatePrev
        UpdatePrev --> Debounce --> MainLoop
    end

    %% --- BLOCCO INTERRUPT ---
    subgraph ISR [3. USART3 IRQ Handler]
        direction TB
        Trigger((IRQ))
        
        CheckTXE{Flag TXE?\n(Data Reg Empty)}:::logic
        CheckTC{Flag TC?\n(Tx Complete)}:::logic
        
        LoadDR[Scrivi USART3->DR\n(Invia Byte)]:::hw
        EnableTC[Abilita TCIE\nDisabilita TXEIE]:::hw
        DisableTC[Disabilita TCIE\nClear TC Flag]:::hw
        FreeBusy[Set tx_busy = 0]:::memory
        
        Trigger --> CheckTXE
        
        CheckTXE -- SI: Buffer Pieno --> LoadDR
        CheckTXE -- SI: Buffer Finito --> EnableTC
        CheckTXE -- NO --> CheckTC
        
        CheckTC -- SI: Fine Trasmissione --> DisableTC --> FreeBusy
        CheckTC -- NO --> Return((RTI))
    end

    %% --- CONNESSIONI LOGICHE ---
    WriteODR -.-> |Opzionale: Avvia TX| Trigger
