// GPIO helpers: every board control line lives here (except the two chip
// selects, which stay with their SPI drivers). Each helper sets the pin's
// direction on every call so it works no matter what ran before it.

#include "states.h"

void init_spi(void)
{
    SET_PIN_OUT(DDRC, DDC1); // SCK1
    SET_PIN_OUT(DDRE, DDE3); // MOSI1
    SET_PIN_IN(DDRC, DDC0); // MISO1 (driven by the slave; no pull-up)

    // SS1 must be an output before SPE is set. If it is left as an input and
    // reads low, the hardware clears MSTR and the port silently stops being a
    // master.
    SET_PIN_OUT(DDRE, DDE2);
    SET_PIN_HIGH(PORTE, PE2);

    SPCR1 = (1 << SPE1) | (1 << MSTR1); // Enable, Master, SPR1:0 = 00 -> f_osc/4
}

// RFM69 reset line: high holds the radio in reset
void rfm69_reset_state(bool state)
{
    SET_PIN_OUT(DDRC, DDC2);
    SET_PIN_TO(PORTC, PC2, state);
}

void led_1_set_state(bool state)
{
    SET_PIN_OUT(DDRD, DDD4);
    SET_PIN_TO(PORTD, PD4, state);
}

void led_2_set_state(bool state)
{
    SET_PIN_OUT(DDRD, DDD6);
    SET_PIN_TO(PORTD, PD6, state);
}

void led_3_set_state(bool state)
{
    SET_PIN_OUT(DDRD, DDD7);
    SET_PIN_TO(PORTD, PD7, state);
}

// Enable line of the LDO that powers the radio and EEPROM
void ldo_set_state(bool state)
{
    SET_PIN_OUT(DDRC, DDC3);
    SET_PIN_TO(PORTC, PC3, state);
}
