-1

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.

Community
  • 1
  • 1
Rajesh
  • 1,085
  • 1
  • 12
  • 25
  • OK, got the answer: `TCCR0B = (TCCR0B & ~(1<>WGM02_IN_MODE)&0x01)< – Rajesh Jul 01 '16 at 16:25
  • Next time, use search before asking please. – 2501 Jul 01 '16 at 16:30
  • And use fixed-width types. Not for being portable (that is not possible for hardware accesses anyway), but for documentation purpose. – too honest for this site Jul 01 '16 at 16:31
  • Sorry, the link provided does not really address the same. It is generic question on setting/clearing bits. My question was copying bit from one position to another position in different variable – Rajesh Jul 01 '16 at 16:32
  • @2501 This is the more appropriate duplicate: http://stackoverflow.com/questions/11193800/c-bit-operations-copy-one-bit-from-one-byte-to-another-byte – yano Jul 01 '16 at 16:52

1 Answers1

0

Given:

#define TCCR0B_WGM02_MASK (1 << 3)
#define MODE_WGM02_MASK   (1 << 2)

then:

TCCR0B = (mode & MODE_WGM02_MASK)) == 0 ?  // If mode WGM02 bit is zero...
         TCCR0B & ~MODE_WGM02_MASK :       // clear WGM02 in TCCR0B,
         TCCR0B | MODE_WGM02_MASK ;        // otherwise set WGM02 in TCCR0B. 
Clifford
  • 88,407
  • 13
  • 85
  • 165