// A test harness for 8 pin UART TX on a single PIO State Machine
// Test project https://wokwi.com/projects/344345628967436882
// uart_tx.h source 
#include "pico/stdlib.h"
#include "hardware/pio.h"
#include "uart_tx.h"

// start at pin 2, so if we want we have UART0 on GP0 and GP1
const uint pin = 2;

// NOTE the simulator doesn't seem to hit this exactly (on my 2015 macbook)
// It ends up being slow by about 6% YMMV
const uint baud = 31250;
const PIO pio = pio0;

uint sm;

void setup() {
  uint offset = pio_add_program(pio, &uart_tx_program);
  sm = pio_claim_unused_sm(pio, true);
  uart_tx_program_init(pio, sm, offset, pin, baud);
}

// Some test messages
uint8_t messages[12] = {
  0x80, 0x3C, 0x00, // Note Off Channel 1, Middle C, Velocity 0
  0x90, 0x3C, 0x7F, // Note On Channel 1, Middle C, Velocity 127
  0x80, 0x3D, 0x00, // Note Off Channel 1, Middle C, Velocity 0
  0x90, 0x3D, 0x7F  // Note On Channel 1, Middle C, Velocity 127
};
uint counter = 0;

void loop() {
  // pull 3 message bytes off
  sendByte(counter++);
  sendByte(counter++);
  sendByte(counter++);
  // delay(1);
  // delayMicroseconds(100);
}

// Send the exact same byte to all outputs
void sendByte(uint idx) {
  uint8_t m = messages[idx];
  uint32_t low = (
    ((m >> 0 & 0x01) << 0) +
    ((m >> 1 & 0x01) << 8) +
    ((m >> 2 & 0x01) << 16) +
    ((m >> 3 & 0x01) << 24)
  ) * 0xFF;
  uint32_t high = (
    ((m >> 4 & 0x01) << 0) +
    ((m >> 5 & 0x01) << 8) +
    ((m >> 6 & 0x01) << 16) +
    ((m >> 7 & 0x01) << 24)
  ) * 0xFF;
  uart_tx_program_putc(pio, sm, low, high);
}
BOOTSELLED1239USBRaspberryPiPico©2020RP2-8020/21P64M15.00TTT
D0D1D2D3D4D5D6D7GNDLOGIC