This post was last edited by Misaka10032 on 2024-6-28 03:57
The previous evaluation articles detailed how to use the Bluetooth function and combine it with the App to receive Bluetooth data (single Hex) sent from the development board. In this section, we will combine a humidity and temperature sensor to send humidity and temperature data to the host computer.
The humidity and temperature sensor used in this chapter is DHT11. Since we are using the Arduino development environment, the driver library for DHT11 can be easily found in the Arduino IDE. We can search for DHT-sensor-library in the Arduino library manager. I have attached the link
One very friendly thing is that this github library also provides a very detailed Demo example
In this library, we can see that there are three sensors supported, namely DHT 11, DHT 22 (AM2302), AM2321 and DHT 21 (AM2301)
We simply modify the above code.
#include <DHT.h>
#include <Arduino.h>
#include <bluefruit.h>
#define DHTPIN 2 // DHT11 数据引脚连接到 Arduino 的数字引脚 2
#define DHTTYPE DHT11 // 定义传感器类型为 DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println("DHT11 test!");
dht.begin();
}
void loop() {
// 延迟两秒钟
delay(1000);
// 获取温度和湿度数据
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
// 检查是否读取失败并打印相应信息
if (isnan(humidity) || isnan(temperature)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// 打印温度和湿度数据
Serial.print(F("Humidity: "));
Serial.print(humidity);
Serial.print(F("% Temperature: "));
Serial.print(temperature);
Serial.println(F("°C"));
}
In this case, by connecting IO2 to DHT11, the data of DHT11 can be read. Then we modify the above code again based on the Bluetooth broadcast code in the previous section to send the humidity temperature data through Bluetooth data.
#include <DHT.h>
#include <bluefruit.h>
#include <Arduino_JSON.h>
#define DHTPIN 2 // DHT11 数据引脚连接到 Arduino 的数字引脚 2
#define DHTTYPE DHT11 // 定义传感器类型为 DHT11
DHT dht(DHTPIN, DHTTYPE);
// BLE Service
BLEDfu bledfu; // OTA DFU service
BLEDis bledis; // device information
BLEUart bleuart; // uart over ble
BLEBas blebas; // battery
void setup() {
Serial.begin(115200);
#if CFG_DEBUG
// Blocking wait for connection when debug mode is enabled via IDE
while (!Serial) yield();
#endif
Serial.println("Bluefruit52 BLEUART Example");
Serial.println("---------------------------\n");
// Setup the BLE LED to be enabled on CONNECT
// Note: This is actually the default behavior, but provided
// here in case you want to control this LED manually via PIN 19
Bluefruit.autoConnLed(true);
// Config the peripheral connection with maximum bandwidth
// more SRAM required by SoftDevice
// Note: All config***() function must be called before begin()
Bluefruit.configPrphBandwidth(BANDWIDTH_MAX);
Bluefruit.begin();
Bluefruit.setTxPower(4); // Check bluefruit.h for supported values
//Bluefruit.setName(getMcuUniqueID()); // useful testing with multiple central connections
Bluefruit.Periph.setConnectCallback(connect_callback);
Bluefruit.Periph.setDisconnectCallback(disconnect_callback);
// To be consistent OTA DFU should be added first if it exists
bledfu.begin();
// Configure and Start Device Information Service
bledis.setManufacturer("Adafruit Industries");
bledis.setModel("Bluefruit Feather52");
bledis.begin();
// Configure and Start BLE Uart Service
bleuart.begin();
// Start BLE Battery Service
blebas.begin();
blebas.write(100);
// Set up and start advertising
startAdv();
dht.begin();
}
void startAdv(void) {
// Advertising packet
Bluefruit.Advertising.addFlags(BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE);
Bluefruit.Advertising.addTxPower();
// Include bleuart 128-bit uuid
Bluefruit.Advertising.addService(bleuart);
// Secondary Scan Response packet (optional)
// Since there is no room for 'Name' in Advertising packet
Bluefruit.ScanResponse.addName();
Bluefruit.Advertising.restartOnDisconnect(true);
Bluefruit.Advertising.setInterval(32, 244); // in unit of 0.625 ms
Bluefruit.Advertising.setFastTimeout(30); // number of seconds in fast mode
Bluefruit.Advertising.start(0); // 0 = Don't stop advertising after n seconds
}
void loop() {
delay(500);
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// 只保留整数部分
int humidityInt = (int)humidity;
int temperatureInt = (int)temperature;
// 创建JSON对象
JSONVar jsonObj;
jsonObj["temperature"] = temperatureInt;
jsonObj["humidity"] = humidityInt;
// 将JSON对象转换为字符串
String jsonString = JSON.stringify(jsonObj);
// 将JSON字符串转换为字节数组
uint8_t buf[64];
int len = jsonString.length();
jsonString.getBytes(buf, len + 1);
// 通过BLE UART发送字节数组
bleuart.write(buf, len);
// 打印到串口监视器
Serial.println(jsonString);
}
// callback invoked when central connects
void connect_callback(uint16_t conn_handle) {
// Get the reference to current connection
BLEConnection* connection = Bluefruit.Connection(conn_handle);
char central_name[32] = { 0 };
connection->getPeerName(central_name, sizeof(central_name));
Serial.print("Connected to ");
Serial.println(central_name);
}
/**
* Callback invoked when a connection is dropped
* @param conn_handle connection where this event happens
* @param reason is a BLE_HCI_STATUS_CODE which can be found in ble_hci.h
*/
void disconnect_callback(uint16_t conn_handle, uint8_t reason) {
(void)conn_handle;
(void)reason;
Serial.println();
Serial.print("Disconnected, reason = 0x");
Serial.println(reason, HEX);
}
As you can see, in the main loop of the above code, after obtaining the humidity temperature data, it is converted into INT type and then converted into JSON format using Arduino_JSON. Then it is sent to the host computer via Bluetooth.
If you don't have Arduino_JSON installed locally, you need to install Arduino_JSON in the library manager first.
After that, we can burn the code into the development board and use the Bluetooth tool I mentioned in the previous section to receive data.
The experimental phenomena are as follows:
Originally, I wanted to use Android Studio to write a host computer software in this chapter to receive Bluetooth data and then display a line chart. But for some reason, my Android phone cannot connect to the Bluetooth of this development board. I don’t know how to develop for iOS. So I can only use the software in the App store to show the effect. If I have any plans later, I should build an Android program to receive Bluetooth data and parse it into ASCII format. Then parse JSON and draw a line chart based on the JSON data object. Another way here is to upload the data to Home Assistant using MQTT. Use Home Assistant on the mobile phone to view this information in real time. But it always feels redundant. I will try my girlfriend’s phone some other day. If it works, I will build an APP and attach the address of the GITHUB warehouse to this post.