在Linux中通过串口通信发送十六进制数据 [英] Sending Hexadecimal data through Serial Port Communication in Linux
问题描述
我有一个任务是在linux中向我的COMPORT发送十六进制数据。我写了这个简单的C代码,但它只发送一个十进制数。任何人都可以帮助我发送一个十六进制位。
这是我写的代码
#include< stdio.h> / *标准输入/输出定义* /
#include< string.h> / *字符串函数定义* /
#include< unistd.h> / * UNIX标准函数定义* /
#include< fcntl.h> / *文件控制定义* /
#include< errno.h> / *错误号码定义* /
#include< termios.h> / * POSIX终端控制定义* /
int number,n;
void main(void){
open_port();
}
int open_port(void)
{
int fd; / *端口的文件描述符* /
fd = open(/ dev / ttyACM0,O_RDWR | O_NOCTTY | O_NDELAY);
if(fd == -1)
{
perror(open_port:Unable to open / dev / ttyACM0 - );
}
else {
printf(Port Opened successfully \\\
);
number = 1;
while(number!= 55){
scanf(%d,& number);
n = write(fd,ATZ \r,number);
if(n <0)
fputs(write()of 4 bytes failed!\\\
,stderr);
}
}
return(fd);
}
请帮忙
在此先感谢:) :)
write
被定义为:
ssize_t write(int fd,const void * buf,size_t count);
也就是说,它将 count
字节发送给 fd
来自 buf
。在你的情况下,数据总是字符串AZTR \r,之后加上未定义的数据(如果count> 5)。您的程序不会发送十六进制或十进制数据。
您想发送二进制数据或一串十六进制字符?
对于选项一,您可以使用: write(fd,somebuffer,len);
,其中一些缓冲区是指向任何一组字节(包括整数等)的指针。
对于选项二,首先使用将数据转换为十六进制字符串, sprintf
与%02X
作为格式字符串,然后继续写入
数据到港口。
I have got a task of sending hexadecimal data to my COMPORT in linux. I have written this simple C code, but it sends only a decimal number. Can anyone help me in sending an hexadecimal bit.
Here is the code I have written
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
int number,n;
void main(void){
open_port();
}
int open_port(void)
{
int fd; /* File descriptor for the port */
fd = open("/dev/ttyACM0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
perror("open_port: Unable to open /dev/ttyACM0 - ");
}
else{
printf("Port Opened successfully\n");
number = 1;
while(number!=55){
scanf("%d",&number);
n = write(fd, "ATZ\r", number);
if (n < 0)
fputs("write() of 4 bytes failed!\n", stderr);
}
}
return (fd);
}
Please help
Thanks in advance :) :)
write
is defined as:
ssize_t write(int fd, const void *buf, size_t count);
That is, it sends count
bytes to fd
from buf
. In your case, the data is always the string "AZTR\r", plus undefined data after that (if count is > 5). Your program sends neither hexadecimal nor decimal data.
Do you want to send binary data or a string of hexadecimal characters?
For option one, you can use: write(fd, somebuffer, len);
, where some buffer is a pointer to any set of bytes (including ints, etc).
For option two, first convert your data to a hexadecimal string using sprintf
with %02X
as the format string, then proceed to write
that data to the port.
这篇关于在Linux中通过串口通信发送十六进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!