0

I'am getting a little PWM signal when my potentiometer is at zero and OCR2B always reads zero on the serial monitor. My LED has low forward voltage but I still get a little PWM on the pin when I prob it. I use timer 1 and it works good. I have a picture of the scope.

#include "RTClib.h"
RTC_DS3231 rtc;

#include <ResponsiveAnalogRead.h>
ResponsiveAnalogRead analog0(A0, true, .001);

unsigned int nowHour;

int analogOutPin3 = 3;
int sensorValueTimer2Pin3;

long z;

int analogOutPin9 = 9;
int analogOutPin10 = 10;

void setup() {
  Serial.begin(9600);
  //===============mode 5 pin 3,11==================//
  TCCR2A |= (1 << COM2A1);
  TCCR2A |= (1 << COM2B1);
  TCCR2A |= (1 << WGM21);
  TCCR2A |= (1 << WGM20);
  TCCR2B |= (1 << WGM22);
  TCCR2B |= (1 << CS22);
  OCR2A = 249;   //1KHz frequency
  TCNT2 = 0;
  //====================mode 5 pin 3,11==============//

  pinMode(3, OUTPUT);

  rtc.adjust(DateTime(2014, 1, 21, 7, 0, 0));
}

void loop() {
  DateTime now = rtc.now();
  nowHour = now.hour();
  analogWrite(9, LOW);
  analogWrite(10, LOW);
  analog0.update();
  sensorValueTimer2Pin3 = ((analog0.getValue() * 249L) / 1024);
  if (nowHour >= 7 && nowHour <= 21) {
    z = sensorValueTimer2Pin3;
    OCR2B = z;
    Serial.println(OCR2B);
  }
}

enter image description here

  • My mistake, it wasn't actually in mode 5, it was in fast PWM, I changed it to phase correct and that worked, it turns off. – northershoveler May 12 '20 at 13:07
  • "My LED has low forward voltage" - what does that have to do with PWM? Hope you're using a resistor for the led. – Sim Son May 12 '20 at 15:20
3

When analogWrite writes 0 or 255 value, it actually disables PWM output and sets the output to 0 or 1 correspondingly (maybe just one of them). That's because there is just 256 values, but with both fully off and fully on PWM you'll need 257 values to archieve it. If you're using direct access into OCRx, you have to make a choice if you want to have not fully on pwm or not fully off pwm (by setting polarity with COM2Xx)

Btw, you should clear TCCR2A/TCCR2B as all of the timers are configured by Arduino core to be running and prepared for the analogWrites...

  • Pretty sure the data sheets mention a spike when trying to attempt 0% or 100% PWM via Fast PWM mode. As per KIIV you should set the pin to High or Low for either extreme of PWM duty. – Etzeitet May 11 '20 at 22:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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