2 * ps2dev.cpp - an interface library for ps2 host.
4 * we do not handle parity errors.
5 * The timing constants are hard coded from the spec. Data rate is
7 * probably lots of room for optimization.
14 //since for the device side we are going to be in charge of the clock,
15 //the two defines below are how long each _phase_ of the clock cycle is
17 // we make changes in the middle of a phase, this how long from the
18 // start of phase to the when we drive the data line
22 * the clock and data pins can be wired directly to the clk and data pins
23 * of the PS2 connector. No external parts are needed.
25 PS2dev::PS2dev(int clk, int data)
34 * according to some code I saw, these functions will
35 * correctly set the clock and data pins for
36 * various conditions. It's done this way so you don't need
43 digitalWrite(pin, HIGH);
50 digitalWrite(pin, LOW);
53 int PS2dev::write(unsigned char data)
56 unsigned char parity = 1;
58 // Serial.print("sending ");
59 //Serial.println(data,HEX);
62 if (digitalRead(_ps2clk) == LOW) {
66 if (digitalRead(_ps2data) == LOW) {
72 delayMicroseconds(CLKHALF);
73 // device sends on falling clock
74 golo(_ps2clk); // start bit
75 delayMicroseconds(CLKFULL);
77 delayMicroseconds(CLKHALF);
87 delayMicroseconds(CLKHALF);
89 delayMicroseconds(CLKFULL);
91 delayMicroseconds(CLKHALF);
93 parity = parity ^ (data & 0x01);
103 delayMicroseconds(CLKHALF);
105 delayMicroseconds(CLKFULL);
107 delayMicroseconds(CLKHALF);
111 delayMicroseconds(CLKHALF);
113 delayMicroseconds(CLKFULL);
115 delayMicroseconds(CLKHALF);
117 delayMicroseconds(50);
122 int PS2dev::read(unsigned char * value)
124 unsigned char data = 0x00;
126 unsigned char bit = 0x01;
128 unsigned char parity = 1;
130 //wait for data line to go low
131 while (digitalRead(_ps2data) == HIGH) {
134 //wait for clock line to go high
135 while (digitalRead(_ps2clk) == LOW) {
140 delayMicroseconds(CLKHALF);
142 delayMicroseconds(CLKFULL);
144 delayMicroseconds(CLKHALF);
146 for (i=0; i < 8; i++)
148 if (digitalRead(_ps2data) == HIGH)
157 delayMicroseconds(CLKHALF);
159 delayMicroseconds(CLKFULL);
161 delayMicroseconds(CLKHALF);
163 parity = parity ^ (data & 0x01);
165 // we do the delay at the end of the loop, so at this point we have
166 // already done the delay for the parity bit
169 delayMicroseconds(CLKHALF);
171 delayMicroseconds(CLKFULL);
173 delayMicroseconds(CLKHALF);
176 delayMicroseconds(CLKHALF);
179 delayMicroseconds(CLKFULL);
181 delayMicroseconds(CLKHALF);