#include <stdio.h> // Standard library for input and output, used for printf.
#include "pico/stdlib.h" // Standard library for basic Pico functions, such as GPIO and timing.
#include "hardware/adc.h" // Library for controlling the ADC (Analog-to-Digital Converter).
// Definitions
#define ADC_TEMPERATURE_CHANNEL 4 // ADC channel corresponding to the internal temperature sensor
// Function to convert the ADC reading to temperature in degrees Celsius
float adc_to_temperature(uint16_t adc_value) {
// Constants provided in the RP2040 datasheet
const float conversion_factor = 3.3f / (1 << 12); // Conversion from 12-bit (0-4095) to 0-3.3V
float voltage = adc_value * conversion_factor; // Converts the ADC value to voltage
float celsius_temperature = 27.0f - (voltage - 0.706f) / 0.001721f; // Equation provided for conversion
return celsius_temperature;
}
// Function to convert Celsius to Fahrenheit
float celsius_to_fahrenheit(float celsius) {
return ((celsius * 1.8f) + 32); // Physics equation for Celsius to Fahrenheit conversion
}
int main() {
// Initializes serial communication to allow printf usage
stdio_init_all();
// Initializes the ADC module of the Raspberry Pi Pico
adc_init();
// Selects ADC channel 4 (internal temperature sensor)
adc_set_temp_sensor_enabled(true); // Enables the internal temperature sensor
adc_select_input(ADC_TEMPERATURE_CHANNEL); // Selects the temperature sensor channel
// Infinite loop for continuous temperature readings
while (true) {
// Reads the ADC value from the selected channel (temperature sensor)
uint16_t adc_value = adc_read();
// Converts the ADC value to temperature in degrees Celsius
float celsius_temperature = adc_to_temperature(adc_value);
// Converts Celsius to Fahrenheit
float fahrenheit_temperature = celsius_to_fahrenheit(celsius_temperature);
// Prints the temperature on the serial communication
printf("Temperature: %.2f °F\n", fahrenheit_temperature);
// Delay of 1000 milliseconds (1 second) between readings
sleep_ms(1000);
}
return 0;
}