MCP cover image

Biblioteca .NET para controlar MCP2221/MCP2221A USB2.0 a I2C/UART Convertidor de protocolo con GPIO

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

相关推荐

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

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

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

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

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

  • Contraband Interactive
  • Emulating Dr. Jordan B. Peterson's style in providing life advice and insights.

  • rustassistant.com
  • Your go-to expert in the Rust ecosystem, specializing in precise code interpretation, up-to-date crate version checking, and in-depth source code analysis. I offer accurate, context-aware insights for all your Rust programming questions.

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

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

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

  • apappascs
  • Descubra la colección más completa y actualizada de servidores MCP en el mercado. Este repositorio sirve como un centro centralizado, que ofrece un extenso catálogo de servidores MCP de código abierto y propietarios, completos con características, enlaces de documentación y colaboradores.

  • Mintplex-Labs
  • La aplicación AI de escritorio todo en uno y Docker con trapo incorporado, agentes de IA, creador de agentes sin código, compatibilidad de MCP y más.

  • ShrimpingIt
  • Manipulación basada en Micrypthon I2C del expansor GPIO de la serie MCP, derivada de AdaFruit_MCP230xx

  • n8n-io
  • Plataforma de automatización de flujo de trabajo de código justo con capacidades de IA nativas. Combine el edificio visual con código personalizado, auto-anfitrión o nube, más de 400 integraciones.

  • open-webui
  • Interfaz de IA fácil de usar (admite Ollama, Operai API, ...)

  • WangRongsheng
  • 🧑‍🚀 全世界最好的 llM 资料总结(数据处理、模型训练、模型部署、 O1 模型、 MCP 、小语言模型、视觉语言模型) | Resumen de los mejores recursos del mundo.

  • metorial
  • Versiones contenedores de cientos de servidores MCP 📡 🧠

  • ravitemer
  • Un poderoso complemento Neovim para administrar servidores MCP (protocolo de contexto del modelo)

    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.