2013-05-18 40 views
1

我已經通過了Linux kernel documents on i2c讀取和寫入代碼,試圖複製命令i2cset -y 0 0x60 0x05 0xff的write()返回-1寫I2C_SLAVE設備

我寫代碼的時候是在這裏:

#include <stdio.h> 
#include <linux/i2c.h> 
#include <linux/i2c-dev.h> 
#include <fcntl.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/ioctl.h> 
#include <stdint.h> 
#include <string.h> 

int main(){ 

int file;  
file = open("/dev/i2c-0", O_RDWR); 
if (file < 0) { 
    exit(1); 
} 

int addr = 0x60; 

if(ioctl(file, I2C_SLAVE, addr) < 0){ 
exit(1); 
} 

__u8 reg = 0x05; 
__u8 res; 
__u8 data = 0xff; 

int written = write(file, &reg, 1); 
printf("write returned %d\n", written); 

written = write(file, &data, 1); 
printf("write returned %d\n", written); 

} 

當我編譯並運行此代碼,我得到: 寫返回-1
寫返回-1

我試着跟隨正是文檔告訴我,我的understandi ng是該地址首先被設置爲ioctl,然後我需要write()這個寄存器,然後是我想要發送到寄存器的數據。

我也試過使用使用SMbus,但我不能讓我的代碼編譯使用它,它抱怨在鏈接階段,它無法找到函數。

我在這段代碼中犯了什麼錯誤嗎?我是i2c的初學者,也沒有很多c的經驗。

編輯:errno給出以下消息:Operation not supported。我以root身份登錄到這臺機器上,所以我不認爲它可能是一個權限的事情,雖然我可能是錯的。

回答

1

我解決這個問題的方法是使用SMBus,特別是功能i2c_smbus_write_byte_datai2c_smbus_read_byte_data。我能夠使用這些功能成功讀取和寫入設備。

我確實發現這些功能有點麻煩,我一直試圖使用apt-get下載庫來安裝適當的頭文件。最後我簡單地下載了文件smbus.csmbus.h

然後我需要的代碼爲:

#include <stdio.h> 
#include <linux/i2c.h> 
#include <linux/i2c-dev.h> 
#include "smbus.h" 
#include <fcntl.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <sys/ioctl.h> 
#include <stdint.h> 
#include <string.h> 
#include <errno.h> 


int main(){ 

int file;  
file = open("/dev/i2c-0", O_RDWR); 
if (file < 0) { 
    exit(1); 
} 

int addr = 0x60; 

if(ioctl(file, I2C_SLAVE, addr) < 0){ 
    exit(1); 
} 

__u8 reg = 0x05; /* Device register to access */ 
__s32 res; 

res = i2c_smbus_write_byte_data(file, reg, 0xff); 
close(file); 
} 

然後,如果我編譯smbus.c文件:gcc -c smbus.c和MYFILE:gcc -c myfile.c,再把它們連接:gcc smbus.o myfile.o -o myexe我得到一個運行我的I2C命令工作的可執行文件。當然,我有smbus.csmbus.h在與myfile.c相同的目錄中。

0

在C中,您可以檢查errno變量的內容,以獲取有關出錯的更多詳細信息。當包含errno.h時會自動聲明,您可以通過調用strerror(errno)來獲得更具描述性的文本。

您是否檢查過您有/dev/i2c-0的寫入權限?

+0

我已經添加了errno輸出,謝謝。 – James