---
disqus: ahb0222
GA : G-VF9ZT413CG
---
# RS485_Arduino&MQTT應用
> [color=#40f1ef][name=LHB阿好伯, 2023/02/05][:earth_africa:](https://www.facebook.com/LHB0222/)
###### tags: `Arduino` `RS485` `MQTT`
[TOC]
# UART(TTL) 轉 RS485 雙向轉換器


:::success
* 3.3V與5.0V電源完美相容
* 3.3V 和 5.0V 信號完美相容
* 工作溫度範圍:-40 °C 至 + 85 °C
* 傳輸距離可達公里(用850米的2*1.5電纜做測試,建議在800米、800米以上使用,請添加中繼器)
* 郵票孔工藝設計,厚度0.8mm,便於作為組合板使用,也可焊接端子使用
* 具有 RXD、TXD 信號燈,可觀察發送和接收狀態
* 通訊方式:半雙工
:::


```cpp=
bool connectedWiFi = false;
bool connectedMQTT = false;
#define WIFI_SSID "SSID" // 無線網路名稱
#define WIFI_PASSWORD "PASSWORD" //無線網路密碼
#include <WiFi.h>
WiFiMulti multi;
WiFiClient espClient;
#include "PubSubClient.h"
PubSubClient client(espClient);
int status = WL_IDLE_STATUS;
const char* mqttServer = "broker.emqx.io"; // mqtt server address
const int mqttPort = 1883; // mqtt port
const char* mqttUser = ""; // your mqtt user
const char* mqttPassword = ""; // your mqtt password
String clientId = "RP2040WClient-"; // Create a random client ID
void MQTTreconnect()
{
if ( (status != WL_CONNECTED) )
{
status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.println("連接WiFi");
// delay(500);
if ( (status != WL_CONNECTED) )
{
Serial.println("未連接WiFi");
// delay(500);
}else{
Serial.println("連接WiFi");
}
}
if (!client.connected())
{
Serial.println("Connecting to MQTT...");
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str(), mqttUser, mqttPassword))
{
Serial.println("connected");
}
else
{
Serial.print("failed with state ");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
#include <WiFi.h>
#include <AsyncMqtt_Generic.h>
const char *PubTopic = "/test/WS"; //MQTT Topic位址
AsyncMqttClient mqttClient;
void printWifiStatus()
{
// print the SSID of the network you're attached to:
Serial.print("Connected to SSID: ");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("Local IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("Signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
}
bool connectToWifi()
{
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE)
{
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
Serial.print(F("Connecting to SSID: ")); Serial.println(WIFI_SSID);
#define MAX_NUM_WIFI_CONNECT_TRIES_PER_LOOP 20
uint8_t numWiFiConnectTries = 0;
// attempt to connect to WiFi network
while ( (status != WL_CONNECTED) && (numWiFiConnectTries++ < MAX_NUM_WIFI_CONNECT_TRIES_PER_LOOP) )
{
status = WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
delay(500);
}
if (status != WL_CONNECTED)
{
// Restart for Portenta as something is very wrong
Serial.println("Resetting. Can't connect to any WiFi");
NVIC_SystemReset();
}
printWifiStatus();
connectedWiFi = (status == WL_CONNECTED);
return (status == WL_CONNECTED);
}
bool isWiFiConnected()
{
// You can change longer or shorter depending on your network response
// Shorter => more responsive, but more ping traffic
static uint8_t theTTL = 10;
// Use ping() to test TCP connections
if (WiFi.ping(WiFi.gatewayIP(), theTTL) == theTTL)
{
return true;
}
return false;
}
void connectToMqttLoop()
{
//if ( (WiFi.status() == WL_CONNECTED) && (WiFi.RSSI() != 0) ) // temporary workaround
if (isWiFiConnected())
{
if (!connectedMQTT)
{
mqttClient.connect();
}
if (!connectedWiFi)
{
Serial.println("WiFi reconnected");
connectedWiFi = true;
}
}
else
{
if (connectedWiFi)
{
Serial.println("WiFi disconnected. Reconnecting");
connectedWiFi = false;
connectToWifi();
}
}
}
void connectToMqtt()
{
Serial.println("Connecting to MQTT...");
mqttClient.connect();
}
void printSeparationLine()
{
Serial.println("************************************************");
}
void onMqttConnect(bool sessionPresent)
{
Serial.print("Connected to MQTT broker: "); Serial.print(MQTT_HOST);
Serial.print(", port: "); Serial.println(MQTT_PORT);
Serial.print("PubTopic: "); Serial.println(PubTopic);
connectedMQTT = true;
printSeparationLine();
Serial.print("Session present: "); Serial.println(sessionPresent);
uint16_t packetIdSub = mqttClient.subscribe(PubTopic, 2);
Serial.print("Subscribing at QoS 2, packetId: "); Serial.println(packetIdSub);
mqttClient.publish(PubTopic, 2, true, "RP2040W Test1");
Serial.println("Publishing at QoS 0");
printSeparationLine();
}
void onMqttPublish(const uint16_t& packetId)
{
Serial.println("Publish acknowledged.");
Serial.print(" packetId: "); Serial.println(packetId);
}
void setup() {
mySerial.begin(4800);
Serial.begin(4800);
// pinMode(RS485De, OUTPUT);
// ---------------Wifi--------------------
multi.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// ------------------MQTT--------------------
client.setBufferSize(512); // option or with need
client.setServer(mqttServer, mqttPort); // need
//client.setCallback(callback); // need
delay(2000);
MQTTreconnect();
}
void loop() {
//輸出詢問碼
mySerial.write((unsigned char)0x01);
mySerial.write((unsigned char)0x03);
mySerial.write((unsigned char)0x00);
mySerial.write((unsigned char)0x00);
mySerial.write((unsigned char)0x00);
mySerial.write((unsigned char)0x01);
mySerial.write((unsigned char)0x84);
mySerial.write((unsigned char)0x0A);
delay(500);
//接收資料
if (mySerial.available() >= 6) {
unsigned char data[7];
for (int i = 0; i < 7; i++) {
data[i] = mySerial.read();
}
//資料轉換
float value = ((data[3] << 8) | data[4]) / 10.0;
Serial.println("風速: " + String(value,1) + "m/s");
String strValue = String(value);
if (client.publish(PubTopic, strValue.c_str()) == true)
{
Serial.println("Success sending message");
}
}
Serial.println("測試");
}
```



## 外殼

https://1drv.ms/u/s!AuqcoLPA0_SIpflCsQo24oitOeKsuA?e=EN9cY5
🌟全文可以至下方連結觀看或是補充
全文分享至
https://www.facebook.com/LHB0222/
https://www.instagram.com/ahb0222/
有疑問想討論的都歡迎於下方留言
喜歡的幫我分享給所有的朋友 \o/
有所錯誤歡迎指教
# [:page_with_curl: 全部文章列表](https://hackmd.io/@LHB-0222/AllWritings)
