/*
 * souffle-starter.c
 *
 * A starting point for your board. Registers only, no HAL, no CubeMX, coz
 * sometimes you just want to see what the chip is actually doing. It reads
 * the nine buttons and lights the matching LEDs. Thats it, the rest is yours.
 *
 * Build:
 *   arm-none-eabi-gcc -mcpu=cortex-m3 -mthumb -Og -g3 -nostdlib \
 *       -T stm32f103c8.ld souffle-starter.c startup.s -o out.elf
 *   arm-none-eabi-objcopy -O binary out.elf out.bin
 *
 * Flash it with an ST-Link on the Tag-Connect pads:
 *   STM32_Programmer_CLI -c port=SWD mode=UR -d out.bin 0x08000000 -v -rst
 *
 * If you think you bricked it, you didnt. Flash souffle-original.bin back
 * over the top and youre where you started.
 *
 *
 * THE TWO THINGS THAT WILL CATCH YOU OUT
 *
 * 1. PA15 and PB4 are JTAG pins at reset (JTDI and NJTRST). Until you turn
 *    JTAG off they arent GPIOs at all, so you can write to them all day and
 *    LED1 and LED2 just sit there. Thats what the AFIO_MAPR write below is
 *    for. Dont turn SW off at the same time or you lose the debugger.
 *
 * 2. The LEDs sink to light. Anode to 3V3, cathode through 120R to the pin,
 *    so pin LOW is on. Backwards from what you'd expect and i got it wrong
 *    the first time. Everything below is written that way round.
 */

#include <stdint.h>

/* ------------------------------------------------------------------ RCC */
#define RCC_APB2ENR (*(volatile uint32_t *)0x40021018u)
#define RCC_APB2_AFIO   (1u << 0)
#define RCC_APB2_GPIOA  (1u << 2)
#define RCC_APB2_GPIOB  (1u << 3)

#define AFIO_MAPR   (*(volatile uint32_t *)0x40010004u)

/* ----------------------------------------------------------------- GPIO */
typedef struct {
  volatile uint32_t CRL, CRH, IDR, ODR, BSRR, BRR, LCKR;
} gpio_t;

#define GPIOA ((gpio_t *)0x40010800u)
#define GPIOB ((gpio_t *)0x40010C00u)

/* CNF:MODE nibbles, from the reference manual */
#define MODE_IN_PULL   0x8u   /* input with pull-up or pull-down */
#define MODE_OUT_2MHZ  0x2u   /* push-pull output, 2 MHz        */

static void pin_mode(gpio_t *port, uint32_t pin, uint32_t nibble)
{
  volatile uint32_t *reg = (pin < 8u) ? &port->CRL : &port->CRH;
  uint32_t shift = (pin & 7u) * 4u;
  *reg = (*reg & ~(0xFu << shift)) | (nibble << shift);
}

/* ------------------------------------------------------------ the board */
/* left to right, as they sit on the front of the card */
static gpio_t *const led_port[9] = { GPIOA, GPIOB, GPIOB, GPIOB, GPIOB,
                                     GPIOB, GPIOB, GPIOB, GPIOB };
static const uint8_t led_pin[9]  = {    15,     4,     5,     6,     7,
                                         8,     9,    10,    11 };

static gpio_t *const btn_port[9] = { GPIOA, GPIOA, GPIOA, GPIOA, GPIOA,
                                     GPIOA, GPIOA, GPIOB, GPIOB };
static const uint8_t btn_pin[9]  = {     1,     2,     3,     4,     5,
                                         6,     7,     0,     1 };
/* index 8 is the offset button, the one labelled ENTER */

static void led(uint32_t i, int on)
{
  /* LOW turns it on, so "on" writes the reset half of BSRR */
  led_port[i]->BSRR = on ? (1u << (led_pin[i] + 16u)) : (1u << led_pin[i]);
}

static int button(uint32_t i)
{
  /* active low against the internal pull-up */
  return (btn_port[i]->IDR & (1u << btn_pin[i])) == 0u;
}

/* startup.s calls this before main. Nothings needed here, the chip comes up
   on its 8 MHz internal oscillator which is plenty until you want USB. */
void SystemInit(void) { }

int main(void)
{
  RCC_APB2ENR |= RCC_APB2_AFIO | RCC_APB2_GPIOA | RCC_APB2_GPIOB;

  /* SWJ_CFG = 010: JTAG off, SW-DP still on. Frees PA15, PB3 and PB4.
     Has to happen before you touch those pins or LED1 and LED2 stay dead. */
  AFIO_MAPR = (AFIO_MAPR & ~(7u << 24)) | (2u << 24);

  for (uint32_t i = 0; i < 9u; i++) {
    pin_mode(led_port[i], led_pin[i], MODE_OUT_2MHZ);
    led(i, 0);
    pin_mode(btn_port[i], btn_pin[i], MODE_IN_PULL);
    btn_port[i]->BSRR = 1u << btn_pin[i];   /* ODR high selects pull-UP */
  }

  for (;;) {
    for (uint32_t i = 0; i < 9u; i++) {
      led(i, button(i));
    }
  }
}

/*
 * WHERE TO GO NEXT
 *
 * Brightness. None of these pins are on timer channels so you cant just use
 * hardware PWM, you have to run a timer interrupt and flip them yourself.
 * The naive way is counting 0..255 every frame, which is 256 interrupts a
 * frame and eats the CPU. The original does binary code modulation instead:
 * eight slots with lengths weighted 1,2,4..128, light the pin during the
 * slots whose bit is set. Same 8-bit brightness for 8 interrupts a frame.
 * Also run the value through a gamma 2.2 table, coz your eyes arent linear
 * and a straight ramp looks like it does nothing and then jumps at the top.
 *
 * Sound. The buzzer is on PA0 = TIM2_CH1, so that one IS a hardware PWM pin.
 * Prescale for a 1 MHz count then ARR = 1000000/Hz - 1. Fair warning, its a
 * piezo so its sharply resonant, loudest around 2.7 kHz and basically silent
 * below 1 kHz. Transpose whatever you write up into that band or you wont
 * hear it, and give notes at least 140 ms or the element doesnt have time to
 * ring up and it just sounds like a click.
 *
 * USB. 72 MHz is the only clock that gets you a valid 48 MHz for USB: HSE
 * 8 MHz, PLL x9, USB prescaler 1.5. Nothing else divides right, which is the
 * whole reason theres an 8 MHz crystal on there. And if the crystal doesnt
 * start, the HAL quietly falls back to the internal oscillator and
 * everything looks fine right up until USB wont enumerate, so read RCC->CFGR
 * back at runtime instead of trusting it.
 *
 * The D+ pull-up is on PA8 instead of being hardwired, so you decide when
 * the computer sees the board. Drop PA8, wait a bit, bring USB up, then
 * raise it. Means you can detach and reattach in software without touching
 * the cable.
 *
 * Happy birthday. Go break it.
 *   - Josh
 */
