Skip to content

Controlling a 2-Channel USB Relay via C# #36

@HamidrezaBahmani

Description

@HamidrezaBahmani

I have managed to write some code that recognizes the device, but I am unsure how to send the correct commands to toggle each relay channel on or off. Below is the code I am currently using:

using System;
using System.IO;
using System.Linq;
using HidSharp;

internal class Program
{
    private static HidDevice _device;

    public static void Main(string[] args)
    {
        int vendorId = 0x16C0; // Replace with your vendor ID
        int productId = 0x05DF; // Replace with your product ID

        var list = DeviceList.Local;
        _device = list.GetHidDevices(vendorId, productId).FirstOrDefault();

        if (_device != null)
        {
            Console.WriteLine("HID device found:");
            Console.WriteLine($"Manufacturer: {_device.GetManufacturer()}");
            Console.WriteLine($"Product: {_device.GetProductName()}");
            Console.WriteLine($"Serial Ports: {_device.GetSerialPorts()}");

            // Example usage
            TurnOnChannel(1);
            Console.WriteLine("Channel 1 turned on.");
            System.Threading.Thread.Sleep(1000);

            TurnOffChannel(1);
            Console.WriteLine("Channel 1 turned off.");
        }
        else
        {
            Console.WriteLine("HID device not found.");
        }
    }

    private static void TurnOnChannel(int channel)
    {
        byte[] command = { 0x00, 0x01, (byte)channel }; // Adjust based on your relay's command structure
        WriteToDevice(command);
    }

    private static void TurnOffChannel(int channel)
    {
        byte[] command = { 0x00, 0x00, (byte)channel }; // Adjust based on your relay's command structure
        WriteToDevice(command);
    }

    private static void WriteToDevice(byte[] command)
    {
        try
        {
            using (var stream = _device.Open())
            {
                stream.Write(command);
            }
        }
        catch (IOException ex)
        {
            Console.WriteLine($"Failed to write to device: {ex.Message}");
        }
    }
}

does anybody knows how to solve this problem?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions