Jump to content
Sign in to follow this  
SirPatrick

MSP430G2553 motor speed control with a potentiometer

Recommended Posts

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

}

Share this post


Link to post
Share on other sites

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 :)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×