Linux下SPI读写外部寄存器的操作


SPI写寄存器操作:

  1. static void mcp251x_write_reg(struct spi_device *spi, uint8_t reg, uint8_t val)  
  2. {  
  3.     struct mcp251x *chip = dev_get_drvdata(&spi->dev);  
  4.     int ret;  
  5.   
  6.     down(&chip->lock);  
  7.   
  8.     chip->spi_transfer_buf[0] = INSTRUCTION_WRITE;  
  9.     chip->spi_transfer_buf[1] = reg;  
  10.     chip->spi_transfer_buf[2] = val;  
  11.   
  12.     ret = spi_write(spi, chip->spi_transfer_buf, 3);  
  13.     if (ret < 0)  
  14.         dev_dbg(&spi->dev, "%s: failed: ret = %d\n", __FUNCTION__, ret);  
  15.   
  16.     up(&chip->lock);  
  17. }  
 
  1. static void mcp251x_write_bits(struct spi_device *spi, uint8_t reg, uint8_t mask, uint8_t val)  
  2. {  
  3.     struct mcp251x *chip = dev_get_drvdata(&spi->dev);  
  4.     int ret;  
  5.   
  6.     down(&chip->lock);  
  7.   
  8.     chip->spi_transfer_buf[0] = INSTRUCTION_BIT_MODIFY;  
  9.     chip->spi_transfer_buf[1] = reg;  
  10.     chip->spi_transfer_buf[2] = mask;  
  11.     chip->spi_transfer_buf[3] = val;  
  12.   
  13.     ret = spi_write(spi, chip->spi_transfer_buf, 4);  
  14.     if (ret < 0)  
  15.         dev_dbg(&spi->dev, "%s: failed: ret = %d\n", __FUNCTION__, ret);  
  16.   
  17.     up(&chip->lock);  
  18. }  
SPI读寄存器操作:
  1. static uint8_t mcp251x_read_reg(struct spi_device *spi, uint8_t reg)  
  2. {  
  3.     struct mcp251x *chip = dev_get_drvdata(&spi->dev);  
  4.     uint8_t *tx_buf, *rx_buf;  
  5.     uint8_t val;  
  6.     int ret;  
  7.   
  8.     tx_buf = chip->spi_transfer_buf;  
  9.     rx_buf = chip->spi_transfer_buf + 8;  
  10.   
  11.     down(&chip->lock);  
  12.   
  13.     tx_buf[0] = INSTRUCTION_READ;  
  14.     tx_buf[1] = reg;  
  15.     ret = spi_write_then_read(spi, tx_buf, 2, rx_buf, 1);  
  16.     if (ret < 0)  
  17.     {  
  18.         dev_dbg(&spi->dev, "%s: failed: ret = %d\n", __FUNCTION__, ret);  
  19.         val = 0;  
  20.     }  
  21.     else  
  22.         val = rx_buf[0];  
  23.   
  24.     up(&chip->lock);  
  25.   
  26.     return val;  
  27. }  
 
  1. static uint8_t mcp251x_read_state(struct spi_device *spi, uint8_t cmd)  
  2. {  
  3.     struct mcp251x *chip = dev_get_drvdata(&spi->dev);  
  4.     uint8_t *tx_buf, *rx_buf;  
  5.     uint8_t val;  
  6.     int ret;  
  7.   
  8.     tx_buf = chip->spi_transfer_buf;  
  9.     rx_buf = chip->spi_transfer_buf + 8;  
  10.   
  11.     down(&chip->lock);  
  12.   
  13.     tx_buf[0] = cmd;  
  14.     ret = spi_write_then_read(spi, tx_buf, 1, rx_buf, 1);  
  15.     if (ret < 0)  
  16.     {  
  17.         dev_dbg(&spi->dev, "%s: failed: ret = %d\n", __FUNCTION__, ret);  
  18.         val = 0;  
  19.     }  
  20.     else  
  21.         val = rx_buf[0];  
  22.   
  23.     up(&chip->lock);  
  24.   
  25.     return val;  
  26. }  

相关内容