rp-rs / rp-hal-boards

Board Support Packages for RP2040 based PCBs
199 stars 82 forks source link

Looking for API to read ADC value on Pico #42

Open abcd-ca opened 11 months ago

abcd-ca commented 11 months ago

I have a 0-3.25V input wired to GPIO26 (ADC0). Where is the API to read an analog value (0-4095)? I think I'm looking for something like,

let adc_pin_0 = pins.gpio26.into_analog_input();

Update: is it into_floating_input()?

jannic commented 11 months ago

I think the method you are looking for is AdcPin::new(): https://docs.rs/rp2040-hal/latest/rp2040_hal/adc/struct.AdcPin.html#method.new

See https://github.com/rp-rs/rp-hal/blob/main/rp2040-hal/examples/adc.rs#L113 for an example.

abcd-ca commented 11 months ago

Thanks @jannic. So, I've got,

use rp_pico::entry;
use panic_halt as _;
use rp_pico::hal::prelude::*;
use rp_pico::hal::pac;
use rp_pico::hal;

...

    let mut adc = hal::adc::Adc::new(pac.ADC, &mut pac.RESETS);
    let mut adc_pin_0 = hal::adc::AdcPin::new(pins.gpio26.into_floating_input());

...

    loop {
        let pin_adc_counts: u16 = adc.read(&mut adc_pin_0).unwrap();

        delay.delay_ms(2000);
    }
}

But I'm getting this error for read:

method `read` is private [E0624] private method

And this error for its arg

Type mismatch [E0308] expected `u8`, but found `&mut AdcPin<Pin<Gpio26, FunctionSio<SioInput>, PullNone>>` 
jannic commented 11 months ago

You are missing use embedded_hal::adc::OneShot. But I see that the error message really isn't nice, as it confuses two different read methods.

abcd-ca commented 11 months ago

Thank you @jannic. So, I was trying to use what I think is the higher level rp_pico crate for Pico but couldn't find a way to get the adc pin set up and reading. Then I found the first usage example here in the rp2040_hal. I'm waiting for my Pico to arrive so I can't physically test it but the example does compile for me. So the example is using what you referred to. Can I conclude that the rp_pico create is missing an adc API and that I must use the lower level hal crate instead?

jannic commented 11 months ago

rp_pico isn't really higher level. The board support packages just add board-specific details like pin naming. And they provide the correct boot2 implementation for the external flash chip the board contains. So there's nothing wrong with directly using the rp2040_hal APIs. They are also re-exported as rp_pico::hal.

abcd-ca commented 11 months ago

Thanks, looking forward to getting my Pico to test this out!

jannic commented 11 months ago

If you like, come to the rp-rs matrix room at https://matrix.to/#/#rp-rs:matrix.org. Nice place to talk, ask questions, share your projects etc.