-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpassthrough.ino
74 lines (54 loc) · 1.54 KB
/
passthrough.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
// Software SPI pins, chosen arbitrarily
// Note: we should use Arduino/mbed SPI capabilities, but there are issues with Serial on Arduino Nano 33 BLE
#define SO_PIN 2
#define SI_PIN 3
#define SC_PIN 4
void setup() {
// Configure pins
pinMode(SO_PIN, INPUT);
pinMode(SI_PIN, OUTPUT);
pinMode(SC_PIN, OUTPUT);
// Initiate serial connection through built-in USB
Serial.begin(9600);
while (!Serial);
}
uint32_t exchange(uint32_t output) {
uint32_t input = 0;
// Send bits, from most- to least-significant
for (int i = 31; i >= 0; --i) {
// Clock falling-edge
digitalWrite(SC_PIN, LOW);
// Write i-th bit
digitalWrite(SI_PIN, (output & (1 << i)) ? HIGH : LOW);
// Wait a bit
delayMicroseconds(4);
// Clock rising-edge, slave will latch the ouput
digitalWrite(SC_PIN, HIGH);
// Read i-th bit as well
input |= (digitalRead(SO_PIN) == HIGH ? 1 : 0) << i;
// Wait a bit
delayMicroseconds(4);
}
// Leave SI high to signal readiness
digitalWrite(SI_PIN, HIGH);
return input;
}
void loop() {
char bytes[4];
uint32_t data;
// Exchange bytes, if available
if (Serial.available() >= 4) {
// Get 32-bits data chunk
Serial.readBytes(bytes, 4);
data = bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24;
// Transfer over SPI
data = exchange(data);
// Send back to host
bytes[0] = data & 0xFF;
bytes[1] = (data >> 8) & 0xFF;
bytes[2] = (data >> 16) & 0xFF;
bytes[3] = (data >> 24) & 0xFF;
Serial.write(bytes, 4);
Serial.flush();
}
}