dac7562 应用层实现dac

 

 

/*
 * dac7562 (using spidev driver)
 *
  */

#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]))

static const char *device = "/dev/spidev0.0";
static uint8_t mode;
static uint8_t bits = 24;
static uint32_t speed = 500000;
static uint16_t delay;

static void transfer(int fd, int cmd)
{
    int ret;
    uint8_t tx[3] ;

    tx[0] = (uint8_t)(cmd >> 24)    // 24bit 命令格式参见表格 12 13 以及 17

    tx[1] = (uint8_t)(cmd >> 16);  //

    tx[2] = (uint8_t)(cmd >> 0);   //
  
    struct spi_ioc_transfer tr = {
        .tx_buf = (unsigned long)tx,
        .rx_buf = NULL,
        .len = 3,
        .delay_usecs = delay,
        .speed_hz = speed,
        .bits_per_word = bits,
    };

    ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr);
    if (ret < 1)
        printf("can't send spi message");

    puts("");
}


int main(int argc, char *argv[])
{
    int ret = 0;
    int fd;
  

    fd = open(device, O_RDWR);
    if (fd < 0)
        printf("can't open device");

     mode |= SPI_CPOL;

    /*
     * spi mode
     */
    ret = ioctl(fd, SPI_IOC_WR_MODE, &mode);
    if (ret == -1)
        printf("can't set spi mode");

   

    /*
     * bits per word
     */
    ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits);
    if (ret == -1)
        printf("can't set bits per word");

 

    /*
     * max speed hz
     */
    ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed);
    if (ret == -1)
        printf("can't set 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;
}

posted on 2016-03-02 14:57  嵌入式操作系统  阅读(791)  评论(0编辑  收藏  举报

导航