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
}
jose can u c
6,9742 gold badges16 silver badges27 bronze badges
asked Mar 12, 2018 at 14:01
3
  • 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? Commented Mar 12, 2018 at 15:19
  • "several clock cycles" is just an arbitrary time where the output is force either high or low. Commented Mar 12, 2018 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 Commented Mar 12, 2018 at 18:35

1 Answer 1

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().

answered Mar 12, 2018 at 18:11
2
  • to clear the bits would i set tccr2b = 0; or just the _bv(0) part? Commented Mar 13, 2018 at 14:12
  • TCCR2B &= ~(_BV(CS20)); will clear just CS20 bit and leave all else the same. Commented Mar 13, 2018 at 14:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.