How do I send 0xff byte across a serial port in C?

痴心易碎 提交于 2019-12-20 07:59:04

问题


So I would like to send a 0xff byte across a serial cable which triggers a computer to send back data via an Ethernet cable . The code is as follows

#include <stdio.h>
#include <stdlib.h>
#include<windows.h>
#include<winsock2.h>
#include <string.h>
#include <time.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define BUFLEN 4097 //Max length of buffer
#define PORT 9090 //The port on which to listen for incoming data

int main()
{
    BOOL Status;
    HANDLE ComPort;
    char str[20] = "\\\\.\\COM";
    char input[4] = "";
    printf("Enter COM port: ");
    fgets(input,4,stdin);
    input[strcspn(input, "\n")] = 0;
    strncat(str,input, 5);
    ComPort = CreateFile((const char*)str,                //port name
                      GENERIC_READ | GENERIC_WRITE, //Read/Write
                      0,                            // No Sharing
                      NULL,                         // No Security
                      OPEN_EXISTING,// Open existing port only
                      0,            // Non Overlapped I/O
                      NULL);        // Null for Comm Devices

  if (ComPort == INVALID_HANDLE_VALUE){
      printf("\nError in opening serial port");
      exit(EXIT_FAILURE);}
  else{
      printf("opening serial port successful");
  }
    DCB dcbSerialParams = { 0 }; // Initializing DCB structure
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    Status = GetCommState(ComPort, &dcbSerialParams);

    dcbSerialParams.BaudRate = CBR_115200;  // Setting BaudRate = 115200
    dcbSerialParams.ByteSize = 8;         // Setting ByteSize = 8
    dcbSerialParams.StopBits = ONESTOPBIT;// Setting StopBits = 1
    dcbSerialParams.Parity   = NOPARITY;  // Setting Parity = None

    SetCommState(ComPort, &dcbSerialParams);
    COMMTIMEOUTS timeouts = { 0 };

    timeouts.ReadIntervalTimeout         = MAXWORD; // in milliseconds
    timeouts.ReadTotalTimeoutConstant    = 10000; // in milliseconds
    timeouts.ReadTotalTimeoutMultiplier  = MAXWORD; // in milliseconds
    timeouts.WriteTotalTimeoutConstant   = 0; // in milliseconds
    timeouts.WriteTotalTimeoutMultiplier = 0; // in milliseconds

    char lpBuffer[] = {255};
    DWORD dNoOFBytestoWrite;         // No of bytes to write into the port
    DWORD dNoOfBytesWritten;     // No of bytes written to the port
    dNoOFBytestoWrite = sizeof(lpBuffer);

    SOCKET s;
    struct sockaddr_in server, si_other;
    int slen , recv_len;
    char buf[BUFLEN];
    WSADATA wsa;

    slen = sizeof(si_other) ;

    //Initialise winsock
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    //Create a socket
    if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
    {
        printf("\nCould not create socket : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( PORT );

    //Bind
    if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
    {
        printf("\nBind failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("\nBinding successful");
    DWORD timeout = 0.2 * 1000;//0.2 second ethernet timeout
    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

    FILE * fPtr;
    char filename[50] = "fpgadat.bin";
    fPtr = fopen((const char*) filename, "wb");//Open file in wb (write) mode.

    // fopen() return NULL if last operation was unsuccessful
    if(fPtr == NULL)
    {
        // File not created hence exit
        printf("Unable to create file.\n");
        exit(EXIT_FAILURE);
    }

    while(1)
    {
        time_t start = time(NULL);
        Status = WriteFile(ComPort,        // Handle to the Serial port
                   lpBuffer,     // Data to be written to the port
                   dNoOFBytestoWrite,  //No of bytes to write
                   &dNoOfBytesWritten, //Bytes written
                   NULL);

    if(Status == 0){
        printf("\nFailed to write to serial port");
        return 0;
    }else{
    printf("\nData successfully written to serial port");
    }
        printf("\nWaiting for data from fpga...");
        fflush(stdout);

        memset(buf,'\0', BUFLEN);//clear the buffer by filling null, it might have previously received data
        //try to receive some data, this is a blocking call
        if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR)
        {
            printf("\nEthernet connection time-out");
            break;

        }

    fwrite(buf , 1 , sizeof(buf) , fPtr );
    printf("%.2f\n", (double)(time(NULL) - start));
    }
    //close file descriptors
    fclose(fPtr);
    CloseHandle(ComPort);
    closesocket(s);
    WSACleanup();

}

I seem to always get a timeout error on the ethernet. I think it is because I am not sending the necessary 0xff byte to trigger the second computer to send back the data via ethernet. What could the issue be?


回答1:


I'm not sure what you are doing before you use this code but I would suggest using Com0com, PortMon or Wire Shark to monitor your Com ports and your ethernet. It'll make your life easier.

Also in your question you should tell us what the result of your code is so we can get a better idea of what's going on.

The link https://www.xanthium.in/Serial-Port-Programming-using-Win32-API is identical to what you are trying to do.

Are you sure that you are chosing the correct com port?

Your code shows that you are trying to write to your serial port which is connected to another PC that is listening on a serial port. Are you sure that the other PC is listening with the same baud and control lines. (It may be set to some default.) You should first try using Terminal.exe on both PCs or something similar to see if you serial communication is working between both PCs. Next you should create an application that only sends to the com port and listen on the other PC with a terminal emulator to see if it reaches.



来源:https://stackoverflow.com/questions/59176419/how-do-i-send-0xff-byte-across-a-serial-port-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!