实战:手机控制esp8266
0.配置
arduino下位机
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
WiFiClient espClient;
PubSubClient client(espClient);
const char* wifissid = "CMCC-wenzheng"; //改成自己家wifi
const char* password = "wenzhengspace666"; //改成自己家wifi
const char* mqtt_server = "106.13.150.28";
const char* mqtt_id = "565402462_ESP"; //改成自己的QQ号+_ESP
const char* Mqtt_sub_topic = "565402462_ESP"; //改成自己的QQ号+_ESP
const char* Mqtt_pub_topic = "565402462"; // 上报消息给 手机APP的TOPIC //改成自己的QQ号
long lastMsg = 0; //定时用的
app上位机
private String host = "tcp://106.13.150.28:1883";
private String userName = "android";
private String passWord = "android";
private String mqtt_id = "565402462"; //定义成自己的QQ号 切记!不然会掉线!!!
private String mqtt_sub_topic = "565402462"; //为了保证你不受到别人的消息 哈哈
private String mqtt_pub_topic = "565402462_ESP"; //为了保证你不受到别人的消息 哈哈 自己QQ好后面加 _PC
private int led_flag =1;
1.手机控制esp8266小灯亮灭
app上位机
image_1 =findViewById(R.id.image_1);
image_1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(led_flag == 0)
{
publishmessageplus(mqtt_pub_topic,"{\"set_led\":1}");
led_flag =1;
}else{
publishmessageplus(mqtt_pub_topic,"{\"set_led\":0}");
led_flag =0;
}
}
arduino下位机
arduino下位机
void callback(char* topic, byte* payload, unsigned int length) {
String msg="";
String LED_set = "";
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++)
{
msg+= (char)payload[i];
}
Serial.println(msg);
if(msg.indexOf("led")) //判断是否是要设置LED灯
{
//取出LED_set数据 并执行
LED_set = msg.substring(msg.indexOf("led\":")+5,msg.indexOf("}")); //起点,终点
digitalWrite(2,!LED_set.toInt());
}
}
2.esp8266上报adc模拟量
app上位机处理数据
case 3: //MQTT 收到消息回传 UTF8Buffer msg=new UTF8Buffer(object.toString());
String T_val = msg.obj.toString().substring(msg.obj.toString().indexOf("temperature\":")+13,msg.obj.toString().indexOf("}"));
String text_val = "温度:"+T_val;
text_test.setText(text_val);
break;
arduino下位机
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
long now = millis();
if (now - lastMsg > 2000)
{
lastMsg = now;
String json = "{\"temperature\":"+String(analogRead(A0))+"}";
//温度上报使用ADC模拟随机数
client.publish(Mqtt_pub_topic,json.c_str());
}
}
注意:
- String json = “{“temperature”:”+String(analogRead(A0))+"}";
之所以用很多转义符“\”是因为:
转义字符""的使用技巧(谢谢这个博主的回答)