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

Fix bug in analogWrite when accessing 16 bit register #94

Merged
merged 2 commits into from
Oct 14, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 12 additions & 2 deletions cores/arduino/wiring_analog.c
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ void analogWrite(uint8_t pin, int val)
uint16_t* timer_cmp_out;
TCB_t *timer_B;

uint8_t savedSREG;

/* Find out Port and Pin to correctly handle port mux, and timer. */
switch (digital_pin_timer) {

Expand All @@ -153,7 +155,10 @@ void analogWrite(uint8_t pin, int val)
timer_cmp_out = ((uint16_t*) (&TCA0.SINGLE.CMP0BUF)) + bit_pos;

/* Configure duty cycle for correct compare channel */
(*timer_cmp_out) = (val);
savedSREG = SREG;
cli();
(*timer_cmp_out) = (val); // non-atomic 16-bit write operation
SREG = savedSREG;

/* Enable output on pin */
TCA0.SINGLE.CTRLB |= (1 << (TCA_SINGLE_CMP0EN_bp + bit_pos));
Expand All @@ -170,7 +175,12 @@ void analogWrite(uint8_t pin, int val)
timer_B = ((TCB_t *)&TCB0 + (digital_pin_timer - TIMERB0));

/* set duty cycle */
timer_B->CCMPH = val;
// (16-bit read/write operation are non-atomic and use a temporary register)
savedSREG = SREG;
cli();
timer_B->CCMPL = timer_B->CCMPL; // copy CCMPL into temporary register
timer_B->CCMPH = val; // set CCMPH value + copy temporary register content into CCMPL
SREG = savedSREG;

/* Enable Timer Output */
timer_B->CTRLB |= (TCB_CCMPEN_bm);
Expand Down