I am getting up-to-speed on the TI MSP430. I am attempting to write code in C to access the built-in comparator on MSP430G2553. I've got a simple program for the comparator but I must be doing something wrong and I'm hoping someone can spot my error.
For my setup I have a potentiometer across Vcc and Gnd with the wiper arm going to P1.1. The comparator is configured to use the internal Vcc/2 reference. My MSP430 is in the TI Launchpad board and I'm trying to drive the red and green LEDs there based on the state of the comparator. If the comparator output is low I want the green LED on and the red LED off; vice-versa if the comparator output is high. I also configured P1.7 to show the contents of the CAOUT register. My code is here:
#include <msp430.h>
#include <msp430g2553.h>
/* This program is for the Launchpad MSP430 development board.
* There is a potentiometer connected from Vcc to Gnd with the
* wiper arm going to CA1 (P1.1). When the wiper voltage is
* below the threshold the green LED should be lit. When it
* exceeds the threshold the red LED should be lit.
*
* For this setup Vcc = 3.53 V
* reference = Vcc/2 = 1.77 V
* Vin = 1.76 V and higher: green LED on?
* Vin = 1.70 V and lower: red LED on?
*
*/
#define GREEN BIT0
#define RED BIT6
#define SWITCH BIT3
int main(void) {
WDTCTL = WDTPW + WDTHOLD; // disable watchdog
P1DIR = GREEN + RED + BIT7; // P1.0 and P1.6 and P1.7 are outputs
CACTL2 = P2CA4; // P1.1 = +comp
CACTL1 = CARSEL + CAREF_2 + CAON; // -comp = 0.5*Vcc; comparator on
P1SEL = BIT7; // P1.7 updates based on CAOUT
unsigned int led_mask = 0;
while(1){
led_mask = P1OUT;
if (CACTL2 & 0x01) {
led_mask &= ~GREEN; // green LED off
led_mask |= RED; // red LED on
} else {
led_mask &= ~RED; // red LED off
led_mask |= GREEN; // green LED on
}
P1OUT = led_mask;
}
}
It compiles and uploads fine but it doesn't behave the way that I intended. When I provide an input voltage of 2 volts I exceed the threshold and CAOUT goes high (verified on P1.7) as expected. However my code is turning on LEDs as though CAOUT were low. Also, if I provide an input voltage of 1.4 volts I'm below the threshold and CAOUT is low (verified on P1.7) as expected. But my code is turning on LEDs as though CAOUT were high.
Why am I not getting the expected results?