-
Notifications
You must be signed in to change notification settings - Fork 0
/
PS2Mouse.cpp
113 lines (90 loc) · 2.23 KB
/
PS2Mouse.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// (c) github.com/jazzycamel/PS2Mouse
#include "PS2Mouse.h"
PS2Mouse::PS2Mouse(int clk, int data){
_ps2clk=clk;
_ps2data=data;
gohi(_ps2clk);
gohi(_ps2data);
}
void PS2Mouse::write(uint8_t data){
uint8_t parity=1;
gohi(_ps2data);
gohi(_ps2clk);
delayMicroseconds(300);
golo(_ps2clk);
delayMicroseconds(300);
golo(_ps2data);
delayMicroseconds(10);
gohi(_ps2clk);
while(digitalRead(_ps2clk)==HIGH);
for(int i=0; i<8; i++){
if(data&0x01) gohi(_ps2data);
else golo(_ps2data);
while(digitalRead(_ps2clk)==LOW);
while(digitalRead(_ps2clk)==HIGH);
parity^=(data&0x01);
data=data>>1;
}
if(parity) gohi(_ps2data);
else golo(_ps2data);
while(digitalRead(_ps2clk)==LOW);
while(digitalRead(_ps2clk)==HIGH);
gohi(_ps2data);
delayMicroseconds(50);
while(digitalRead(_ps2clk)==HIGH);
while((digitalRead(_ps2clk)==LOW)||(digitalRead(_ps2data)==LOW));
golo(_ps2clk);
}
uint8_t PS2Mouse::read(void){
uint8_t data=0, bit=1;
gohi(_ps2clk);
gohi(_ps2data);
delayMicroseconds(50);
while(digitalRead(_ps2clk)==HIGH);
delayMicroseconds(5);
while(digitalRead(_ps2clk)==LOW);
for(int i=0; i<8; i++){
while(digitalRead(_ps2clk)==HIGH);
bit=digitalRead(_ps2data);
while(digitalRead(_ps2clk)==LOW);
bitWrite(data,i,bit);
}
while(digitalRead(_ps2clk)==HIGH);
while(digitalRead(_ps2clk)==LOW);
while(digitalRead(_ps2clk)==HIGH);
while(digitalRead(_ps2clk)==LOW);
golo(_ps2clk);
return data;
}
void PS2Mouse::begin(void){
write(0xFF); // reset, 100Hz
for(int i=0; i<2; i++) read(); // JB: changed from 3 reads to 2
write(0xF0); // set remote (poll) mode
read();
delayMicroseconds(100);
}
void PS2Mouse::getPosition(uint8_t &stat, int &x, int &y){
write(0xEB); // read data cmd
read();
stat=read();
uint8_t _x=read();
uint8_t _y=read();
bool negx=bitRead(stat,4);
bool negy=bitRead(stat,5);
x=twos(_x, negx);
y=twos(_y, negy);
}
void PS2Mouse::golo(int pin){
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
}
void PS2Mouse::gohi(int pin){
pinMode(pin, INPUT);
digitalWrite(pin, HIGH);
}
const int m=0x100;
int PS2Mouse::twos(uint8_t value, bool sign){
int v=(int)value;
if(sign) v|=0xFF00;
return v;
}