[实验]Nodemcu软串口通信(读取网络时间并通过串口传输)

参考博客:ESP8266(NODEMCU)Arduino环境下实现多个软串口通信

接线方式:

D5——D8
D6——D7

实验原理与步骤

通过向硬串口发送Show time 字符串激活单片机去更新网络时间,然后通过软串口一发出,然后硬串口会打出串口二接收到的数据。模拟了两个单片机实现串口通信的过程。

代码

#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <SoftwareSerial.h>

SoftwareSerial uart1(14,12);//RX=d5,TX=d6
SoftwareSerial uart2(13,15);//RX=d7,TX=d8

//ESP8266 NODEMCU
const char *ssid     = "your wifi name ";
const char *password = "your wifi password";
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "ntp1.aliyun.com",60*60*8, 30*60*1000);
void setup()
{
   Serial.begin(9600);
   uart1.begin(9600);
   uart2.begin(9600);
   uart1.listen();
   uart2.listen();
   pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
   WiFi.begin(ssid, password);
   while ( WiFi.status() != WL_CONNECTED ) {
     delay ( 500 );
     Serial.print ( "." );
     digitalWrite(LED_BUILTIN, HIGH);
  }
  timeClient.begin();
}
String time1="";
bool dian=false;
int h,m,s,d;
String uart1string="";
String uart2string="";
void loop()
{
  
  if(Serial.available()>0){
    if(Serial.peek()!=‘\n‘){
      uart1string+=(char)Serial.read();
    }
    else{
      Serial.read();
      if(uart1string=="Show time"){
        timeClient.update();
        time1=timeClient.getFormattedTime();
        uart1.println(time1);
      }
      uart1string="";
    }
  }
  if(uart2.available()>0){
    if(uart2.peek()!=‘\n‘){
      uart2string+=(char)uart2.read();
    }
    else{
      uart2.read();
      Serial.print("UART2 DATA:");
      Serial.println(uart2string);
      uart2.println(uart2string);
    }
  }
    /*Serial.println("ok");
    timeClient.update();
    time1=timeClient.getFormattedTime();
    d=timeClient.getDay();
    h=timeClient.getHours();
    m=timeClient.getMinutes();
    s=timeClient.getSeconds();
    Serial.print(d);Serial.print("   ");Serial.print(h);Serial.print(":");Serial.print(m);Serial.print(":");Serial.println(s);
    delay(1000);*/ 
}

[实验]Nodemcu软串口通信(读取网络时间并通过串口传输)

上一篇:基于分布式锁解决分布式定时任务重复执行的方法


下一篇:restTemplate使用实例