【问题标题】:I2C with C#/Mono on linux在 Linux 上使用 C#/Mono 的 I2C
【发布时间】:2014-02-22 04:09:03
【问题描述】:

我有一个小型嵌入式设备(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;
}

【问题讨论】:

  • 示例使用ioctls,这在 C# 中并不是最简单的事情。我可能会写一个薄包装,然后 p/Invoke 。否则,它看起来只是文件访问。
  • 你能举个例子,或者一些指针吗?不知道我会怎么做?

标签: c# linux mono i2c


【解决方案1】:

我不确定这是否为时已晚,但我已经使用单声道在 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# 方法可以更安全/有效地执行此操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    相关资源
    最近更新 更多