在嵌入式 C 编程中检查 GPIO 状态

标签 c embedded 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 变量中。现在剩下的代码就变成了对给定条件的直接实现,所以...

"if Left LED is on and Down is Pressed Change to Right LED"

    if (currentState == stateLeftLED) {
        if (Joystick == "D") {
            WriteLED ('R', LED_ON);
            WriteLED ('L', LED_OFF);
            currentState = stateRightLED;
        }
    }

关于在嵌入式 C 编程中检查 GPIO 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55489106/

相关文章:

c - Raspberry PI、GPIO 带 SYSFS 的上拉/下拉电阻

c++ - 使用 C++ 的 GPIO 引脚 RaspberryPi

c++ - 如何将系统命令输出存储在变量中?

c - C 中的输出文本 block

programming-languages - 有哪些可用的在微小内存中运行的交互式语言?

c - Atmega1 6's PORTs don' 工作

c - ioctl 和执行时间

python - 树莓派 RS485/Uart Modbus

c++ - 从自己的程序中获取程序元数据

c - fork 调用子进程和父进程后,值会有什么不同?