查看: 411|回复: 1

[未解决] 请求各位大神 关于红外遥控和mqtt协议的一些问题

[复制链接]

该用户从未签到

发表于 2019-5-10 19:10 | 显示全部楼层 |阅读模式

为什么我的代码中加入红外遥控的代码后mqtt连接就会这样,但把这些代码注释掉后就正常了
请教各位大神
谢谢
file:///C:/Users/balala/AppData/Roaming/Tencent/Users/1106821350/QQ/WinTemp/RichOle/1TKQVV$WPD0]2%7BIE%7B~88H9J.jpg
file:///C:/Users/balala/AppData/Roaming/Tencent/Users/1106821350/QQ/WinTemp/RichOle/1TKQVV$WPD0]2%7BIE%7B~88H9J.jpg
file:///C:/Users/balala/AppData/Roaming/Tencent/Users/1106821350/QQ/WinTemp/RichOle/1TKQVV$WPD0]2%7BIE%7B~88H9J.jpg
  完整代码:
#include "DHT.h"
#include <LiquidCrystal.h>
#define DHTPIN A5
#define DHTTYPE DHT11
#define LEDPIN 13
#define SW 2
#include <IRremote.h>
//外部库
#include "WiFiEsp.h"
#include "SoftwareSerial.h"
SoftwareSerial Serial1(6, 8);    // RX, TX
#include <PubSubClient.h>         // MQTT通信使用的库

//连接路由器需要的变量与常量
char ssid[] = "Hao";            // your network SSID (name)
char pass[] = "123456789";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status
WiFiEspClient client;
DHT dht(DHTPIN, DHTTYPE);
const int rs = 12, en = 11, d4 = A3, d5 = 4, d6 = A4, d7 = A2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
const int sensorPin = A0;
int buzzerPin = 7;
int sensorValue = 0;
int sensorMin = 149;
int sensorMax = 670;
int val = 0;
int old_val = 0;
int state = 0;
int state1 = 0;
float sinVal;
int toneVal;
int m = 0;
int w=0;
int v;
volatile byte ledState = LOW;

int ledvalue=255;
int led1 = 9;
int led2 = 10;
/////////////////////////////////////////////////////////
int RECV_PIN = 5;
IRrecv irrecv(RECV_PIN);
decode_results results;
/////////////////////////////////////////////////////
//定义MQTT服务器地址和端口
char server[] = "172.20.10.3";
int port = 1883;
//MQTT初始化和回调函数
char topic[] = "fjjxu/iot/#"; //消息的主题
int count = 0;
int countPub = 0;
char i[10]={0};
void callback(char* topic, byte* payload, unsigned int length) {  //回调函数
  count++;
  char str[length];
  Serial.print(count );
  Serial.print(" - Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    str = (char)payload; //构建字符串,方便以后判断
    Serial.print((char)payload);
  }
  Serial.println();//Serial.println(str);
  
  int a=atoi(str);
if(strcmp(topic,"fjjxu/iot/sw")==0){
  Serial.print("00");
  if(a==1){
    digitalWrite(LEDPIN,HIGH);
    state=1;
     
    }else if(a==0){

      digitalWrite(LEDPIN,LOW);
       state=0;
      }
  }
   if(strcmp(topic,"fjjxu/iot/LEDlight")==0){
    ledvalue=a;
  
  
    analogWrite(LEDPIN,ledvalue);//显示led亮度
    }
}
PubSubClient pubSubClient(server, port, callback, client); // 初始化MQTT客户端对象
//连接到路由器
void connectToInternet() {
  // 初始化ESP模块的串口   这里需要先将ESP-01波特率设置为9600
  Serial1.begin(9600);
  // 初始化ESP模块
  WiFi.init(&Serial1);
  // 检查ESP模块是否存在
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("【ERROR】WiFi shield not present");
    // 什么也不做
    while (true);
  }
  // 尝试连接到WiFi网络
  while ( status != WL_CONNECTED) {
    Serial.print("【INFO】Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // 连接到Wifi网络
    status = WiFi.begin(ssid, pass);
  }
  //连接成功
  Serial.println("【INFO】Connection Successful");
}
void reconnect() {
  // Loop until we're reconnected
  while (!pubSubClient.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (pubSubClient.connect("arduinoClient_43424234")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      //pubSubClient.publish("outTopic","hello world");
      // ... and resubscribe
      //pubSubClient.subscribe("inTopic");
    } else {
      Serial.print("failed, rc=");
      Serial.print(pubSubClient.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//订阅MQTT消息
void doMQTTsub() {
  Serial.println("【INFO】 Connecting to MQTT Broker...");
  // 尝试连接到MQTT服务器
  if (pubSubClient.connect("arduinoClient_43424234")) {
    Serial.println("【INFO】 Connection to MQTT Broker Successful");
    // 订阅消息
     pubSubClient.subscribe("fjjxu/iot/sw");
    pubSubClient.subscribe("fjjxu/iot/LEDlight");
    Serial.print("【INFO】 Successfully Subscribed to MQTT Topic:");
    Serial.println(topic);
  } else {
    Serial.print("【INFO】 Connection to MQTT Broker failed");
    Serial.print(", rc=");
    Serial.println(pubSubClient.state());
  }
}

//发布MQTT消息
void doMQTTpub (const char*topic,const char * message) {
  Serial.println("【INFO】 Connecting to MQTT Broker...");
  // 尝试连接到MQTT服务器
  if (pubSubClient.connect("arduinoClient_43424234")) {
    countPub++;
    Serial.println("【INFO】 Connection to MQTT Broker Successful");
    // 连接后,发布消息.
    pubSubClient.publish(topic, message);
    Serial.print(countPub);
    Serial.print(" - 【INFO】 Publishing to MQTT Broker:");
    Serial.println(message);
    Serial.println(topic);
    Serial.println(message);
  } else {
    Serial.print("【INFO】 Connection to MQTT Broker failed");
    Serial.print(", rc=");
    Serial.println(pubSubClient.state());
  }
}
void buttonPress() {
  w=1;
  ledState = !ledState;
  digitalWrite(LEDPIN, ledState);
}
void setup() {
  lcd.begin(16, 2);
  Serial.begin(9600);
//////////////////////////////
irrecv.enableIRIn();
  Serial.println("DHT test!");
  dht.begin();
Serial.begin(9600);
  while (millis() < 5000) {
    sensorValue = analogRead(sensorPin);
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }
pinMode(LEDPIN, OUTPUT);
  pinMode(SW, INPUT);
  ledState = LOW;
attachInterrupt(0, buttonPress, RISING);
pinMode(buzzerPin, OUTPUT);
pinMode(led1,OUTPUT);
  pinMode(led2,OUTPUT);
  randomSeed(analogRead(A0));
  //初始化串口以进行调试
  Serial.begin(9600);
  //连接到路由器
  connectToInternet();
  //printWifiData();
  //订阅MQTT消息
  doMQTTsub();
}
unsigned long previousMillis = 0;
const long interval = 2000;

void newtone(int buzzerPin,int frequency, int duration)
{
pinMode(buzzerPin,OUTPUT);
int period = 1000000 / frequency;
int pulse = period / 2;
for (long p = 0;p< duration * 1000; p += period) {
digitalWrite(buzzerPin, HIGH);
delayMicroseconds(pulse);
digitalWrite(buzzerPin, LOW);
delayMicroseconds(pulse);
}
}
void setColor(int red,int green,int blue)
{
  analogWrite(led1,255-red);
  analogWrite(led2,255-green);
}
void loop() {
   float h = dht.readHumidity();
  float t = dht.readTemperature();
  float f = dht.readTemperature(true);
  //等待MQTT消息
  if (!pubSubClient.connected()) {
    reconnect();
  }
//开关
if (w==1){
   doMQTTpub("fjjxu/iot/sw",itoa(state, i, 10));
   w=0;
}
  pubSubClient.loop();
  unsigned long currentMillis = millis();
  int num = random(10, 41);
  char str[] = "";
  dtostrf(count,3,0,str);
  itoa(num, str, 10);
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    //发布MQTT消息
   doMQTTpub("fjjxu/iot/temp",itoa(t, i, 10));
    pubSubClient.loop();
doMQTTpub("fjjxu/iot/humi",itoa(h, i, 10));
    pubSubClient.loop();
doMQTTpub("fjjxu/iot/light",itoa(v, i, 10));
    pubSubClient.loop();
/*doMQTTpub("fjjxu/iot/sw",itoa(state, i, 10));
    pubSubClient.loop();
doMQTTpub("fjjxu/iot/LEDlight",itoa(ledvalue, i, 10));
   pubSubClient.loop();*/
  }
  
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  float hif = dht.computeHeatIndex(f, h);
  float hic = dht.computeHeatIndex(t, h, false);
  sensorValue = analogRead(sensorPin);
  v = map(sensorValue, sensorMin, sensorMax, 0, 100);
  v = constrain(v, 0, 100);
val = digitalRead(SW);
  if ((val == HIGH) && old_val == LOW) {
    state = 1 - state;
    delay(10);
  }
  old_val = val;
  Serial.println(state);
  if (v < 5) {
    state1 = 1;
  } else {
    state1 = 0;
  }
  if (state == 1 || state1 == 1) {
    digitalWrite(LEDPIN, HIGH);
  } else {
    digitalWrite(LEDPIN, LOW);
  }
  
   if (h >= 90 || h <= 50) {
    newtone(7,440,1000);
    for (m = 0; m < 255; m++) { //变数从0到254之间变化(渐强)
      setColor(m,0,0);     //设定LED亮度
      delay(4);               //延时10ms,因为analogWrite执行瞬间完成,
      //速度太快不易察觉
    }
    for (m = 255; m > 0; m--) { //变数从255到1之间变化(渐弱)
      setColor(m,0,0);     //设定LED亮度
      delay(4);              //延时10ms
    }
  } else {
    digitalWrite(buzzerPin,LOW);
     setColor(0,0,0);
  }

  if (t >= 30|| t <= 15) {
     newtone(7,1000,1000);
    for (m = 0; m < 255; m++) { //变数从0到254之间变化(渐强)
      setColor(0,m,0);     //设定LED亮度
      delay(4);               //延时10ms,因为analogWrite执行瞬间完成,
      //速度太快不易察觉
    }
    for (m = 255; m > 0; m--) { //变数从255到1之间变化(渐弱)
      setColor(0,m,0);      //设定LED亮度
      delay(4);              //延时10ms
    }
  }else {
    digitalWrite(buzzerPin,LOW);
    setColor(0,0,0);
  }
  /*
   if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    if (results.value == 0xFFA25D) //CH-
    {
       digitalWrite(buzzerPin,LOW);
       delay(10000); //延迟10s
       //while(1); //死循环就可以了
    }
    irrecv.resume(); // Receive the next value
  }

*/
  delay(100);
  lcd.clear();
  lcd.print("H:");
  lcd.setCursor(2, 0);
  lcd.print((int)h);
  lcd.setCursor(5, 0);
  lcd.print("T:");
  lcd.setCursor(7, 0);
  lcd.print((int)t);
  lcd.print((char)223);
  lcd.print("C");
  lcd.setCursor(12, 0);
  lcd.print("L:");
  lcd.print(v);
  lcd.setCursor(0, 1);
lcd.print("LED:");
  if (state == 0 && state1 == 0) {
    lcd.print("OFF");
  } else {
    lcd.print("ON");
  }
  lcd.setCursor(9, 1);
  lcd.print("44 DZH");
}


QQ图片20190510190740.png
QQ图片20190510190634.png
QQ图片20190510190629.png
QQ图片20190510190625.jpg
QQ图片20190510190613.jpg

该用户从未签到

 楼主| 发表于 2019-5-10 19:11 | 显示全部楼层
第一个监视器截图是注释后
您需要登录后才可以回帖 登录 | 立即注册  

本版积分规则

热门推荐

全国机器人等级考试配件购买
全国机器人等级考试配件购
本人想自己教小孩机器人等级考试,需要购买机器人等级考试的配件,可是淘宝上的太
【干货分享】mega2560原理图PCB图纸altium designer18
【干货分享】mega2560原理
分享一下mega2560的板子 AD版本 **** 本内容被作者隐藏 **** ergo
为什么我的atmega328最小系统板反应这么迟钝?
为什么我的atmega328最小
是不是少了什么? 视频链接:https://b23.tv/av68105950
[项目]microbit 控制的第一人称视角3D太空飞行游戏
[项目]microbit 控制的第
前言 家里有本《揭秘宇宙》,娃娃很喜欢,即使爸爸讲的都听烦了,娃娃还是不厌其烦的
【Arduino】108种传感器模块系列实验(116)--- 2.4G24L01无线模块
【Arduino】108种传感器模
37款传感器与模块的提法,在网络上广泛流传,其实Arduino能够兼容的传感器模块肯定是
Copyright   ©2015-2016  Arduino中文社区  Powered by©Discuz!   ( 蜀ICP备14017632号-3 )
快速回复 返回顶部 返回列表