Skip to content

Commit

Permalink
Fix bug in analogWrite when accessing 16 bit register (#94)
Browse files Browse the repository at this point in the history
Fix bug in analogWrite when accessing 16 bit register
  • Loading branch information
landret authored Oct 14, 2021
1 parent 5256fdc commit c31614b
Showing 1 changed file with 12 additions and 2 deletions.
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

0 comments on commit c31614b

Please sign in to comment.