“按下P1^4,LED闪烁时间加快,按下时间越长,闪烁频率越快。 释放开关,频率固定停在当前值闪烁。这才是编程思维挑战“
首先声明:对于这里的多数人,这当然不是什么编程思维挑战,只不过有人一定要这么说,为了说明这个论坛水平,我这个中低手做了这么一段C代码在visual c++ 的演示,供辉阳的心等初学者参考。我相信有更多的人能做出比这更好的代码。因此,敬请某些人不必再怀疑本论坛众人的智商。
class CLEDTestDlg : public CDialog { struct LEDStatus { int frequency; int counter; bool status; } m_LEDStatus;
enum Keyboard { NOKEY, LEFTKEY, RIGHTKEY } KEYBOARD;
struct KeyStatus { Keyboard key; Keyboard pressedKey; int keyState; int keyTimer; bool keyEventHandled; } m_KeyStatus;
CStatic LED1; //模仿LED 闪烁。
********************************************************************** BOOL CLEDTestDlg::OnInitDialog() { CDialog::OnInitDialog(); this->SetTimer(1, 20, NULL); //用定时器模仿定时中断。 m_LEDStatus.frequency = 50; //1 second; m_LEDStatus.counter = 0; m_KeyStatus.key = NOKEY; m_KeyStatus.pressedKey = NOKEY; m_KeyStatus.keyState = 0; return TRUE; }
void CLEDTestDlg::OnTimer(UINT_PTR nIDEvent) //定时中断 { BlinkLED(); DetectKeyPress(); }
void CLEDTestDlg::BlinkLED() { if (++m_LEDStatus.counter >= m_LEDStatus.frequency) { m_LEDStatus.counter = 0; LED1.SetWindowText(m_LEDStatus.status ? " " : "*"); //Led 闪烁。 m_LEDStatus.status = !m_LEDStatus.status; }
if (m_KeyStatus.key != NOKEY && !m_KeyStatus.keyEventHandled) { m_KeyStatus.keyEventHandled = true; if (m_KeyStatus.key == LEFTKEY) { m_LEDStatus.frequency -= 10; if (m_LEDStatus.frequency <= 0) m_LEDStatus.frequency = 0; } else if (m_KeyStatus.key == RIGHTKEY) { m_LEDStatus.frequency += 10; if (m_LEDStatus.frequency >= 500) m_LEDStatus.frequency = 500; } } }
void CLEDTestDlg::DetectKeyPress() //模仿键盘处理过程 { switch (m_KeyStatus.keyState) { case 0: if (m_KeyStatus.pressedKey != NOKEY) m_KeyStatus.keyState++; //去抖动 break; case 1: if (m_KeyStatus.pressedKey == NOKEY) m_KeyStatus.keyState--; else { m_KeyStatus.key = m_KeyStatus.pressedKey; m_KeyStatus.keyEventHandled = false; m_KeyStatus.keyTimer = 100; //2 seconds m_KeyStatus.keyState++; } break; case 2: if (m_KeyStatus.key != m_KeyStatus.pressedKey) { m_KeyStatus.keyState = 0; m_KeyStatus.key = NOKEY; } else { if (--m_KeyStatus.keyTimer == 0) { m_KeyStatus.keyTimer = 50; // 1 second m_KeyStatus.keyEventHandled = false; } } break; default: m_KeyStatus.keyState = 0; } }
//处理鼠标左右键的按下 BOOL CLEDTestDlg::PreTranslateMessage(MSG* pMsg) { switch (pMsg->message) { case WM_LBUTTONDOWN: m_KeyStatus.pressedKey = LEFTKEY; break; case WM_RBUTTONDOWN: m_KeyStatus.pressedKey = RIGHTKEY; break; case WM_LBUTTONUP: case WM_RBUTTONUP: m_KeyStatus.pressedKey = NOKEY; break; } return CDialog::PreTranslateMessage(pMsg); }
欢迎讨论。
|