Ubuntu 20.04 驱动LCUS_HID USB继电器

本文介绍如何在Ubuntu Linux环境下使用C语言编程控制USB继电器模块。文章提供了设备识别和控制的源代码示例,并详细说明了编译及运行步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近买了个USB继电器模块,想要在Ubuntu Linux下进行设备操作。在淘宝店家找到了跟这个型号相似的通过串口命令驱动的模块,按照相同的协议试了下是可以工作的,就构建了这样一篇操作代码的说明。

1、设备外观

2、操作命令

3、连接电脑,查看设备

$ lsusb
Bus 001 Device 088: ID 5131:2007 
...省略其他...

$ ls /dev/hidraw*
/dev/hidraw0  /dev/hidraw1  /dev/hidraw2  /dev/hidraw3  /dev/hidraw4  /dev/hidraw5

4、访问代码

#include <linux/types.h>
#include <linux/input.h>
#include <linux/hidraw.h>

#include <sys/types.h>
#include <sys/ioctl.h>
#include <sys/stat.h>

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <errno.h>

int find_usbrelay()
{
	int found = 0;
	int fd = -1;
	int result;
	int id;

	char path[32];
	
	const struct hidraw_devinfo usb_relay_info = 
	{
		.bustype = BUS_USB,
		.vendor = 0x5131,
		.product = 0x2007
	};

	struct hidraw_devinfo t_info;

	for(id = 0; !found; id++)	
	{
		sprintf(path, "/dev/hidraw%d", id);

		fd = open(path, O_RDWR | O_NONBLOCK);
		if (fd < 0)
			break;

		result = ioctl(fd, HIDIOCGRAWINFO, &t_info);
		if (result < 0)
			break;
	
		if ((t_info.bustype == usb_relay_info.bustype)
		&& (t_info.vendor == usb_relay_info.vendor)
		&& (t_info.product = usb_relay_info.product))
		{
			found = 1;
			break;
		}

		close(fd);
		fd = -1;
	}

	if (fd >= 0)
		close(fd);

	return found ? id : -1;
}

int set_usbrelay_onoff(int id, int ch, int onoff)
{
	int fd = -1;
	uint8_t cmd[8];

	char path[32];

	do
	{
		sprintf(path, "/dev/hidraw%d", id);

		fd = open(path, O_RDWR | O_NONBLOCK);
		if (fd < 0)
			break;

		cmd[0] = 0xA0;
		cmd[1] = ch;    // 1, 2
		cmd[2] = onoff; // 0, 1
		cmd[3] = cmd[0] + cmd[1] + cmd[2];

		write(fd, cmd, 4);

	} while(0);

	if (fd >= 0)
		close(fd);

	return 0;
}

int main(int argc, char *argv[])
{
	int result;
	int id;
	int ch;
	int onoff;
	char path[32];

	do
	{
		if (argc != 3)
		{
			printf("Usage:\n"
			"\tusbrelay ch on|off\n");
			break;
		}

		ch = atoi(argv[1]);
		if (strcmp(argv[2], "on") == 0)
			onoff = 1;
		else if (strcmp(argv[2], "off") == 0)
			onoff = 0;
		else
			break;

		id = find_usbrelay();
		if (id < 0)
		{
			printf("usbrelay not found\n");
			break;
		}

		set_usbrelay_onoff(id, ch, onoff);

	} while(0);

	return 0;
}

5、编译程序

gcc -o usbrelay main.c

6、运行程序,继电器有通断动作

$ sudo ./usbrelay 1 on
$ sudo ./usbrelay 1 off
$ sudo ./usbrelay 2 on
$ sudo ./usbrelay 2 off
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值