基于mbed使用ps2摇杆模块的代码
时间: 2024-01-24 15:02:19 浏览: 116
以下是一个基于mbed的使用PS2摇杆模块的示例代码,可以供您参考:
```C++
#include "mbed.h"
#define PS2_DAT PTE4
#define PS2_CMD PTE5
#define PS2_SEL PTE6
#define PS2_CLK PTE7
DigitalIn ps2dat(PS2_DAT);
DigitalOut ps2cmd(PS2_CMD);
DigitalOut ps2sel(PS2_SEL);
DigitalIn ps2clk(PS2_CLK);
void ps2_write(unsigned char data)
{
unsigned char parity = 1;
ps2cmd = 0;
wait_us(100);
ps2clk = 0;
wait_us(100);
ps2dat = 0;
wait_us(100);
ps2clk = 1;
wait_us(10);
ps2dat = 1;
wait_us(10);
ps2clk = 0;
for (int i = 0; i < 8; i++) {
if (data & 1) {
ps2dat = 1;
} else {
ps2dat = 0;
}
parity = parity ^ (data & 1);
wait_us(10);
ps2clk = 1;
wait_us(10);
ps2clk = 0;
data >>= 1;
}
if (parity) {
ps2dat = 1;
} else {
ps2dat = 0;
}
wait_us(10);
ps2clk = 1;
wait_us(10);
ps2clk = 0;
ps2dat = 1;
wait_us(10);
ps2cmd = 1;
wait_us(100);
}
unsigned char ps2_read()
{
unsigned char data = 0;
unsigned char parity = 1;
ps2cmd = 1;
wait_us(100);
ps2clk = 1;
wait_us(10);
while (ps2clk) {
wait_us(10);
}
for (int i = 0; i < 8; i++) {
wait_us(10);
ps2clk = 0;
wait_us(10);
data >>= 1;
if (ps2dat) {
data |= 0x80;
parity = parity ^ 1;
}
ps2clk = 1;
}
wait_us(10);
ps2clk = 0;
wait_us(10);
if (ps2dat != parity) {
data = 0;
}
wait_us(100);
return data;
}
int main()
{
int x, y;
unsigned char data[3];
while (1) {
ps2sel = 0;
ps2cmd = 1;
ps2clk = 1;
wait_us(100);
ps2_write(0x01);
ps2_read();
ps2_read();
ps2_read();
data[0] = ps2_read();
data[1] = ps2_read();
data[2] = ps2_read();
ps2sel = 1;
x = data[0] - 128;
y = data[1] - 128;
if (x < -30) {
printf("Left\n");
}
if (x > 30) {
printf("Right\n");
}
if (y < -30) {
printf("Up\n");
}
if (y > 30) {
printf("Down\n");
}
wait_ms(100);
}
}
```
此代码使用mbed库来读取PS2摇杆模块的位置,并将其打印到终端上。您需要将代码中的引脚定义改为您使用的实际引脚。
阅读全文