RTES / Mbed 2 deprecated mbed_pwmLib

Dependencies:   mbed

main.cpp

Committer:
jiteshg
Date:
2015-10-09
Revision:
3:66a52943c525
Parent:
2:bf817b299c19
Child:
4:acb62dee5ba9

File content as of revision 3:66a52943c525:

/*
Using pwm to run a servo motor
Connect the red wire of the servo motor to 3.3V and not 5V

DC motor pins - p5 and p6 to control the direction of the motor
                p23 to control the duty cycle and period                
*/
#include "mbed.h"
PwmOut pwm1(p21);       //Servo Motor-1 PWM channel
PwmOut pwm2(p22);       //Servo Motor-2 PWM channel

DigitalOut dc1(p5);     //DC motor input-1
DigitalOut dc2(p6);     //DC motor input-2
PwmOut pwm3(p23);       //DC motor PWM channel

AnalogIn button(p15);   //Analog input from the floor buttons

Serial pc(USBTX, USBRX);

void openGate();
void closeGate();
int getState(float adc_val);

int currentState = 1;

int main() {
    //Setting dc1 to high and dc2 to low initially
    dc1 = 1;
    dc2 = 0;
    pwm3.period_ms(20);
    pwm3.write(0);
    
    //Setting the period and duty cycle for Servo motors
    pwm1.period_ms(20);
    pwm2.period_ms(20);
    pwm1.write(0);
    pwm2.write(0);
    
    while(1){
        //char c = pc.getc();
        //int val = c - 48;
        float adc_val = button.read();
        int val = getState(adc_val);
        //pc.printf("Floor-%d\n",val);
        //wait(1);
        if(val==currentState){
            pwm3.write(0);
        }
        else if(val > currentState){
            //Move Up
            dc1 = 1;
            dc2 = 0;
            pwm3.write(0.1);
            wait(2);
            pwm3.write(0);
        }else{
            //Move Down
            dc1 = 0;
            dc2 = 1;
            pwm3.write(0.1);
            wait(2);
            pwm3.write(0);
        }
        currentState = val;
        //openGate();
        //closeGate();
    }
}

void openGate(){
    pwm1.write(0.0375); // 3.75% duty cycle - Open the gate
    pwm2.write(0.1125); // 11.25% duty cycle - Open the gate
    wait(2);            // 2 sec delay
    pwm1.write(0);      // Stop
    pwm2.write(0);      // Stop
    wait(2);  
}

void closeGate(){
    pwm1.write(0.1125); // 11.25% duty cycle - Close the gate
    pwm2.write(0.0375); // 3.75% duty cycle - Close the gate
    wait(2);            // 2 sec delay
    pwm1.write(0);      // Stop
    pwm2.write(0);      // Stop  
    wait(2);
}

int getState(float adc_val){
    int state = 0;
    if(adc_val > 0.15 && adc_val < 0.25){
        state = 1;
    }
    else if(adc_val > 0.35 && adc_val < 0.45){
        state = 2;
    }
    else if(adc_val > 0.55 && adc_val < 0.65){
        state = 3;
    }
    else if(adc_val > 0.75 && adc_val < 0.85){
        state = 4;
    }
    else if(adc_val > 0.95 && adc_val < 1.05){
        state = 5;
    }
    return state;           
}