C++ 如何插入十六进制值并发送到串行端口?

C++ 如何插入十六进制值并发送到串行端口?,c++,serial-port,hex,hyperterminal,C++,Serial Port,Hex,Hyperterminal,下面是我的代码。我想发送十六进制值,并在超级终端中获得十六进制输出。我不知道怎么寄 我在超级终端输出中得到一些垃圾值。它正在读取但不发送十六进制输出 #include "stdafx.h" #include <Windows.h> #include <stdio.h> #include <string.h> #include <conio.h> #include <stdint.h> #define BUFFERLENGTH 25

下面是我的代码。我想发送十六进制值,并在超级终端中获得十六进制输出。我不知道怎么寄

我在超级终端输出中得到一些垃圾值。它正在读取但不发送十六进制输出

#include "stdafx.h"
#include <Windows.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdint.h>
#define    BUFFERLENGTH 256


int main(void)
{
    HANDLE hComm;                          // Handle to the Serial port
    char ComPortName[] = "\\\\.\\COM6"; // Name of the Serial port(May Change) to be opened,
    BOOL   Status;
    DWORD dwEventMask;                     // Event mask to trigger
    unsigned char TempChar;             // Temperory Character
    char  SerialBuffer[256];               // Buffer Containing Rxed Data
    DWORD NoBytesRead;                     // Bytes read by ReadFile()
    int i = 0;


    printf("\n\n +==========================================+");
    printf("\n |  Serial Communication (Win32 API)         |");
    printf("\n +==========================================+\n");
    /*----------------------------------- Opening the Serial Port --------------------------------------------*/

    hComm = CreateFile(ComPortName,                       // Name of the Port to be Opened
        GENERIC_READ | GENERIC_WRITE,      // Read/Write Access
        0,                                 // No Sharing, ports cant be shared
        NULL,                              // No Security
        OPEN_EXISTING,                     // Open existing port only
        0,                                 // Non Overlapped I/O
        NULL);                             // Null for Comm Devices

    if (hComm == INVALID_HANDLE_VALUE)
        printf("\n   Error! - Port %s can't be opened", ComPortName);
    else
        printf("\n   Port %s Opened\n ", ComPortName);


    /*------------------------------- Setting the Parameters for the SerialPort ------------------------------*/

    DCB dcbSerialParams = { 0 };                        // Initializing DCB structure
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);

    Status = GetCommState(hComm, &dcbSerialParams);     //retreives  the current settings

    if (Status == FALSE)
        printf("\n   Error! in GetCommState()");

    dcbSerialParams.BaudRate = CBR_9600;      // Setting BaudRate = 9600
    dcbSerialParams.ByteSize = 8;             // Setting ByteSize = 8
    dcbSerialParams.StopBits = ONESTOPBIT;    // Setting StopBits = 1
    dcbSerialParams.Parity = EVENPARITY;      // Setting Parity = None 

    Status = SetCommState(hComm, &dcbSerialParams);  //Configuring the port according to settings in DCB 

    if (Status == FALSE)
    {
        printf("\n   Error! in Setting DCB Structure");
    }
    else
    {
        printf("\n   Setting DCB Structure Successfull\n");
        printf("\n       Baudrate = %d", dcbSerialParams.BaudRate);
        printf("\n       ByteSize = %d", dcbSerialParams.ByteSize);
        printf("\n       StopBits = %d", dcbSerialParams.StopBits);
        printf("\n       Parity   = %d", dcbSerialParams.Parity);
    }

    /*------------------------------------ Setting Timeouts --------------------------------------------------*/

    while (1)
    {

        COMMTIMEOUTS timeouts = { 0 };

        timeouts.ReadIntervalTimeout = 5000;
        timeouts.ReadTotalTimeoutConstant = 5000;
        timeouts.ReadTotalTimeoutMultiplier = 1000;
        timeouts.WriteTotalTimeoutConstant = 5000;
        timeouts.WriteTotalTimeoutMultiplier = 1000;

        if (SetCommTimeouts(hComm, &timeouts) == FALSE)
            printf("\n   Error! in Setting Time Outs");
        else
            printf("\n\n   Setting Serial Port Timeouts Successfull");

        printf("\n |---------  Serial Communication (Win32 API) --------|");

        printf("Starting to write......");

        //char   lpBuffer[] = "ABC";               // lpBuffer should be  char or byte array, otherwise write wil fail

        uint8_t message[15];
        message[0] = 0x16;
        message[1] = 0x16;
        message[2] = 0x02;
        message[3] = 0x01;
        message[4] = 0x07;
        message[5] = 0x08;
        message[6] = 0x00;
        message[7] = 0xFF;
        message[8] = 0xFF;
        message[9] = 0x01;
        message[10] = 0x00;
        message[11] = 0x01;
        message[12] = 0x00;
        message[13] = 0xFF;
        message[14] = 0xFF;

        //byte(bytestosend)[15] = { message[0], message[1], message[2], message[3], message[4], message[5], message[6], message[7], message[8], message[9],message[10], message[11],message[12], message[13], message[14] };

        DWORD  dNoOFBytestoWrite;              // No of bytes to write into the port
        DWORD  dNoOfBytesWritten = 0;          // No of bytes written to the port

        dNoOFBytestoWrite = sizeof(message); // Calculating the no of bytes to write into the port
        Status = WriteFile(hComm,               // Handle to the Serialport
            message,            // Data to be written to the port 
            dNoOFBytestoWrite,   // No of bytes to write into the port
            &dNoOfBytesWritten,  // No of bytes written to the port
            NULL);

        if (Status == TRUE)
            printf("\n\n    %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X- Written to %s", message[0], int(message[1]), int(message[2]), int(message[3]), int(message[4]), int(message[5]), int(message[6]), int(message[7]), int(message[8]), int(message[9]), int(message[10]), int(message[11]), int(message[12]), int(message[13]), int(message[14]), ComPortName);
        else
            printf("\n\n   Error %d in Writing to Serial Port", GetLastError());


        int k;
        for (k = 0; k < 50; k++)
        {
            printf("");
        }


        /*-----------------------------------Read --------------------------------------------*/


        int l;
        for (l = 0; l < 50; l++)
        {
            printf("");
        }


        printf("\n\n    Waiting for Data Reception");
        dwEventMask = 1;

        //Status = WaitCommEvent(hComm, &dwEventMask, NULL); //Wait for the character to be received

        /*-------------------------- Program will Wait here till a Character is received ------------------------*/

        if (Status == FALSE)
        {
            printf("\n    Error! in Setting WaitCommEvent()");
        }
        else //If  WaitCommEvent()==True Read the RXed data using ReadFile();
        {
            printf("\n\n    Characters Received");

            do
            {
                //byte(TempChar)[15] = { message[0], message[1], message[2], message[3], message[4], message[5], message[6], message[7], message[8], message[9],message[10], message[11],message[12], message[13], message[14] };
                //if(! ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL))
                if (!ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL))
                ///*    ReadFile(
                //      _In_ HANDLE hFile,
                //      _Out_writes_bytes_to_opt_(nNumberOfBytesToRead, *lpNumberOfBytesRead) __out_data_source(FILE) LPVOID lpBuffer,
                //      _In_ DWORD nNumberOfBytesToRead,
                //      _Out_opt_ LPDWORD lpNumberOfBytesRead,
                //      _Inout_opt_ LPOVERLAPPED lpOverlapped
                //  );*/
                //if (!ReadFile(hComm, SerialBuffer, BUFFERLENGTH, &NoBytesRead, NULL))
                {
                    printf("wrong character" );
                }

                //printf("/n /n %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X", int(TempChar[0]), int(TempChar[1]), int(TempChar[2]), int(TempChar[3]), int(TempChar[4]), int(TempChar[5]), int(TempChar[6]), int(TempChar[7]), int(TempChar[8]), int(TempChar[9]), int(TempChar[10]), int(TempChar[11]), int(TempChar[12]), int(TempChar[13]), int(TempChar[14]));
                SerialBuffer[i] = TempChar;
                //printf("%X is the read", SerialBuffer[i]);
                i++;
            } while (NoBytesRead > 0);

            /*------------Printing the RXed String to Console----------------------*/

            printf("\n\n    ");
            int j = 0;
            for (j = 0; j < i - 1; j++)     // j < i-1 to remove the dupliated last character
                printf("%X are the values read", SerialBuffer[j]);

        }
    }

    CloseHandle(hComm);//Closing the Serial Port
    printf("\n ==========================================\n");
    _getch();

}
#包括“stdafx.h”
#包括
#包括
#包括
#包括
#包括
#定义缓冲区长度256
内部主(空)
{
HANDLE hComm;//串行端口的句柄
char ComPortName[]=“\\.\\COM6”;//要打开的串行端口的名称(可能会更改),
布尔状态;
DWORD dwEventMask;//要触发的事件掩码
无符号字符TempChar;//临时字符
char SerialBuffer[256];//包含RX数据的缓冲区
DWORD NoBytesRead;//读取文件()读取的字节数
int i=0;
printf(“\n\n+===============================================================+”;
printf(“\n |串行通信(Win32 API)|”);
printf(“\n+==========================================================+\n”);
/*-----------------------------------打开串行端口--------------------------------------------*/
hComm=CreateFile(ComPortName,//要打开的端口的名称
GENERIC_READ | GENERIC_WRITE,//读/写访问
0,//不共享,无法共享端口
NULL,//没有安全性
打开现有端口,//仅打开现有端口
0,//非重叠I/O
NULL);//对于通信设备为NULL
if(hComm==无效的句柄值)
printf(“\n错误!-无法打开端口%s”,ComPortName);
其他的
printf(“\n端口%s已打开\n”,ComPortName);
/*-------------------------------设置串行端口的参数------------------------------*/
DCB dcbSerialParams={0};//初始化DCB结构
dcbSerialParams.DCBlength=sizeof(dcbSerialParams);
Status=GetCommState(hComm,&dcbSerialParams);//检索当前设置
如果(状态==FALSE)
printf(“\n错误!在GetCommState()中”);
dcbSerialParams.BaudRate=CBR_9600;//设置BaudRate=9600
dcbSerialParams.ByteSize=8;//设置ByteSize=8
dcbSerialParams.StopBits=ONESTOPBIT;//设置StopBits=1
dcbSerialParams.Parity=EVENPARITY;//设置奇偶性=None
Status=SetCommState(hComm,&dcbSerialParams);//根据DCB中的设置配置端口
如果(状态==FALSE)
{
printf(“\n设置DCB结构时出错”);
}
其他的
{
printf(“\n设置DCB结构成功\n”);
printf(“\n波特率=%d”,dcbSerialParams.Baudrate);
printf(“\n字节大小=%d”,dcbSerialParams.ByteSize);
printf(“\n停止位=%d”,dcbSerialParams.StopBits);
printf(“\n奇偶校验=%d”,dcbSerialParams.Parity);
}
/*------------------------------------设置超时--------------------------------------------------*/
而(1)
{
COMMTIMEOUTS timeouts={0};
timeouts.ReadIntervalTimeout=5000;
timeouts.ReadTotalTimeoutConstant=5000;
timeouts.readTotalTimeout乘数=1000;
timeouts.WriteTotalTimeoutConstant=5000;
timeouts.WriteTotalTimeout乘数=1000;
if(设置通信超时(hComm和超时)==FALSE)
printf(“\n设置超时时出错”);
其他的
printf(“\n\n设置串行端口超时成功”);
printf(“\n |----------串行通信(Win32 API)------”;
printf(“开始写……”);
//char lpBuffer[]=“ABC”;//lpBuffer应该是char或byte数组,否则写入将失败
uint8_t消息[15];
消息[0]=0x16;
消息[1]=0x16;
消息[2]=0x02;
消息[3]=0x01;
消息[4]=0x07;
消息[5]=0x08;
消息[6]=0x00;
消息[7]=0xFF;
消息[8]=0xFF;
消息[9]=0x01;
消息[10]=0x00;
消息[11]=0x01;
消息[12]=0x00;
消息[13]=0xFF;
消息[14]=0xFF;
//字节(bytestosend)[15]={消息[0],消息[1],消息[2],消息[3],消息[4],消息[5],消息[6],消息[7],消息[8],消息[9],消息[10],消息[11],消息[12],消息[13],消息[14]};
DWORD dNoOFBytestoWrite;//要写入端口的字节数
DWORD DNoofBytes writed=0;//写入端口的字节数
dNoOFBytestoWrite=sizeof(message);//计算要写入端口的字节数
Status=WriteFile(hComm,//串行端口的句柄
消息,//要写入端口的数据
dNoOFBytestoWrite,//要写入端口的字节数
&DNOOFByteswrited,//写入端口的字节数
无效);
如果(状态==真)
printf(“\n\n%X%X%X%X%X%X%X%X%X%X%X%X%X-写入%s”,消息[0]、int(消息[1])、int(消息[2])、int(消息[3])、int(消息[4])、int(消息[5])、int(消息[6])、int(消息[7])、int(消息[8])、int(消息[9])、int(消息[10])、int(消息[11])、int(消息[12])、int(消息[13])、int(消息[14])、ComPortName;
其他的
printf(“\n\n将错误%d写入串行端口”,GetLastError());
int k;
对于(k=0;k<50;k++)
{
printf(“”);
}
/*-----------------------------------阅读--------------------------------------------*/
int l;
对于(l=0;l<50;l++)
{
printf(“”);
}
printf(“\n\n正在等待
char a[] = { 0x61, 0x62, 0x63, 0 };
char b[] = {   97,   98,   99, 0 };
std::vector<char> received = readFromSerial();
// assuming arbitrary data..

for(auto c : received)
    std::cout << std::setfill('0') << std::hex << std::setw(2)
        << static_cast<unsigned int>(static_cast<unsigned char>(c)) << std::endl;