Author Topic: understanding bit shifting  (Read 386 times)

0 Members and 1 Guest are viewing this topic.

Offline khatusTopic starter

  • Regular Contributor
  • *
  • Posts: 146
  • Country: gl
understanding bit shifting
« on: April 07, 2020, 08:27:23 pm »
https://www.best-microcontroller-projects.com/pwm-pic.html


Controlling the PIC PWM output
The PIC microcontrollers are very easy to use with PWM as they have built in PWM generators - all you do is set up the relevant control registers

Code: [Select]
// Timer 2 PIC PWM
PR2=199; // 4 MHz clock -> 5kHz PWM frequency
T2CON = (1<<TMR2ON);

// Initialize Control PIC PWM
CCPR1L = 30; // Initial Duty
CCP1CON = 0x0f; // PWM mode set and 5,4 duty = 0

...and then control the duty cycle:

CCPR1L = j;

Note that the above control only controls the upper 8 bits of the 10 bit PWM module (the other two bits are in a CCP1CON).

Here how does T2CON = (1<<TMR2ON); works??




 

Offline Siwastaja

  • Super Contributor
  • ***
  • Posts: 8180
  • Country: fi
Re: understanding bit shifting
« Reply #1 on: April 07, 2020, 08:49:50 pm »
TMR2ON is #defined elsewhere (likely in some .h file provided by Microchip), and hopefully equals to 2. This means, the compiler preprocessor replaces TMR2ON with 2.

(1<<2) means that value 1 is shifted left by two places:
0000 0001
->
0000 0010
->
0000 0100
 

Offline admiralk

  • Regular Contributor
  • *
  • Posts: 178
  • Country: us
Re: understanding bit shifting
« Reply #2 on: April 07, 2020, 09:23:43 pm »
It is not a very good idea to use equality (=) to do that as it could also change all the other bits, if they are not already 0. If you are only wanting to change one bit, you should or (|=) the value. So
Code: [Select]
T2CON |= (1 << TMR2ON);is the proper way to do it. That way you only set the TMR2ON bit and leave the rest unchanged.
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf