Cover image

.NET库控制MCP2221/MCP2221A USB2.0至I2C/UART协议转换器使用GPIO

3 years

Works with Finder

3

Github Watches

5

Github Forks

12

Github Stars

GitHub license GitHub issues tests/main CodeQL

Smdn.Devices.MCP2221

NuGet Smdn.Devices.MCP2221

Smdn.Devices.MCP2221 is a .NET library for controlling MCP2221/MCP2221A USB2.0 to I2C/UART Protocol Converter with GPIO. This library enables you to control MCP2221/MCP2221A's GPIO, I2C interface, and other functionalities via USB-HID interface.

With this library, you can control I2C devices and others devices on any PCs with USB ports. It is not needed the board like the Raspberry Pi or Arduino. Also it is not required to install native device drivers on your system.

See Smdn.Devices.MCP2221 examples.

Smdn.Devices.MCP2221.GpioAdapter

NuGet Smdn.Devices.MCP2221.GpioAdapter

Smdn.Devices.MCP2221.GpioAdapter provides the MCP2221/MCP2221A adapter interface for System.Device.Gpio. This library enables you to use the many device bindings provided by Iot.Device.Bindings.

See Smdn.Devices.MCP2221.GpioAdapter examples.

Supported MCP2221/MCP2221A features

  • GP functionalities
    • GPIO
      • GPIO read/write value
      • GPIO get/set direction (some methods throw NotImplementedException)
    • ADC inputs
    • DAC outputs
    • Clock output
    • Interrupt detection
    • Other functionalities
      • Configure GP0 as SSPND
      • Configure GP0 as LED_URx
      • Configure GP1 as LED_UTx
      • Configure GP2 as USBCFG
      • Configure GP3 as LED_I2C
      • Set initial value (Negating logic level)
  • I2C functionalities
    • I2C read/write (7-bit address) (Transferring larger than 60 bytes have not been tested with actual device)
    • I2C read/write (10-bit address)
    • configure communication speed
      • Standard mode (100kbps)
      • Fast mode (400kbps)
      • Low speed mode (10kbps)
      • Non-standard custom speed
  • Flash/SRAM functionalities
    • SRAM read/write
      • GP settings
      • Chip settings
    • Flash read/write
      • GP Settings
      • Chip Settings
      • USB Manufacturer Descriptor String (read only)
      • USB Product Descriptor String (read only)
      • USB Serial Number Descriptor String (read only)
      • Chip Factory Serial Number (read only, always returns 01234567 (issue #8))
      • Hardware/Firmware revision (read only)
      • Passwords and chip setting protection
  • Reset

Haven't tested with the actual MCP2221, but it is expected that works as same as MCP2221A.

Library API features

  • Frameworks/Platforms
    • .NET Standard 2.1/.NET 5
    • Windows/Linux/MacOS and any other platforms which USB-HID driver supports
  • Smdn.Devices.MCP2221
    • Read/Write and other command methods
    • Can handle multiple MCP2221/MCP2221A by finding target with Predicate<IUsbHidDevice>
    • I2C bus scanning (example)
    • Using HIDSharp as default USB-HID driver, LibUsbDotNet also supported.
  • Smdn.Devices.MCP2221.GpioAdapter

Getting started and examples

Firstly, add package Smdn.Devices.MCP2221 to your project.

dotnet add package Smdn.Devices.MCP2221

Nextly, write your codes. The simplest code, blinking the LEDs connected to the GP pins is like below.

using System;
using System.Threading;
using Smdn.Devices.MCP2221;

using var device = MCP2221.Open();

// configure GP0-GP3 as GPIO output
device.GP0.ConfigureAsGPIO(PinMode.Output);
device.GP1.ConfigureAsGPIO(PinMode.Output);
device.GP2.ConfigureAsGPIO(PinMode.Output);
device.GP3.ConfigureAsGPIO(PinMode.Output);

// blink GP0-GP3
foreach (var gp in device.GPs) {
  Console.WriteLine($"blink {gp.PinDesignation}");

  for (var n = 0; n < 10; n++) {
    gp.SetValue(false); Thread.Sleep(100);
    gp.SetValue(true); Thread.Sleep(100);
  }
}

For detailed instructions, including wiring of the devices and parts, see blink example page.

More examples can be found in following examples directory.

Troubleshooting

Linux

DllImport resolving

LibUsbDotNet do DllImport-ing a shared library with the filename libusb-1.0.so.0.

If the libusb's .so filename installed on your system is different from that, use the NativeLibrary.SetDllImportResolver() to load installed .so file like below.

$ find /lib/ -name "libusb-*.so*"
/lib/x86_64-linux-gnu/libusb-1.0.so.x.y.z
/lib/i386-linux-gnu/libusb-1.0.so.x.y.z
using System.Runtime.InteropServices;

static void Main() {
  // libusb.so filename which is installed on your system
  const string fileNameLibUsb = "libusb-1.0.so.x.y.z";

  NativeLibrary.SetDllImportResolver(
    typeof(global::LibUsbDotNet.LibUsb.UsbDevice).Assembly,
    (libraryName, assembly, searchPath) => {
      if (string.Equals(libraryName, "libusb-1.0.so.0", StringComparison.OrdinalIgnoreCase)) {
        if (NativeLibrary.TryLoad(fileNameLibUsb, out var handleOfLibUsb))
          return handleOfLibUsb;
      }

      return IntPtr.Zero;
    }
  );

  // your codes here
    ︙
    ︙
}

Unbinding usbhid driver

When using LibUsbDotNet, you need to unbind the devices that are bound to the usbhid driver.

If you got the exception like below, configure the MCP2221/MCP2221A to unbind, and reconnect it again. See udev rule file for detail.

Unhandled exception. Smdn.Devices.MCP2221.DeviceUnavailableException: MCP2221/MCP2221A is not available, not privileged or disconnected.
  ---> LibUsbDotNet.LibUsb.UsbException: Resource busy
    at LibUsbDotNet.LibUsb.ErrorExtensions.ThrowOnError(Error error)
    at LibUsbDotNet.LibUsb.UsbDevice.ClaimInterface(Int32 interfaceID)

Permitting device access

If you got the exception like below, you need to run as the root user, the command like sudo dotnet run.

LibUsbDotNet:

Unhandled exception. Smdn.Devices.MCP2221.DeviceUnavailableException: MCP2221/MCP2221A is not available, not privileged or disconnected.
 ---> LibUsbDotNet.LibUsb.UsbException: Access denied (insufficient permissions)
   at LibUsbDotNet.LibUsb.ErrorExtensions.ThrowOnError(Error error)
   at LibUsbDotNet.LibUsb.UsbDevice.Open()

HIDSharp:

Unhandled exception. Smdn.Devices.MCP2221.DeviceUnavailableException: MCP2221/MCP2221A is not available, not privileged or disconnected.
 ---> HidSharp.Exceptions.DeviceIOException: Unable to open HID class device (OK).
   at HidSharp.Platform.Linux.LinuxHidStream.DeviceHandleFromPath(String path, HidDevice hidDevice, oflag oflag)
   at HidSharp.Platform.Linux.LinuxHidDevice.TryParseReportDescriptor(ReportDescriptor& parser, Byte[]& reportDescriptor)
   at HidSharp.Platform.Linux.LinuxHidDevice.RequiresGetInfo()
   at HidSharp.Platform.Linux.LinuxHidDevice.OpenDeviceDirectly(OpenConfiguration openConfig)
   at HidSharp.Device.OpenDeviceAndRestrictAccess(OpenConfiguration openConfig)
   at HidSharp.Device.Open(OpenConfiguration openConfig)
   at HidSharp.Device.Open()
   at HidSharp.HidDevice.Open()

If you want to give access privileges to a non-root user instead, you can use udev rule file. See 90-MCP2221-HIDSharp.rules or 90-MCP2221-LibUsbDotNet.rules

相关推荐

  • Joshua Armstrong
  • Confidential guide on numerology and astrology, based of GG33 Public information

  • https://suefel.com
  • Latest advice and best practices for custom GPT development.

  • Alexandru Strujac
  • Efficient thumbnail creator for YouTube videos

  • Emmet Halm
  • Converts Figma frames into front-end code for various mobile frameworks.

  • Elijah Ng Shi Yi
  • Advanced software engineer GPT that excels through nailing the basics.

  • lumpenspace
  • Take an adjectivised noun, and create images making it progressively more adjective!

  • Lists Tailwind CSS classes in monospaced font

  • https://maiplestudio.com
  • Find Exhibitors, Speakers and more

  • https://appia.in
  • Siri Shortcut Finder – your go-to place for discovering amazing Siri Shortcuts with ease

  • Carlos Ferrin
  • Encuentra películas y series en plataformas de streaming.

  • Yusuf Emre Yeşilyurt
  • I find academic articles and books for research and literature reviews.

  • tomoyoshi hirata
  • Sony α7IIIマニュアルアシスタント

  • apappascs
  • 发现市场上最全面,最新的MCP服务器集合。该存储库充当集中式枢纽,提供了广泛的开源和专有MCP服务器目录,并提供功能,文档链接和贡献者。

  • ShrimpingIt
  • MCP系列GPIO Expander的基于Micropython I2C的操作,源自ADAFRUIT_MCP230XX

  • jae-jae
  • MCP服务器使用剧作《无头浏览器》获取网页内容。

  • ravitemer
  • 一个功能强大的Neovim插件,用于管理MCP(模型上下文协议)服务器

  • patruff
  • Ollama和MCP服务器之间的桥梁,使本地LLMS可以使用模型上下文协议工具

  • pontusab
  • 光标与风浪冲浪社区,查找规则和MCP

  • av
  • 毫不费力地使用一个命令运行LLM后端,API,前端和服务。

  • Mintplex-Labs
  • 带有内置抹布,AI代理,无代理构建器,MCP兼容性等的多合一桌面和Docker AI应用程序。

  • WangRongsheng
  • 🧑‍🚀 llm 资料总结(数据处理、模型训练、模型部署、 o1 模型、mcp 、小语言模型、视觉语言模型)|摘要世界上最好的LLM资源。

  • appcypher
  • 很棒的MCP服务器 - 模型上下文协议服务器的策划列表

    Reviews

    2 (1)
    Avatar
    user_dhMtZLtL
    2025-04-17

    As a dedicated user of Smdn.Devices.MCP2221, I am thoroughly impressed with its functionality and ease of use. This library by smdn is incredibly well-documented and versatile for various USB-to-UART/I2C tasks. The seamless integration with my projects has significantly boosted my productivity. Highly recommend to anyone needing reliable MCP2221 support! Check it out at https://github.com/smdn/Smdn.Devices.MCP2221.