esp8266/esp12f安装MQTT Client 客户端
代码我已经写好了,由于只有一个esp12f,发布和订阅用的是一个模块。
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
// Update these with values suitable for your network.
const char* ssid = "replace with your ssid";
const char* password = "replace with ssid's password";
const char* mqtt_server = "ip address of mqtt server";
unsigned long lastMsg = 0;
char msg[50];
int light=2;
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
char msg[8]={};
for (int i = 0; i < length; i++) {
msg[i]=(char)payload[i];
Serial.print(msg[i]);
}
Serial.println();
// use function to control led with value that had received.if you have not rod,disnable
//this function
driveled_pwm(msg);
}
int driveled_pwm(char msg[4]){
int lightpin=2;
pinMode(lightpin,OUTPUT);
int brightness=atoi(msg);
analogWrite(lightpin, brightness);
}
int msg_pub(){
int sensorpin=A0;
pinMode(A0,INPUT);
int drive=analogRead(sensorpin);
return drive;
}
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish("light", "1024");
// ... and resubscribe
client.subscribe("light");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
unsigned long now = millis();
//you can chang the inteval to what you want speed
if (now - lastMsg > 200) {
lastMsg = now;
//used value anologread from A0,you can give a const value,max 1024,min 0
char a[4];
const char* pubmsg=itoa(msg_pub(), a,10);
client.publish("light", pubmsg);
}
}
`
代码安装在ESP12F上能正常与MOSQUITTO正常连接``
517



被折叠的 条评论
为什么被折叠?



