0

I have a 62.5 kHz square wave created by timer2 on the pin 3. I would like to be able to use digitalWrite(3, HIGH) to force pin 3 high for several clock cycles, but then I would like it to return the 62.5 kHz square wave. Is there a way to reset a single output without resetting the entire program?

void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT); //Output for OCR2B (Timer 2)
  //The following block allows sets the Timer2 properties for PWM
  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS20);
  OCR2A = 255; //Sets the period to 16us (62.5kHz)
  OCR2B = 0; //Sets the duty cycle of the signal (8-bit(255) resolution)
}

void loop() {
  int pot = analogRead(A0);
  int duty = map(pot, 0, 1023, 0, 255); //scale to duty cycle resolution
  OCR2B = duty; //set duty cycle
  delay(10000); //arbitrary wait time
  digitalWrite(3, HIGH);
  delay(10000); //arbitrary wait time
  //undo the digitalWrite to continue the pulse train here
}
  • Can you show how you are currently setting up the square wave? That is, are you using a library in Arduino, or are you using the timer/counter registers directly to produce the waveform? Are the "several clock cycles" actual MCU clock cycles, or cycles of the 62.5 kHz waveform? – jose can u c Mar 12 '18 at 15:19
  • "several clock cycles" is just an arbitrary time where the output is force either high or low. – Micah Spurrell Mar 12 '18 at 16:40
  • please do not put code in comments .... somebody moved the code to your question, where it is supposed to be .... please delete the two comments – jsotola Mar 12 '18 at 18:35
1

If you clear the clock select bits in TCCR2B, then the PWM stops and you can control the port normally. To re-start the PWM, set the CS20 bit just as you did in setup().

  • to clear the bits would i set tccr2b = 0; or just the _bv(0) part? – Micah Spurrell Mar 13 '18 at 14:12
  • TCCR2B &= ~(_BV(CS20)); will clear just CS20 bit and leave all else the same. – jose can u c Mar 13 '18 at 14:20

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.