Skip to content

Commit 39faf90

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 596ca61 commit 39faf90

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
@@ -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
@@ -127,8 +130,9 @@ void noInterrupts(void);
127130

128131
int digitalPinToInterrupt(pin_size_t pin);
129132

130-
void analogReadResolution(int bits);
133+
#if defined(CONFIG_DAC) || defined(CONFIG_PWM)
131134
void analogWriteResolution(int bits);
135+
#endif
132136

133137
#include <variant.h>
134138

cores/arduino/zephyrCommon.cpp

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -445,9 +445,20 @@ void analogReference(uint8_t mode) {
445445
}
446446
}
447447

448+
// Note: We can not update the arduino_adc structure as it is read only...
449+
static int read_resolution = 10;
450+
451+
void analogReadResolution(int bits) {
452+
read_resolution = bits;
453+
}
454+
455+
int analogReadResolution() {
456+
return read_resolution;
457+
}
458+
448459
int analogRead(pin_size_t pinNumber) {
449460
int err;
450-
int16_t buf;
461+
uint16_t buf;
451462
struct adc_sequence seq = {.buffer = &buf, .buffer_size = sizeof(buf)};
452463
size_t idx = analog_pin_index(pinNumber);
453464

@@ -477,7 +488,17 @@ int analogRead(pin_size_t pinNumber) {
477488
return err;
478489
}
479490

480-
return buf;
491+
/*
492+
* If necessary map the return value to the
493+
* number of bits the user has asked for
494+
*/
495+
if (read_resolution == seq.resolution) {
496+
return buf;
497+
}
498+
if (read_resolution < seq.resolution) {
499+
return buf >> (seq.resolution - read_resolution);
500+
}
501+
return buf << (read_resolution - seq.resolution);
481502
}
482503

483504
#endif

0 commit comments

Comments
 (0)