Afgesplitste versie van motor control waarbij we ook iets met EMG gaan doen

Dependencies:   mbed QEI HIDScope biquadFilter MODSERIAL FastPWM

main.cpp

Committer:
Jellehierck
Date:
2019-10-04
Revision:
4:28d71b0a29aa
Parent:
3:2d45e3d0b0f0
Child:
5:54ce02ad7a50

File content as of revision 4:28d71b0a29aa:

#include "mbed.h"
//#include "HIDScope.h"
#include "QEI.h"
#include "MODSERIAL.h"
//#include "BiQuad.h"
#include "FastPWM.h"

DigitalOut ledr(LED_RED);
DigitalOut ledg(LED_GREEN);
DigitalOut ledb(LED_BLUE);
PwmOut led1(D10);
DigitalIn button1(D11);
AnalogIn potmeter(A0);
DigitalIn sw(SW2);
MODSERIAL pc(USBTX, USBRX);
DigitalIn encA(D13);
DigitalIn encB(D12);
QEI encoder(D13,D12,NC,64,QEI::X4_ENCODING);

DigitalOut motor2Direction(D4);
FastPWM motor2Power(D5);
DigitalOut motor1Direction(D7);
FastPWM motor1Power(D6);

Ticker motorTicker;
Ticker encoderTicker;

const float maxVelocity = 7.958701; // 76 RPM to rad/s
const float PWM_period = 1e-6;

volatile int counts; // Encoder counts
volatile int countsPrev = 0;
volatile int deltaCounts;

float factorin = 6.23185/64; // Convert encoder counts to angle in rad
float gearratio = 131.25; // Gear ratio of gearbox

float getRefVelocity()
{
    float refVelocity;

    if (button1) {
        refVelocity = potmeter.read() * maxVelocity;
    } else {
        refVelocity = potmeter.read() * maxVelocity * -1;
    }
    return refVelocity;
}

void motorControl()
{
    float potValue = potmeter.read();
    motor1Power.pulsewidth(potValue * PWM_period);
}

void readEncoder()
{
    counts = encoder.getPulses();
    deltaCounts = counts - countsPrev;

    countsPrev = counts;
}

int main()
{
    pc.baud(115200);
    pc.printf("\r\nStarting...\r\n\r\n");

    motor1Power.period(PWM_period);

    motorTicker.attach(motorControl, 0.01);
    
    float T_encoder = 0.1;
    encoderTicker.attach(readEncoder, T_encoder);

    motor1Direction = 0;

    while (true) {

        float potValue = potmeter.read(); // Read potmeter
        
        float angle = counts * factorin / gearratio; // Angle of motor shaft in rad
        float omega = deltaCounts / T_encoder * factorin / gearratio; // Angular velocity of motor shaft in rad/s
        
        pc.printf("Potmeter: %f \r\n", potValue);
        pc.printf("Counts: %i   DeltaCounts: %i\r\n", counts, deltaCounts);
        pc.printf("Angle:  %f   Omega:       %f\r\n", angle, omega);
        
        wait(0.5);
    }
}