繁体   English   中英

在Linux上使用C#/ Mono进行I2C

[英]I2C with C#/Mono on linux

我有一个小型嵌入式设备(Beaglebone Black),其I2C设备挂在/dev/i2c-2

现在,我正在尝试通过C#/ Mono与该设备进行通信,这怎么可能? 我看过一些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;
}

我不确定是否为时已晚,但是我已经在BBB上使用mono做到了。 您需要查看DLLImport属性。 基本上,您需要编写一个小的C ++文件并对其进行编译,其中包含一个自定义方法,该方法仅调用名为invoke_ioctl(...)的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#方式可以更安全/有效地执行此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM