Nrf-hal How do I use the ADC

Hi,
I am trying to use the ADC on my Microbit. I must admit that I am new to Rust. So far I managed to get the ADC initialization to compile. But now I m stuck at using the read function from nrf-hal-common/src/adc.rs:

impl<PIN> OneShot<Adc, i16, PIN> for Adc
where
    PIN: Channel<Adc, ID = u8>,
{
    type Error = ();

    fn read(&mut self, _pin: &mut PIN) -> nb::Result<i16, Self::Error> {
        let original_inpsel = self.0.config.read().inpsel();
        match PIN::channel() {
            0 => self.0.config.modify(|_, w| w.psel().analog_input0()),

Short question: How do I define the PIN for the read function?
A physical pin does not work:

        let mut anapin = board.adc_pins.adc03;

Long Question: The implementation uses a generic type which has a trait with more generic parameters as its type?

     PIN: Channel<Adc, ID = u8>,

Any hints are appreciated.

Cheers,
Torsten

Ok, I figured it out. It is the solution to a newbie problem. Let's see how often the default immutability is going to bite me.

The change

            adc.read(&anapin);

to

            adc.read(&mut anapin);

made it compile.

Cheers,
Torsten

2 Likes

It probably should not bite you too often. You were already looking at the source for the method, and the method signature has all the info you need:

fn read(&mut self, _pin: &mut PIN) -> nb::Result<i16, Self::Error>

Just from looking at this, you can see that self (your adc binding) must be let mut, and _pin must be an exclusively borrowed (aka &mut) PIN type.

So, it looks like you started out down the right path, you just weren't sure what to look for. Now it should be more apparent the next time you are faced with a similar problem.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.