Linux串口编程(向空调发送十六进制指令)

本文介绍了在Ubuntu系统中进行串口编程以控制空调的步骤,重点在于如何获取打开串口的权限,包括添加用户至dialout组或创建udev规则。此外,分享了一个用于发送格力空调关闭命令的C++程序,强调不同空调或命令需修改通讯变量。还提及了十进制转十六进制的方法。
摘要由CSDN通过智能技术生成

一 首先需要提示:ubuntu下面打开串口需要超级权限,可以用下面两种方法来获得打开串口的权限。
方法一:
由于tty属于“dialout”组别,将用户加入到dialout用户组即可。例如我用户名是thinker,操作如下。
sudo usermod -aG dialout thinker
方法二:
在 /etc/udev/rules.d 目录下面添加一个 :
20-usb-serial.rules的文件, 内容如下:

    KERNEL=="ttyUSB*"  MODE="0666"  

注销或者重启电脑即可。

二 该程序发送的命令是格力立式空调的关闭命令,其他空调或者其他命令需要修改下面comm变量的值。
main.cpp

#include "nfraredSerial.h"
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
#include <cstring>
#include <stdlib.h>
int main(int argc, char **argv)
{
    char comm[10] = {
  0};
    comm[0] = 0x04;
    comm[1] = 0x00;
    comm[2] = 0x08;
    comm[3] = 0x08
在树莓派Linux环境下,可以使用C语言的串口API来发送十六进制数。具体步骤如下: 1. 打开串口设备文件。 ```c int fd = open("/dev/ttyS0", O_WRONLY | O_NOCTTY); if (fd == -1) { perror("open"); exit(1); } ``` 其中`/dev/ttyS0`是串口设备文件名,`O_WRONLY`表示以只写方式打开文件,`O_NOCTTY`表示不将串口设备作为控制终端。 2. 配置串口参数。 ```c struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, B9600); // 设置波特率为9600 cfsetospeed(&options, B9600); options.c_cflag &= ~PARENB; // 禁用奇偶校验 options.c_cflag &= ~CSTOPB; // 设置停止位为1 options.c_cflag &= ~CSIZE; // 设置数据位为8 options.c_cflag |= CS8; options.c_cflag &= ~CRTSCTS; // 禁用硬件流控制 options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // 禁用规范模式和回显 tcsetattr(fd, TCSANOW, &options); ``` 3. 发送十六进制数。 ```c unsigned char data[] = {0x12, 0x34}; int len = write(fd, data, sizeof(data)); if (len == -1) { perror("write"); } ``` 其中`data`是要发送的数据,`sizeof(data)`是数据长度。`write`函数将数据写入串口设备文件,返回写入的字节数。如果返回值为-1,则表示发送失败。 4. 关闭串口设备文件。 ```c close(fd); ``` 完整的代码示例如下: ```c #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <termios.h> #include <unistd.h> int main() { int fd = open("/dev/ttyS0", O_WRONLY | O_NOCTTY); if (fd == -1) { perror("open"); exit(1); } struct termios options; tcgetattr(fd, &options); cfsetispeed(&options, B9600); cfsetospeed(&options, B9600); options.c_cflag &= ~PARENB; options.c_cflag &= ~CSTOPB; options.c_cflag &= ~CSIZE; options.c_cflag |= CS8; options.c_cflag &= ~CRTSCTS; options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); tcsetattr(fd, TCSANOW, &options); unsigned char data[] = {0x12, 0x34}; int len = write(fd, data, sizeof(data)); if (len == -1) { perror("write"); } close(fd); return 0; } ``` 注意,如果要发送多个十六进制数,可以将它们存储在一个数组中,然后一次性发送
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值