stm32-rs / stm32l0xx-hal

A hardware abstraction layer (HAL) for the STM32L0 series microcontrollers written in Rust
BSD Zero Clause License
96 stars 60 forks source link

Implement ADC self-calibration #233

Closed jcard0na closed 10 months ago

jcard0na commented 10 months ago

Implement the ACD self-calibration procedure, which is defined in the RM377 reference manual as follows:

The ADC has a calibration feature. During the procedure, the ADC calculates a calibration factor which is internally applied to the ADC until the next ADC power-off. The application must not use the ADC during calibration and must wait until it is complete. Calibration should be performed before starting A/D conversion.

jcard0na commented 10 months ago

Thanks for looking at this, @jamwaffles

Looks good but I'm a bit hesitant about the 1000 loop iterations. Would it be better to use a while loop and make the assumption that the hardware will always clear ADCAL?

Yes, I'm not too proud about that loop, but also I'm kind paranoid about introducing potential infinite loops so deep down. If you are happy with it, I'll change it to a while loop. At least on my hardware ADCAL seems to always be cleared.

Also, the manual says:

Calibration can only be initiated when the ADC is disabled (when ADEN = 0)

Is that ensured in the context of calibrate()? I'm not familiar with the ADC code in this crate.

Yep, I'm checking for that here: https://github.com/stm32-rs/stm32l0xx-hal/pull/233/files#diff-09d1f58a7f7c271d63f1a9a00c0c48c886e094bc98c207a8d7688c9f874259bbR132

jcard0na commented 10 months ago

By the way, on my STM32L072, the ADC errors dropped from 6% to 0.05% after calibration(), so it is a big deal :straight_ruler:

jamwaffles commented 10 months ago

Let's go for a while loop... we can change it if someone complains 😁

Yep, I'm checking for that here

Ah thanks, I missed that... 💤

jamwaffles commented 10 months ago

By the way, on my STM32L072, the ADC errors dropped from 6% to 0.05% after calibration(), so it is a big deal 📏

Nice! It's great to validate these changes, and that's a huge improvement.

jamwaffles commented 10 months ago

Thanks!