Created
October 15, 2017 20:00
-
-
Save dirkjanfaber/49cfb90c7aaee848284647d31f4889e1 to your computer and use it in GitHub Desktop.
Read as54047d sensor from c on raspberry pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <unistd.h> | |
#include <sys/ioctl.h> | |
#include <linux/types.h> | |
#include <linux/spi/spidev.h> | |
#include <stdint.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <stdlib.h> | |
static uint8_t mode = 1; | |
static uint8_t bits = 8; | |
static uint32_t speed = 1000000; | |
static uint16_t delay = 0; | |
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) | |
static void pabort(const char *s) { | |
perror(s); | |
abort(); | |
} | |
static void transfer(int fd) { | |
int i = 0; | |
int ret; | |
uint8_t tx[] = { 0xff, 0xff }; | |
float angle; | |
uint8_t rx[ARRAY_SIZE(tx)] = {0, }; | |
struct spi_ioc_transfer tr = { | |
.tx_buf = (unsigned long)tx, | |
.rx_buf = (unsigned long)rx, | |
.len = ARRAY_SIZE(tx), | |
.delay_usecs = delay, | |
.speed_hz = speed, | |
.bits_per_word = 0, | |
}; | |
while (1 == 1) { | |
ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr); | |
angle = (((rx[0] << 8) | rx[1]) & 0B0011111111111111); | |
printf("%0.2f\n", angle * 0.02197265625); | |
//i++; | |
} | |
} | |
int main(int argc, char **argv) | |
{ | |
char *name; | |
int fd; | |
struct spi_ioc_transfer xfer[2]; | |
unsigned char buf[32], *bp; | |
int len, status; | |
int ret = 0; | |
name = argv[1]; | |
fd = open(name, O_RDWR); | |
if (fd < 0) { | |
perror("open"); | |
return 1; | |
} | |
// spi mode | |
ret = ioctl(fd, SPI_IOC_WR_MODE, &mode); | |
if (ret == -1 ) | |
pabort("can't set spi mode"); | |
ret = ioctl(fd, SPI_IOC_RD_MODE, &mode); | |
if (ret == -1) | |
pabort("can't get spi mode"); | |
/* | |
* bits per word | |
*/ | |
ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits); | |
if (ret == -1) | |
pabort("can't set bits per word"); | |
ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits); | |
if (ret == -1) | |
pabort("can't get bits per word"); | |
/* | |
* max speed hz | |
*/ | |
ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed); | |
if (ret == -1) | |
pabort("can't set max speed hz"); | |
ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed); | |
if (ret == -1) | |
pabort("can't get max speed hz"); | |
printf("spi mode: %d\n", mode); | |
printf("bits per word: %d\n", bits); | |
printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000); | |
transfer(fd); | |
close(fd); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment