![](/media/cache/img/default_profile.jpg.50x50_q85.jpg)
Demo program to read ABZ Quadrature Encoder in Hardware on the Nucleo F401RE
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 00003 // Hardware Quadrature Encoder ABZ for Nucleo F401RE 00004 // Output on debug port to host PC @ 9600 baud 00005 // 00006 // By Nigel Webb, November 2014 00007 00008 /* Connections 00009 PA_0 = Encoder A 00010 PA_1 = Encoder B 00011 PA_4 = Encoder Z 00012 */ 00013 00014 InterruptIn ZPulse(PA_4) ; // Setup Interrupt for Z Pulse 00015 00016 void EncoderInitialise(void) { 00017 // configure GPIO PA0 & PA1 as inputs for Encoder 00018 RCC->AHB1ENR |= 0x00000001; // Enable clock for GPIOA 00019 00020 GPIOA->MODER |= GPIO_MODER_MODER0_1 | GPIO_MODER_MODER1_1 ; //PA0 & PA1 as Alternate Function /*!< GPIO port mode register, Address offset: 0x00 */ 00021 GPIOA->OTYPER |= GPIO_OTYPER_OT_0 | GPIO_OTYPER_OT_1 ; //PA0 & PA1 as Inputs /*!< GPIO port output type register, Address offset: 0x04 */ 00022 GPIOA->OSPEEDR |= GPIO_OSPEEDER_OSPEEDR0 | GPIO_OSPEEDER_OSPEEDR1 ; // Low speed /*!< GPIO port output speed register, Address offset: 0x08 */ 00023 GPIOA->PUPDR |= GPIO_PUPDR_PUPDR0_1 | GPIO_PUPDR_PUPDR1_1 ; // Pull Down /*!< GPIO port pull-up/pull-down register, Address offset: 0x0C */ 00024 GPIOA->AFR[0] |= 0x00000011 ; // AF01 for PA0 & PA1 /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ 00025 GPIOA->AFR[1] |= 0x00000000 ; // /*!< GPIO alternate function registers, Address offset: 0x20-0x24 */ 00026 00027 // configure TIM2 as Encoder input 00028 RCC->APB1ENR |= 0x00000001; // Enable clock for TIM2 00029 00030 TIM2->CR1 = 0x0001; // CEN(Counter ENable)='1' < TIM control register 1 00031 TIM2->SMCR = 0x0003; // SMS='011' (Encoder mode 3) < TIM slave mode control register 00032 TIM2->CCMR1 = 0xF1F1; // CC1S='01' CC2S='01' < TIM capture/compare mode register 1 00033 TIM2->CCMR2 = 0x0000; // < TIM capture/compare mode register 2 00034 TIM2->CCER = 0x0011; // CC1P CC2P < TIM capture/compare enable register 00035 TIM2->PSC = 0x0000; // Prescaler = (0+1) < TIM prescaler 00036 TIM2->ARR = 0xffffffff; // reload at 0xfffffff < TIM auto-reload register 00037 00038 TIM2->CNT = 0x0000; //reset the counter before we use it 00039 } 00040 00041 // Z Pulse routine 00042 void ZeroEncoderCount() { 00043 TIM2->CNT=0 ; //reset count to zero 00044 } 00045 00046 int main() { 00047 EncoderInitialise() ; 00048 00049 ZPulse.rise(&ZeroEncoderCount) ; //Setup Interrupt for rising edge of Z pulse 00050 ZPulse.mode(PullDown) ; // Set input as pull down 00051 00052 unsigned int EncoderPosition ; 00053 00054 while (true) { 00055 // Print Encoder Quadrature count to debug port every 0.5 seconds 00056 EncoderPosition = TIM2->CNT ; // Get current position from Encoder 00057 printf("Encoder Position %i\r\n", EncoderPosition); 00058 wait(0.5); 00059 } 00060 00061 00062 }
Generated on Fri Jul 15 2022 10:05:15 by
![doxygen](doxygen.png)