如何将浮点数分隔为十六进制数组元素

时间:2019-02-01 16:43:07

标签: arduino bluetooth-lowenergy arduino-c++

在以下BLE示例中:我想将浮点数分隔为可以分配给CUSTOM_UUID的元素。

例如:取12345.67并以某种方式将其分配给CUSTOM_UUID []作为

    const uint8_t CUSTOM_UUID[] =
    {
        0X00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x00, 0x01, 0x32, 0x54, 0x67
    };

    BLEUuid uuid = BLEUuid(CUSTOM_UUID);

当前格式在BLE广告中显示为: 00000000-0000-0000-0000-000000000000 所以我想做些类似的事情: 第一步是00000000-0000-0000-0000-000001234567 下一步将处理小数。

 /*********************************************************************
 This is an example for our nRF52 based Bluefruit LE modules

 Pick one up today in the adafruit shop!

 Adafruit invests time and resources providing this open source code,
 please support Adafruit and open-source hardware by purchasing
 products from Adafruit!

 MIT license, check LICENSE for more information
 All text above, and the splash screen below must be included in
 any redistribution

 Author: KTOWN (Kevin Townsend)
 Copyright (C) Adafruit Industries 2017
*********************************************************************/

/*  This example constantly advertises a custom 128-bit UUID, and is
 *  intended to be used in combination with a Central sketch that scans
 *  for this UUID, and then displays an alert message, sorting matching
 *  devices by their RSSI level which is an approximate indication of
 *  distance (although highly subject to environmental obstacles).
 *  
 *  By including a custom UUID in the advertising packet, we can easily
 *  filter the scan results on the Central device, rather than manually
 *  parsing the advertising packet(s) of every device in range.
 *  
 *  This example is intended to be run with the *_central.ino version
 *  of this application.
 */

#include <bluefruit.h>
#include <ble_gap.h>

//int test_hex = 0x55;

// Software Timer for blinking RED LED
SoftwareTimer blinkTimer;

// Custom UUID used to differentiate this device.
// Use any online UUID generator to generate a valid UUID.
// Note that the byte order is reversed ... CUSTOM_UUID
// below corresponds to the follow value:
// df67ff1a-718f-11e7-8cf7-a6006ad3dba0
const uint8_t CUSTOM_UUID[] =
{
    0X00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};

BLEUuid uuid = BLEUuid(CUSTOM_UUID);




void setup() 
{
  Serial.begin(115200);
  while ( !Serial ) delay(10);   // for nrf52840 with native usb

  Serial.println("Bluefruit52 Peripheral Proximity Example");
  Serial.println("----------------------------------------\n");


  // Initialize blinkTimer for 1000 ms and start it
  blinkTimer.begin(1000, blink_timer_callback);
  blinkTimer.start();

  err_t err = Bluefruit.begin();
  if (err)
  {
    Serial.print("Unable to init Bluefruit (ERROR CODE: ");
    Serial.print(err);
    Serial.println(")");
    while(1)
    {
      digitalToggle(LED_RED);
      delay(100);
    }
  }
  else
  {
    Serial.println("Bluefruit initialized (peripheral mode)");
  }

  // Set max power. Accepted values are: -40, -30, -20, -16, -12, -8, -4, 0, 4
  Bluefruit.setTxPower(4);
  Bluefruit.setName("Bluefruit52");

  // Set up and start advertising
  startAdv();

  Serial.println("Advertising started"); 

}

void startAdv(void)
{   
  // Note: The entire advertising packet is limited to 31 bytes!

  // Advertising packet
  Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
  Bluefruit.Advertising.addTxPower();

  // Preferred Solution: Add a custom UUID to the advertising payload, which
  // we will look for on the Central side via Bluefruit.Scanner.filterUuid(uuid);
  // A valid 128-bit UUID can be generated online with almost no chance of conflict
  // with another device or etup
  Bluefruit.Advertising.addUuid(uuid);


  // Alternative Solution: Manufacturer Specific Data (MSD)
  // You could also send a custom MSD payload and filter for the 'Company ID'
  // via 'Bluefruit.Scanner.filterMSD(CID);', although this does require a
  // valid CID, which is why the UUID method above is more appropriate in
  // most situations. For a complete list of valid company IDs see:
  // https://www.bluetooth.com/specifications/assigned-numbers/company-identifiers
  // For test purposes, 0xFFFF CAN be used, but according to the Bluetooth SIG:
  // > "This value may be used in the internal and interoperability tests before a
  // >  Company ID has been assigned. This value shall not be used in shipping end
  // >  products."
  uint8_t msd_payload[4]; // Two bytes are required for the CID, so we have 2 bytes user data, expand as needed
  uint16_t msd_cid = 0xFFFF;
  memset(msd_payload, 0, sizeof(msd_payload));
  memcpy(msd_payload, (uint8_t*)&msd_cid, sizeof(msd_cid));
  msd_payload[2] = 0x11;
  msd_payload[3] = 0x22;

  Bluefruit.Advertising.addData(BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA, msd_payload, sizeof(msd_payload));


  // Not enough room in the advertising packet for name
  // so store it in the Scan Response instead
  Bluefruit.ScanResponse.addName();

  /* Start Advertising
   * - Enable auto advertising if disconnected
   * - Interval:  fast mode = 20 ms, slow mode = 152.5 ms
   * - Timeout for fast mode is 30 seconds
   * - Start(timeout) with timeout = 0 will advertise forever (until connected)
   * 
   * For recommended advertising interval
   * https://developer.apple.com/library/content/qa/qa1931/_index.html
   */
  Bluefruit.Advertising.restartOnDisconnect(true);
  Bluefruit.Advertising.setInterval(32, 244);    // in units of 0.625 ms
  Bluefruit.Advertising.setFastTimeout(30);      // number of seconds in fast mode
  Bluefruit.Advertising.start();
}

void loop() 
{
}

/**
 * Software Timer callback is invoked via a built-in FreeRTOS thread with
 * minimal stack size. Therefore it should be as simple as possible. If
 * a periodically heavy task is needed, please use Scheduler.startLoop() to
 * create a dedicated task for it.
 * 
 * More information http://www.freertos.org/RTOS-software-timer.html
 */
void blink_timer_callback(TimerHandle_t xTimerID)
{
  (void) xTimerID;
  digitalToggle(LED_RED);
}

3 个答案:

答案 0 :(得分:0)

我使用此标准例程将2个字节合并为1个字节。 浮点数中的点变为“ E”,如果您不希望这样做,则可以将浮点数更改为长整数。

uint8_t CUSTOM_UUID[16];

void setup() {
  Serial.begin(115200);
}

void loop() {
  /* example with standard UUID: */
  stringToByte("E2C56DB5-DFFB-48D2-B060-D0F5A71096E0");
  for (int i = 0; i < 16; i++) {
    Serial.println(CUSTOM_UUID[i], HEX);
  }
  Serial.println();

  /* example with float: */
  float number = 12345.67;
  char floatToString[32];
  dtostrf(number, 32, 2, floatToString);
  stringToByte(floatToString);
  for (int i = 0; i < 16; i++) {
    Serial.println(CUSTOM_UUID[i], HEX);
  }
  while(1);
}

void stringToByte(char * data)
{
  // Create two pointers that point to the start of the data
  char *leader = data;
  char *follower = leader;
  int counter = 0;

  // Iterate till at the end of the string
  while (*leader) {
      // Check to see if the current character is a -
      if (*leader != '-') {

          // Grab the next two characters and move leader forwards
          char high = *leader;
          leader++;
          char low = *leader;

          // Convert ASCII 0-9A-F to a value 0-15
          if (high > 0x39) high -= 7;
          high &= 0x0f;

          // Same again for the low byte:
          if (low > 0x39) low -= 7;
          low &= 0x0f;

          // Combine the two into a single byte and store in follower:
          *follower = (high << 4) | low;
          CUSTOM_UUID[counter] = *follower;

      } else {
          counter--;
      }

      // Move both pointers to the next character:
      leader++;
      follower++;
      // increase counter:
      counter++;
  }
}

答案 1 :(得分:0)

这是从广告包中获得更多带宽的一种有趣方法,但是它与UUID的预期用途背道而驰,UUID的用途是识别外围设备的服务配置文件和可用特性。 (我假设你打算动态地生成基于一些浮点传感器值的UUID。)

当您尝试使用中央(主)设备的BLE通信堆栈连接到设备时,更改UUID会造成很多麻烦。 Android或IOS手机。 BLE中央设备希望从给定的外围设备中收集特征性UUID的静态层次结构,然后使用这些UUID标识相应的特征值。例如,IOS BLE堆栈具有用于标识这些众所周知的广告UUID的常量,这些常量在连接前均可用:CBAdvertisementDataLocalNameKey,CBAdvertisementDataManufacturerDataKey,CBAdvertisementDataServiceUUIDsKey,CBAdvertisementDataSolicitedServiceUUIDsKey。

相反,请注意,通用属性配置文件包括数据类型输入,可让您直接设置和恢复浮点和双浮点IEEE-754浮点特性值,以及定点特性类型,它们可能更好地满足您的目的。

在主机BLE堆栈上的文档中搜索“特征表示格式描述符”,以找到用于标识类型的常量。

我建议您花一些时间研究用于BLE通信的iOS或Android代码示例,以及各种描述BLE设备配置文件的层次结构的Bluetooth / GATT教程。在此处找到符合GATT配置文件之一的廉价BLE设备:https://www.bluetooth.com/specifications/gatt(您可能需要创建一个免费帐户。)并尝试通过手机或PC与它联系。 或者,查看是否可以找到使该设备符合著名的GATT配置文件的Arduino示例代码,并将其用作外围设备。

答案 2 :(得分:0)

正如其他人所说,在运行时更改UUID并不是真正的预期行为,尤其是当中央设备(如智能手机)可以将外围设备的配置文件保存在缓存中时。因此,动态更改可能会引起一些麻烦。

通过BLE广告包发送自定义数据的预期方式是使用“制造商特定数据”字段。它以2个字节的公司ID开头,然后可以跟自定义数据。只要您同时控制中央和外围应用程序,就可以根据需要存储浮点数。

还要小心,因为在广告包中同时发送自定义UUID和特定于制造商的数据可能会占用一些空间,并且广告包受到限制。如果您需要发送更多数据(例如多个浮动),请查看扫描响应