Skip to content

Commit 4f12abb

Browse files
KurtEsoburi
authored andcommitted
Implement analogReadResolution
Co-Authored-by: Kurt Eckhardt <kurte@rockisland.com> Signed-off-by: TOKITA Hiroshi <tokita.hiroshi@gmail.com>
1 parent a8f57a1 commit 4f12abb

2 files changed

Lines changed: 26 additions & 2 deletions

File tree

cores/arduino/Arduino.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,9 @@ enum analogPins {
104104
DT_FOREACH_PROP_ELEM(DT_PATH(zephyr_user), adc_pin_gpios, AN_ENUMS)
105105
};
106106

107+
// We provide analogReadResolution APIs
108+
void analogReadResolution(int bits);
109+
107110
#endif
108111

109112
#ifdef CONFIG_DAC

cores/arduino/zephyrCommon.cpp

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -504,9 +504,20 @@ void analogReference(uint8_t mode) {
504504
}
505505
}
506506

507+
// Note: We can not update the arduino_adc structure as it is read only...
508+
static int read_resolution = 10;
509+
510+
void analogReadResolution(int bits) {
511+
read_resolution = bits;
512+
}
513+
514+
int analogReadResolution() {
515+
return read_resolution;
516+
}
517+
507518
int analogRead(pin_size_t pinNumber) {
508519
int err;
509-
int16_t buf;
520+
uint16_t buf;
510521
struct adc_sequence seq = {.buffer = &buf, .buffer_size = sizeof(buf)};
511522
size_t idx = analog_pin_index(pinNumber);
512523

@@ -536,7 +547,17 @@ int analogRead(pin_size_t pinNumber) {
536547
return err;
537548
}
538549

539-
return buf;
550+
/*
551+
* If necessary map the return value to the
552+
* number of bits the user has asked for
553+
*/
554+
if (read_resolution == seq.resolution) {
555+
return buf;
556+
}
557+
if (read_resolution < seq.resolution) {
558+
return buf >> (seq.resolution - read_resolution);
559+
}
560+
return buf << (read_resolution - seq.resolution);
540561
}
541562

542563
#endif

0 commit comments

Comments
 (0)