Problem getting structure

Tagged: ,

Viewing 10 reply threads
  • Author
    Posts
    • #31164
      poe
      Participant

        Hello!
        I have a transmitter that needs to transmit a structure

        void Task_LoRaSender(void) {
        struct LoraData {
        char type[3] = "ND";
        uint8_t dev_id = config.DevID;
        int32_t latitude = gnss_latitude;
        int32_t longitude = gnss_longitude;
        int32_t altitude = gnss_altitude;
        uint8_t crc8;
        } lora_data;
        lora_data.crc8 = get_crc_8((const char *)&lora_data, sizeof(lora_data) - sizeof(lora_data.crc8));
        
        ResponseStatus response_status = LORA_E32.sendFixedMessage(BASE_ADDR_H, BASE_ADDR_L, BASE_RF_CHANNEL, &lora_data, sizeof(lora_data));
        
        char buffer_navigation_data[256];
        snprintf(buffer_navigation_data, sizeof(buffer_navigation_data),
        "Type: %s, ID: %d | LTD: %ld, LNG: %ld, ALT: %ld | CRC: 0x%02X",
        lora_data.type, lora_data.dev_id,
        lora_data.latitude, lora_data.longitude, lora_data.altitude,
        lora_data.crc8);
        SEND_DEBUG_MSG(buffer_navigation_data);
        }

        In the serial port I see (Its Ok):
        Type: ND, ID: 3 | LTD: 59916757, LNG: 33590709, ALT: 127690 | CRC: 0xE0
        I am successfully sending data over the air.
        =================================
        On the receiving side my code is:

        struct LoRaNavData {
        char type[3];
        uint8_t dev_id;
        int32_t latitude;
        int32_t longitude;
        int32_t altitude;
        uint8_t crc8;
        };
        
        void Task_LoRa(void) {
        if (LORA_E32.available() > 1) {
        char type[3];
        ResponseContainer rs = LORA_E32.receiveInitialMessage(sizeof(type));
        
        String type_str = rs.data;
        if (type_str == "ND") {
        SEND_DEBUG_MSG("Navigation Data");
        ResponseStructContainer rsc = LORA_E32.receiveMessage(sizeof(LoRaNavData));
        struct LoRaNavData nav_data = *(LoRaNavData *)rsc.data;
        
        char buffer_navigation_data[256];
        snprintf(buffer_navigation_data, sizeof(buffer_navigation_data),
        "Type: %s, ID: %d | LTD: %ld, LNG: %ld, ALT: %ld | CRC: 0x%02X",
        type_str, nav_data.dev_id,
        nav_data.latitude, nav_data.longitude, nav_data.altitude,
        nav_data.crc8);
        SEND_DEBUG_MSG(buffer_navigation_data);
        rsc.close();
        } else {
        Serial.println("Something Goes Wrong!");
        }
        }
        }

        In the serial port I see something like this (not what I expected):
        Type: ND, ID: 54 | LTD: -1526807549, LNG: 57776641, ALT: 0 | CRC: 0x00

        I did everything according to the example, the structures are the same, but I get something completely different from what I send.

        How to correctly receive structures?

      • #31165
        Renzo Mischianti
        Keymaster

          Hi Poe,
          try to pass

          
          char type[3] = "NDX";
          

          and give us feedback.
          Bye Renzo

        • #31166
          poe
          Participant

            On the sender’s side?
            Compilation error: initializer-string for ‘char [3]’ is too long [-fpermissive]

          • #31167
            Renzo Mischianti
            Keymaster

              Hi,
              ahh! Yes, the Terminator character.
              It’s strange. Try to add this.

              
              #pragma pack(push, 1)
              struct LoRaNavData {
                  char type[3];
                  uint8_t dev_id;
                  int32_t latitude;
                  int32_t longitude;
                  int32_t altitude;
                  uint8_t crc8;
              };
              #pragma pack(pop)
              

              Bye RM

            • #31168
              poe
              Participant

                Not working
                My sender

                    struct LoraData {
                      char type[3] = "ND";                           // Тип структуры (навигационные данные)
                      uint8_t dev_id = config.DevID;                 // ID Устройства
                      int32_t latitude = gnss_latitude;              // Широта (миллионные доли градуса)
                      int32_t longitude = gnss_longitude;            // Долгота (миллионные доли градуса)
                      int32_t altitude = gnss_altitude;              // Высота (миллиметр)
                      int32_t speed = gnss_speed;                    // Скорость
                      int32_t course = gnss_course;                  // Курс (тысячные доли градуса по часовой стрелке от севера)
                      uint8_t num_satellites = gnss_num_satellites;  // Количество видимых спутников (штук)
                      uint8_t hdop = gnss_hdop;                      // Точность позиционирования (десятые доли, 11 соответствует 1.1)
                      uint16_t sdeg = servo_deg;                     // Текущий угол серво машинки
                      uint8_t crc8;                                  // Контрольная сумма структуры
                    } lora_data;
                    lora_data.crc8 = get_crc_8((const char *)&lora_data, sizeof(lora_data) - sizeof(lora_data.crc8));
                
                    char buffer_navigation_data[256];
                    snprintf(buffer_navigation_data, sizeof(buffer_navigation_data),
                             "Type: %s, ID: %d | LTD: %ld, LNG: %ld, ALT: %ld | SPD: %ld, CRS: %ld | SATs: %d, HDOP: %d, SDeg: %d | CRC: 0x%02X",
                             lora_data.type, lora_data.dev_id,
                             lora_data.latitude, lora_data.longitude, lora_data.altitude,
                             lora_data.speed, lora_data.course,
                             lora_data.num_satellites, lora_data.hdop, lora_data.sdeg,
                             lora_data.crc8);
                    SEND_DEBUG_MSG(buffer_navigation_data);
                
                    /* Отправляем пакет */
                    ResponseStatus response_status = LORA_E32.sendFixedMessage(BASE_ADDR_H, BASE_ADDR_L, BASE_RF_CHANNEL, &lora_data, sizeof(LoraData));

                Serial Out:
                Debug Sensor: Type: ND, ID: 1 | LTD: 53916881, LNG: 27590083, ALT: 220450 | SPD: 0, CRS: 199210 | SATs: 8, HDOP: 16, SDeg: 0 | CRC: 0xE9

                My receiver

                /* Структура навигационных данных */
                #pragma pack(push, 1)
                struct NavData {
                  char type[3];            // Тип структуры (навигационные данные)
                  uint8_t dev_id;          // ID Устройства
                  int32_t latitude;        // Широта (миллионные доли градуса)
                  int32_t longitude;       // Долгота (миллионные доли градуса)
                  int32_t altitude;        // Высота (миллиметр)
                  int32_t speed;           // Скорость
                  int32_t course;          // Курс (тысячные доли градуса по часовой стрелке от севера)
                  uint8_t num_satellites;  // Количество видимых спутников (штук)
                  uint8_t hdop;            // Точность позиционирования (десятые доли, 11 соответствует 1.1)
                  uint16_t sdeg;           // Текущий угол серво машинки
                  uint8_t crc8;            // Контрольная сумма структуры
                };
                #pragma pack(pop)
                
                void Task_LoRa(void) {
                  if (LORA_E32.available() > 1) {
                    char type[3];
                    ResponseContainer rs = LORA_E32.receiveInitialMessage(sizeof(type));
                
                    /* Извлекаем тип пакета */
                    String type_str = rs.data;
                    if (type_str == "ND") {
                
                      ResponseStructContainer rsc = LORA_E32.receiveMessage(sizeof(NavData));
                      struct NavData lora_data = *(NavData *)rsc.data;
                
                      char buffer_navigation_data[256];
                      snprintf(buffer_navigation_data, sizeof(buffer_navigation_data),
                               "Type: %s, ID: %d | LTD: %ld, LNG: %ld, ALT: %ld | SPD: %ld, CRS: %ld | SATs: %d, HDOP: %d, SDeg: %d | CRC: 0x%02X",
                               type_str, lora_data.dev_id,
                               lora_data.latitude, lora_data.longitude, lora_data.altitude,
                               lora_data.speed, lora_data.course,
                               lora_data.num_satellites, lora_data.hdop, lora_data.sdeg,
                               lora_data.crc8);
                      SEND_DEBUG_MSG(buffer_navigation_data);
                
                      rsc.close();
                    } else {
                      Serial.println("Something Goes Wrong!");
                    }
                  }
                }

                Serial Out:
                Debug Base: Type: ND, ID: 54 | LTD: -1526879741, LNG: 56181761, ALT: 0 | SPD: 88983040, CRS: 1116160 | SATs: 0, HDOP: 240, SDeg: 1550 | CRC: 0x00

                I receive something completely different from what I sent.

              • #31169
                Renzo Mischianti
                Keymaster

                  But do you use the same MCU for the sender and receiver?

                • #31170
                  Renzo Mischianti
                  Keymaster

                    Aaah, no, wait, you read the first 3 bytes, then you try to reread the first 3 bytes again.
                    You must create a structure for the remaining data.

                    Check this article that explains how to manage the initial message.

                    Ebyte LoRa E32 device for Arduino, esp32 or esp8266: power saving and sending structured data – Part 5

                    Bye RM

                  • #31171
                    poe
                    Participant

                      I have two ESP32 modules and two LoRa E32-443T33D.
                      One set sends data (structure).
                      The second set receive data.

                      I output a formatted string with the values ​​in the structure to the console.

                      Both structures are the same (transmitter and receiver).
                      The types of variables in the structure are also the same.
                      For example, I send dev_id = 1, and receive 54.

                      Sender
                      Debug Sensor: Type: ND, ID: 1 | LTD: 53916832, LNG: 27590070, ALT: 220810 | SPD: 0, CRS: 199210 | SATs: 8, HDOP: 16, SDeg: 0 | CRC: 0x89
                      Reciver
                      Debug Base: Type: ND, ID: 54 | LTD: -1526821373, LNG: 53004801, ALT: 0 | SPD: 50997760, CRS: 919552 | SATs: 0, HDOP: 197, SDeg: 0 | CRC: 0x00

                      • This reply was modified 1 year, 2 months ago by poe.
                    • #31173
                      Renzo Mischianti
                      Keymaster

                        The structure can’t be the same if you read the first 3 bytes.

                        Check the last sketch in the link I posted before.

                        Bye RM

                      • #31174
                        poe
                        Participant

                          Yes, it worked!
                          Thank you!

                        • #31176
                          poe
                          Participant

                            Another question arose about calculating the checksum of the structure…
                            In the transmitter, I form a static structure (for testing) and send it.

                            #pragma pack(push, 1)
                                struct LoraData {
                                  char type[3] = "ND";         // Тип структуры (навигационные данные)
                                  uint8_t dev_id = 1;          // ID Устройства
                                  int32_t latitude = 2;        // Широта (миллионные доли градуса)
                                  int32_t longitude = 3;       // Долгота (миллионные доли градуса)
                                  int32_t altitude = 4;        // Высота (миллиметр)
                                  int32_t speed = 5;           // Скорость
                                  int32_t course = 6;          // Курс (тысячные доли градуса по часовой стрелке от севера)
                                  uint8_t num_satellites = 7;  // Количество видимых спутников (штук)
                                  uint8_t hdop = 8;            // Точность позиционирования (десятые доли, 11 соответствует 1.1)
                                  uint16_t sdeg = 9;           // Текущий угол серво машинки
                                  uint8_t crc8;                // Контрольная сумма структуры
                                } lora_data;
                            #pragma pack(pop)
                                lora_data.crc8 = get_crc_8((const char *)&lora_data, sizeof(lora_data) - sizeof(lora_data.type) - sizeof(lora_data.crc8));
                            
                                ResponseStatus response_status = LORA_E32.sendFixedMessage(BASE_ADDR_H, BASE_ADDR_L, BASE_RF_CHANNEL, &lora_data, sizeof(LoraData));

                            The checksum is 0x88 (without the type and crc8 fields)

                            Receiver code

                            void Task_LoRa(void) {
                              if (LORA_E32.available() > 1) {
                                /* Извлекаем тип пакета */
                                char type[3];
                                ResponseContainer rs = LORA_E32.receiveInitialMessage(sizeof(type));
                                String type_str = rs.data;
                            
                                if (type_str == "ND") {
                                  /* Пакет с навигационными данными */
                                  /* Создаем структуру с точным количеством выделенной памяти */
                            #pragma pack(push, 1)
                                  struct NavData {
                                    uint8_t dev_id;          // ID Устройства
                                    int32_t latitude;        // Широта (миллионные доли градуса)
                                    int32_t longitude;       // Долгота (миллионные доли градуса)
                                    int32_t altitude;        // Высота (миллиметр)
                                    int32_t speed;           // Скорость
                                    int32_t course;          // Курс (тысячные доли градуса по часовой стрелке от севера)
                                    uint8_t num_satellites;  // Количество видимых спутников (штук)
                                    uint8_t hdop;            // Точность позиционирования (десятые доли, 11 соответствует 1.1)
                                    uint16_t sdeg;           // Текущий угол серво машинки
                                    uint8_t crc8;            // Контрольная сумма структуры
                                  } nav_data;
                            #pragma pack(pop)
                                  ResponseStructContainer rsc = LORA_E32.receiveMessage(sizeof(NavData));
                                  nav_data = *(NavData *)rsc.data;
                            
                                  /* Проверяем контрольную сумму */
                                  uint8_t crc8_calc = get_crc_8((const char *)&nav_data, sizeof(nav_data) - sizeof(nav_data.crc8));
                                  char buffer_crc[256];
                                  snprintf(buffer_crc, sizeof(buffer_crc),
                                           "ID: %d | Rem CRC8: 0x%02X | Cal CRC8: 0x%02X",
                                           nav_data.dev_id, nav_data.crc8, crc8_calc);
                                  SEND_DEBUG_MSG(buffer_crc);
                                  if (crc8_calc != nav_data.crc8) {
                                    SEND_DEBUG_MSG("ER! CRC8 Navigation Data");
                                    rsc.close();
                                    return;
                                  }
                            
                                  rsc.close();
                                } else {
                                  Serial.println("Something Goes Wrong!");
                                }
                              }
                            }

                            But the checksum is 0x04 (without crc8 fields)
                            I use receiveInitialMessage.
                            What could be the problem with the checksum calculation?
                            The calculation function is the same on both sides.

                            • This reply was modified 1 year, 2 months ago by poe.
                        Viewing 10 reply threads
                        • You must be logged in to reply to this topic.
                        Exit mobile version