-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSPIbridge.ino
108 lines (101 loc) · 2.38 KB
/
SPIbridge.ino
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
/*
USB to SPI bridge
Copyright (C) Paul Brook <[email protected]>
Released under the terms of the GNU General Public License version 3
*/
#include <SPI.h>
static const uint8_t cs_pin = 10;
static const uint8_t led_pin = SS;
#define NUM_BUTTONS 10
static bool button_state[NUM_BUTTONS];
void setup()
{
int i;
Serial.begin(9600);
pinMode(cs_pin, OUTPUT);
digitalWrite(cs_pin, 1);
SPI.setBitOrder(MSBFIRST);
SPI.setClockDivider(SPI_CLOCK_DIV8);
SPI.setDataMode(SPI_MODE3);
SPI.begin();
for (i = 0; i < NUM_BUTTONS; i++)
{
pinMode(i, INPUT_PULLUP);
}
Keyboard.begin();
}
static void
check_buttons(void)
{
int i;
static long next_check;
long now;
bool new_state;
now = millis();
if (next_check)
{
if (now - next_check < 0)
return;
next_check = 0;
}
for (i = 0; i < NUM_BUTTONS; i++)
{
new_state = (digitalRead(i) == 0);
if (new_state != button_state[i])
{
button_state[i] = new_state;
if (new_state)
{
Keyboard.press('0' + i);
}
else
{
Keyboard.release('0' + i);
}
next_check = now + 100;
}
}
}
void loop()
{
int c;
bool new_connection = true;
SPCR &= ~_BV(SPIE);
// Access SPSR followed by SPDR to clear SPIF
SPSR;
SPDR = 0xff;
while ((SPSR & _BV(SPIF)) == 0)
/* no-op */;
while (true)
{
while (!Serial.available())
check_buttons();
if (new_connection)
{
Serial.write(0xfe);
Serial.write('L');
Serial.write('E');
Serial.write('D');
new_connection = false;
}
digitalWrite(cs_pin, 0);
TXLED1;
while (true)
{
c = Serial.read();
// The Arduino SPI code waits for the transmit to complete before returning.
// Poke data directly at the SPI hardware so that we can be reading more USB
// data while that is happening
while ((SPSR & _BV(SPIF)) == 0)
/* no-op */;
if (c == -1)
break;
SPDR = c;
}
TXLED0;
digitalWrite(cs_pin, 1);
if (!Serial)
new_connection = true;
delayMicroseconds(10);
}
}