Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve ADC accuracy #75

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
37 changes: 33 additions & 4 deletions Firmware/LowLevel/src/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ SerialPIO uiSerial(PIN_UI_TX, PIN_UI_RX, 250);
#define R_SHUNT 0.003f
#define CURRENT_SENSE_GAIN 100.0f

int next_adc_offset_sample = 0;
float adc_offset_samples[20] = {0};
float adc_offset = 0.0f;
// Limit adc_offset to 3%
#define MAX_ADC_OFFSET_PC 0.03f

#define BATT_ABS_MAX 28.7f
#define BATT_ABS_Min 21.7f

Expand Down Expand Up @@ -677,15 +683,38 @@ void loop() {
updateNeopixel();

status_message.v_battery =
(float) analogRead(PIN_ANALOG_BATTERY_VOLTAGE) * (3.3f / 4096.0f) * ((VIN_R1 + VIN_R2) / VIN_R2);
status_message.v_charge =
(float) analogRead(PIN_ANALOG_CHARGE_VOLTAGE) * (3.3f / 4096.0f) * ((VIN_R1 + VIN_R2) / VIN_R2);
((float)analogRead(PIN_ANALOG_BATTERY_VOLTAGE) - adc_offset) * (3.33f / 4096.0f) * ((VIN_R1 + VIN_R2) / VIN_R2);
#ifndef IGNORE_CHARGING_CURRENT
status_message.charging_current =
(float) analogRead(PIN_ANALOG_CHARGE_CURRENT) * (3.3f / 4096.0f) / (CURRENT_SENSE_GAIN * R_SHUNT);
((float)analogRead(PIN_ANALOG_CHARGE_CURRENT) - adc_offset) * (3.33f / 4096.0f) / (CURRENT_SENSE_GAIN * R_SHUNT);
#else
status_message.charging_current = -1.0f;
#endif
status_message.v_charge = ((float)analogRead(PIN_ANALOG_CHARGE_VOLTAGE) - adc_offset) * (3.33f / 4096.0f) * ((VIN_R1 + VIN_R2) / VIN_R2);


// If mowing use charge current ADC to determine adc offset
if(
ROS_running &&
last_high_level_state.current_mode == HighLevelMode::MODE_AUTONOMOUS &&
last_high_level_state.gps_quality != 0
) {
adc_offset_samples[next_adc_offset_sample++] = (float)analogRead(PIN_ANALOG_CHARGE_VOLTAGE);
next_adc_offset_sample %= 20;

float tmp = 0.0f;
for(int i=0; i<20; i++) {
tmp += adc_offset_samples[i];
}
float new_adc_offset = tmp / 20.0f;
// Limit maximum offset
if(new_adc_offset > 0.0f) {
adc_offset = min(new_adc_offset, (4096 * MAX_ADC_OFFSET_PC));
} else {
adc_offset = max(new_adc_offset, -(4096 * MAX_ADC_OFFSET_PC));
}
}

status_message.status_bitmask = (status_message.status_bitmask & 0b11111011) | ((charging_allowed & 0b1) << 2);
status_message.status_bitmask = (status_message.status_bitmask & 0b11011111) | ((sound_available & 0b1) << 5);

Expand Down