0
void setup() { pinMode(9, OUTPUT); pinMode(10, OUTPUT); TCCR2A = TCCR2A & B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A TCCR2B = TCCR2B & B11110000 | B00000001;//Prescaller set TCNT2=0;//Start Counting ffrom 0 OCR2A=127;//Set TOP value) } void loop() { } 
1
  • 3
    It may not be strictly necessary, but it would probably good to say what you're seeing instead of the expected signal. Commented Oct 28, 2021 at 12:26

1 Answer 1

4
TCCR2A = TCCR2A & B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A 

What you have here clears TCCR2A's COM2A1 but preserves its original COM2A0.

When I print out TCCR2A prior to modification, I see a value of 0x01 (COM2A is 0; both bits of it).

Printing out TCCR2A after you've manipulated it 0x02. So, in TCCR2A, you are winding up with zeros for your COM2A1 and COM2A0 bits, which is all cases is "Normal port operation; OC2A disconnected". That is, you're not going to see whatever signal you might otherwise have configured to generate because it just hasn't been routed to the (Arduino pin 10)/(gpio PB4)/OC2A

It's usually better to not rely on the bootloader and the start code and the Arduino core to have left a hardware register in a particular state.

The following is probably closer to what you intended:

TCCR2A = B01010000 | B00000010 ; // CTC mode activated, Toggle OC2A 

It's still not entirely correct to the problem description (not the correct frequency), but it does send a signal out of the Arduino MEGA's digital pin 10. It also is configured to toggle OC2B, so unless you wanted that:

TCCR2A = B01000000 | B00000010 ; // CTC mode activated, Toggle OC2A 

This can be made more readable by using the bit field names for the given:

TCCR2A = (1 << COM2A0) // CTC mode activated (note COM2A1 is zero) | (2 << WGM20); // lower two bits of WGM value 2 

You can do this same sort of thing for TCCR2B. And likewise, it is best that you don't rely on the previous value of TCCR2B.

With OCR2A = 127;, you are toggling (reaching a half-period) every 128/16,000,000 seconds, or a 8 uS half-period, for a 16 uS period. Generating 62.5 KHz, which is below your target 150 KHz. Knowing it's half-periods, an OCR2A of 63 gets you to 125 KHz.

An OCR2A of 52 or less gets you into the greater than 150 kHz range, at least if we take your 16 MHz clock rate very seriously. You might need to be a little lower to be sure.

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.