I want to set or clear the bit number 3 in a register named TCCR0B depending on the value of the bit number 2 in a variable named ‘mode’. If bit 2 is high in mode, bit 3 in TCCR0B has to be set without disturbing other bits. In case bit 2 in mode is low, I want to clear bit 3 in TCCR0B. Basically I want to copy one bit to other bit. I thought it is going to be simple, but now I feel we need conditional statement to do this. I am not sure if I am making this code complex. Is there any easy method to achieve this? I wrote below code to test this.
#define WGM02 3
#define WGM02_IN_MODE 2
int main (void)
{
unsigned int TCCR0B;
unsigned int mode;
while(1)
{
printf("enter the TCCRB\n");
fflush(stdin);
scanf("%X",&TCCR0B);
printf("TCCRB = %x\n",TCCR0B);
fflush(stdin);
printf("enter the mode\n");
scanf("%X",&mode);
mode=((mode>>WGM02_IN_MODE)&0x01);
if(mode)
{
TCCR0B = (TCCR0B & ~(1<<WGM02)) | (mode<<WGM02);
}
else
{
TCCR0B = (TCCR0B & ~(1<<WGM02)) & ~(mode<<WGM02);
}
printf("TCCRB = %x\n",TCCR0B);
}
}
Edit: I looked at the post in How do you set, clear, and toggle a single bit?. But it is related to setting clearing etc of individual bits and not copy from one to another.