Skip to content

Instantly share code, notes, and snippets.

@PhirePhly
Created February 20, 2011 20:18
Show Gist options
  • Save PhirePhly/836262 to your computer and use it in GitHub Desktop.
Save PhirePhly/836262 to your computer and use it in GitHub Desktop.
Experiment with both CC registers for Timer A on the MSP430G2231
#include <msp430g2211.h>
#define LED_0 BIT0
#define LED_1 BIT6
#define LED_OUT P1OUT
#define LED_DIR P1DIR
unsigned int timerCount = 0;
unsigned int timerCount1 = 0;
void main(void)
{
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
LED_DIR |= (LED_0 | LED_1); // Set P1.0 and P1.6 to output direction
LED_OUT &= ~(LED_0 | LED_1) ; // Set the LEDs off
TACCTL0 = CCIE;
TACCTL1 = CCIE;
TACTL = TASSEL_2 | MC_2; // Set the timer A to SMCLCK, Continuous
// Clear the timer and enable timer interrupt
__enable_interrupt();
__bis_SR_register(LPM0 + GIE); // LPM0 with interrupts enabled
}
// Timer A0 interrupt service routine
#pragma vector=TIMERA0_VECTOR
__interrupt void Timer_A0 (void)
{
timerCount = (timerCount + 1) % 8;
if(timerCount ==0)
P1OUT ^= (LED_0);
}
// Timer A1 interrupt service routine
#pragma vector=TIMERA1_VECTOR
__interrupt void Timer_A1 (void)
{
TAIV &= ~(0x02); // CLEAR INTERRUPT
timerCount1 = (timerCount1 + 1) % 9; //4096;
if(timerCount1 ==0)
P1OUT ^= (LED_1);
}
@micro256
Copy link

micro256 commented Sep 1, 2011

Hi PhirePhly. I'm trying to understand how to use timers in micro-controllers, specifically the msp430g2231. I'm dissecting your code shown in gist 836262 and I understand a lot of it, but I have a few questions. The first one I can think relates to line 34: timerCount = (timerCount + 1) % 8.
What does the %8 have to do with the code. Why is it needed? Same applies for the "%9" in line 44. When I run the code as is, everything works, but when I delete the %8, and %9, I encounter errors. I'm still familiarizing myself with the C/C++ code, so forgive me if this question seems trivial. Thanks

@PhirePhly
Copy link
Author

The % is the modulus operator. Think of it as the remainder from dividing by that number.

So line 34 takes the modulus base 8 of (timerCount + 1), so timerCount is going to go 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, ... This is done so that line 35 is true every 8 increments, instead of every 65536 increments, which is what you tried.

I can appreciate that you might be challenged by my code. I tend to use and abuse as many symbols from the language as I can, to produce terse code. Best resource on the matter is K&R C:
http://www.amazon.com/Programming-Language-2nd-Brian-Kernighan/dp/0131103628/

@micro256
Copy link

micro256 commented Sep 4, 2011

Thanks for your reply. You explained it clearly. I now understand the purpose of the modulus operator and how it is applied in the code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment