Basic DC motor control test, rpm feedback by simple impulse signal, PID speed control.
Dependencies: FastPWM mbed FastIO MODSERIAL
Diff: main.cpp
- Revision:
- 4:7cb8986200a7
- Parent:
- 3:f6c30ada5370
- Child:
- 5:ec4d6e435822
diff -r f6c30ada5370 -r 7cb8986200a7 main.cpp --- a/main.cpp Fri Mar 23 12:35:12 2018 +0000 +++ b/main.cpp Mon Mar 26 13:00:32 2018 +0000 @@ -2,41 +2,92 @@ #include "FastPWM.h" #include "FastIO.h" +#define MODSERIAL_DEFAULT_RX_BUFFER_SIZE 16 +#define MODSERIAL_DEFAULT_TX_BUFFER_SIZE 64 +#include "MODSERIAL.h" + +static const PinName IMPULSE_SENSOR_PIN = PinName(10); + FastPWM mypwm(PWM_OUT); +FastIn<IMPULSE_SENSOR_PIN> pinImpulseSensorIn; DigitalOut myled(LED1); +Timer myTimer; + //------------------------------------ // Hyperterminal configuration // 9600 bauds, 8-bit data, no parity //------------------------------------ -Serial pcLink(SERIAL_TX, SERIAL_RX); +MODSERIAL pcLink(SERIAL_TX, SERIAL_RX); + +static const us_timestamp_t periodImpSens = 100000UL; +static const us_timestamp_t periodLEDBlink = 1000000UL; +static const us_timestamp_t periodPWMWrite = 10000000UL; + +static us_timestamp_t tStampImpSens = 0UL; +static us_timestamp_t tStampLEDBlink = 0UL; +static us_timestamp_t tStampPWMWrite = 0UL; + +static unsigned int uiImpSens = 0U; int main() { + unsigned int uiImpSensTemp = 0U; + int iImpSensLastState = 0; + + pcLink.baud(115200); + pcLink.format(8, SerialBase::None, 1); + mypwm.period_us(100); mypwm.write(0.0); - pcLink.printf("pwm set to %.2f %%\n", mypwm.read() * 100); - + myTimer.start(); + while(1) { - int iCnt = 0; double dPwmDuty = 0.0; - mypwm.write(dPwmDuty); - pcLink.printf("pwm set to %.2f %%\n", mypwm.read() * 100); + us_timestamp_t tStamp; + + tStamp = myTimer.read_high_resolution_us(); + + if (periodLEDBlink < (tStamp - tStampLEDBlink)) + { + tStampLEDBlink = tStamp; + + myled = !myled; + } + + if (periodImpSens < (tStamp - tStampImpSens)) + { + tStampImpSens = tStamp; - if (10 < iCnt++) { - iCnt = 0; + uiImpSens = uiImpSensTemp; + uiImpSensTemp = 0U; - dPwmDuty += 0.1; + pcLink.printf("IMP: %u imp.\n", uiImpSens); + } - if (1.0 < dPwmDuty) { + if (periodPWMWrite < (tStamp - tStampPWMWrite)) + { + tStampPWMWrite = tStamp; + + mypwm.write(dPwmDuty); + pcLink.printf("PWM: %.2f %%\n", mypwm.read() * 100); + + dPwmDuty += 0.1; + + if (1.0 < dPwmDuty) + { dPwmDuty = 0.0; } } - - myled = !myled; - - wait(1); + + // Impulse sensor + int iTemp = pinImpulseSensorIn.read(); + if (iTemp != iImpSensLastState) + { + iImpSensLastState = iTemp; + uiImpSensTemp++; + } } }