Position calibration added to encoder code

Dependencies:   Encoder MODSERIAL mbed

Fork of Assignment_3_3_encoder by Casper Kroon

Committer:
CasperK
Date:
Mon Oct 01 14:27:53 2018 +0000
Revision:
0:1907291f2887
Child:
1:9330bbc04857
First try to get counts from motor encoder. Counter doesn't reset yet after 8400 counts.

Who changed what in which revision?

UserRevisionLine numberNew contents of line
CasperK 0:1907291f2887 1 #include "mbed.h"
CasperK 0:1907291f2887 2 #include "MODSERIAL.h"
CasperK 0:1907291f2887 3 #include "encoder.h" //getPosition(), setPosition(), getSpeed()
CasperK 0:1907291f2887 4
CasperK 0:1907291f2887 5 PwmOut pwmpin(D6);
CasperK 0:1907291f2887 6 PwmOut led(D10);
CasperK 0:1907291f2887 7 DigitalIn button(D2);
CasperK 0:1907291f2887 8 DigitalOut directionpin(D7);
CasperK 0:1907291f2887 9 Encoder motor1(D13,D12);
CasperK 0:1907291f2887 10 MODSERIAL pc(USBTX, USBRX);
CasperK 0:1907291f2887 11
CasperK 0:1907291f2887 12 int main()
CasperK 0:1907291f2887 13 {
CasperK 0:1907291f2887 14 int counts; //number of counts,
CasperK 0:1907291f2887 15 const int max_counts = 8400; //maximum number of counts from the X4 encoding
CasperK 0:1907291f2887 16 int motor_angle;
CasperK 0:1907291f2887 17 pc.printf("** reset **\r\n");
CasperK 0:1907291f2887 18 directionpin = 1; //turn forward
CasperK 0:1907291f2887 19 led = 1; //turn led on
CasperK 0:1907291f2887 20
CasperK 0:1907291f2887 21 /* this could be placed in the while loop
CasperK 0:1907291f2887 22 //"lompe" functions to let the counter count from 0-8400 and from -8400 to 0, could possibly be done better
CasperK 0:1907291f2887 23 if (counts > max_counts) {counts = 0;}
CasperK 0:1907291f2887 24 else if (counts < 0) {counts = max_counts;}
CasperK 0:1907291f2887 25 else if (counts < -1*max_counts) {counts = 0;}
CasperK 0:1907291f2887 26
CasperK 0:1907291f2887 27 //converting the counts to degrees
CasperK 0:1907291f2887 28 degrees_per_count = 360/max_counts;
CasperK 0:1907291f2887 29 motor_angle = counts*degrees_per_counts;
CasperK 0:1907291f2887 30 */
CasperK 0:1907291f2887 31
CasperK 0:1907291f2887 32 while (true) {
CasperK 0:1907291f2887 33 //if the button is pressed, turn of the led and turn the motor
CasperK 0:1907291f2887 34 if (button == false){
CasperK 0:1907291f2887 35 pwmpin = 0.6;
CasperK 0:1907291f2887 36 led = 0;
CasperK 0:1907291f2887 37 }
CasperK 0:1907291f2887 38 //if the button is not pressed, keep the led on and the motor off
CasperK 0:1907291f2887 39 else {
CasperK 0:1907291f2887 40 pwmpin = 0;
CasperK 0:1907291f2887 41 led = 1;
CasperK 0:1907291f2887 42 }
CasperK 0:1907291f2887 43 counts = motor1.getPosition(); //get the number of counts from the encoder. Will keep counting up/down if not reset or stopped
CasperK 0:1907291f2887 44 pc.printf("%i\r\n", counts);
CasperK 0:1907291f2887 45 wait(0.1f);
CasperK 0:1907291f2887 46 }
CasperK 0:1907291f2887 47 }