// (C) 2020 Philip Endecott.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENCE.txt or copy at https://www.boost.org/LICENSE_1_0.txt

#include "registers.hh"


static void uart0_setup()
{
  // Baud rate:
  // The PLL is not enabled so CCLK = OSC = 19.6608 MHz.
  // The APB divider by default divides by 4, so PCLK = CCLK/4 = 4.9152 MHz.
  // baud = PCLK / (16 * U0DLM:U0DLL)
  // For 38400 baud, U0DLM:U0DLL = PCLK / ( 38400 * 16 ) = 8.
  // I.e. U0DLM = 0, U0DLL = 8.
  // We need to set the DLAB bit in U0LCR while settings these values.

  uint8_t LCR = 0b00000011;  // 8 bits, 1 stop bit, no parity.

  *U0LCR = LCR | 0b10000000;  // Set DLAB.
  *U0DLM = 0;
  *U0DLL = 8;
  *U0LCR = LCR;
  
  *U0FCR = 0b0000001;  // Bit 0 enables.
}


static void uart0_send(const char* s)
{
  const char* p = s;
  while (*p) {
    while (!(*U0LSR & 0b00100000)) {}  // Test THRE bit
    *U0THR = *p;
    ++p;
  }
}


int main(int argc, char* argv[])
{
  uart0_setup();
  while (1) {
    uart0_send("Hello World!\r\n");
  }
}

