/**
* @ brief ADC sampling and SPI transmission on the Raspberry Pi Pico.
*
* Reads an analogue voltage from ADC0, formats the raw value and computed voltage
* into a human-readable string, and transmits that string over SPI0 to a custom chip
* once per second.
*
* @author Michael Gao
* @date 2026
* @license MIT
*/
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
#include "hardware/adc.h"
#include "hardware/spi.h"
// GPIO pin used for SPI chip select line.
#define PIN_CS 17
int main() {
// Initialize stdio for serial console
stdio_init_all();
// ADC setup
adc_init();
adc_gpio_init(26); // Configure GPIO26 for ADC input
adc_select_input(0); // Route ADC0 to result register
printf("ADC0 initialized.\n");
spi_init(spi0, 1000 * 1000); // 1 MHz clock
gpio_set_function(18, GPIO_FUNC_SPI); // GPIO18 for SCK line
gpio_set_function(19, GPIO_FUNC_SPI); // GPIO19 for SDI line
gpio_init(PIN_CS); // GPIO17 for nCS line
gpio_set_dir(PIN_CS, GPIO_OUT); // Drive chip select manually
gpio_put(PIN_CS, 1); // Deassert nCS
while (true) {
// Sample ADC and convert reading to voltage
uint16_t raw = adc_read();
float voltage = raw * (3.3f / 4095.0f);
// Push ADC reading into a buffer
char msg[64];
snprintf(msg, sizeof(msg), "ADC Value: %u (%.2fV)\n", raw, voltage);
// Transmit the ADC reading over SPI, manually setting the nCS line
gpio_put(PIN_CS, 0);
spi_write_blocking(spi0, (uint8_t *)msg, strlen(msg));
gpio_put(PIN_CS, 1);
// Debug
printf("SPI sent: %s", msg);
// Sample every 1 second
sleep_ms(1000);
}
}