Question about a timer and state machine (timerCallback) - timer

I'm incredibly new to C and embedded systems in general, so my question might have an obvious answer, but I have no idea what to do here and the explanation is extremely vague from our instructor/school (SNHU).
Call your state machine every 500000 us
This is the part I am not understanding (I really don't know how timers work and the TI header file explains this so poorly).
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
/* Driver Header files */
#include <ti/drivers/GPIO.h>
/* Driver configuration */
#include "ti_drivers_config.h"
// Include the Timer
#include <ti/drivers/Timer.h>
int btnPress = 0;
int timerCount = 0;
void timerCallback(Timer_Handle myHandle, int_fast16_t status)
{
}
void initTimer(void)
{
Timer_Handle timer0;
Timer_Params params;
Timer_init();
Timer_Params_init(&params);
params.period = 1000000;
params.periodUnits = Timer_PERIOD_US;
params.timerMode = Timer_CONTINUOUS_CALLBACK;
params.timerCallback = timerCallback;
timer0 = Timer_open(CONFIG_TIMER_0, &params);
if (timer0 == NULL) {
/* Failed to initialized timer */
while (1) {}
}
if (Timer_start(timer0) == Timer_STATUS_ERROR) {
/* Failed to start timer */
while (1) {}
}
}
void morseCodeSOS() {
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
usleep(3 * 500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
usleep(3 * 500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
usleep(7 * 500000);
}
void morseCodeOK() {
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
usleep(3 * 500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
usleep(500000);
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_OFF);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_ON);
usleep(1500000);
GPIO_write(CONFIG_GPIO_LED_1, CONFIG_GPIO_LED_OFF);
usleep(7 * 500000);
}
/*
* ======== gpioButtonFxn0 ========
* Callback function for the GPIO interrupt on CONFIG_GPIO_BUTTON_0.
*
* Note: GPIO interrupts are cleared prior to invoking callbacks.
*/
void gpioButtonFxn0(uint_least8_t index)
{
/* Toggle an LED */
// GPIO_toggle(CONFIG_GPIO_LED_0);
btnPress = 1;
}
/*
* ======== gpioButtonFxn1 ========
* Callback function for the GPIO interrupt on CONFIG_GPIO_BUTTON_1.
* This may not be used for all boards.
*
* Note: GPIO interrupts are cleared prior to invoking callbacks.
*/
void gpioButtonFxn1(uint_least8_t index)
{
/* Toggle an LED */
// GPIO_toggle(CONFIG_GPIO_LED_1);
btnPress = 0;
}
enum morseCodeMsg {BTN_Init, BTN_SOS, BTN_OK} BTN_State;
// Create a state machine that checks for a button press interrupt (Call every 500,000
microseconds)
// If the button hasn't been pressed, execute the SOS message continuously.
// If the button has been pressed, finish SOS message, then signal OK message.
void switchStates() {
while(1) {
switch(BTN_State) {
case BTN_Init:
BTN_State = BTN_SOS;
btnPress = 0;
morseCodeSOS();
break;
case BTN_SOS:
if (btnPress == 0){
morseCodeSOS();
}
else if (btnPress == 1) {
morseCodeOK();
}
break;
case BTN_OK:
if (btnPress == 0) {
morseCodeSOS();
}
else if (btnPress == 1) {
morseCodeOK();
}
break;
default:
BTN_State = BTN_Init;
break;
}
}
}
/*
* ======== mainThread ========
*/
void *mainThread(void *arg0)
{
/* Call driver init functions */
GPIO_init();
/* Configure the LED and button pins */
GPIO_setConfig(CONFIG_GPIO_LED_0, GPIO_CFG_OUT_STD | GPIO_CFG_OUT_LOW);
GPIO_setConfig(CONFIG_GPIO_LED_1, GPIO_CFG_OUT_STD | GPIO_CFG_OUT_LOW);
GPIO_setConfig(CONFIG_GPIO_BUTTON_0, GPIO_CFG_IN_PU | GPIO_CFG_IN_INT_FALLING);
/* Turn on user LED */
GPIO_write(CONFIG_GPIO_LED_0, CONFIG_GPIO_LED_ON);
/* Install Button callback */
GPIO_setCallback(CONFIG_GPIO_BUTTON_0, gpioButtonFxn0);
/* Enable interrupts */
GPIO_enableInt(CONFIG_GPIO_BUTTON_0);
/*
* If more than one input pin is available for your device, interrupts
* will be enabled on CONFIG_GPIO_BUTTON1.
*/
if (CONFIG_GPIO_BUTTON_0 != CONFIG_GPIO_BUTTON_1) {
/* Configure BUTTON1 pin */
GPIO_setConfig(CONFIG_GPIO_BUTTON_1, GPIO_CFG_IN_PU | GPIO_CFG_IN_INT_FALLING);
/* Install Button callback */
GPIO_setCallback(CONFIG_GPIO_BUTTON_1, gpioButtonFxn1);
GPIO_enableInt(CONFIG_GPIO_BUTTON_1);
switchStates();
}
return (NULL);
}
I'm pretty sure that my state machine and general morseCode functions are not ideal, but they work for what I am trying to do. I just have no idea how to implement the timer with the timerCallback function or the initTimer. I don't even know what either do, per say.
If anyone can help, that'd be greatly appreciated.

Related

sim808 freezes after one SMS using stm32

I am trying to design a GPS car tracker with a SIM808 module using a STM32F103RET6 header board and I want to get the location link messaged to my phone by sending an SMS to the module. Right now my code works but only when I reset the board after sending each SMS. I attached my code can you figure out what is the problem?
main code :
#include <stm32f10x.h>
#include "usart.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
char S=0x1A;
#define Enter usart_sendchar('\n');
#define CR usart_sendchar('\r');
#define GIM usart_sendchar('"');
#define SUB usart_sendchar(S);
#include "stm32f10x.h"
#include <string.h>
char get_Enter = 0;
uint8_t ch;
char str1[300];
char str2[100];
int i=0;
char flag=0;
char str_tmp[20];
char str_tmp2[20];
char* p;
volatile uint32_t msTicks;
//calling all the functions
void Send_SMS(char *text);
void CMTI(void);
void wait_to_get(char ch);
void del_All_SMS(void);
void CMGF_1(void);
void Delay (uint32_t Time);
void CMGR (void);
void CGNSPWR_1(void);
void CGNSINF(void);
void interrupt_activation(void);
void CGNSINF_C(void);
void AT(void);
void Delay (uint32_t dlyTicks);
void SysTick_Handler(void);
// the interrupt handler for the systick module
void SysTick_Handler(void) {
msTicks++;
}
void Delay (uint32_t dlyTicks) {
uint32_t curTicks;
curTicks = msTicks;
while ((msTicks - curTicks)< dlyTicks);
}
void Send_SMS(char *text)
{
CMGF_1();
Delay(500);
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"AT+CMGS=");
Delay(500);
usart_sendstring(str_tmp);
GIM
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"+98905xxxxxxx");
Delay(500);
usart_sendstring(str_tmp);
GIM
Enter
CR
Delay(500);
usart_sendstring(text);
Enter
CR
str_tmp[0]='\0';
Delay(500);
SUB
Delay(100);
del_All_SMS();
}
void USART1_IRQHandler(void) {
ch = USART1->DR & 0xFF;
if (ch == '\n'){ // 13 enter
get_Enter =1;
}
else{
str1[i]= ch;
i++;
}
}
void CMGF_1(void)
{
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"AT+CMGF=1");
Delay(500);
usart_sendstring(str_tmp);
Enter
CR
}
void del_All_SMS(void)
{
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"AT+CMGD=1,4");
Delay(500);
usart_sendstring(str_tmp);
Enter
CR
}
void CMGR(void)
{
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"AT+CMGR=1");
Delay(500);
usart_sendstring(str_tmp);
Enter
CR
}
void CGNSINF(void)
{
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"AT+CGNSINF");
Delay(500);
usart_sendstring(str_tmp);
Enter
CR
}
void CGNSPWR_1(void)
{
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"AT+CGNSPWR=1");
Delay(500);
usart_sendstring(str_tmp);
Enter
CR
}
void AT(void)
{
str_tmp[0]='\0';
Delay(100);
strcpy(str_tmp,"AT");
Delay(500);
usart_sendstring(str_tmp);
Enter
CR
}
int main()
{
SystemInit();
SysTick_Config(SystemCoreClock/1000); // setup systick timer for 1ms interrupts
usart_init();
AT();
p=NULL;
check:AT();
Delay(2000);
p=strstr(str1,"OK");
if(p==NULL) goto check;
CMGF_1();
Delay(500);
CGNSPWR_1();
Delay(500);
del_All_SMS();
Delay(500);
RCC->APB2ENR |= (1<<3);
GPIOB->CRL &= ~0xF;
GPIOB->CRL |= 0x3;
while (1)
{
if (get_Enter ==1)
{
if (flag==0){
////waiting for +CMTI: from sim800
do
{
p=strstr(str1,"+CMTI:");
}
while(p==NULL);
Delay(1000);
// sending AT+CMGR=1 command
if (p!=NULL)
{
CMGR();
Delay(350);
flag=1;
}
}
if (flag==1) {
p=strstr(str1,"+CMGR");
if (p){
p=strstr(str1,"loc");
if (p!=NULL)
{
CGNSINF();
Delay(300);
}
else if (p==NULL)
{
del_All_SMS();
memset(str1, 0, 300);
flag=0;
}
p=strstr(str1,"+CGNSINF:");
if (p)
{
float a[5];
char str2[80];
const char s[2] = ",";
char *token;
// getting the lattitude and longitude
token = strtok(p, s);
for (int i=0;i<5;i++){
sprintf( str2," %s\n", token );
a[i]=atof(str2);
token = strtok(NULL, s);
}
sprintf(str2,"https://maps.google.com/?q=%.6f,%.6f",a[3],a[4]);
Send_SMS(str2);
p=NULL;
del_All_SMS();
flag=0;
memset(str1, 0, 300);
}
}
}
}
}
}
usart code :
#include "stm32f10x.h"
#include "usart.h"
char str[200];
char data;
//// initialize usart
void usart_init(void)
{
RCC->APB2ENR |= ( 1UL << 0); /* enable clock Alternate Function */
AFIO->MAPR &= ~( 1UL << 2); /* clear USART1 remap */
RCC->APB2ENR |= ( 1UL << 2); /* enable GPIOA clock */
GPIOA->CRH &= ~(0xFFUL << 4); /* clear PA9, PA10 */
GPIOA->CRH |= (0x0BUL << 4); /* USART1 Tx (PA9) output push-pull */
GPIOA->CRH |= (0x04UL << 8); /* USART1 Rx (PA10) input floating */
RCC->APB2ENR |= ( 1UL << 14); /* enable USART#1 clock */
USART1->BRR=0x1D4C; // 9600 #72MHz
// USART1->BRR = 0x0271; /* 115200 baud # PCLK2 72MHz */
USART1->CR1 = (( 1UL << 2) | /* enable RX */
( 1UL << 3) | /* enable TX */
( 0UL << 12) ); /* 1 start bit, 8 data bits */
USART1->CR2 = 0x0000; /* 1 stop bit */
USART1->CR3 = 0x0000; /* no flow control */
USART1->CR1 |= ( 1 << 13); /* enable USART */
USART1->CR1 |= ( 1UL << 5); // RXNE interrupt enable
NVIC_SetPriority(USART1_IRQn,5); /* Default priority group 0, can be 0(highest) - 31(lowest) */
NVIC_EnableIRQ(USART1_IRQn); /* Enable UART0 Interrupt */
}
void usart_sendchar(char data){
while(!(USART1->SR&(1<<7)));
USART1->DR=data;
}
char usart_getchar(void)
{
while (!(USART1->SR&(1<<5)));
data=USART1->DR ;
return data;
}
void usart_getstring(char *str)
{
char *temp = str;
do{
*temp = usart_getchar();
usart_sendchar (*temp) ;
} while(*(temp++) != 0x0D );
*(temp-1) = 0;
}
void usart_sendstring(char *s)
{
while (*s)
{
usart_sendchar(*s);
s++;
}
}

Why does the stm32 instantly leave stop mode as soon as it enters?

I am currently working on a device that requires a button press to put the device into STOP low-power mode and then a different button press to cause an interrupt to wake-up the device again. Currently the first button press interrupt does work and the and the device is put into STOP mode. However, rather than waiting for the other button to be pressed the device instantly exits STOP mode. I have tried searching but I haven't found any other indication of another interrupt being called that would cause the WFI to trigger and wake-up the device. Below is my code that I am using:
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_hal.h"
#define BUTTON_WAKE_PIN GPIO_PIN_0
#define BUTTON_WAKE_PORT GPIOA
#define BUTTON_SLEEP_PIN GPIO_PIN_9
#define BUTTON_SLEEP_PORT GPIOE
#define LED_GR_PIN GPIO_PIN_0
#define LED_GR_PORT GPIOD
#define LED_RG_PIN GPIO_PIN_1
#define LED_RG_PORT GPIOD
/* Private variables ---------------------------------------------------------*/
static uint8_t buttonPress = 0;
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config ( void );
static void Gpio_Sleep_Mode ( void );
/**
* #brief This function handles (wakeup) interrupts.
*/
void EXTI0_IRQHandler ( void )
{
/* Clear pending */
HAL_GPIO_EXTI_IRQHandler(BUTTON_WAKE_PIN); /* IRQ_CH0 */
}
/**
* #brief This function handles (sleep) interrupts.
*/
void EXTI9_5_IRQHandler(void)
{
if ( EXTI->PR & EXTI_PR_PR9 ) /* IRQ_CH9 */
{
HAL_GPIO_EXTI_IRQHandler(BUTTON_SLEEP_PIN);
buttonPress = 1;
}
}
/* Turn on LED */
void LED_Off ( void )
{
HAL_GPIO_WritePin( LED_GR_PORT, LED_GR_PIN, GPIO_PIN_RESET );
HAL_GPIO_WritePin( LED_RG_PORT, LED_RG_PIN, GPIO_PIN_RESET );
}
/* Turn off LED */
void LED_On ( void )
{
HAL_GPIO_WritePin( LED_GR_PORT, LED_GR_PIN, GPIO_PIN_SET );
HAL_GPIO_WritePin( LED_RG_PORT, LED_RG_PIN, GPIO_PIN_RESET );
}
/* Initialize LED GPIOs */
void LED_Init ( void )
{
GPIO_InitTypeDef GPIO_InitStruct;
/* Start clock */
__HAL_RCC_GPIOD_CLK_ENABLE();
/* Default input settings */
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Pin = LED_GR_PIN;
HAL_GPIO_WritePin( LED_GR_PORT, LED_GR_PIN, GPIO_PIN_RESET );
HAL_GPIO_Init(LED_GR_PORT, &GPIO_InitStruct);
GPIO_InitStruct.Pin = LED_RG_PIN;
HAL_GPIO_WritePin( LED_RG_PORT, LED_RG_PIN, GPIO_PIN_RESET );
HAL_GPIO_Init(LED_RG_PORT, &GPIO_InitStruct);
LED_On();
HAL_Delay(50);
LED_Off();
HAL_Delay(50);
LED_On();
HAL_Delay(50);
LED_Off();
HAL_Delay(50);
}
/* Initialize button used for wakeup */
void Wake_Button_Init ( void )
{
GPIO_InitTypeDef GPIO_InitStruct;
/* Start clock */
__HAL_RCC_GPIOA_CLK_ENABLE();
/* Default input settings */
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Pin = BUTTON_WAKE_PIN;
HAL_GPIO_WritePin( BUTTON_WAKE_PORT, BUTTON_WAKE_PIN, GPIO_PIN_RESET );
HAL_GPIO_Init(BUTTON_WAKE_PORT, &GPIO_InitStruct);
__HAL_GPIO_EXTI_CLEAR_IT ( BUTTON_WAKE_PIN );
__HAL_GPIO_EXTI_CLEAR_IT ( BUTTON_SLEEP_PIN );
HAL_NVIC_SetPriority ( EXTI0_IRQn, 0, 0);
HAL_NVIC_ClearPendingIRQ ( EXTI9_5_IRQn );
HAL_NVIC_ClearPendingIRQ ( EXTI0_IRQn );
HAL_NVIC_EnableIRQ ( EXTI0_IRQn );
}
/* Initialize button used for sleep */
void Sleep_Button_Init ( void )
{
GPIO_InitTypeDef GPIO_InitStruct;
/* Start clock */
__HAL_RCC_GPIOE_CLK_ENABLE();
/* Default input settings */
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Pin = BUTTON_SLEEP_PIN;
HAL_GPIO_WritePin( BUTTON_SLEEP_PORT, BUTTON_SLEEP_PIN, GPIO_PIN_RESET );
HAL_GPIO_Init(BUTTON_SLEEP_PORT, &GPIO_InitStruct);
__HAL_GPIO_EXTI_CLEAR_IT ( BUTTON_SLEEP_PIN );
HAL_NVIC_SetPriority ( EXTI9_5_IRQn, 0, 0);
HAL_NVIC_ClearPendingIRQ ( EXTI9_5_IRQn );
HAL_NVIC_EnableIRQ ( EXTI9_5_IRQn );
}
void System_Init ( void )
{
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
buttonPress = 0;
LED_Init();
Sleep_Button_Init();
}
/* All GPIOs analog */
void Gpio_Sleep_Mode ( void )
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOE_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
/* Configure as analog */
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Pin = GPIO_PIN_All;
HAL_GPIO_Init( GPIOA, &GPIO_InitStruct );
HAL_GPIO_Init( GPIOB, &GPIO_InitStruct );
HAL_GPIO_Init( GPIOC, &GPIO_InitStruct );
HAL_GPIO_Init( GPIOD, &GPIO_InitStruct );
HAL_GPIO_Init( GPIOE, &GPIO_InitStruct );
HAL_GPIO_Init( GPIOH, &GPIO_InitStruct );
/* Disable GPIOs clock */
__HAL_RCC_GPIOA_CLK_DISABLE();
__HAL_RCC_GPIOB_CLK_DISABLE();
__HAL_RCC_GPIOC_CLK_DISABLE();
__HAL_RCC_GPIOD_CLK_DISABLE();
__HAL_RCC_GPIOE_CLK_DISABLE();
__HAL_RCC_GPIOH_CLK_DISABLE();
/* Disble all interrupt sources */
EXTI->IMR = 0;
}
/**
* #brief Puts the system into sleep mode
*/
void System_Sleep ( void )
{
Gpio_Sleep_Mode();
/* Enable button interrupt */
Wake_Button_Init();
/* FLASH Deep Power Down Mode enabled */
HAL_PWREx_EnableFlashPowerDown();
/* Enter Stop Mode */
HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
__HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU);
System_Init();
}
/**
* #brief The application entry point.
*/
int main(void)
{
System_Init();
// Allow debugger to work in stop mode
DBGMCU->CR = DBGMCU_CR_DBG_STOP;
/* Infinite loop */
while (1)
{
LED_On();
HAL_Delay(500);
LED_Off();
HAL_Delay(500);
if ( buttonPress == 1 )
{
HAL_Delay ( 500 );
buttonPress = 0;
System_Sleep();
}
}
}
/**
* #brief System Clock Configuration
* #retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
/* Configure the main internal regulator output voltage */
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/* Initializes the CPU, AHB and APB busses clocks */
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE|RCC_OSCILLATORTYPE_LSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.LSEState = RCC_LSE_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLM = 2;
RCC_OscInitStruct.PLL.PLLN = 96;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV6;
RCC_OscInitStruct.PLL.PLLQ = 4;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/* Initializes the CPU, AHB and APB busses clocks */
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Configure the Systick interrupt time */
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
/**Configure the Systick */
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/**
* #brief This function is executed in case of error occurrence.
*/
void _Error_Handler(char *file, int line)
{
/* User can add his own implementation to report the HAL error return state */
while(1);
}
You have enabled the SysTick interrupt. Could the SysTick interrupt be waking up the processor? Do you know if the SysTick clock source stops or if the SysTick interrupt gets disabled when you enter stop mode?
Try suspending and resuming the SysTick interrupt like this.
HAL_SuspendTick();
/* Enter Stop Mode */
HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI);
HAL_ResumeTick();

STM32 Blinking LEDs with a Timer

I'm trying to blink 4 LEDs with a Timer Interrupt, at different frequencies.
I came up with this code
/*********** Includes ****************/
#include "stm32f4xx.h"
#include "stm32f4_discovery.h"
/*********** Defines *****************/
#define TIM3_CK_CNT 50000
/*********** Declarations *************/
/*------ Function prototypes ---------*/
void TimerConfiguration(void);
/* ----- Global variables ----------- */
volatile uint16_t CCR1_Val = 50000;
volatile uint16_t CCR2_Val = 40000;
volatile uint16_t CCR3_Val = 30000;
volatile uint16_t CCR4_Val = 20000;
/************ Main *********************/
int main(void)
{
// LED initialization
STM_EVAL_LEDInit(LED3); // Orange
STM_EVAL_LEDInit(LED4); // Green
STM_EVAL_LEDInit(LED5); // Red
STM_EVAL_LEDInit(LED6); // Blue
/* TIM3 Configuration */
TimerConfiguration();
while (1);
}
/*********** Functions *****************/
/**
* #brief Configure the TIM3 TIMER.
* #param None
* #retval None
*/
void TimerConfiguration(void)
{
uint16_t PrescalerValue = 0;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
/* TIM3 clock enable */
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
/* Time base configuration */
TIM_TimeBaseStructure.TIM_Period = 65535;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
/* Prescaler configuration */
PrescalerValue = (uint16_t) ((SystemCoreClock / 2) / TIM3_CK_CNT) - 1;
TIM_PrescalerConfig(TIM3, PrescalerValue, TIM_PSCReloadMode_Immediate);
/* Output Compare Timing Mode configuration: Channel1 */
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_Timing;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = CCR1_Val;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM3, TIM_OCPreload_Disable);
/*Channel2 */
TIM_OCInitStructure.TIM_Pulse = CCR2_Val;
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
/*Channel3 */
TIM_OCInitStructure.TIM_Pulse = CCR3_Val;
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
/*Channel4 */
TIM_OCInitStructure.TIM_Pulse = CCR4_Val;
TIM_OC4Init(TIM3, &TIM_OCInitStructure);
/* Configure the TIM3 gloabal Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
/* TIM Interrupts enable */
TIM_ITConfig(TIM3, TIM_IT_CC1, ENABLE);
TIM_ITConfig(TIM3, TIM_IT_CC2, ENABLE);
TIM_ITConfig(TIM3, TIM_IT_CC3, ENABLE);
TIM_ITConfig(TIM3, TIM_IT_CC4, ENABLE);
/* TIM3 counter enable */
TIM_Cmd(TIM3, ENABLE);
}
int LedCount6 = 0;
int LedCount5 = 0;
int LedCount4 = 0;
int LedCount3 = 0;
/************ Interrupt Handlers *************/
/**
* #brief This function handles TIM3 global interrupt request.
* #param None
* #retval None
*/
void TIM3_IRQHandler(void)
{
uint16_t capture = 0;
LedCount6++;
LedCount5++;
LedCount4++;
LedCount3++;
if ((TIM_GetITStatus(TIM3, TIM_IT_CC2) != RESET) && (TIM_GetITStatus(TIM3, TIM_IT_CC1) != RESET) && (TIM_GetITStatus(TIM3, TIM_IT_CC3) != RESET) && (TIM_GetITStatus(TIM3, TIM_IT_CC4) != RESET))
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
TIM_ClearITPendingBit(TIM3, TIM_IT_CC2);
TIM_ClearITPendingBit(TIM3, TIM_IT_CC3);
TIM_ClearITPendingBit(TIM3, TIM_IT_CC4);
int val6 = 100000;
int val5 = 70000;
int val4 = 60000;
int val3 = 50000;
if (LedCount6 >= val6 ) {
/* LED6 toggling */
STM_EVAL_LEDToggle(LED6);
LedCount6 = 0;
/* Update CH1 OCR */
capture = TIM_GetCapture1(TIM3);
TIM_SetCompare1(TIM3, capture + CCR1_Val);}
if (LedCount5 >= val5) {
/* LED5 toggling */
STM_EVAL_LEDToggle(LED5);
LedCount5 = 0;
/* Update CH2 OCR */
capture = TIM_GetCapture2(TIM3);
TIM_SetCompare2(TIM3, capture + CCR2_Val);}
if (LedCount4 >= val4) {
/* LED4 toggling */
STM_EVAL_LEDToggle(LED4);
LedCount4 = 0;
/* Update CH3 OCR */
capture = TIM_GetCapture3(TIM3);
TIM_SetCompare3(TIM3, capture + CCR3_Val);}
if (LedCount3 >= val3 ) {
/* LED3 toggling */
STM_EVAL_LEDToggle(LED3);
LedCount3 = 0;
/* Update CH4 OCR */
capture = TIM_GetCapture4(TIM3);
TIM_SetCompare4(TIM3, capture + CCR4_Val);}
}
}
Now, all the code that blinks the 4 leds is inside the interrupt handler (void TIM3_IRQHandler(void)).
The 4 LEDs blink, but blink all at the same time, how can i change their frequencies to be all different?
Changing the TIM3_CK_CNT value will change the frequency of all 4, but because it's a define i cannot manipulate it through the code to change for each led.
The TIMER (TIM3) has 4 channels which all can cause an interrupt, but the interrupt handler will be the same one for all channels.
Replace your IRQ handler like this (Change the LED toggle as you wish):
void TIM3_IRQHandler(void)
{
uint16_t capture = 0;
if (TIM_GetITStatus(TIM3, TIM_IT_CC2) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC2);
/* LED6 toggling */
STM_EVAL_LEDToggle(LED6);
/* Update CH1 OCR */
capture = TIM_GetCapture1(TIM3);
TIM_SetCompare1(TIM3, capture + CCR1_Val);
}
else if (TIM_GetITStatus(TIM3, TIM_IT_CC1) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC1);
/* LED5 toggling */
STM_EVAL_LEDToggle(LED5);
/* Update CH2 OCR */
capture = TIM_GetCapture2(TIM3);
TIM_SetCompare2(TIM3, capture + CCR2_Val);
}
else if (TIM_GetITStatus(TIM3, TIM_IT_CC3) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC3);
/* LED4 toggling */
STM_EVAL_LEDToggle(LED4);
/* Update CH3 OCR */
capture = TIM_GetCapture3(TIM3);
TIM_SetCompare3(TIM3, capture + CCR3_Val);
}
else if (TIM_GetITStatus(TIM3, TIM_IT_CC4) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_CC4);
/* LED3 toggling */
STM_EVAL_LEDToggle(LED3);
/* Update CH4 OCR */
capture = TIM_GetCapture4(TIM3);
TIM_SetCompare4(TIM3, capture + CCR4_Val);
}
}
With this change, LED will toggle with respect to each channel interrupt. i.e Only one LED blinks at each interrupt. In order to Blink with different frequencies, you need to check the datasheet, how configure different frequency for different LED channel.
The code is too large to place it here.
Here is my solution:
https://www.diymat.co.uk/arm-blinking-led-driver/
Any number of LEDs, any frequencies (off and on time can be different) any number of blinks (+continous) and the callbacks at the end of the sequence.

STM32 SPI not working as expected

I'm trying to enable the LED's on my MCP23S09 by writing to the GPIO register using SPI.
There are two chips on the board one is for the inputs and the other one is for the outputs, so the LED's.
I connected everything like I should, so I took CH2 low and connected the MOSI and SCK pin to my microcontroller.
I'm using a Nucleo STM32F411 in combination with the CubeMX software, So I'm trying to send data to the registers to enable functionality.
But unfortunately none of the LED's lit up on my IO Expander.
Next thing I tried was STM32duino, so I can write Arduino code for my board. But as far as I know this is just another layer on top of the HAL libraries.
To my suprise it worked just fine! It's the same piece of code, I just changed it a bit to work for Arduino.
But I still don't understand why it doesn't work when using the HAL libraries generated by CubeMX.
Arduino Code:
#include <SPI.h>
#define IODIR 0x00
#define IPOL 0x01
#define GPINTEN 0x02
#define DEFVAL 0x03
#define INTCON 0x04
#define IOCON 0x05
#define GPPU 0x06
#define INTF 0x07
#define INTCAP 0x08
#define GPIO 0x09
#define OLAT 0x0A
#define OPCODEW 0x40
#define OPCODER 0x41
// CS0 -> D2
const int slaveAPin = 2;
// CS1 -> D3
const int slaveBPin = 3;
// LED VAL
const uint8_t value = ~0x3F;
void setup() {
// put your setup code here, to run once:
// initialize SPI:
SPI.begin(); //Initialize the SPI_1 port.
SPI.setBitOrder(MSBFIRST); // Set the SPI_1 bit order
SPI.setDataMode(SPI_MODE0); //Set the SPI_1 data mode 0
SPI.setClockDivider(SPI_CLOCK_DIV64);
pinMode (slaveAPin, OUTPUT); // First chip for inputs
pinMode (slaveBPin, OUTPUT); // Second chip for outputs
digitalWrite (slaveAPin, HIGH);
digitalWrite (slaveBPin, HIGH);
}
void loop() {
// configuration led-io-expander
sendDataSPI(IOCON, 0x20);
// all pins = output
sendDataSPI(IODIR, 0x00);
// Enable LEDS
sendDataSPI(GPIO, value);
}
void sendDataSPI(uint8_t reg, uint8_t value){
digitalWrite (slaveBPin, LOW); // Take slave-select low
SPI.transfer(OPCODEW); // Send the MCP23S09 opcode, and write byte
SPI.transfer(reg); // Send the register we want to write
SPI.transfer(value); // Send the byte
digitalWrite (slaveBPin, HIGH); // Take slave-select high
}
STM32 HAL:
/**
******************************************************************************
* File Name : main.c
* Description : Main program body
******************************************************************************
** This notice applies to any and all portions of this file
* that are not between comment pairs USER CODE BEGIN and
* USER CODE END. Other portions of this file, whether
* inserted by the user or by software development tools
* are owned by their respective copyright owners.
*
* COPYRIGHT(c) 2017 STMicroelectronics
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of STMicroelectronics nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f4xx_hal.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* USER CODE BEGIN Defines */
#define IODIR 0x00
#define IPOL 0x01
#define GPINTEN 0x02
#define DEFVAL 0x03
#define INTCON 0x04
#define IOCON 0x05
#define GPPU 0x06
#define INTF 0x07
#define INTCAP 0x08
#define GPIO 0x09
#define OLAT 0x0A
#define OPCODEW 0x40
#define OPCODER 0x41
#define SPI_TRANSFER_TIMEOUT 1000
/* USER CODE END Defines */
/* Private variables ---------------------------------------------------------*/
SPI_HandleTypeDef hspi1;
UART_HandleTypeDef huart2;
/* USER CODE BEGIN PV */
/* Private variables ---------------------------------------------------------*/
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void MX_GPIO_Init(void);
static void MX_SPI1_Init(void);
static void MX_USART2_UART_Init(void);
void sendDataSPI(uint8_t reg, uint8_t value);
int fgetc(FILE *f);
int fputc(int c, FILE *f);
/* USER CODE BEGIN PFP */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE END PFP */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
int main(void)
{
// LED VAL
uint8_t value = 0x3F;
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_SPI1_Init();
MX_USART2_UART_Init();
/* USER CODE BEGIN 2 */
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
// configuration led-io-expander
sendDataSPI(IOCON, 0x20);
// all pins = output
sendDataSPI(IODIR, 0x00);
// Enable LEDS
sendDataSPI(GPIO, value);
}
/* USER CODE END 3 */
}
// REGISTER, VALUE
void sendDataSPI(uint8_t reg, uint8_t value){
HAL_GPIO_WritePin(CS1_GPIO_Port, CS1_Pin, GPIO_PIN_RESET); // Take slave-select low
HAL_SPI_Transmit(&hspi1,(uint8_t *)OPCODEW,sizeof(uint8_t),SPI_TRANSFER_TIMEOUT); // Send the MCP23S09 opcode, and write bit
HAL_SPI_Transmit(&hspi1,(uint8_t *)&reg,sizeof(uint8_t),SPI_TRANSFER_TIMEOUT); // Send the register we want to write
HAL_SPI_Transmit(&hspi1,(uint8_t *)&value,sizeof(uint8_t),SPI_TRANSFER_TIMEOUT); // Send the byte
HAL_GPIO_WritePin(CS1_GPIO_Port, CS1_Pin, GPIO_PIN_SET); // Take slave-select high
}
int fputc(int c, FILE *f) {
return (HAL_UART_Transmit(&huart2, (uint8_t *)&c,1,HAL_MAX_DELAY));
}
int fgetc(FILE *f) {
char ch;
HAL_UART_Receive(&huart2,(uint8_t*)&ch,1,HAL_MAX_DELAY);
return (ch);
}
/** System Clock Configuration
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct;
RCC_ClkInitTypeDef RCC_ClkInitStruct;
/**Configure the main internal regulator output voltage
*/
__HAL_RCC_PWR_CLK_ENABLE();
__HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.HSICalibrationValue = 16;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
RCC_OscInitStruct.PLL.PLLM = 16;
RCC_OscInitStruct.PLL.PLLN = 336;
RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4;
RCC_OscInitStruct.PLL.PLLQ = 4;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Initializes the CPU, AHB and APB busses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
/**Configure the Systick interrupt time
*/
HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);
/**Configure the Systick
*/
HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);
/* SysTick_IRQn interrupt configuration */
HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
}
/* SPI1 init function */
static void MX_SPI1_Init(void)
{
/* SPI1 parameter configuration*/
hspi1.Instance = SPI1;
hspi1.Init.Mode = SPI_MODE_MASTER;
hspi1.Init.Direction = SPI_DIRECTION_2LINES;
hspi1.Init.DataSize = SPI_DATASIZE_8BIT;
hspi1.Init.CLKPolarity = SPI_POLARITY_LOW;
hspi1.Init.CLKPhase = SPI_PHASE_1EDGE;
hspi1.Init.NSS = SPI_NSS_SOFT;
hspi1.Init.BaudRatePrescaler = SPI_BAUDRATEPRESCALER_64;
hspi1.Init.FirstBit = SPI_FIRSTBIT_MSB;
hspi1.Init.TIMode = SPI_TIMODE_DISABLE;
hspi1.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE;
hspi1.Init.CRCPolynomial = 10;
if (HAL_SPI_Init(&hspi1) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
/* USART2 init function */
static void MX_USART2_UART_Init(void)
{
huart2.Instance = USART2;
huart2.Init.BaudRate = 115200;
huart2.Init.WordLength = UART_WORDLENGTH_8B;
huart2.Init.StopBits = UART_STOPBITS_1;
huart2.Init.Parity = UART_PARITY_NONE;
huart2.Init.Mode = UART_MODE_TX_RX;
huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart2.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart2) != HAL_OK)
{
_Error_Handler(__FILE__, __LINE__);
}
}
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
*/
static void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOH_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(CS0_GPIO_Port, CS0_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(CS1_GPIO_Port, CS1_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin : B1_Pin */
GPIO_InitStruct.Pin = B1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(B1_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : CS0_Pin */
GPIO_InitStruct.Pin = CS0_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(CS0_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : CS1_Pin */
GPIO_InitStruct.Pin = CS1_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(CS1_GPIO_Port, &GPIO_InitStruct);
}
/* USER CODE END 4 */
You do not wait the SPI transfer to be completed before starting the next transmission in your sendDataSPI function. It should be modified like this:
void sendDataSPI(uint8_t reg, uint8_t value){
HAL_GPIO_WritePin(CS1_GPIO_Port, CS1_Pin, GPIO_PIN_RESET); // Take slave-select low
HAL_SPI_Transmit(&hspi1,(uint8_t *)OPCODEW,sizeof(uint8_t),SPI_TRANSFER_TIMEOUT); // Send the MCP23S09 opcode, and write bit
while(HAL_SPI_GetState(&hspi1) != HAL_SPI_STATE_READY);
HAL_SPI_Transmit(&hspi1,(uint8_t *)&reg,sizeof(uint8_t),SPI_TRANSFER_TIMEOUT); // Send the register we want to write
while(HAL_SPI_GetState(&hspi1) != HAL_SPI_STATE_READY);
HAL_SPI_Transmit(&hspi1,(uint8_t *)&value,sizeof(uint8_t),SPI_TRANSFER_TIMEOUT); // Send the byte
while(HAL_SPI_GetState(&hspi1) != HAL_SPI_STATE_READY);
HAL_GPIO_WritePin(CS1_GPIO_Port, CS1_Pin, GPIO_PIN_SET); // Take slave-select high
}
Also this line just sends rubbish and not 0x40.
HAL_SPI_Transmit(&hspi1,(uint8_t *)OPCODEW,sizeof(uint8_t),SPI_TRANSFER_TIMEOUT); // Send the MCP23S09 opcode, and write bit
Notice that your are casting OPCODEW to a uint8_t* so actually you will pass the 0x40 as a pointer (pointing to some random memory) and not as the data.

How to use timer's OSTmrCreate to implement task scheduling with MicroC/OS II?

I got 2 tasks in MicroC to simulate a moving vehicle: ControlTask and VehicleTask. Now my project should replace the context switch with a timer for more appropriate timing but I can't seem to get it done. The program now uses the statement OSTimeDlyHMSM to implement periods but instead soft timers should be used with semaphores. OSTmrCreate in C/OS-II ReferenceManual (Chapter 16). I can start a timer then I can place it in the start code but I'm failing to call the timer and sync properly between the two tasks replacing the OSTimeDlyHMSM with a timer. I think my solution is getting more complicated than neccesary because I might not understand all details e.g. why I need semaphores and why it's more exact with a timer than the builtin OSTimeDlyHMSM. My complete effort this far looks like the following:
#include <stdio.h>
#include "system.h"
#include "includes.h"
#include "altera_avalon_pio_regs.h"
#include "sys/alt_irq.h"
#include "sys/alt_alarm.h"
#define DEBUG 1
#define HW_TIMER_PERIOD 100 /* 100ms */
/* Button Patterns */
#define GAS_PEDAL_FLAG 0x08
#define BRAKE_PEDAL_FLAG 0x04
#define CRUISE_CONTROL_FLAG 0x02
/* Switch Patterns */
#define TOP_GEAR_FLAG 0x00000002
#define ENGINE_FLAG 0x00000001
/* LED Patterns */
#define LED_RED_0 0x00000001 // Engine
#define LED_RED_1 0x00000002 // Top Gear
#define LED_GREEN_0 0x0001 // Cruise Control activated
#define LED_GREEN_2 0x0002 // Cruise Control Button
#define LED_GREEN_4 0x0010 // Brake Pedal
#define LED_GREEN_6 0x0040 // Gas Pedal
/*
* Definition of Tasks
*/
#define TASK_STACKSIZE 2048
OS_STK StartTask_Stack[TASK_STACKSIZE];
OS_STK ControlTask_Stack[TASK_STACKSIZE];
OS_STK VehicleTask_Stack[TASK_STACKSIZE];
// Task Priorities
#define STARTTASK_PRIO 5
#define VEHICLETASK_PRIO 10
#define CONTROLTASK_PRIO 12
// Task Periods
#define CONTROL_PERIOD 300
#define VEHICLE_PERIOD 300
/*
* Definition of Kernel Objects
*/
// Mailboxes
OS_EVENT *Mbox_Throttle;
OS_EVENT *Mbox_Velocity;
// Semaphores
OS_EVENT *aSemaphore;
// SW-Timer
OS_TMR *SWTimer;
OS_TMR *SWTimer1;
BOOLEAN status;
/*
* Types
*/
enum active {on, off};
enum active gas_pedal = off;
enum active brake_pedal = off;
enum active top_gear = off;
enum active engine = off;
enum active cruise_control = off;
/*
* Global variables
*/
int delay; // Delay of HW-timer
INT16U led_green = 0; // Green LEDs
INT32U led_red = 0; // Red LEDs
int sharedMemory=1;
void ContextSwitch()
{
printf("ContextSwitch!\n");
sharedMemory=sharedMemory*-1;
}
int buttons_pressed(void)
{
return ~IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_KEYS4_BASE);
}
int switches_pressed(void)
{
return IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_TOGGLES18_BASE);
}
/*
* ISR for HW Timer
*/
alt_u32 alarm_handler(void* context)
{
OSTmrSignal(); /* Signals a 'tick' to the SW timers */
return delay;
}
static int b2sLUT[] = {0x40, //0
0x79, //1
0x24, //2
0x30, //3
0x19, //4
0x12, //5
0x02, //6
0x78, //7
0x00, //8
0x18, //9
0x3F, //-
};
/*
* convert int to seven segment display format
*/
int int2seven(int inval){
return b2sLUT[inval];
}
/*
* output current velocity on the seven segement display
*/
void show_velocity_on_sevenseg(INT8S velocity){
int tmp = velocity;
int out;
INT8U out_high = 0;
INT8U out_low = 0;
INT8U out_sign = 0;
if(velocity < 0){
out_sign = int2seven(10);
tmp *= -1;
}else{
out_sign = int2seven(0);
}
out_high = int2seven(tmp / 10);
out_low = int2seven(tmp - (tmp/10) * 10);
out = int2seven(0) << 21 |
out_sign << 14 |
out_high << 7 |
out_low;
IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_HEX_LOW28_BASE,out);
}
/*
* shows the target velocity on the seven segment display (HEX5, HEX4)
* when the cruise control is activated (0 otherwise)
*/
void show_target_velocity(INT8U target_vel)
{
}
/*
* indicates the position of the vehicle on the track with the four leftmost red LEDs
* LEDR17: [0m, 400m)
* LEDR16: [400m, 800m)
* LEDR15: [800m, 1200m)
* LEDR14: [1200m, 1600m)
* LEDR13: [1600m, 2000m)
* LEDR12: [2000m, 2400m]
*/
void show_position(INT16U position)
{
}
/*
* The function 'adjust_position()' adjusts the position depending on the
* acceleration and velocity.
*/
INT16U adjust_position(INT16U position, INT16S velocity,
INT8S acceleration, INT16U time_interval)
{
INT16S new_position = position + velocity * time_interval / 1000
+ acceleration / 2 * (time_interval / 1000) * (time_interval / 1000);
if (new_position > 24000) {
new_position -= 24000;
} else if (new_position < 0){
new_position += 24000;
}
show_position(new_position);
return new_position;
}
/*
* The function 'adjust_velocity()' adjusts the velocity depending on the
* acceleration.
*/
INT16S adjust_velocity(INT16S velocity, INT8S acceleration,
enum active brake_pedal, INT16U time_interval)
{
INT16S new_velocity;
INT8U brake_retardation = 200;
if (brake_pedal == off)
new_velocity = velocity + (float) (acceleration * time_interval) / 1000.0;
else {
if (brake_retardation * time_interval / 1000 > velocity)
new_velocity = 0;
else
new_velocity = velocity - brake_retardation * time_interval / 1000;
}
return new_velocity;
}
/*
* The task 'VehicleTask' updates the current velocity of the vehicle
*/
void VehicleTask(void* pdata)
{
INT8U err;
void* msg;
INT8U* throttle;
INT8S acceleration; /* Value between 40 and -20 (4.0 m/s^2 and -2.0 m/s^2) */
INT8S retardation; /* Value between 20 and -10 (2.0 m/s^2 and -1.0 m/s^2) */
INT16U position = 0; /* Value between 0 and 20000 (0.0 m and 2000.0 m) */
INT16S velocity = 0; /* Value between -200 and 700 (-20.0 m/s amd 70.0 m/s) */
INT16S wind_factor; /* Value between -10 and 20 (2.0 m/s^2 and -1.0 m/s^2) */
printf("Vehicle task created!\n");
while(1)
{
err = OSMboxPost(Mbox_Velocity, (void *) &velocity);
OSTimeDlyHMSM(0,0,0,VEHICLE_PERIOD);
/* Non-blocking read of mailbox:
- message in mailbox: update throttle
- no message: use old throttle
*/
msg = OSMboxPend(Mbox_Throttle, 1, &err);
if (err == OS_NO_ERR)
throttle = (INT8U*) msg;
/* Retardation : Factor of Terrain and Wind Resistance */
if (velocity > 0)
wind_factor = velocity * velocity / 10000 + 1;
else
wind_factor = (-1) * velocity * velocity / 10000 + 1;
if (position < 4000)
retardation = wind_factor; // even ground
else if (position < 8000)
retardation = wind_factor + 15; // traveling uphill
else if (position < 12000)
retardation = wind_factor + 25; // traveling steep uphill
else if (position < 16000)
retardation = wind_factor; // even ground
else if (position < 20000)
retardation = wind_factor - 10; //traveling downhill
else
retardation = wind_factor - 5 ; // traveling steep downhill
acceleration = *throttle / 2 - retardation;
position = adjust_position(position, velocity, acceleration, 300);
velocity = adjust_velocity(velocity, acceleration, brake_pedal, 300);
printf("Position: %dm\n", position / 10);
printf("Velocity: %4.1fm/s\n", velocity /10.0);
printf("Throttle: %dV\n", *throttle / 10);
show_velocity_on_sevenseg((INT8S) (velocity / 10));
}
}
/*
* The task 'ControlTask' is the main task of the application. It reacts
* on sensors and generates responses.
*/
void ControlTask(void* pdata)
{
INT8U err;
INT8U throttle = 40; /* Value between 0 and 80, which is interpreted as between 0.0V and 8.0V */
void* msg;
INT16S* current_velocity;
printf("Control Task created!\n");
while(1)
{
msg = OSMboxPend(Mbox_Velocity, 0, &err);
current_velocity = (INT16S*) msg;
err = OSMboxPost(Mbox_Throttle, (void *) &throttle);
OSTimeDlyHMSM(0,0,0, CONTROL_PERIOD);
}
}
/*
* The task 'StartTask' creates all other tasks kernel objects and
* deletes itself afterwards.
*/
void StartTask(void* pdata)
{
INT8U err;
void* context;
static alt_alarm alarm; /* Is needed for timer ISR function */
/* Base resolution for SW timer : HW_TIMER_PERIOD ms */
delay = alt_ticks_per_second() * HW_TIMER_PERIOD / 1000;
printf("delay in ticks %d\n", delay);
/*
* Create Hardware Timer with a period of 'delay'
*/
if (alt_alarm_start (&alarm,
delay,
alarm_handler,
context) < 0)
{
printf("No system clock available!n");
}
/*
* Create and start Software Timer
*/
SWTimer = OSTmrCreate(0,
CONTROL_PERIOD/(4*OS_TMR_CFG_TICKS_PER_SEC),
OS_TMR_OPT_PERIODIC,
ContextSwitch,
NULL,
NULL,
&err);
if (err == OS_ERR_NONE) {
/* Timer was created but NOT started */
printf("SWTimer was created but NOT started \n");
}
status = OSTmrStart(SWTimer,
&err);
if (err == OS_ERR_NONE) {
/* Timer was started */
printf("SWTimer was started!\n");
}
/*
* Creation of Kernel Objects
*/
// Mailboxes
Mbox_Throttle = OSMboxCreate((void*) 0); /* Empty Mailbox - Throttle */
Mbox_Velocity = OSMboxCreate((void*) 0); /* Empty Mailbox - Velocity */
/*
* Create statistics task
*/
OSStatInit();
/*
* Creating Tasks in the system
*/
err = OSTaskCreateExt(
ControlTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&ControlTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
CONTROLTASK_PRIO,
CONTROLTASK_PRIO,
(void *)&ControlTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
err = OSTaskCreateExt(
VehicleTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&VehicleTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
VEHICLETASK_PRIO,
VEHICLETASK_PRIO,
(void *)&VehicleTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
printf("All Tasks and Kernel Objects generated!\n");
/* Task deletes itself */
OSTaskDel(OS_PRIO_SELF);
}
/*
*
* The function 'main' creates only a single task 'StartTask' and starts
* the OS. All other tasks are started from the task 'StartTask'.
*
*/
int main(void) {
printf("Cruise Control\n");
aSemaphore = OSSemCreate(1); // binary semaphore (1 key)
OSTaskCreateExt(
StartTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
(void *)&StartTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
STARTTASK_PRIO,
STARTTASK_PRIO,
(void *)&StartTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);
OSStart();
return 0;
}
Running the above program the callback contextswitch is executed but it doesn't yet solve the problem of using timers instead of the builtin yield and how to apply it with semaphores.
Cruise Control
delay in ticks 100
SWTimer was created but NOT started
SWTimer was started!
All Tasks and Kernel Objects generated!
Vehicle task created!
Control Task created!
ContextSwitch!
Position: 0m
Velocity: 0.5m/s
Throttle: 4V
ContextSwitch!
Position: 0m
Velocity: 1.0m/s
Throttle: 4V
Position: 0m
Velocity: 1.5m/s
Throttle: 4V
ContextSwitch!
Position: 0m
Velocity: 2.0m/s
Throttle: 4V
ContextSwitch!
Position: 1m
Velocity: 2.5m/s
Throttle: 4V
ContextSwitch!
Position: 2m
Velocity: 3.0m/s
Throttle: 4V
ContextSwitch!
Update 141001 15:57 CET
2 semaphores + 2 timers seem like a good improvement. I hope it can be checked or tested...
#include <stdio.h>
#include "system.h"
#include "includes.h"
#include "altera_avalon_pio_regs.h"
#include "sys/alt_irq.h"
#include "sys/alt_alarm.h"
#define DEBUG 1
#define HW_TIMER_PERIOD 100 /* 100ms */
/* Button Patterns */
#define GAS_PEDAL_FLAG 0x08
#define BRAKE_PEDAL_FLAG 0x04
#define CRUISE_CONTROL_FLAG 0x02
/* Switch Patterns */
#define TOP_GEAR_FLAG 0x00000002
#define ENGINE_FLAG 0x00000001
/* LED Patterns */
#define LED_RED_0 0x00000001 // Engine
#define LED_RED_1 0x00000002 // Top Gear
#define LED_GREEN_0 0x0001 // Cruise Control activated
#define LED_GREEN_2 0x0002 // Cruise Control Button
#define LED_GREEN_4 0x0010 // Brake Pedal
#define LED_GREEN_6 0x0040 // Gas Pedal
/*
* Definition of Tasks
*/
#define TASK_STACKSIZE 2048
OS_STK StartTask_Stack[TASK_STACKSIZE];
OS_STK ControlTask_Stack[TASK_STACKSIZE];
OS_STK VehicleTask_Stack[TASK_STACKSIZE];
// Task Priorities
#define STARTTASK_PRIO 5
#define VEHICLETASK_PRIO 10
#define CONTROLTASK_PRIO 12
// Task Periods
#define CONTROL_PERIOD 300
#define VEHICLE_PERIOD 300
/*
* Definition of Kernel Objects
*/
// Mailboxes
OS_EVENT *Mbox_Throttle;
OS_EVENT *Mbox_Velocity;
// Semaphores
OS_EVENT *aSemaphore;
OS_EVENT *aSemaphore2;
// SW-Timer
OS_TMR *SWTimer;
OS_TMR *SWTimer1;
BOOLEAN status;
/*
* Types
*/
enum active {on, off};
enum active gas_pedal = off;
enum active brake_pedal = off;
enum active top_gear = off;
enum active engine = off;
enum active cruise_control = off;
/*
* Global variables
*/
int delay; // Delay of HW-timer
INT16U led_green = 0; // Green LEDs
INT32U led_red = 0; // Red LEDs
int sharedMemory=1;
void TimerCallback(params)
{
// Post to the semaphore to signal that it's time to run the task.
OSSemPost(aSemaphore); // Releasing the key
}
void ContextSwitch()
{
printf("ContextSwitch!\n");
sharedMemory=sharedMemory*-1;
}
int buttons_pressed(void)
{
return ~IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_KEYS4_BASE);
}
int switches_pressed(void)
{
return IORD_ALTERA_AVALON_PIO_DATA(DE2_PIO_TOGGLES18_BASE);
}
/*
* ISR for HW Timer
*/
alt_u32 alarm_handler(void* context)
{
OSTmrSignal(); /* Signals a 'tick' to the SW timers */
return delay;
}
void release()
{
printf("release key!\n");
//OSSemPost(aSemaphore); // Releasing the key
OSSemPost(aSemaphore2); // Releasing the key
printf("released key!\n");
}
void release2()
{
printf("release2!\n");
OSSemPost(aSemaphore2); // Releasing the key
printf("release2!\n");
}
static int b2sLUT[] = {0x40, //0
0x79, //1
0x24, //2
0x30, //3
0x19, //4
0x12, //5
0x02, //6
0x78, //7
0x00, //8
0x18, //9
0x3F, //-
};
/*
* convert int to seven segment display format
*/
int int2seven(int inval){
return b2sLUT[inval];
}
/*
* output current velocity on the seven segement display
*/
void show_velocity_on_sevenseg(INT8S velocity){
int tmp = velocity;
int out;
INT8U out_high = 0;
INT8U out_low = 0;
INT8U out_sign = 0;
if(velocity < 0){
out_sign = int2seven(10);
tmp *= -1;
}else{
out_sign = int2seven(0);
}
out_high = int2seven(tmp / 10);
out_low = int2seven(tmp - (tmp/10) * 10);
out = int2seven(0) << 21 |
out_sign << 14 |
out_high << 7 |
out_low;
IOWR_ALTERA_AVALON_PIO_DATA(DE2_PIO_HEX_LOW28_BASE,out);
}
/*
* shows the target velocity on the seven segment display (HEX5, HEX4)
* when the cruise control is activated (0 otherwise)
*/
void show_target_velocity(INT8U target_vel)
{
}
/*
* indicates the position of the vehicle on the track with the four leftmost red LEDs
* LEDR17: [0m, 400m)
* LEDR16: [400m, 800m)
* LEDR15: [800m, 1200m)
* LEDR14: [1200m, 1600m)
* LEDR13: [1600m, 2000m)
* LEDR12: [2000m, 2400m]
*/
void show_position(INT16U position)
{
}
/*
* The function 'adjust_position()' adjusts the position depending on the
* acceleration and velocity.
*/
INT16U adjust_position(INT16U position, INT16S velocity,
INT8S acceleration, INT16U time_interval)
{
INT16S new_position = position + velocity * time_interval / 1000
+ acceleration / 2 * (time_interval / 1000) * (time_interval / 1000);
if (new_position > 24000) {
new_position -= 24000;
} else if (new_position < 0){
new_position += 24000;
}
show_position(new_position);
return new_position;
}
/*
* The function 'adjust_velocity()' adjusts the velocity depending on the
* acceleration.
*/
INT16S adjust_velocity(INT16S velocity, INT8S acceleration,
enum active brake_pedal, INT16U time_interval)
{
INT16S new_velocity;
INT8U brake_retardation = 200;
if (brake_pedal == off)
new_velocity = velocity + (float) (acceleration * time_interval) / 1000.0;
else {
if (brake_retardation * time_interval / 1000 > velocity)
new_velocity = 0;
else
new_velocity = velocity - brake_retardation * time_interval / 1000;
}
return new_velocity;
}
/*
* The task 'VehicleTask' updates the current velocity of the vehicle
*/
void VehicleTask(void* pdata)
{
INT8U err;
void* msg;
INT8U* throttle;
INT8S acceleration; /* Value between 40 and -20 (4.0 m/s^2 and -2.0 m/s^2) */
INT8S retardation; /* Value between 20 and -10 (2.0 m/s^2 and -1.0 m/s^2) */
INT16U position = 0; /* Value between 0 and 20000 (0.0 m and 2000.0 m) */
INT16S velocity = 0; /* Value between -200 and 700 (-20.0 m/s amd 70.0 m/s) */
INT16S wind_factor; /* Value between -10 and 20 (2.0 m/s^2 and -1.0 m/s^2) */
printf("Vehicle task created!\n");
// Create a semaphore to represent the "it's time to run" event.
// Initialize the semaphore count to zero because it's not time
// to run yet.
// Create a periodic software timer which calls TimerCallback()
// when it expires.
/*
* Create and start Software Timer
*/
SWTimer1 = OSTmrCreate(0,
CONTROL_PERIOD/(4*OS_TMR_CFG_TICKS_PER_SEC),
OS_TMR_OPT_PERIODIC,
TimerCallback,
NULL,
NULL,
&err);
if (err == OS_ERR_NONE) {
/* Timer was created but NOT started */
printf("SWTimer1 was created but NOT started \n");
}
status = OSTmrStart(SWTimer1,
&err);
if (err == OS_ERR_NONE) {
/* Timer was started */
printf("SWTimer1 was started!\n");
}
while(1)
{
OSSemPend(aSemaphore, 0, &err); // Trying to access the key
err = OSMboxPost(Mbox_Velocity, (void *) &velocity);
//OSTimeDlyHMSM(0,0,0,VEHICLE_PERIOD);
/* Non-blocking read of mailbox:
- message in mailbox: update throttle
- no message: use old throttle
*/
msg = OSMboxPend(Mbox_Throttle, 1, &err);
if (err == OS_NO_ERR)
throttle = (INT8U*) msg;
/* Retardation : Factor of Terrain and Wind Resistance */
if (velocity > 0)
wind_factor = velocity * velocity / 10000 + 1;
else
wind_factor = (-1) * velocity * velocity / 10000 + 1;
if (position < 4000)
retardation = wind_factor; // even ground
else if (position < 8000)
retardation = wind_factor + 15; // traveling uphill
else if (position < 12000)
retardation = wind_factor + 25; // traveling steep uphill
else if (position < 16000)
retardation = wind_factor; // even ground
else if (position < 20000)
retardation = wind_factor - 10; //traveling downhill
else
retardation = wind_factor - 5 ; // traveling steep downhill
acceleration = *throttle / 2 - retardation;
position = adjust_position(position, velocity, acceleration, 300);
velocity = adjust_velocity(velocity, acceleration, brake_pedal, 300);
printf("Position: %dm\n", position / 10);
printf("Velocity: %4.1fm/s\n", velocity /10.0);
printf("Throttle: %dV\n", *throttle / 10);
show_velocity_on_sevenseg((INT8S) (velocity / 10));
//OSSemPost(aSemaphore); // Releasing the key
}
}
/*
* The task 'ControlTask' is the main task of the application. It reacts
* on sensors and generates responses.
*/
void ControlTask(void* pdata)
{
INT8U err;
INT8U throttle = 40; /* Value between 0 and 80, which is interpreted as between 0.0V and 8.0V */
void* msg;
INT16S* current_velocity;
printf("Control Task created!\n");
while(1)
{
OSSemPend(aSemaphore2, 0, &err); // Trying to access the key
msg = OSMboxPend(Mbox_Velocity, 0, &err);
current_velocity = (INT16S*) msg;
printf("Control Task!\n");
err = OSMboxPost(Mbox_Throttle, (void *) &throttle);
//OSSemPost(aSemaphore2); // Releasing the key
//OSTimeDlyHMSM(0,0,0, CONTROL_PERIOD);
}
}
/*
* The task 'StartTask' creates all other tasks kernel objects and
* deletes itself afterwards.
*/
void StartTask(void* pdata)
{
INT8U err;
void* context;
static alt_alarm alarm; /* Is needed for timer ISR function */
/* Base resolution for SW timer : HW_TIMER_PERIOD ms */
delay = alt_ticks_per_second() * HW_TIMER_PERIOD / 1000;
printf("delay in ticks %d\n", delay);
/*
* Create Hardware Timer with a period of 'delay'
*/
if (alt_alarm_start (&alarm,
delay,
alarm_handler,
context) < 0)
{
printf("No system clock available!n");
}
/*
* Create and start Software Timer
*/
SWTimer = OSTmrCreate(0,
CONTROL_PERIOD/(4*OS_TMR_CFG_TICKS_PER_SEC),
OS_TMR_OPT_PERIODIC,
release,
NULL,
NULL,
&err);
if (err == OS_ERR_NONE) {
/* Timer was created but NOT started */
printf("SWTimer was created but NOT started \n");
}
status = OSTmrStart(SWTimer,
&err);
if (err == OS_ERR_NONE) {
/* Timer was started */
printf("SWTimer was started!\n");
}
/*
* Creation of Kernel Objects
*/
// Mailboxes
Mbox_Throttle = OSMboxCreate((void*) 0); /* Empty Mailbox - Throttle */
Mbox_Velocity = OSMboxCreate((void*) 0); /* Empty Mailbox - Velocity */
/*
* Create statistics task
*/
OSStatInit();
/*
* Creating Tasks in the system
*/
err = OSTaskCreateExt(
ControlTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&ControlTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
CONTROLTASK_PRIO,
CONTROLTASK_PRIO,
(void *)&ControlTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
err = OSTaskCreateExt(
VehicleTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
&VehicleTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
VEHICLETASK_PRIO,
VEHICLETASK_PRIO,
(void *)&VehicleTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK);
printf("All Tasks and Kernel Objects generated!\n");
/* Task deletes itself */
OSTaskDel(OS_PRIO_SELF);
}
/*
*
* The function 'main' creates only a single task 'StartTask' and starts
* the OS. All other tasks are started from the task 'StartTask'.
*
*/
int main(void) {
printf("Cruise Control 2014\n");
aSemaphore = OSSemCreate(1); // binary semaphore (1 key)
aSemaphore2 = OSSemCreate(0); // binary semaphore (1 key)
OSTaskCreateExt(
StartTask, // Pointer to task code
NULL, // Pointer to argument that is
// passed to task
(void *)&StartTask_Stack[TASK_STACKSIZE-1], // Pointer to top
// of task stack
STARTTASK_PRIO,
STARTTASK_PRIO,
(void *)&StartTask_Stack[0],
TASK_STACKSIZE,
(void *) 0,
OS_TASK_OPT_STK_CHK | OS_TASK_OPT_STK_CLR);
OSStart();
return 0;
}
Output:
Cruise Control 2014
delay in ticks 100
SWTimer was created but NOT started
SWTimer was started!
All Tasks and Kernel Objects generated!
Vehicle task created!
SWTimer1 was created but NOT started
SWTimer1 was started!
Control Task created!
Position: 0m
Velocity: 0.4m/s
Throttle: 3V
release key!
released key!
Control Task!
Position: 0m
Velocity: 0.9m/s
Throttle: 4V
release key!
released key!
Control Task!
Position: 0m
Velocity: 1.4m/s
My impression is that you have two tasks that you want to run at regular intervals. And you want to accomplish this with a software timer and semaphore. If that's correct then you can accomplish this as follows.
Each task will use it's own semaphore and timer. A semaphore can be used as a signal that an event has occurred. In this case use the semaphore to indicate that the timer has expired and it's time for the task to run. Set up the software timer to expire periodically and call a callback function. The callback function should post to the semaphore. The task should pend on the semaphore within its while loop. This way the task runs one iteration through the loop every time the timer expires.
Here is some psuedo-code:
void TimerCallback(params)
{
// Post to the semaphore to signal that it's time to run the task.
}
void TaskFunction(void)
{
// Create a semaphore to represent the "it's time to run" event.
// Initialize the semaphore count to zero because it's not time
// to run yet.
// Create a periodic software timer which calls TimerCallback()
// when it expires.
while(1)
{
// Wait until it's time to run by pending on the semaphore.
// Do task specific stuff.
}
}
The periodic nature of this software-timer-and-semaphore implementation is more precise than using OSTimeDlyHMSM(). The reason is that the software timer period runs independent of the execution time of the task. But the period of OSTimeDlyHMSM() is in addition to the execution time of the task. And the execution time of the task may vary from one iteration to the next if it is preempted by other tasks or interrupts. So using OSTimeDlyHMSM() is not a very precise way to get a periodic event.
OSTimeDlyHMSM() This call allows you to specify the delay time in HOURS,
MINUTES, SECONDS and MILLISECONDS instead of ticks. This means you don't let a task work until a proper time is out. Even when all other task worked and/or the CPU is "free" your task is not going to continue its work until the proper time ticks, in your case seconds or whatever, are out. If you really need an event to be happened after such a "big" time, its still worth using this of course.
However the approach of timer usage should not be messed up with Semaphores. The latter are used against data violation and to protect shared resource or critical sections of code from multiple reentrance.
Without deep digging into your code, I would suggest to try to organize your system with OSTimeDly() where possible. As for semaphores, use them when you have a situation that more than one task can call the same function asynchronously or access the same resource like memory,registers, data buses or any hardware.
The problem with both OSTimeDlyHMSM() and OSTimeDly() for periodic processes is that they do not take into account the processing time of the rest of the thread. For example in:
// Task loop
for(;;)
{
OSTimeDly( 100 ) ;
doStuffHere() ;
}
You migh expect doStuffHere() to run every 100 ticks, which it will unless doStuffHere() itself takes longer the 1 tick period. It may for example itself contain a delay, or block on some other event.
// Task loop
for(;;)
{
OSTimeDly( 100 ) ;
doStuffHere() ;
}
By using a timer, this can be overcome:
// Note this is illustrative and not uC/OS-II code
timer_handle = createTimer( 100, PERIODIC ) ;
// Task loop
for(;;)
{
waitForTimer( timer_handle ) ;
doStuffHere() ;
}
Here, doStuffHere() only needs to take less than 100 ticks for the loop to be exactly periodic - that is far better than one tick.
All that said if you can guarantee that that doStuffHere() will take less than one tick - even when pre-empted by higher priority tasks, then a delay is much simpler.
A further advantage of using a timer on the other hand is that a blocking on a delay can only react to expiry of the delay, whereas a task blocking on a semaphore can react to any event that gives the semaphore, so can be caused to run on multiple events including the timer. Similarly for other IPC mechanisms such as queues or event flags.

Resources