Raspberry piにはアナログ入力端子がありません。Microchip Technology 社のSPI接続ADコンバータIC MCP3208を使用してアナログ電圧の入力ができるようにてみました。
回路図は前回の投稿を見てください。
プログラム C言語
#include <stdint.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/types.h> #include <linux/spi/spidev.h> #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) void pabort(const char *s) { perror(s); abort(); } static const char *device = "/dev/spidev0.0"; static uint8_t mode = SPI_MODE_0; static uint8_t bits = 8; static uint32_t speed = 500000; static uint16_t delay = 0; /* * SPIの初期化 * 戻り値: SPIのfd */ int initSPI(void) { int ret = 0; int fd; fd = open(device, O_RDWR); if (fd < 0) pabort("can't open device"); /* * 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\n", speed, speed/1000); return fd; } int transfer(int fd,int ch) { int ret; unsigned val = 0; double x; uint8_t tx[3]; uint8_t rx[3]; 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 = bits, }; tx[0] = 0x06|((ch>>2)&0x01); //AD start , single end tx[1] = ch<<6; tx[2] = 0x00; ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr); if (ret < 1) pabort("can't send spi message"); val = ((rx[1] & 0x0f) << 8) | rx[2]; return val; } int main(int argc, char *argv[]) { int fd; int val; fd = initSPI(); val = transfer(fd,0); printf("value = %04x\n",val); return 0; }
参考