顯示具有 onewire 標籤的文章。 顯示所有文章
顯示具有 onewire 標籤的文章。 顯示所有文章

2026年11月22日 星期日

ESP32 IoT in Practice EP1: One DS18B20, Four Paths — Serial, Bluetooth, MQTT and a Self-Hosted Pi | ESP32 物聯網實戰 EP1:一顆溫度感測器的四條路(序列埠、藍牙、MQTT、自架 Pi)

📺 影片版(約 17 分鐘,有章節可跳著看):本集整理成一支影片,細節在下方文字與各篇原文。
YouTube:https://youtu.be/U8Ih9Xif6Vc(winson-DIY 頻道)

這是「ESP32 物聯網實戰」系列第一集的總整理。同一顆 DS18B20 溫度感測器,我在 2023 年陸續試了四種把讀值送出去的方法:序列埠接 C# 畫曲線、藍牙 SPP 上手機、公用 MQTT broker 接 Node-RED、在 Raspberry Pi 自架 Mosquitto 再用 cpolar 開通道。這篇把五篇原文串成一條線,並整理每條路的坑。

This is the wrap-up of EP1 of the "ESP32 IoT in Practice" series: one DS18B20 sensor, four ways to move its reading — serial to a C# chart, Bluetooth SPP to a phone, a public MQTT broker to Node-RED, and a self-hosted Mosquitto broker on a Raspberry Pi exposed through a cpolar tunnel.

本集用到的原文 | Original posts

第一章 DS18B20 與 1-Wire

一條資料線、每顆 64 位元序號、一條線可掛多顆;12 位元轉換要 750 ms,上電預設 85°C、斷線讀到 -127。DQ 要 4.7kΩ 上拉,ESP32 建議接 3.3V。序列埠指令 VER/DS18B20_ON/DS18B20_OFF(小寫自動轉大寫,用 strstr 比對)。

第二章 序列埠+C# 曲線

Node5 把溫度包成 JSON 經 Mesh 交給接 USB 的 Node1,C# 解析後畫曲線;手握探頭,不到 40 秒從約 23.7°C 升到 31°C。兩個坑:requestTemperatures 卡 750 ms、C# DataReceived 收到半行要先緩衝。

第三章 藍牙 SPP 上手機

BluetoothSerial 開「BT_BS18B20」,送「E+溫度」給手機 App 畫曲線。程式一輪呼叫兩次轉換(約 1.5 秒一筆)、手機端指令函式是空的;ESP32-S3/C3 與 iPhone 要改 BLE。

第四章 MQTT+Node-RED

公用 broker mqtt.eclipseprojects.io,發布 winsondiy/ESP32/temp 與環保署新竹 PM2.5,訂閱 winsondiy/ESP32/led 控制 GPIO16;先用 MQTT Explorer 驗證,再接 Node-RED。公用 broker 人人可讀寫,只適合測試。

第五章 Pi 自架 Mosquitto+cpolar

apt 安裝 mosquitto、兩個終端機 sub/pub 測試、一行腳本裝 Node-RED,cpolar 把本機 1883 開成 1.tcp.cpolar.io:10521,ESP32 只改 server 與 port。Mosquitto 2.0 預設只聽本機,區網直連要加 listener 與帳密。

第六章 四條路怎麼選

桌邊量測用序列埠、現場看用藍牙、快速驗證用公用 MQTT、長期使用自架 broker。下一集:沒有路由器也能組網的 ESP32 WiFi Mesh。

補充:原文沒寫到的原理與常見坑

補充一:DS18B20 與 1-Wire 重點

DS18B20 是 1-Wire 數位溫度感測器:一條資料線 DQ 同時負責傳指令和回資料,每顆出廠都有唯一的 64 位元 ROM 序號,所以同一條線可以並聯很多顆,用序號分辨。

項目規格(datasheet)
量測範圍-55~+125°C
精度±0.5°C(-10~+85°C)
解析度/轉換時間9 位元 93.75 ms、10 位元 187.5 ms、11 位元 375 ms、12 位元 750 ms(0.0625°C)
電源3.0~5.5V,也可寄生供電
特殊讀值上電預設 +85°C;DallasTemperature 讀不到時回 -127(DEVICE_DISCONNECTED_C)

接線注意:DQ 要有 4.7kΩ 上拉到 VCC(小模組板通常已焊好,防水探頭要自己加)。原文電路是 5V 供電、資料接 GPIO4;若上拉接 5V,DQ 閒置就是 5V,超過 ESP32 GPIO 的 3.3V 額定,建議 DS18B20 改接 3.3V。

補充二:讀溫度不要卡住主迴圈

requestTemperatures() 預設會等轉換完成才返回,12 位元要等 750 ms。主迴圈還要處理 Mesh、藍牙或 MQTT 時,改成「先發轉換、下一輪再讀」:

sensors.setResolution(12);
sensors.setWaitForConversion(false);   // 不等 750 ms
sensors.requestTemperatures();
unsigned long last = 0;

void loop() {
  if (millis() - last >= 2000) {        // 間隔要大於轉換時間
    last = millis();
    float t = sensors.getTempCByIndex(0);   // 上一輪的結果
    sensors.requestTemperatures();          // 立刻發下一次
    if (t != DEVICE_DISCONNECTED_C) { /* 送出 t */ }
  }
  // 其他工作:mesh.update()/MQTTClient.loop()…
}

(範例程式未實機編譯。)

補充三:藍牙 SPP 的限制

  • SPP(Serial Port Profile)是傳統藍牙(Classic BT)的「無線序列埠」,Arduino-ESP32 的 BluetoothSerial 用起來跟 Serial 一樣。
  • 只有原始 ESP32 有傳統藍牙;ESP32-S3、ESP32-C3 只有 BLE,沒有 BluetoothSerial,要改用 BLE(例如 Nordic UART Service)。
  • iPhone 一般 App 不能用傳統藍牙 SPP,要給 iPhone 看也得改 BLE。
  • 原文 SPP 版程式在 flag.DS18B20Flag == 1 時,先呼叫 vDS18B20Task()(裡面已 requestTemperatures 一次),接著又 requestTemperatures 一次,等於一輪等兩次轉換,12 位元下約 1.5 秒才送一筆(由程式推算);只呼叫一次即可。
  • 原文 BTprocessCommand() 是空函式,所以 DS18B20_ON/OFF 仍從 USB 序列埠下;要從手機開關,把 processCommand() 的判斷搬進去即可。SerialBT.readString() 會等到逾時(預設 1 秒)才返回,指令短的話改用 readStringUntil('\n')。

補充四:MQTT 要知道的幾件事

  • topic 用斜線分層,原文用 winsondiy/ESP32/temp、winsondiy/ESP32/pm2.5_avg(發布)、winsondiy/ESP32/led(訂閱);訂閱端可用 +、# 萬用字元,例如 winsondiy/ESP32/#。
  • QoS 0/1/2:0 送了就算、1 至少一次、2 剛好一次。PubSubClient 發布只支援 QoS 0,訂閱可 0 或 1;預設封包上限 256 位元組(setBufferSize() 可調),keepalive 15 秒。
  • retain:broker 保留最後一筆,新訂閱者一連上就拿到,適合「目前溫度」。遺囑(Last Will):裝置斷線時 broker 代發,例如 status = offline。
  • 公用 broker(mqtt.eclipseprojects.io、test.mosquitto.org)不用註冊,但任何人都能訂閱、也能發布到你的 led topic;只適合測試,topic 前綴取得獨特一點。
  • loop() 裡每 5 秒做一次 HTTPS 查詢(環保署 API),查詢期間 MQTTClient.loop() 跑不到;API 很慢時,可把查詢拉長間隔(PM2.5 每小時才更新),或放到另一個 FreeRTOS 任務。原文程式的間隔是 5000 ms,註解寫「每10秒」,以程式為準。

補充五:Pi 自架 Mosquitto 的設定坑

Mosquitto 2.0 起,沒有設定 listener 時只聽本機(127.0.0.1)。原文用 cpolar 從 Pi 本機轉送 1883,所以不受影響;但同一個區網的 ESP32 直接連 Pi 的 IP 會被拒絕。要讓區網連線,在 /etc/mosquitto/conf.d/ 加一個檔:

listener 1883
allow_anonymous false
password_file /etc/mosquitto/passwd

用 sudo mosquitto_passwd -c /etc/mosquitto/passwd esp32 建帳號,重啟 sudo systemctl restart mosquitto;ESP32 端把 MQTTUser/MQTTPassword 填上。透過 cpolar 對外公開時更要設帳密。通道重開後位址或埠號若改變,ESP32 程式的 MQTTServer、MQTTPort 要跟著改;固定位址或改走 Tailscale 等 VPN 可避免(見本系列 EP3)。

補充六:四條路怎麼選

方式距離需要網路適合
序列埠+C#USB 線(或 Mesh 接力)不用桌邊量測、產線治具、要存檔畫圖
藍牙 SPP約 10 公尺不用現場用手機看、單人單機
公用 MQTT有網路就行要快速驗證、多人同時看
自架 MQTT+通道有網路就行要長期使用、資料自己管

ESP32 物聯網實戰系列 | ESP32 IoT in Practice

2023年7月25日 星期二

DS18B20 temperature recorder - ESP32 Bluetooth SPP control

Purpose:

手機安裝Bluetooth Terminal/Graphics APP

Use the mobile phone APP to read the temperature display curve or value of the DS18B20 read by the ESP32 through the Bluetooth SPP profile on the mobile phone.

利用手機APP經由藍芽 SPP profile將ESP32讀取到的DS18B20的溫度顯示曲線或數值在手機

圖一: Bluetooth Terminal/Graphics APP
圖二: Bluetooth SPP Profile

Fundamental :

1-Wire communication is a protocol operating through one wire between the controller device and the peripheral device.

SPP (Serial Port Profile) is a Classic Bluetooth profile, SPP defines the requirements for Bluetooth devices necessary for setting up emulated serial cable connections using RFCOMM between two peer devices. The requirements are expressed in terms of services provided to applications, and by defining the features and procedures that are required for interoperability between Bluetooth devices.

圖三: 1-Wire structure

圖四: DS18B20 components

Circuit:

Code Introduce:

#include <OneWire.h>
#include <DallasTemperature.h>
#include <BluetoothSerial.h>
//--------- Flag structure --------------------------------------
typedef struct _vFlag
{
  uint8_t BTFlag = 0;
  uint8_t DC_Flag = 0;
  uint8_t CANFlag = 0;
  uint8_t I2C_Flag = 0;
  uint8_t BMP180Flag = 0;
  uint8_t DS18B20Flag = 0;
  uint8_t JSONFlag = 0;
  uint8_t LEDFlag = 1;
  uint8_t sensor_Flag = 0;
  uint8_t sensor1_Flag = 0;
  uint8_t initial_Flag = 0;
  uint8_t Tone_Flag = -1;
  uint8_t IR_RECV_Flag=0;
  uint8_t IR_SEND_Flag=0;
  uint8_t FunctionFlag = 3;
  uint8_t SendFlag = 0;
  uint8_t BMPCnt = 0;
} vFlag;
vFlag *flag_Ptr;
vFlag flag;

//-----   DS18B20  ------------------
#define DQ_Pin 4

OneWire oneWire(DQ_Pin);
DallasTemperature sensors(&oneWire);

byte data[12]; // buffer for data
byte address[8]; // 64 bit device address

#define LED_BUILTIN 2
BluetoothSerial SerialBT;
//----------uart--------------
#define LINE_BUFFER_LENGTH 64
//--------- uart structure --------------------------------------
typedef struct _vUart
{
  char c;
  int lineIndex = 0;
  int line1Index = 0;
  int BTlineIndex = 0;
  bool lineIsComment;
  bool lineSemiColon;
  //char *line;
  char line[128];
  //char line1[128];
  char BTline[20];
  //char R_line[20];
  //char L_line[20];
  String inputString;
  String BTinputString;
  String S1inputString;
  int V[16];
  char ctemp[30];
  char I2C_Data[80];
  int DC_Spped = 50;
  float Voltage[16];
  int Buffer[128];
  int StartCnt = 0;
  int ReadCnt = 0;
  int sensorValue = 0;
} vUart;
vUart *Uart_Ptr;
vUart Uart;

//-------------------------------------------------
void setup()
{
  Serial.begin(9600);
  Serial.println(F("init"));
  pinMode(LED_BUILTIN, OUTPUT);
  SerialBT.begin("BT_BS18B20");// BTName

  if (oneWire.search(address))
  {
    Serial.println("Slave device found!");
    Serial.print("Device Address = ");
    Serial.println(address[0]);
  }
  else
  {
    Serial.println("Slave device not found!");
  }
  //-----DS-----------
  sensors.begin();
}
//-----------------------------------------
void loop()
{
  Serial.print(F("Main at core:"));
  Serial.println(xPortGetCoreID());
  while(1)
  {
    if(flag.LEDFlag == 1)
    {
      digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
      vTaskDelay(300);
      digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
      vTaskDelay(300);
    }
    while (Serial.available() > 0)
    {
      Uart.c = Serial.read();

      if ((Uart.c == '\n') || (Uart.c == '\r'))
      { // End of line reached
        if (Uart.lineIndex > 0)
        { // Line is complete. Then execute!
          Uart.line[Uart.lineIndex] = '\0'; // Terminate string

          processCommand(Uart.line); // do something with the command
          SerialBT.println(Uart.line);

          Uart.lineIndex = 0;
          Uart.inputString = "";
        }
        else
        {
          // Empty or comment line. Skip block.
        }
        Uart.lineIsComment = false;
        Uart.lineSemiColon = false;
        Serial.println(F("ok>"));
      }
      else
      {
        //Serial.println( c );
        if ((Uart.lineIsComment) || (Uart.lineSemiColon))
        {
          if (Uart.c == ')')
            Uart.lineIsComment = false; // End of comment. Resume line.
        }
        else
        {
          if (Uart.c == '/')
          { // Block delete not supported. Ignore character.
          }
          else if (Uart.c == '~')
          { // Enable comments flag and ignore all characters until ')' or EOL.
            Uart.lineIsComment = true;
          }
          else if (Uart.c == ';')
          {
            Uart.lineSemiColon = true;
          }
          else if (Uart.lineIndex >= LINE_BUFFER_LENGTH - 1)
          {
            Serial.println("ERROR - lineBuffer overflow");
            Uart.lineIsComment = false;
            Uart.lineSemiColon = false;
          }
          else if (Uart.c >= 'a' && Uart.c <= 'z')
          { // Upcase lowercase
            Uart.line[Uart.lineIndex] = Uart.c - 'a' + 'A';
            Uart.lineIndex = Uart.lineIndex + 1;
            Uart.inputString += (char)(Uart.c - 'a' + 'A');
          }
          else
          {
            Uart.line[Uart.lineIndex] = Uart.c;
            Uart.lineIndex = Uart.lineIndex + 1;
            Uart.inputString += Uart.c;
          }
        }
      }
    } //while (Serial.available() > 0)
    while (SerialBT.available())
    {
      String BTdata = SerialBT.readString();

      Serial.println(BTdata);
      BTprocessCommand(BTdata);
    }//while (BT.available())
 
    if(flag.DS18B20Flag == 1)
    {
      vDS18B20Task();
      sensors.requestTemperatures();
      SerialBT.print("E");
      SerialBT.println(sensors.getTempCByIndex(0));
    }

  }
}
//-------------------------------------
void BTprocessCommand(String data)
{
 
}
//----------------------------------------
void processCommand(char *data)
{
  int len, xlen, ylen, zlen, alen;
  int tempDIO;
  String stemp;

  len = Uart.inputString.length();
  //---------------------------------------
  if (strstr(data, "VER") != NULL)
  {
    Serial.println(F("ESP32_20230710"));
  }
  if (strstr(data, "DS18B20_ON") != NULL)
  {
    flag.DS18B20Flag = 1;
    Serial.println(F("DS18B20_ON"));

  }
  if (strstr(data, "DS18B20_OFF") != NULL)
  {
    flag.DS18B20Flag = 0;
    Serial.println(F("DS18B20_OFF"));

  }
}
//-----------------------------------------

//-------------------------------------------
void vDS18B20Task()
{
  Serial.print("Temperatures --> ");
  sensors.requestTemperatures();
  Serial.println(sensors.getTempCByIndex(0));
}

YouTube Demonstration:










延伸閱讀

2023年7月16日 星期日

ESP32 one Wire Bus Application – DS18B20 section

 Fundamental:

This article provides a general overview of Maxim’s 1-Wire® technology, its communication concept and the benefit of low pin count package options. The main section discusses 1-Wire devices by their feature set and explains the typical applications. The article concludes with practical information on how to evaluate 1-Wire devices, explains device customization options, and references resources that assist customers with integration of 1-Wire technology in their systems.


Purpose:

1-Wire communication is a protocol operating through one wire between the controller device and the peripheral device. This article covers the basics of using the 1-Wire protocol with an ESP32 with the help of the OneWire library. The following sections provide information about the 1-Wire protocol, interface, power, addressing devices, reading devices and finally a short glimpse into the library's history.


DS18B20 introduce:

The DS18B20 temperature sensor is widely used in electronic projects that uses a single wire to acquire data, therefore claiming it as single wire programmable in nature. It uses a single GPIO pin of the microcontroller to output the current temperature reading of its surroundings. By using the least number of pins, we can conveniently access multiple temperature readings by hooking up DS18B20 sensors on the same GPIO pin.



Circuit:

YouTube:

ESP32 Code Introduce:
#include <OneWire.h>
#include <DallasTemperature.h>
//--------- Flag structure --------------------------------------
typedef struct _vFlag
{
  uint8_t BTFlag = 0;
  uint8_t DC_Flag = 0;
  uint8_t CANFlag = 0;
  uint8_t I2C_Flag = 0;
  uint8_t BMP180Flag = 0;
  uint8_t DS18B20Flag = 0;
  uint8_t JSONFlag = 0;
  uint8_t Radar_L_Flag = 0;
  uint8_t Radar_R_Flag = 0;
  uint8_t sensor_Flag = 0;
  uint8_t sensor1_Flag = 0;
  uint8_t initial_Flag = 0;
  uint8_t Tone_Flag = -1;
  uint8_t IR_RECV_Flag=0;
  uint8_t IR_SEND_Flag=0;
  uint8_t FunctionFlag = 3;
  uint8_t SendFlag = 0;
  uint8_t BMPCnt = 0;
} vFlag;
vFlag *flag_Ptr;
vFlag flag;

//-----   DS18B20  ------------------
#define DQ_Pin 4

OneWire oneWire(DQ_Pin);
DallasTemperature sensors(&oneWire);

byte data[12]; // buffer for data
byte address[8]; // 64 bit device address

//----------uart--------------
#define LINE_BUFFER_LENGTH 64
//--------- uart structure --------------------------------------
typedef struct _vUart
{
  char c;
  int lineIndex = 0;
  int line1Index = 0;
  int BTlineIndex = 0;
  bool lineIsComment;
  bool lineSemiColon;
  //char *line;
  char line[128];
  //char line1[128];
  char BTline[20];
  //char R_line[20];
  //char L_line[20];
  String inputString;
  String BTinputString;
  String S1inputString;
  int V[16];
  char ctemp[30];
  char I2C_Data[80];
  int DC_Spped = 50;
  float Voltage[16];
  int Buffer[128];
  int StartCnt = 0;
  int ReadCnt = 0;
  int sensorValue = 0;
} vUart;
vUart *Uart_Ptr;
vUart Uart;

//-------------------------------------------------
void setup()
{
  Serial.begin(9600);
  Serial.println(F("init"));
  if (oneWire.search(address))
  {
    Serial.println("Slave device found!");
    Serial.print("Device Address = ");
    Serial.println(address[0]);
  }
  else
  {
    Serial.println("Slave device not found!");
  }

  //-----DS-----------
  sensors.begin();
}
//-----------------------------------------
void loop()
{
  Serial.print(F("Main at core:"));
  Serial.println(xPortGetCoreID());
  while(1)
  {
    while (Serial.available() > 0)
    {
      Uart.c = Serial.read();

      if ((Uart.c == '\n') || (Uart.c == '\r'))
      { // End of line reached
        if (Uart.lineIndex > 0)
        { // Line is complete. Then execute!
          Uart.line[Uart.lineIndex] = '\0'; // Terminate string
          //Serial.println( F("Debug") );
          //Serial.println( Uart.inputString );
          processCommand(Uart.line); // do something with the command
          //傳輸給藍芽
         
          Uart.lineIndex = 0;
          Uart.inputString = "";
        }
        else
        {
          // Empty or comment line. Skip block.
        }
        Uart.lineIsComment = false;
        Uart.lineSemiColon = false;
        Serial.println(F("ok>"));
      }
      else
      {
        //Serial.println( c );
        if ((Uart.lineIsComment) || (Uart.lineSemiColon))
        {
          if (Uart.c == ')')
            Uart.lineIsComment = false; // End of comment. Resume line.
        }
        else
        {
          if (Uart.c == '/')
          { // Block delete not supported. Ignore character.
          }
          else if (Uart.c == '~')
          { // Enable comments flag and ignore all characters until ')' or EOL.
            Uart.lineIsComment = true;
          }
          else if (Uart.c == ';')
          {
            Uart.lineSemiColon = true;
          }
          else if (Uart.lineIndex >= LINE_BUFFER_LENGTH - 1)
          {
            Serial.println("ERROR - lineBuffer overflow");
            Uart.lineIsComment = false;
            Uart.lineSemiColon = false;
          }
          else if (Uart.c >= 'a' && Uart.c <= 'z')
          { // Upcase lowercase
            Uart.line[Uart.lineIndex] = Uart.c - 'a' + 'A';
            Uart.lineIndex = Uart.lineIndex + 1;
            Uart.inputString += (char)(Uart.c - 'a' + 'A');
          }
          else
          {
            Uart.line[Uart.lineIndex] = Uart.c;
            Uart.lineIndex = Uart.lineIndex + 1;
            Uart.inputString += Uart.c;
          }
        }
      }
    } //while (Serial.available() > 0)
 
    if(flag.DS18B20Flag == 1)
    {
      vDS18B20Task();
    }

  }
}
//----------------------------------------
void processCommand(char *data)
{
  int len, xlen, ylen, zlen, alen;
  int tempDIO;
  String stemp;

  len = Uart.inputString.length();
  //---------------------------------------
  if (strstr(data, "VER") != NULL)
  {
    Serial.println(F("ESP32_20230710"));
  }
  if (strstr(data, "DS18B20_ON") != NULL)
  {
    flag.DS18B20Flag = 1;
    Serial.println(F("DS18B20_ON"));

  }
  if (strstr(data, "DS18B20_OFF") != NULL)
  {
    flag.DS18B20Flag = 0;
    Serial.println(F("DS18B20_OFF"));

  }
}
//-----------------------------------------

//-------------------------------------------
void vDS18B20Task()
{
  Serial.print("Temperatures --> ");
  sensors.requestTemperatures();
  Serial.println(sensors.getTempCByIndex(0));
  //flag.DS18B20Flag = 0;
}

YouTube:





延伸閱讀