SirPatrick 35 Posted October 23, 2012 Share Posted October 23, 2012 This code just controls the speed of a small 3V DC motor on P1.2. The speed is controlled by a potentiometer on P1.1. Feel free to suggest improvements as I am new to the MSP430. #include #define motorPin BIT2 #define analogInPin INCH_1 void initADC(); void stopWDT(); void initTimerA(); long map(long x, long in_min, long in_max, long out_min, long out_max); int analogRead(unsigned int pin); void main(void) { volatile unsigned int potentiometerValue; stopWDT(); initTimerA(); initADC(); for (; { potentiometerValue = map(analogRead(analogInPin),0,1023,0,1000); CCR1 = potentiometerValue; // CCR1 PWM duty cycle set by potentiometer } } long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } int analogRead(unsigned int pin) { ADC10CTL1 = ADC10SSEL_2 + pin; ADC10CTL0 |= ENC + ADC10SC; for(; { if ((ADC10CTL1 ^ ADC10BUSY) & ((ADC10CTL0 & ADC10IFG)==ADC10IFG)) { ADC10CTL0 &= ~(ADC10IFG +ENC); break; } } return ADC10MEM; } void initADC() { ADC10CTL0 = ADC10ON + ADC10SHT_0 + SREF_0; } void stopWDT() { WDTCTL = WDTPW + WDTHOLD; } void initTimerA() { P1DIR |= motorPin; // PWM out on P1.2 P1SEL |= motorPin; CCR0 = 1000-1; // Setting PWM period CCTL1 = OUTMOD_7; // CCR1 reset/set TACTL = TASSEL_2 + MC_1; // SMCLK configured for up mode } Goodfellarich and jsolarski-backup 2 Quote Link to post Share on other sites
jsolarski-backup 22 Posted October 24, 2012 Share Posted October 24, 2012 I would improve it by having the ADC just transfer the data to the variable automatically. so when the Timer ISR happens you can run your map function and change the pwm with out any real cpu usage outside of the isr. But otherwise I like your code, Simple and short and works Quote Link to post Share on other sites
jpnorair 340 Posted November 10, 2012 Share Posted November 10, 2012 Why are you passing longs in a system where the hardware has 16 bit registers? That is, CCR1 is 16 bits. Quote Link to post Share on other sites
SirPatrick 35 Posted November 10, 2012 Author Share Posted November 10, 2012 Oversight and neglecting to use standard definitions in stdint.h. I am new to this. Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.