DCS_TEAM / Mbed 2 deprecated Chemical_Sensor_DMA

Dependencies:   mbed

Dependents:   DCS_FINAL_CODE

Fork of Chemical_Sensor_DMA by Jared Baxter

Sample/quad.cpp

Committer:
baxterja
Date:
2015-10-29
Revision:
2:3771b3195c7b

File content as of revision 2:3771b3195c7b:

#include "quad.h"

void quad_init() {
    
    // Enable clock for FTM2
    SIM_SCGC3 |= SIM_SCGC3_FTM2_MASK; // there are two of them for some reason
    SIM_SCGC6 |= SIM_SCGC6_FTM2_MASK; // 
    
    // Enable clock for PortB
    SIM_SCGC5 |= SIM_SCGC5_PORTB_MASK;
    
    //enable the counter
    FTM2_MODE |= FTM_MODE_WPDIS_MASK; // unlock write protection on certain FTM bits and registers
    FTM2_MODE |= FTM_MODE_FTMEN_MASK; 
    
    //enable the counter to run in the BDM mode
    FTM2_CONF |= FTM_CONF_BDMMODE(3);
    
    //load the Modulo register and counter initial value
    FTM2_MOD = 4095;
    FTM2_CNTIN = 0;
    
    //configuring FTM for quadrature mode
    FTM2_QDCTRL = 0;
    FTM2_QDCTRL |= FTM_QDCTRL_QUADEN_MASK; // enable Quadrature decoding
    FTM2_QDCTRL &= ~FTM_QDCTRL_QUADMODE_MASK; // select phase A and phase B decoding mode (this is what the angle encoder uses)
    FTM2_QDCTRL |= FTM_QDCTRL_PHAPOL_MASK; // change direction of counting by changing the phase of input A (for some reason QUADIR wouldn't work)
    
    
    // start the timer clock, source is the external clock
    FTM2_SC |= FTM_SC_CLKS(3);
    
    //configuring the input pins:
    PORTB_PCR18 = PORT_PCR_MUX(6); // FTM2_QD_PHA  (PTB18) ALT6
    PORTB_PCR19 = PORT_PCR_MUX(6); // FTM2_QD_PHB  (PTB19) ALT6
    
    // Enable write protection
    FTM2_MODE |= FTM_MODE_WPDIS_MASK; // Lock write protection on certain FTM bits and registers
    
}   
 
int32_t quad_read() {
    int angle = FTM2_CNT;
    if(angle > 2048) angle -= 4096;
    return angle;  // this is the register with the counter in it.
}

void quad_update(int value) {
    if(value < 0) value = value + 4096; // convert back to raw form (both absolute angle and relative angle are actually integers between 0-4095)
    FTM2_CNTIN = value; // change reset value to desired value
    FTM2_CNT = 0; // writing anything to FTM_CNT loads FTM2_CNTIN into FTM_CNT;
    FTM2_CNTIN = 0; // change reset value back to 0
}

void quad_invert(){
    FTM2_QDCTRL &= ~FTM_QDCTRL_PHAPOL_MASK; // change direction of counting by changing the phase of input A
}