NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Setting register bits back to 0

November 11, 2010
by carlhako
carlhako's Avatar

Quick question about settings the bits.

I know this bit of code works

TCCR0B |= (1<<CS01) | (1<<CS00);

Im not too sure how its setting 2 bits in 1 go using a or statment?

My reason for the question is I have the following bit of code to turn the clock off and im not sure if it will work.

if (timer0_disable) TCCR0B &= ~(1<<CS01) | ~(1<<CS00);
if (!timer0_disable) TCCR0B |= (1<<CS01) | (1<<CS00);

Since im flipping the bits i am not sure if a | is correct. Ive googled a few c if guides and gone through the forums but cant find this explained.


November 11, 2010
by carlhako
carlhako's Avatar

Ok I think i figured this one out, after going over bitwise again.


A = 00001010 B = 1 C = 1

A &= ~((B<<3) | (C<1));

will be this 00001010 and 11110101

= 00000000

I think im right. My original command will work.

November 11, 2010
by bretm
bretm's Avatar

That's right. The previous post wouldn't work because it's missing some parenthesis:

if (timer0_disable) TCCR0B &= ~(1<<CS01) | ~(1<<CS00);

~(1<<CS01) is 11111101

~(1<<CS00) is 11111110

OR them together and you get 11111111

AND that with TCCR0B and nothing will happen

You need

if (timer0_disable) TCCR0B &= ~((1<<CS01) | ~(1<<CS00));
January 15, 2011
by carlhako
carlhako's Avatar

I am working on a new project where I am setting 2 pins back to low, I easily forget stuff so I have had to re go over this.

Im pretty sure that last command is incorrect. Was probably just overlooked.

 if (timer0_disable) TCCR0B &= ~((1<<CS01) | ~(1<<CS00));

should be

 if (timer0_disable) TCCR0B &= ~((1<<CS01) | (1<<CS00));

if you use the first command

(1<<CS01) = 00000010 ~(1<<CS00) = 11111110 or that you get 11111111

need to get rid of the ~ within the parenthesis

(1<<CS01) = 00000010 (1<<CS00) = 00000001 or that you get 00000011 flip those bits around with a ~ then &= it on the register to just set those bits to 0.

I ended up finding an easier way to alternate something between on/off. Every time this bit of code executes the bit is flipped.

 TCCR1B ^= (1<<CS11);

Post a Reply

Please log in to post a reply.

Did you know that any circuit of voltage sources and resistors can be simplified to a "Thevenin" equivalent circuit? Learn more...