/*
* JR-IDE Project
* - (c) 2017 Alan Hightower
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see .
*/
#include "netpi.h"
#include
#include
static int spi_fd = -1;
static uint32_t spi_bitrate = 0;
int spi_init (int cs, uint32_t rate)
{
if (spi_fd < 0)
spi_term ();
char *path;
if (cs == 0)
path = "/dev/spidev0.0";
else if (cs == 1)
path = "/dev/spidev0.1";
else
return -1;
if ((spi_fd = open (path, O_RDWR)) < 0)
{
LOGERR("Unable to open SPI device '%s' - %s",
path, strerror (errno));
return -1;
}
// Rest of settings are non-fatal
uint8_t mode = 0;
ioctl (spi_fd, SPI_IOC_RD_MODE, &mode);
ioctl (spi_fd, SPI_IOC_WR_MODE, &mode);
uint8_t bpw = 8;
ioctl (spi_fd, SPI_IOC_RD_BITS_PER_WORD, &bpw);
ioctl (spi_fd, SPI_IOC_WR_BITS_PER_WORD, &bpw);
spi_bitrate = rate;
ioctl (spi_fd, SPI_IOC_RD_MAX_SPEED_HZ, &rate);
ioctl (spi_fd, SPI_IOC_WR_MAX_SPEED_HZ, &rate);
LOGDBG("Opened SPI:%d interface @ %.2f MHz\n", cs, spi_bitrate / 1000000.0);
return 0;
}
int spi_xfer (void *buf, int len)
{
struct spi_ioc_transfer spi;
memset (&spi, 0, sizeof (spi));
spi.tx_buf = (unsigned long) buf;
spi.rx_buf = (unsigned long) buf;
spi.len = len;
spi.delay_usecs = 0;
spi.speed_hz = spi_bitrate;
spi.bits_per_word = 8;
return (ioctl (spi_fd, SPI_IOC_MESSAGE(1), &spi) == len) ? len : -1;
}
void spi_term (void)
{
if (spi_fd >= 0)
{
close (spi_fd);
LOGDBG("Closed SPI interface\n");
}
spi_fd = -1;
return;
}