Hello. I’m writting a new firmware for an APM 2.6.1 board. I want to read several analog values (DC inputs from 0 to 5v). I’m trying the following code but I’m getting random values (varying constantly) around 1 when unplugged (I guess it’s picking noise?) and 1.8-2.6 when I connect it to a constant 5.1v external source. I’ve also tried lower voltages and I always get the same values. I’ve tried the example located at libraries\AP_HAL\examples\AnalogIn\ with the same results. I can’t find any documentation about this topic. What I may be doing wrong? Thank you.
#include <AP_Common.h>
#include <AP_Progmem.h>
#include <AP_Math.h>
#include <AP_Param.h>
#include <AP_HAL.h>
#include <AP_HAL_AVR.h>
#include <AP_GPS.h>
#include <AP_GPS_Glitch.h>
#include <AP_ADC.h>
#include <AP_ADC_AnalogSource.h>
#include <AP_Baro.h>
#include <Filter.h>
#include <AP_Compass.h>
#include <AP_Declination.h>
#include <AP_InertialSensor.h>
#include <AP_AHRS.h>
#include <AP_Airspeed.h>
#include <AP_Vehicle.h>
#include <DataFlash.h>
#include <AC_PID.h>
#include <APM_PI.h>
#include <AP_Buffer.h>
#include <GCS_MAVLink.h>
#include <AP_Notify.h>
#include <AP_InertialNav.h>
const AP_HAL::HAL& hal = AP_HAL_BOARD_DRIVER;
AP_HAL::AnalogSource* ain;
void setup() {
ain = hal.analogin->channel(0);
}
void loop() {
float v=ain->voltage_average();
hal.console->printf_P(PSTR("%.3f\n"),v);
}
AP_HAL_MAIN();