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– jose can u c2018年03月12日 15:19:55 +00:00Commented Mar 12, 2018 at 15:19
-
"several clock cycles" is just an arbitrary time where the output is force either high or low.Micah Spurrell– Micah Spurrell2018年03月12日 16:40:55 +00:00Commented 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 commentsjsotola– jsotola2018年03月12日 18:35:06 +00:00Commented Mar 12, 2018 at 18:35
1 Answer 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– Micah Spurrell2018年03月13日 14:12:10 +00:00Commented Mar 13, 2018 at 14:12
-
TCCR2B &= ~(_BV(CS20));
will clear just CS20 bit and leave all else the same.jose can u c– jose can u c2018年03月13日 14:20:32 +00:00Commented Mar 13, 2018 at 14:20