Skip to content

Commit abd7065

Browse files
KurtEsoburi
authored andcommitted
cores: arduino: Implement analogReadResolution
69b644f Co-Authored-by: Kurt Eckhardt <kurte@rockisland.com> Signed-off-by: TOKITA Hiroshi <tokita.hiroshi@gmail.com>
1 parent 920891d commit abd7065

2 files changed

Lines changed: 28 additions & 3 deletions

File tree

cores/arduino/Arduino.h

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,9 @@ enum analogPins {
9494
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), adc_pin_gpios, AN_ENUMS)
9595
};
9696

97+
// We provide analogReadResolution APIs
98+
void analogReadResolution(int bits);
99+
97100
#endif
98101

99102
#ifdef CONFIG_DAC
@@ -117,8 +120,9 @@ void noInterrupts(void);
117120

118121
int digitalPinToInterrupt(pin_size_t pin);
119122

120-
void analogReadResolution(int bits);
123+
#if defined(CONFIG_DAC) || defined(CONFIG_PWM)
121124
void analogWriteResolution(int bits);
125+
#endif
122126

123127
#include <variant.h>
124128

cores/arduino/zephyrCommon.cpp

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -436,9 +436,20 @@ void analogReference(uint8_t mode) {
436436
}
437437
}
438438

439+
// Note: We can not update the arduino_adc structure as it is read only...
440+
static int read_resolution = 10;
441+
442+
void analogReadResolution(int bits) {
443+
read_resolution = bits;
444+
}
445+
446+
int analogReadResolution() {
447+
return read_resolution;
448+
}
449+
439450
int analogRead(pin_size_t pinNumber) {
440451
int err;
441-
int16_t buf;
452+
uint16_t buf;
442453
struct adc_sequence seq = {.buffer = &buf, .buffer_size = sizeof(buf)};
443454
size_t idx = analog_pin_index(pinNumber);
444455

@@ -468,7 +479,17 @@ int analogRead(pin_size_t pinNumber) {
468479
return err;
469480
}
470481

471-
return buf;
482+
/*
483+
* If necessary map the return value to the
484+
* number of bits the user has asked for
485+
*/
486+
if (read_resolution == seq.resolution) {
487+
return buf;
488+
}
489+
if (read_resolution < seq.resolution) {
490+
return buf >> (seq.resolution - read_resolution);
491+
}
492+
return buf << (read_resolution - seq.resolution);
472493
}
473494

474495
#endif

0 commit comments

Comments
 (0)