Android Code Snippet Send structure from C++ to B4X in prefix mode

Discussion in 'Code Snippets' started by johnf2013, Feb 10, 2018.

  1. johnf2013

    johnf2013 Member Licensed User

    I needed to send a structure from an STM32 running an Arduino core to an Android device using Async Streams in prefix mode over Bluetooth. This snippet should work with the 8 bitters too.
    Seems to work for me. Better programmers than me are sure to find holes in it so I am waiting to learn.

    Code:
    typedef struct __PACKED {
        ...
        ...
    } Pkt_Struct;
    Pkt_Struct pkt;

    void SendPacket() {
        static uint32_t cPktPrefix = sizeof(Pkt_Struct);

        #ifdef __ORDER_LITTLE_ENDIAN__
        Serial2.write((uint8_t)(cPktPrefix & 0xff));
        Serial2.write((uint8_t)((cPktPrefix >> 8) & 0xff));
        Serial2.write((uint8_t)((cPktPrefix >> 16) & 0xff));
        Serial2.write((uint8_t)((cPktPrefix >> 24) & 0xff));
        #else
        Serial2.write(reinterpret_cast<uint8_t*>(&cPktPrefix), sizeof(cPktPrefix));
        #endif

        Serial2.write(reinterpret_cast<uint8_t*>(&pkt), sizeof(Pkt_Struct));
    }
     
    Erel likes this.
  2. Erel

    Erel Administrator Staff Member Licensed User

    Looks correct. Note that you must set the endianess correctly in the B4X side.
     
Loading...
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice