forked from KalicoCrew/kalico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spi_software.c
75 lines (68 loc) · 2.09 KB
/
spi_software.c
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
// Software SPI emulation
//
// Copyright (C) 2019 Kevin O'Connor <[email protected]>
//
// This file may be distributed under the terms of the GNU GPLv3 license.
#include "board/gpio.h" // gpio_out_setup
#include "basecmd.h" // oid_alloc
#include "command.h" // DECL_COMMAND
#include "sched.h" // sched_shutdown
#include "spicmds.h" // spidev_set_software_bus
struct spi_software {
struct gpio_in miso;
struct gpio_out mosi, sclk;
uint8_t mode;
};
void
command_spi_set_software_bus(uint32_t *args)
{
uint8_t mode = args[4];
if (mode > 3)
shutdown("Invalid spi config");
struct spidev_s *spi = spidev_oid_lookup(args[0]);
struct spi_software *ss = alloc_chunk(sizeof(*ss));
ss->miso = gpio_in_setup(args[1], 1);
ss->mosi = gpio_out_setup(args[2], 0);
ss->sclk = gpio_out_setup(args[3], 0);
ss->mode = mode;
spidev_set_software_bus(spi, ss);
}
DECL_COMMAND(command_spi_set_software_bus,
"spi_set_software_bus oid=%c miso_pin=%u mosi_pin=%u sclk_pin=%u"
" mode=%u rate=%u");
void
spi_software_prepare(struct spi_software *ss)
{
gpio_out_write(ss->sclk, ss->mode & 0x02);
}
void
spi_software_transfer(struct spi_software *ss, uint8_t receive_data
, uint8_t len, uint8_t *data)
{
while (len--) {
uint8_t outbuf = *data;
uint8_t inbuf = 0;
for (uint_fast8_t i = 0; i < 8; i++) {
if (ss->mode & 0x01) {
// MODE 1 & 3
gpio_out_toggle(ss->sclk);
gpio_out_write(ss->mosi, outbuf & 0x80);
outbuf <<= 1;
gpio_out_toggle(ss->sclk);
inbuf <<= 1;
inbuf |= gpio_in_read(ss->miso);
} else {
// MODE 0 & 2
gpio_out_write(ss->mosi, outbuf & 0x80);
outbuf <<= 1;
gpio_out_toggle(ss->sclk);
inbuf <<= 1;
inbuf |= gpio_in_read(ss->miso);
gpio_out_toggle(ss->sclk);
}
}
if (receive_data)
*data = inbuf;
data++;
}
}