【发布时间】:2021-11-17 10:34:45
【问题描述】:
我想向写入函数发送一个十六进制值。 (例如,0×90)。 这是因为需要通信的设备以十六进制数字接收命令。 未使用的变量在测试和注释时出现,丢失十六进制值,稍后将被删除。 怎么写除String以外的十六进制值的写函数?
对于初学者, 请告诉我们如何通过读写函数交换十六进制值。
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>
#include <pthread.h>
int main(void)
{
int fd;
fd=open("/dev/ttyHSL6", O_RDWR|O_NOCTTY );
struct termios newtio;
char buffer[2000];
int bytes_read=0;
char *data;
//int *a=0x90;
char *a="0X90";
const int *num1;
if (fd == -1)
{
printf("Error! in opening port");
exit(-100);
}
memset(&newtio, 0, sizeof(struct termios));
newtio.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
newtio.c_iflag = IGNPAR;
newtio.c_oflag = 0;
newtio.c_lflag = 0;
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 1;
tcflush(fd, TCIFLUSH);
tcsetattr(fd, TCSANOW, &newtio);
data=malloc(sizeof(char)*140);
while(1){
const char *str ="0x91";
//write(fd, str, strlen(str)+1);
bytes_read = read(fd,buffer,sizeof(buffer));
if (bytes_read > 0)
{
buffer[bytes_read]=0;
printf("%s", buffer);
}
usleep(100000);
}
close(fd);
return 0;
}
目前进展:
我设置了发送和接收变量,并使用unsigned char编译了代码,但是出现了这样的错误。
./serial.c:48:10: warning: format ‘%x’ expects argument of type ‘unsigned int’, but argument 2 has type ‘unsigned char *’ [-Wformat=]
printf("%x\n",str);
如果我使用%p,没有编译错误,但是如你所知,地址值是打印出来的,所以和我想要的结果不一样。我是初学者,不知道怎么做。
修改部分如下。
while(1){
//const char *str ="0x91";
unsigned char str[13] = {0xA5,0x80,0x90,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xBD};
write(fd, str, strlen(str));
printf("%x\n",str);
bytes_read = read(fd,buffer,sizeof(buffer));
// printf("%x\n",*str);
if (bytes_read > 0)
{
buffer[bytes_read]=0;
printf("%p\n", buffer);
}
usleep(100000);
//printf("%s\r\n",buffer);
}
close(fd);
return 0;
【问题讨论】:
-
"我怎样才能写一个除字符串以外的十六进制值的写函数"。十六进制不是数据格式。那只是一个数据表示。如果您的意思是发送二进制数据而不是文本数据,则类似于:
int val = 0x91; write(fd, &val, sizeof(val));。但实际上你问的不是很清楚。 -
如果你提到十六进制数字,你是在说字符串吗?您要将 字符串
"x90"发送到设备还是要将与0220或144相同的 值0x90发送到设备?如果只讲值,“十六进制”没有任何意义。 -
您的 termios 初始化不可靠。请参阅Setting Terminal Modes Properly 和示例代码:stackoverflow.com/questions/12437593/…
-
如果要将字节数组显示为十六进制值,则必须单独转换每个字节。没有单一的 printf() 说明符可以为您执行此操作。见stackoverflow.com/questions/6947413/…
标签: c serial-port uart unistd.h