c - 在嵌入式 C 编程中检查 GPIO 状态
问题描述
我们有一个嵌入式 C 编程任务,我们必须实现一个状态机,该状态机根据操纵杆输入改变一系列 LED。其中两个条件是:“如果左侧 LED 亮起并且按下向下,则更改为右侧 LED”和“如果右侧 LED 亮起并且按下向下,则更改为左侧 LED”。我知道如何在按下按钮时打开某些 LED,但我不知道如何检查 GPIO 引脚/LED 的状态并根据使用操纵杆时的状态更改另一个 LED。我基本上只是想知道如何“调用” LED 的状态。
这是目前的状态机示例代码:
void
StateMachine ()
{
// REPLACE THE FOLLOW CODE WITH YOUR SOLUTION
// This code just toggles top LED and set left or right LED.
//
// Solution.
uint8_t Joystick;
uint8_t Toggle = 0;
while (1)
{
Joystick = GetJoystick();
if (Joystick == 'L')
{
WriteLED ('L', LED_ON);
WriteLED ('R', LED_OFF);
}
else if (Joystick == 'R')
{
WriteLED ('L', LED_OFF);
WriteLED ('R', LED_ON);
}
if (Toggle == 0)
{
WriteLED ('T', LED_ON);
Toggle = 1;
}
else
{
WriteLED ('T', LED_OFF);
Toggle = 0;
}
}
}
更新:这是我的WriteLED
方法
void
WriteLED (uint8_t LED, uint8_t State)
{
// Check for correct state
if ((State != LED_OFF) && (State != LED_ON))
{
return;
}
// Turn on/off the LED
switch (LED)
{
case 'L':
HAL_GPIO_WritePin (LD4_GPIO_Port, LD4_Pin, State);
break;
case 'T':
HAL_GPIO_WritePin (LD3_GPIO_Port, LD3_Pin, State);
break;
case 'B':
HAL_GPIO_WritePin (LD6_GPIO_Port, LD6_Pin, State);
break;
case 'R':
HAL_GPIO_WritePin (LD5_GPIO_Port, LD5_Pin, State);
break;
}
return;
}
解决方案
如果任务特别要求“状态机”,那么软件应该以某种方式具有对应于不同 LED 输出要求的不同内部“状态”。有很多方法可以表示状态机——(你看到过一种吗?)——例如:
// enumeration of the required states
enum OutputState {
stateAllOff, // I'm *guessing* this is the required initial state?
stateLeftLED,
stateRightLED,
// ... any other states that are specified.
// ... but *not* random combinations of LEDs that are not part of the specification.
};
enum OutputState currentState = stateAllOff; // or whatever initial state is required
// [...] I'm not going to do the actual assignment here
状态机不必读取 LED 状态,它只是在currentState
变量中“记住”它们。现在剩下的代码变成了你给定条件的直接实现,所以......
“如果左侧 LED 亮起并且按下向下,则更改为右侧 LED”
if (currentState == stateLeftLED) {
if (Joystick == "D") {
WriteLED ('R', LED_ON);
WriteLED ('L', LED_OFF);
currentState = stateRightLED;
}
}