A program to monitor some parameters for a motor

Dependencies:   mbed-dev BufferSerial

Thanks to David Lowe for https://developer.mbed.org/users/gregeric/code/Nucleo_Hello_Encoder/ which I adapted for the use of TIM2 32bit timer as an encoder reader on the Nucleo L432KC board.

main.cpp

Committer:
tonnyleonard
Date:
2017-03-11
Revision:
2:958e9094b198
Parent:
1:a611582bffa7
Child:
4:4f115819171f

File content as of revision 2:958e9094b198:

/*
 * Using STM32's counter peripherals to interface rotary encoders.
 * Encoders are supported on F4xx's TIM1,2,3,4,5. TIM2 & TIM5 have 32bit count, others 16bit.
 * Beware mbed uses TIM5 for system timer, SPI needs TIM1, others used for PWM.
 * Check your platform's PeripheralPins.c & PeripheralNames.h if you need both PWM & encoders.
 *
 * Edit HAL_TIM_Encoder_MspInitFx.cpp to suit your mcu & board's available pinouts & pullups/downs.
 *
 * Thanks to:
 * http://petoknm.wordpress.com/2015/01/05/rotary-encoder-and-stm32/
 *
 * References:
 * http://www.st.com/st-web-ui/static/active/en/resource/technical/document/user_manual/DM00122015.pdf
 * http://www.st.com/st-web-ui/static/active/en/resource/technical/document/reference_manual/DM00096844.pdf
 * http://www.st.com/web/en/resource/technical/document/application_note/DM00042534.pdf
 * http://www.st.com/web/en/resource/technical/document/datasheet/DM00102166.pdf
 * 
 * David Lowe Jan 2015
 */

#include "mbed.h"
#include "Encoder.h"

TIM_Encoder_InitTypeDef encoder1, encoder2;
TIM_HandleTypeDef timer1,  timer2;

int main()
{
    
    //counting on A-input only, 2 ticks per cycle, rolls over at 100
    EncoderInit(&encoder1, &timer1, TIM1, 0xffff, TIM_ENCODERMODE_TI12);

    //counting on both A&B inputs, 4 ticks per cycle, full 32-bit count
    //For L432KC to work with TIM2 one needs to reassign the system ticker 
    //from TIM2 to TIM7 in TARGET/../device/hal_tick.h
    EncoderInit(&encoder2, &timer2, TIM2, 0xffffffff, TIM_ENCODERMODE_TI12);
    
    printf("\n\rSTM HAL encoder demo\n\r");
    
    while(1) {
        uint16_t count1=0;
        uint32_t count2=0;
        int8_t dir1, dir2;

        
        //OK 401 411 446 TICKER 030
        //count1=TIM1->CNT;
        //dir1=TIM1->CR1&TIM_CR1_DIR;
        count1= __HAL_TIM_GET_COUNTER(&timer1);
        dir1 = __HAL_TIM_IS_TIM_COUNTING_DOWN(&timer1);

        //OK 401 411 446 NOK 030
        //count2=TIM2->CNT;
        //dir2=TIM2->CR1&TIM_CR1_DIR;
        count2=__HAL_TIM_GET_COUNTER(&timer2);
        dir2 = __HAL_TIM_IS_TIM_COUNTING_DOWN(&timer2);

        
        printf("%d%s %d%s\r\n", count1, dir1==0 ? "+":"-", count2, dir2==0 ? "+":"-" );
        wait(0.1);
    }
}