#include <avr/interrupt.h>
#include <avr/io.h>

#define SEI() asm volatile ("sei")
#define CLI() asm volatile ("cli")

//#define F_CPU (3333333UL)
#define F_CPU   (20000000UL)

#define PIN_SDI (1 << 1)
#define PIN_SDO (1 << 2)
#define PIN_SCK (1 << 3)
#define PIN_CSA (1 << 4)
#define PIN_CSB (1 << 5)
#define PIN_CSC (1 << 6)
#define PIN_CSN (PIN_CSA | PIN_CSB | PIN_CSC)

void delay(void) {
  for (volatile int i = 0; i < 4; i++);
}

// SPI mode 3, clock change on negative edge
// default clock rate is 16 MHz for the attiny404
// max clock rate is 4 MHz

void spi_enable(void) {
  // pin change + delay
  VPORTA_OUT &= ~PIN_CSN;
  delay();
}
void spi_disable(void) {
  // pin change + delay
  delay();
  VPORTA_OUT |= PIN_CSN;
}

void spi_send_bit(int bit) {
  // pin change + delay
  int tmp = VPORTA_OUT;
  if (!bit) {
    tmp &= (~PIN_SCK) | (~PIN_SDO);
  } else {
    tmp &= ~PIN_SCK;
    tmp |= PIN_SDO;
  }
  VPORTA_OUT = tmp;
  delay();
  VPORTA_OUT |= PIN_SCK;
  delay();
}

int main() {
  SEI();

  VPORTA_DIR |= PIN_SDO | PIN_SCK | PIN_CSN;
  VPORTA_DIR &= ~PIN_SDI;
  VPORTA_OUT = PIN_CSN | PIN_SCK; // deselect all chip select pins, set clock high

  spi_enable();

  // TODO

  spi_disable();
  while (1);

  return 0;
}
