//! Blinks the LED on a Pico board
//!
//! This will blink an LED attached to GP25, which is the pin the Pico uses for the on-board LED.
#![no_std]
#![no_main]

use bsp::{entry, hal::gpio};
use defmt::*;
use defmt_rtt as _;
use embedded_hal::digital::v2::OutputPin;
use embedded_hal::spi::MODE_0;
use max31855::{Max31855, Unit};
use panic_probe as _;

// Provide an alias for our BSP so we can switch targets quickly.
// Uncomment the BSP you included in Cargo.toml, the rest of the code does not need to change.
use rp_pico as bsp;

use bsp::hal::{
    clocks::{init_clocks_and_plls, Clock},
    fugit::RateExtU32,
    pac,
    sio::Sio,
    spi::Spi,
    watchdog::Watchdog,
};

#[entry]
fn main() -> ! {
    info!("Program start");
    let mut pac = pac::Peripherals::take().unwrap();
    let core = pac::CorePeripherals::take().unwrap();
    let mut watchdog = Watchdog::new(pac.WATCHDOG);
    let sio = Sio::new(pac.SIO);

    // External high-speed crystal on the pico board is 12Mhz
    let external_xtal_freq_hz = 12_000_000u32;
    let clocks = init_clocks_and_plls(
        external_xtal_freq_hz,
        pac.XOSC,
        pac.CLOCKS,
        pac.PLL_SYS,
        pac.PLL_USB,
        &mut pac.RESETS,
        &mut watchdog,
    )
    .ok()
    .unwrap();

    let mut delay = cortex_m::delay::Delay::new(core.SYST, clocks.system_clock.freq().to_Hz());

    let pins = bsp::Pins::new(
        pac.IO_BANK0,
        pac.PADS_BANK0,
        sio.gpio_bank0,
        &mut pac.RESETS,
    );

    let mut led_pin = pins.led.into_push_pull_output();
    let mut external_led_pin = pins.gpio14.into_push_pull_output();
    //clk
    let thermometer_spi_sck = pins.gpio2.into_function::<gpio::FunctionSpi>();
    //MOSI, I think unused?
    let thermometer_spi_tx = pins.gpio3.into_function::<gpio::FunctionSpi>();
    //do, or MISO.
    let thermometer_spi_rx = pins.gpio4.into_function::<gpio::FunctionSpi>();
    //cs
    let mut thermometer_spi_csn = pins
        .gpio5
        .into_push_pull_output_in_state(gpio::PinState::Low);

    let thermometer_spi_device = pac.SPI0;
    let spi_pin_layout = (thermometer_spi_tx, thermometer_spi_rx, thermometer_spi_sck);
    let mut spi = Spi::<_, _, _, 8>::new(thermometer_spi_device, spi_pin_layout).init(
        &mut pac.RESETS,
        125_000_000u32.Hz(),
        4u32.MHz(),
        MODE_0,
    );


    loop {
        led_pin.set_high().unwrap();
        external_led_pin.set_low().unwrap();
        delay.delay_ms(1000);
        led_pin.set_low().unwrap();
        external_led_pin.set_high().unwrap();
        delay.delay_ms(1000);
        let value = spi.read_thermocouple(&mut thermometer_spi_csn, Unit::Celsius).unwrap();
        info!("temp is {}", value);
    }
}
