Motor control

Dependencies:   mbed QEI HIDScope biquadFilter MODSERIAL FastPWM

Revision:
0:e4858e2df9c7
Child:
1:08e8cc33fcae
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Fri Oct 11 09:40:16 2019 +0000
@@ -0,0 +1,78 @@
+#include "mbed.h"
+//#include "HIDScope.h"
+#include "QEI.h"
+#include "MODSERIAL.h"
+//#include "BiQuad.h"
+#include "FastPWM.h"
+
+// Button and potmeter control
+InterruptIn button1(D11);
+InterruptIn button2(D10);
+AnalogIn potmeter(A0);
+
+// Encoder
+DigitalIn encA(D13);
+DigitalIn encB(D12);
+QEI encoder(D13,D12,NC,64,QEI::X4_ENCODING);
+
+// Motor
+DigitalOut motor2Direction(D4);
+FastPWM motor2Power(D5);
+DigitalOut motor1Direction(D7);
+FastPWM motor1Power(D6);
+
+//Motorcontrol
+bool motordir;
+double motorpwm;
+double u;
+double potValue;
+
+// PC connection
+MODSERIAL pc(USBTX, USBRX);
+
+// Intializing tickers
+Ticker motorTicker;
+Ticker controlTicker;
+Ticker directionTicker;
+
+const float PWM_period = 1e-6;
+
+volatile int counts; // Encoder counts
+volatile int countsPrev = 0;
+volatile int deltaCounts;
+
+// motor1Direction = 1;
+volatile int motor1Toggle = 1;
+
+float factorin = 6.23185/64; // Convert encoder counts to angle in rad
+float gearratio = 131.25; // Gear ratio of gearbox
+
+void motorControl()
+{
+    potValue= potmeter.read();
+    u= (potValue*2)-1;
+    motorpwm= abs(u);
+    if (u<0){
+        motordir= 0;}
+    else {
+         motordir= 1;}
+    motor1Power.pulsewidth(motorpwm * PWM_period * motor1Toggle);
+    motor1Direction= motordir;
+}
+
+
+int main()
+{
+    pc.baud(115200);
+    pc.printf("\r\nStarting...\r\n\r\n");
+    
+    motor1Power.period(PWM_period);
+    motorTicker.attach(motorControl, 0.01);
+    
+    while (true) {
+        float potValue = potmeter.read(); // Read potmeter
+
+        pc.printf("Potmeter: %f \r\n", potValue);
+        wait(0.5);
+    }
+}