Skip to content

Commit 2efc679

Browse files
committed
spi: bit bang via UART in Scala
1 parent c0836fd commit 2efc679

File tree

1 file changed

+67
-13
lines changed

1 file changed

+67
-13
lines changed

src/main/scala/spi/SerialSpiTest.scala

Lines changed: 67 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,80 @@ class SerialSpiTest {
77
}
88

99
object SerialSpiTest extends App {
10+
11+
def writeRead(s: String): String = {
12+
for (c <- s) {
13+
out.write(c.toByte)
14+
}
15+
// println("Wrote: " + s)
16+
val buf = new Array[Byte](1)
17+
var ret = ""
18+
var stop = false
19+
while (!stop) {
20+
if (port.bytesAvailable() > 0) {
21+
port.readBytes(buf, 1)
22+
val c = buf(0).toChar
23+
ret = ret + c
24+
stop = c == '\n'
25+
}
26+
}
27+
// print("Received: " + ret)
28+
Thread.sleep(300)
29+
ret
30+
}
31+
32+
def writeByte(v: Int) = {
33+
for (i <- 0 until 8) {
34+
val bits = ((v >> (7-i)) & 1) << 1
35+
// clock off, set data
36+
writeRead(s"w44$bits\r")
37+
// clock on, keep data
38+
writeRead(s"w44${bits + 1}\r")
39+
}
40+
// not now, writeRead("w440\r") // clock off
41+
}
42+
43+
def readByte() = {
44+
var v = 0
45+
for (i <- 0 until 8) {
46+
writeRead("w440\r") // clock off
47+
// data changes after neg edge
48+
writeRead("w441\r") // clock on
49+
// sample on pos edge
50+
val rx = writeRead("r")
51+
// println("received: " + rx(8))
52+
// '8' is bit set
53+
val bit = if (rx(8) == '8') 1 else 0
54+
v = (v << 1) | bit
55+
}
56+
writeRead("w440\r") // clock off (maybe?), does not heart on multibyte read
57+
v
58+
}
59+
60+
def readAdx(cmd: Int): Int = {
61+
writeRead("w444\r")
62+
writeRead("w440\r")
63+
writeByte(cmd)
64+
writeByte(0)
65+
val ret = readByte()
66+
writeRead("w444\r")
67+
ret
68+
}
69+
1070
// TODO: fix this hard coded thing
1171
val port = SerialPort.getCommPort("/dev/tty.usbserial-210292B408601")
1272
port.openPort()
1373
port.setBaudRate(115200)
1474
// port.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0)
1575
port.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING, 0, 0)
1676
val out = port.getOutputStream
17-
val buf = new Array[Byte](1)
18-
val s = "Hello World"
19-
for (i <- 0 until 10) {
20-
val v = s(i)
21-
out.write(v)
22-
Thread.sleep(100)
23-
println(s"Wrote ${v.toChar}")
24-
if (port.bytesAvailable() != 0) {
25-
println(s"Bytes available: ${port.bytesAvailable()}")
26-
val cnt = port.readBytes(buf, 1)
27-
println("read: " + cnt + " " + (buf(0).toChar))
28-
}
29-
}
77+
78+
print(writeRead("w444\r"))
79+
print(writeRead("w440\r"))
80+
print(writeRead("r"))
81+
val v = readAdx(0x0b) // dev id
82+
println("device id is 0x" + v.toHexString)
83+
writeRead("w444\r")
3084
out.close()
3185
port.closePort()
3286
}

0 commit comments

Comments
 (0)