forked from riyas-org/rf24pi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spi.cpp
executable file
·132 lines (113 loc) · 2.24 KB
/
spi.cpp
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/*
* File: spi.cpp
* Author: Purinda Gunasekara <[email protected]>
*
* Created on 24 June 2012, 11:00 AM
*
* Inspired from spidev test in linux kernel documentation
* www.kernel.org/doc/Documentation/spi/spidev_test.c
*/
#include "spi.h"
SPI::SPI() {
// this->device = "/dev/spidev0.0";;
this->bits = 8;
// this->speed = 24000000; // 24Mhz - proly doesnt work
// this->speed = 16000000; // 16Mhz
// this->speed = 8000000; // 8Mhz
this->speed = 2000000; // 2Mhz
this->mode = 0;
// this->init();
}
void SPI::setbits( uint8_t bits )
{
this->bits = bits;
}
void SPI::setspeed( uint32_t speed )
{
this->speed = speed;
}
void SPI::setdevice( string devicefile )
{
this->device = devicefile;
}
void SPI::init()
{
int ret;
this->fd = open(this->device.c_str(), O_RDWR);
if (this->fd < 0)
{
perror("can't open device");
abort();
}
/*
* spi mode
*/
ret = ioctl(this->fd, SPI_IOC_WR_MODE, &this->mode);
if (ret == -1)
{
perror("can't set spi mode");
abort();
}
ret = ioctl(this->fd, SPI_IOC_RD_MODE, &this->mode);
if (ret == -1)
{
perror("can't set spi mode");
abort();
}
/*
* bits per word
*/
ret = ioctl(this->fd, SPI_IOC_WR_BITS_PER_WORD, &this->bits);
if (ret == -1)
{
perror("can't set bits per word");
abort();
}
ret = ioctl(this->fd, SPI_IOC_RD_BITS_PER_WORD, &this->bits);
if (ret == -1)
{
perror("can't set bits per word");
abort();
}
/*
* max speed hz
*/
ret = ioctl(this->fd, SPI_IOC_WR_MAX_SPEED_HZ, &this->speed);
if (ret == -1)
{
perror("can't set max speed hz");
abort();
}
ret = ioctl(this->fd, SPI_IOC_RD_MAX_SPEED_HZ, &this->speed);
if (ret == -1)
{
perror("can't set max speed hz");
abort();
}
}
uint8_t SPI::transfer(uint8_t tx_)
{
int ret;
// One byte is transfered at once
uint8_t tx[] = {0};
tx[0] = tx_;
uint8_t rx[ARRAY_SIZE(tx)] = {0};
struct spi_ioc_transfer tr;
tr.tx_buf = (unsigned long)tx;
tr.rx_buf = (unsigned long)rx;
tr.len = ARRAY_SIZE(tx);
tr.delay_usecs = 0;
// tr.cs_change = 1;
tr.speed_hz = this->speed;
tr.bits_per_word = this->bits;
ret = ioctl(this->fd, SPI_IOC_MESSAGE(1), &tr);
if (ret < 1)
{
perror("can't send spi message");
abort();
}
return rx[0];
}
SPI::~SPI() {
close(this->fd);
}