Other Parts Discussed in Thread: EK-TM4C123GXL
Hello everyone,
I'm using EK-TM4C123GXL launchpad board and trying use Timer0 as a delay function but having a strange problem and I don't quite understand why my code doesn't work. The code is very simple as shown below:
#include <stdbool.h>
#include <stdint.h>
#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "driverlib/pin_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/timer.h"
#include "driverlib/uart.h"
#include "utils/uartstdio.h"
//*****************************************************************************
//
// Delay ms
//
//*****************************************************************************
void Delay_ms(uint16_t ui16ms)
{
TimerEnable(TIMER0_BASE, TIMER_A);
while (ui16ms--)
{
while (!TimerIntStatus(TIMER0_BASE, TIMER_A))
{
TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
}
}
TimerDisable(TIMER0_BASE, TIMER_A);
}
//*****************************************************************************
//
// Configure Timer0A as a 32-bit periodic
//
//*****************************************************************************
int
main(void)
{
//
// Config system clock for 80MHz using PLL with external 16MHz oscillator
//
SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_PLL | SYSCTL_OSC_MAIN |
SYSCTL_XTAL_16MHZ);
//
// Enable Peripheral Clocks for port PB
//
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
//
// Enable pin PB for GPIOOutput
//
GPIOPinTypeGPIOOutput(GPIO_PORTB_BASE, GPIO_PIN_0);
GPIOPinTypeGPIOOutput(GPIO_PORTB_BASE, GPIO_PIN_1);
//
// Wait for PB is ready
//
while(!SysCtlPeripheralReady(SYSCTL_PERIPH_GPIOB));
//
// Enable The Timer0 peripheral.
//
SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0);
//
// Wait for Timer0 is ready
while(!SysCtlPeripheralReady(SYSCTL_PERIPH_TIMER0));
//
// Config Timer0 32 bit periodic
//
TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC);
//
// Preload Timer0A for 1ms timeout
//
TimerLoadSet(TIMER0_BASE, TIMER_A, SysCtlClockGet() / 1000);
//
// Configure the Timer0A interrupt for timer timeout.
//
TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT);
//
// Enable Timer0A.
//
TimerEnable(TIMER0_BASE, TIMER_A);
//
// Loop forever while the Timer0B runs.
//
while(1)
{
//
// Toggle port PB0 every 50ms
//
GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_0, 1);
Delay_ms(1);
GPIOPinWrite(GPIO_PORTB_BASE, GPIO_PIN_0, 0);
Delay_ms(1);
}
}
The problem I have is the Timer0 seems to overflow much faster than I expected. I used the scope to look at the port pin PB0 and see it toggle around 1.5us instead of 1ms. The system clock is running at 80MHz. I checked the Timer0 TIMER_TAILR register and the preload value is correct with 0x00013880 which is 80000 in decimal. Would you all please look into my code and tell me where my mistakes are?
Thank you all in advance and have a wonderful Mon.
Best regards,
TLN