Protocols used to talk between an embedded CPU and a PC

前端 未结 8 1940
梦谈多话
梦谈多话 2021-01-31 20:21

I am building a small device with its own CPU (AVR Mega8) that is supposed to connect to a PC. Assuming that the physical connection and passing of bytes has been accomplished,

8条回答
  •  我在风中等你
    2021-01-31 20:37

    I've done stuff like this with a simple binary format

    struct PacketHdr
    {
      char syncByte1;
      char syncByte2;
      char packetType;
      char bytesToFollow;  //-or- totalPacketSize
    };
    
    struct VoltageSet
    { 
       struct PacketHdr;
       int16 channelId;
       int16 voltageLevel; 
       uint16 crc;
    };
    
    struct VoltageResponse
    {
       struct PacketHdr;
       int16 data[N];  //Num channels are fixed
       uint16 crc;
    }
    

    The sync bytes are less critical in a synchronous protocol than in an asynchronous one, but they still help, especially when the embedded system is first powering up, and you don't know if the first byte it gets is the middle of a message or not.

    The type should be an enum that tells how to intepret the packet. Size could be inferred from type, but if you send it explicitly, then the reciever can handle unknown types without choking. You can use 'total packet size', or 'bytes to follow'; the latter can make the reciever code a little cleaner.

    The CRC at the end adds more assurance that you have valid data. Sometimes I've seen the CRC in the header, which makes declaring structures easier, but putting it at the end lets you avoid an extra pass over the data when sending the message.

    The sender and reciever should both have timeouts starting after the first byte of a packet is recieved, in case a byte is dropped. The PC side also needs a timeout to handle the case when the embedded system is not connected and there is no response at all.

    If you are sure that both platforms use IEEE-754 floats (PC's do) and have the same endianness, then you can use floats as the data type. Otherwise it's safer to use integers, either raw A/D bits, or a preset scale (i.e. 1 bit = .001V gives a +/-32.267 V range)

提交回复
热议问题