Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
HamidrezaBahmani opened this issue Oct 13, 2024 · 0 comments
Open

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

HamidrezaBahmani opened this issue Oct 13, 2024 · 0 comments

Comments

@HamidrezaBahmani
Copy link

HamidrezaBahmani commented Oct 13, 2024

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant