I was trying to read some voltages from a sensor, but before doing that, I checked how readings would look like, when nothing is connected to pins.
Here's my code based on examples:
#include <stdio.h>
#include "pico/stdlib.h"
#include "hardware/gpio.h"
#include "hardware/adc.h"
int main() {
stdio_init_all();
const float conversion_factor = 3.3f / (1 << 12);
adc_init();
gpio_set_dir_all_bits(0);
for (int i = 2; i < 30; i) {
gpio_set_function(i, GPIO_FUNC_SIO);
if (i >= 26) {
gpio_disable_pulls(i);
gpio_set_input_enabled(i, false);
}
}
gpio_init(PICO_DEFAULT_LED_PIN);
gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT);
adc_set_temp_sensor_enabled(true);
bool enabled = 0;
while (1) {
float result[3];
for (int i=0; i<3; i )
{
adc_select_input(i);
sleep_ms(10);
result[i] = adc_read() * conversion_factor;
}
adc_select_input(4);
sleep_ms(10);
float temp_adc = (float)adc_read() * conversion_factor;
float tempC = 27.0f - (temp_adc - 0.706f) / 0.001721f;
printf("Voltage 0-2: %f,%f,%f V, temp: %f\r\n", result[0], result[1], result[2], tempC);
enabled = (enabled 1) % 2;
gpio_put(PICO_DEFAULT_LED_PIN, enabled);
sleep_ms(2000);
}
}
I got the output in which only onboard temperature seems reasonable and not changing:
Voltage 0-2: 1.145654,0.374634,1.025610 V, temp: 23.861492
Voltage 0-2: 0.407666,1.086035,0.441504 V, temp: 23.393347
Voltage 0-2: 1.136792,0.359326,1.046558 V, temp: 23.393347
Voltage 0-2: 0.558325,0.605859,0.579272 V, temp: 23.861492
Voltage 0-2: 0.645337,0.504346,0.696094 V, temp: 23.861492
In addition, I have two Raspberry Pi Pico's, and got similar result's on both.
Why values from ADC 0 to 2 are not equal/near 0, and they're changing so rapidly, when completely nothing is connected to the Pico?
CodePudding user response:
This is happens when pins aren't connected to anything - it is called noise. elegant explanation here
CodePudding user response:
Pins are never not connected. They have a pullup/down resistor that can be switched on or off and they are connected to the read and write circuitry that can be switched between.
Those aren't physical switches. When you switch the pullup/down resistor off what that really means is that you make that a really high resistor. A bit of current will always leak across the switch.
You also have current running through nearby pins that might induce a current in the floating pin.
You might also simply have residual charge left on the pin from when it was connected or was an output pin. If a floating pin was output HIGH and you switch it to read the next value you read is probably going to be HIGH. Reading that drains a bit of the left over charge so if you wait a bit the next read might be LOW.
Measuring a floating pin is basically meaningless but might be a source for random bits. For anything else that's what the pullup/down resistors are for. [If the Pico doens't have those you have to connect one externally].