-1

I have to use PWM to control some lights. I do this successfully with: analogWrite(11, 127); for a 50% PWM pulse on pin 11.

Now, i also have to have tone() support on my code. When I do: tone(10, melodyArray[thisNote], noteDuration); I invoke the tone() function on pin 10.

When I do so, then PWM pulse is corrupted. Since I do not have an oscilloscope, I cannot exactly understand what happens. But from the effects on the lights, I can speculate that the PWM pin (pin 11) is always HIGH or always LOW.

It is obvious that the PWM pin and the tone() pin are different.

Why does this happen? Perhaps the tone() uses some timers that interfere with the PWM? When I comment out the tone() line, the PWM works as intended.

Is there a solution to this? Can I use the tone() function and still have PWM support (on another pin)?

1 Answer 1

4

To quote from the Arduino documentation of tone():

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

So yes, you should use a different pin than 3 or 11 for analogWrite(). This is because tone() will configure the hardware Timer2 for outputting these timed signals via hardware. PWM on these pins is also tied to Timer2. When both functions are trying to configure Timer2 in a different way, there will be conflicts.

Note: The documentation talks about "boards other than the Mega", which was true when there weren't other Arduino boards than the old Uno/Nano/Mini (based on the Atmega328p). Nowadays there are so much boards, which all can be programmed with the Arduino framework, that this sentence is a real stretch. Instead I would say "on boards based on the Atmega328p". Depending on your used board your mileage may very. Check the microcontrollers datasheet for the hardware Timers it has and their connected pins.

3
  • "on boards other than Mega". looks like it was written long time ago when every Arduino had a classic ATmega MCU
    – Juraj
    Commented Apr 16, 2023 at 9:29
  • @Juraj Yes, very much. Though Uno/Nano is still used widely. I will add a sentence to comment on that
    – chrisl
    Commented Apr 16, 2023 at 9:32
  • Thank you so much! Embarrassingly, I spent months being stuck on this... Commented Apr 17, 2023 at 23:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.