2014-02-22 86 views
0

我有一個小型嵌入式設備(Beaglebone黑色)與I2C設備掛鉤/dev/i2c-2I2C與Linux上的C#/單聲道

現在我試圖從C#/單聲道該設備進行通信,這怎麼可能? 我已經看過一些C++代碼,但在該語言中我不是很強大,但它看起來像它可能只是將其作爲文件打開並寫入它?雖然我不知道這個代碼如何轉換爲C#。

//C++ sample of i2c communication... 
int BMA180Accelerometer::writeI2CDeviceByte(char address, char value){ 
    cout << "Starting BMA180 I2C sensor state write" << endl; 
    char namebuf[MAX_BUS]; 
    snprintf(namebuf, sizeof(namebuf), "/dev/i2c-%d", I2CBus); 
    int file; 
    if ((file = open(namebuf, O_RDWR)) < 0){ 
     cout << "Failed to open BMA180 Sensor on " << namebuf << " I2C Bus" << endl; 
     return(1); 
    } 
    if (ioctl(file, I2C_SLAVE, I2CAddress) < 0){ 
      cout << "I2C_SLAVE address " << I2CAddress << " failed..." << endl; 
      return(2); 
    } 

    char buffer[2]; 
    buffer[0] = address; 
     buffer[1] = value; 
    if (write(file, buffer, 2) != 2) { 
     cout << "Failure to write values to I2C Device address." << endl; 
     return(3); 
    } 
    close(file); 
    cout << "Finished BMA180 I2C sensor state write" << endl; 
    return 0; 
} 
+1

該示例使用'ioctl's,這不是C#中最簡單的事情。我可能會寫一個薄包裝,然後p /調用它。否則,它看起來只是文件訪問。 – Mitch

+0

你能舉個例子,還是一些指針?不知道我會怎麼做? –

回答

0

我不確定這是否爲時已晚,但我已經在使用單聲道的BBB上完成了這項工作。您需要查看DLLImport屬性。基本上,你需要編寫一個小的C++文件並編譯它,它包含一個只調用ioctl()的自定義方法,稱爲invoke_ioctl(...),然後將編譯後的DLL放到BBB的/ bin目錄中,並將其添加到C#項目代碼。

[DllImport("pinvoke.dll")] 
[SuppressUnmanagedCodeSecurityAttribute()] //Optional, for speed 
private static extern int invoke_ioctl(int file_handle, int address); 

public static FileStream getI2CStream(byte address) 
{ 
    FileStream result = File.Open("/dev/i2c-2", FileMode.Open); 
    invoke_ioctl(result.SafeFileHandle.DangerousGetHandle().ToInt32(), address); 
    return result; 
} 

這將在寫入特定I2C地址時爲I2C線設置ioctl()。只需打開I2C線上每個器件的文件即可。可能有一種C#方法可以更安全/更有效地執行此操作。