2020-05-16 09:50 PM
Good day guys I am trying to learn the delay to activate output. I found a tutorial on the timer delay. I defined the delay as 5ms. I found that the code works on a single GPIO.
Now I wanted to activate 2 GPIOs with each having their own 5ms delay. Now problem happens when I activate LED_GPIO2 when LED_GPIO1 is already activated prior to activating LED_GPIO2. The delay becomes more than 5msec for the LED_GPIO2.
May I ask how to write the code so that both codes are independent of each other. Thank you very much for your time.
/*Define the function*/
void timedelay(int delay)
{
TIM2 -> CR1 |= TIM_CR1_CEN;
myticks = 0;
while(myticks < delay);
TIM2 -> CR1 &= ~TIM_CR1_CEN;
}
/*Define Callback of TIM2*/
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if(htim -> Instance == TIM2)
{
myticks++;
TIM2 -> SR &= ~TIM_SR_UIF;
}
}
/*Main code*/
while (1)
{
{
if(HAL_GPIO_ReadPin(BUTTON_GPIO1_GPIO_Port, BUTTON_GPIO1_Pin))
{
timedelay(5); //delay equals 5ms
HAL_GPIO_WritePin(LED_GPIO1_GPIO_Port, LED_GPIO1_Pin, GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(LED_GPIO1_GPIO_Port, LED_GPIO1_Pin, GPIO_PIN_RESET);
}
}
{
if(HAL_GPIO_ReadPin(BUTTON_GPIO2_GPIO_Port, BUTTON_GPIO2_Pin))
{
timedelay(5); //delay equals 5ms
HAL_GPIO_WritePin(LED_GPIO2_GPIO_Port, LED_GPIO2_Pin, GPIO_PIN_SET);
}
else
{
HAL_GPIO_WritePin(LED_GPIO2_GPIO_Port, LED_GPIO2_Pin, GPIO_PIN_RESET);
}
}
}
2020-05-17 12:59 AM
There are many way how to accomplish this, depending on how precise you want the timing and on other circumstances of the application.
One way of doing it would be to leave the timer running all the time, with perhaps having myticks incremented in the interrupt as it is now; then
t1 = 0; t2 = 0; ticks = 0; myticks = 0;
EnableTimer();
while(1) {
if (ticks != myticks) { // i.e. the following is executed only once in a ms
ticks++; // i.e. go with ticks in the direction of myticks
if (Button1Down()) {
if (t1 <= 5) { // still counting up?
if (t1 == 5) {
Led1On(); // finished counting, do action
}
t1++;
}
} else {
if (t1 != 0) {
Led1Off();
t1 = 0;
}
}
if (Button2Down()) {
if (t2 <= 5) { // still counting up?
if (t2 == 5) {
Led2On(); // finished counting, do action
}
t2++;
}
} else {
if (t2 != 0) {
Led2Off();
t2 = 0;
}
}
}
}
Note, that the resulting delay will be between 5ms and 6ms, depending on when exactly the button was pressed related to the timer interrupt "ticking".
JW
2020-05-17 04:02 AM
Thank you for the hint Sir!