关于STM32的joystick(五向开关)的一些代码分享
[复制链接]
关于JOYSTICK,之前有在GFX02Z1上面做过一些开发,正好可以用 Nathan Xi大佬的控制代码。
.Cpp文件:
/*
* MB1818ButtonController.cpp
*
* Created on: Apr 30, 2024
* Author: user
*/
#include <MB1818ButtonController.hpp>
#include <main.h>
#include <touchgfx/hal/HAL.hpp>
void MB1818ButtonController::init()
{
previousState = 0;
}
bool MB1818ButtonController::sample(uint8_t& key)
{
uint8_t state = getKeyState();
if (state == previousState)
{
return false;
}
previousState = state;
if (state != 0)
{
key = state;
return true;
}
return false;
}
//
uint8_t MB1818ButtonController::getKeyState(void)
{
uint8_t keyPressed = 0;
if (touchgfx::HAL::getInstance()->getDisplayOrientation() == touchgfx::ORIENTATION_PORTRAIT)
{
if (HAL_GPIO_ReadPin(KEY_CENTER_GPIO_Port, KEY_CENTER_Pin) == GPIO_PIN_RESET)
{
keyPressed = '5'; // Corresponds to keyboard keypad center
}
else if (HAL_GPIO_ReadPin(KEY_LEFT_GPIO_Port, KEY_LEFT_Pin) == GPIO_PIN_RESET)
{
keyPressed = '4'; // Corresponds to keyboard keypad left
}
else if (HAL_GPIO_ReadPin(KEY_RIGHT_GPIO_Port, KEY_RIGHT_Pin) == GPIO_PIN_RESET)
{
keyPressed = '6'; // Corresponds to keyboard keypad right
}
else if (HAL_GPIO_ReadPin(KEY_UP_GPIO_Port, KEY_UP_Pin) == GPIO_PIN_RESET)
{
keyPressed = '8'; // Corresponds to keyboard keypad up
}
else if (HAL_GPIO_ReadPin(KEY_DOWN_GPIO_Port, KEY_DOWN_Pin) == GPIO_PIN_RESET)
{
keyPressed = '2'; // Corresponds to keyboard keypad down
}
//Blue user button on Nucleo boad
else if (HAL_GPIO_ReadPin(BUTTON_USER_GPIO_Port, BUTTON_USER_Pin) == GPIO_PIN_RESET)
{
keyPressed = '0';
}
}
else
{
if (HAL_GPIO_ReadPin(KEY_CENTER_GPIO_Port, KEY_CENTER_Pin) == GPIO_PIN_RESET)
{
keyPressed = '5'; // Corresponds to keyboard keypad enter
}
else if (HAL_GPIO_ReadPin(KEY_LEFT_GPIO_Port, KEY_LEFT_Pin) == GPIO_PIN_RESET)
{
keyPressed = '8'; // Corresponds to keyboard keypad up
}
else if (HAL_GPIO_ReadPin(KEY_RIGHT_GPIO_Port, KEY_RIGHT_Pin) == GPIO_PIN_RESET)
{
keyPressed = '2'; // Corresponds to keyboard keypad down
}
else if (HAL_GPIO_ReadPin(KEY_UP_GPIO_Port, KEY_UP_Pin) == GPIO_PIN_RESET)
{
keyPressed = '6'; // Corresponds to keyboard keypad right
}
else if (HAL_GPIO_ReadPin(KEY_DOWN_GPIO_Port, KEY_DOWN_Pin) == GPIO_PIN_RESET)
{
keyPressed = '4'; // Corresponds to keyboard keypad left
}
//Blue user button on Nucleo boad
else if (HAL_GPIO_ReadPin(BUTTON_USER_GPIO_Port, BUTTON_USER_Pin) == GPIO_PIN_RESET)
{
keyPressed = '0';
}
}
return keyPressed;
}
.hpp文件:
/*
* MB1818ButtonController.hpp
*
* Created on: Apr 30, 2024
* Author: user
*/
#ifndef APPLICATION_USER_CORE_MB1818BUTTONCONTROLLER_HPP_
#define APPLICATION_USER_CORE_MB1818BUTTONCONTROLLER_HPP_
#include <platform/driver/button/ButtonController.hpp>
class MB1818ButtonController : public touchgfx::ButtonController
{
virtual void init();
virtual bool sample(uint8_t& key);
private:
uint8_t getKeyState(void);
uint8_t previousState;
};
#endif /* APPLICATION_USER_CORE_MB1818BUTTONCONTROLLER_HPP_ */
不过要注意的一点是,这部分代码是给TOUCHGFX用的C++代码,具体使用的时候要适当修改
|