Arduino version 2

Dependencies:   mbed arduino

arduino2.cpp

Committer:
ea78anana
Date:
2021-11-02
Revision:
1:4df9f94facd5
Parent:
0:c9022327ece6
Child:
2:46365fee3503

File content as of revision 1:4df9f94facd5:

#include "mbed.h"
#include "arduino.h"

#define PinA A1 //A phase
#define PinZ A3 //Z phase
#define PinB A2 //B phase

#define HIGH 1
#define LOW 0

//Initialize Variable
unsigned long time1 = 0; // Time
float time_cw;
float time_ccw;
int counter = 0;
const float d = 0.06; //Radius of the wheel
const float pi = 3.141592654;//PI
int num = 0;//number of turns
double t;//time per turn
float velocity;
double time3;//Time of phase Z detected, use for calculate the velocity
Timer f;

DigitalIn a11(PinA);
DigitalIn a12(PinB);
InterruptIn a14(PinA);
InterruptIn a13(PinZ);

Serial pc(USBTX, USBRX);

void Encode()
{

    //Ignore noise pulses
    
    //When the two reading is bigger than 5ms then count it as correct pulse
    //uint32_t m = f.read_ms();
    
    //if ((m - time1) > 5)

    {

        //When Phase A is falling will be detected 
        
        if ((a11 == LOW) && (a12 == HIGH))
        
        {   pc.printf("backward ");
        
            counter--;
        
        }
        
             else
        
        {    pc.printf("fordward ");
        
              counter++;
        
        }
    
    }
    
    //time1 = m;
    
}

void setup(){
    a11.mode(PullUp);
    a12.mode(PullUp);
    a13.fall(&Encode);
    //a14.rise(&Encode);
    //a14.fall(&Encode);
}

void Set_state(){
    counter = 0;
    uint32_t p = f.read_ms();
    time3 = p;//Time when Z phase detected
}

void loop()

{
    double  distance;
    //clockwise turning
    uint32_t n = f.read_ms();
    if (counter == 25)
    {
//      Printf("ok");//Testing
      num = num + 25;
      Set_state();
      t = n- time3;
      t = t / 1000;
      distance = num * d * pi; 
      velocity = d * pi / t;
      pc.printf("The wheel has run ");pc.printf("%f", distance); pc.printf("m.");
      pc.printf("The cw_speed is ");pc.printf("%f", velocity); pc.printf("m/s.");
      pc.printf("The time is ");pc.printf("%f", t); pc.printf("s.");
    }
    //anti-clockwise turning
    else if (counter == -25)
    {
//      Printf("ok");//Testing
      num = num + 25;
      Set_state();
      t = n - time3;
      t = t / 1000;
      distance = num * d * pi; 
      velocity = d * pi / t;
      pc.printf("The wheel has run ");pc.printf("%f", distance); pc.printf("m.");
      pc.printf("The cw_speed is ");pc.printf("%f", velocity); pc.printf("m/s.");
      pc.printf("The time is ");pc.printf("%f", t); pc.printf("s.");
    }
    //pc.printf("%d \n",counter);
}



int main(void){
    setup();
    pc.printf("start");
    f.start();
    while(1){
        loop();
    }
}