73 lines
1.7 KiB
C++
73 lines
1.7 KiB
C++
/*
|
|
*******************************************************************************
|
|
* INCLUDE
|
|
*******************************************************************************
|
|
*/
|
|
#include "SPI.h"
|
|
#include <Poco/Format.h>
|
|
#include <Poco/Exception.h>
|
|
#include <linux/spi/spidev.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/ioctl.h>
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
|
|
namespace Hardware
|
|
{
|
|
/*
|
|
*******************************************************************************
|
|
* CLASS DEFINE
|
|
*******************************************************************************
|
|
*/
|
|
const uint8_t SPI::MODE_0 = SPI_MODE_0;
|
|
const uint8_t SPI::MODE_1 = SPI_MODE_1;
|
|
const uint8_t SPI::MODE_2 = SPI_MODE_2;
|
|
const uint8_t SPI::MODE_3 = SPI_MODE_3;
|
|
|
|
SPI::SPI(int bus, int cs)
|
|
{
|
|
_fd = open(Poco::format("/dev/spidev%d.%d", bus, cs).c_str(), O_RDWR);
|
|
if (_fd < 0)
|
|
throw Poco::IOException("SPI: Open device FAIL");
|
|
}
|
|
|
|
SPI::~SPI()
|
|
{
|
|
close(_fd);
|
|
}
|
|
|
|
int SPI::setSpeed(uint32_t speed)
|
|
{
|
|
return ioctl(_fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
|
|
}
|
|
|
|
int SPI::setMode(uint8_t mode)
|
|
{
|
|
return ioctl(_fd, SPI_IOC_WR_MODE, &mode);
|
|
}
|
|
|
|
int SPI::setBitsPerWord(uint8_t bits)
|
|
{
|
|
return ioctl(_fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
|
|
}
|
|
|
|
int SPI::setLSBFirst(bool enable)
|
|
{
|
|
uint8_t lsb = enable ? 1 : 0;
|
|
return ioctl(_fd, SPI_IOC_WR_LSB_FIRST, &lsb);
|
|
}
|
|
|
|
int SPI::writeThenRead(const uint8_t* tx, int txlen, uint8_t* rx, int rxlen)
|
|
{
|
|
struct spi_ioc_transfer trans[2] = {{0}, {0}};
|
|
|
|
trans[0].tx_buf = (unsigned long)tx;
|
|
trans[0].rx_buf = 0;
|
|
trans[0].len = txlen;
|
|
|
|
trans[1].tx_buf = 0;
|
|
trans[1].rx_buf = (unsigned long)rx;
|
|
trans[1].len = rxlen;
|
|
return ioctl(_fd, SPI_IOC_MESSAGE(2), trans);
|
|
}
|
|
}
|