Motor control in Ticker

Dependencies:   FastPWM MODSERIAL mbed QEI

Fork of Motorcontrol by Laurence B

main.cpp

Committer:
s1680897
Date:
2018-10-08
Revision:
5:1e85f68b5580
Parent:
4:7f7974aec29d

File content as of revision 5:1e85f68b5580:

#include "mbed.h"
#include "FastPWM.h"
#include "MODSERIAL.h"
#include "QEI.h"

Ticker Motorticker;
Ticker Printticker;

FastPWM motor1_pwm(D6);
DigitalOut motor1_richting(D7);
FastPWM motor2_pwm(D5);
DigitalOut motor2_richting(D4);
QEI encoder1(D10, D11, NC, 32);
QEI encoder2(D12, D13, NC, 32);

AnalogIn pot1(A0);
AnalogIn pot2(A1);
MODSERIAL pc(USBTX, USBRX);

float AnalogVoltage1;
float AnalogVoltage2;

void Print_pot()
{
    pc.baud(115200);
    
    AnalogVoltage1 = pot1.read()*2 - 1;
    AnalogVoltage2 = pot2.read()*2 - 1;
    
    float rel_pos1=encoder1.getPulses()/32.0/131.25*2.0*3.1416;
    float rel_pos2=encoder2.getPulses()/32.0/131.25*2.0*3.1416;
    
    pc.printf("pot1 = %f \t pot2 = %f \t Position 1 = %f \t Position 2 = %f \r\n", AnalogVoltage1, AnalogVoltage2, rel_pos1, rel_pos2);
}

void Motor_control()
{        
        AnalogVoltage1 = pot1.read()*2 - 1;
        AnalogVoltage2 = pot2.read()*2 - 1;
        
        //Motor1
        
        if (AnalogVoltage1 <= 0) 
        {
            motor1_richting = 0;
            motor1_pwm.write(-AnalogVoltage1); //write Duty cycle 
        }
        
        if (AnalogVoltage1 >= 0) 
        {
            motor1_richting = 1;
            motor1_pwm.write(AnalogVoltage1); //write Duty cycle 
        }
            
        //Motor 2
            
        if (AnalogVoltage2 <= 0) 
        {
            motor2_richting = 0;
            motor2_pwm.write(-AnalogVoltage2); //write Duty cycle 
        }
        if (AnalogVoltage2 >= 0) 
        {
            motor2_richting = 1;
            motor2_pwm.write(AnalogVoltage2); //write Duty cycle 
        }
}

int main()
{
    int frequency_pwm = 16700; //16.7 kHz PWM
        
    Motorticker.attach(Motor_control,0.1); 
    Printticker.attach(Print_pot, 0.5);
    motor1_pwm.period(1.0/frequency_pwm); // T = 1/f
    
    while(true)
    {}
}