NodeMCU多串口通信(轮询)

作者

郑楠

前言

今天准备把原来用 Yun 的气象站项目硬件换成 NodeMCU,然鹅事情并没想的那么简单…

硬件

NodeMCU
Arduino UNO (方案一)

方案一

将多个传感器数据通过 Arduino UNO 间接传输到 Node MCU 。

Arduino UNO 的引脚数比 NodeMCU 多,虽然 CPU 不及但内存相对来说较高。可以通过建立多个软串口读取数据,然后再将数据进行整合,通过另一个串口传输到 NodeMCU 去。

此方案需要手动设计两块板子之间的通讯协议,并且需要注意 ArduinoUNO 的 TTL 串口电平是 5V 的,而 NodeMCU 的 TTL 串口电平是 3.3V 的,需要进行电平转换,否则会烧板子。

样例代码

Arduino UNO

#include <SoftwareSerial.h>

/*
Copyright (c) 2015 PTC Inc. 
Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies 
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

This sketch demonstrate how to send data through REST Calls using linux processes
 on an Arduino Yún. 
 created 25 February 2015
 by Veronica MIHAI IoT Application Engineer at PTC (vmihai@ptc.com)
 */

 int timeBetweenRefresh = 500;

SoftwareSerial airSerial(11, 12); // RX, TX
int air[7];
SoftwareSerial mySerial(9, 10); // RX, TX
char databuffer[35];
SoftwareSerial sm(3, 4); // RX, TX
float temp;

void setup()
{
  Serial.begin(9600);
  airSerial.begin(2400);
  mySerial.begin(9600);
  sm.begin(9600);
}
void loop()
{ 
  getBuffer();//Begin!
  int windDirection = WindDirection();
  float windSpeedOneMinute = WindSpeedAverage();
  float rainFallOneHour = RainfallOneHour();
  float temperature = Temperature();
  float humidity = Humidity();
  float pressure = BarPressure();
  float air = calPM(800);
  if(temperature < 0 || temperature > 100 || humidity < 0 || humidity > 100 || pressure < 0 || air < 0 || windDirection < 0 || windSpeedOneMinute < 0){
  }else{
    runShellCommand(temperature,humidity,air,pressure,windDirection,windSpeedOneMinute);
    delay(timeBetweenRefresh);
  }
}

void getBuffer()                                                                    //Get weather status data
{
  int index;
  mySerial.listen();
  for (index = 0;index < 35;index ++)
  {
    if(mySerial.available())
    {
      databuffer[index] = mySerial.read();
      if (databuffer[0] != 'c')
      {
        index = -1;
      }
    }
    else
    {
      index --;
    }
  }
}

void getAirBuffer() //Get weather status data
{
  int index;
  airSerial.listen();
  for (index = 0;index < 7;index ++)
  {
    if(airSerial.available())
    {
      air[index] = airSerial.read();
      if ((air[0] != 0xAA) || (air[index] == 0xFF && index != 6)){
        index = -1;
      }
    }
    else
    {
      index --;
    }
  }
}

int transCharToInt(char *_buffer,int _start,int _stop)                               //char to int)
{
  int _index;
  int result = 0;
  int num = _stop - _start + 1;
  int _temp[num];
  for (_index = _start;_index <= _stop;_index ++)
  {
    _temp[_index - _start] = _buffer[_index] - '0';
    result = 10*result + _temp[_index - _start];
  }
  return result;
}

int WindDirection()                                                                  //Wind Direction
{
  return transCharToInt(databuffer,1,3);
}

float WindSpeedAverage()                                                             //air Speed (1 minute)
{
  temp = 0.44704 * transCharToInt(databuffer,5,7);
  return temp;
}

float Temperature()                                                                  //Temperature ("C")
{
  temp = (transCharToInt(databuffer,13,15) - 32.00) * 5.00 / 9.00;
  return temp;
}

float RainfallOneHour()                                                              //Rainfall (1 hour)
{
  temp = transCharToInt(databuffer,17,19) * 25.40 * 0.01;
  return temp;
}

int Humidity()                                                                       //Humidity
{
  return transCharToInt(databuffer,25,26);
}

float BarPressure()                                                                  //Barometric Pressure
{
  temp = transCharToInt(databuffer,28,32);
  //temp = temp / 10;
  return temp / 10;
}

float calPM(float A){
  float ret = 0;
  getAirBuffer();
  float Vout = (air[1]*256+air[2])*1.0/1024*5;
  ret = Vout * A;
  return ret;
}

void runShellCommand(float t, float h, float a, float p, float d, float s){

  char temp[10];
  //create a process variable that will send the two Shell commands 
  //for setting the temperature and humidity properties to Thingworx 

 // transform float value of temperature into a String so that it can be concatenated 
 // in the setTemperature command 

  String tempAsString;
  String humidityAsString;
  String airAsString;
  String pressureAsString;
  String windDirectionAsString;
  String windSpeedOneMinuteAsString;
//  String rainFallOneHourAsString;

  dtostrf(t,1,2,temp);
  tempAsString=String(temp);

  dtostrf(h,1,2,temp);
  humidityAsString=String(temp);

  dtostrf(a,1,2,temp);
  airAsString=String(temp);

  dtostrf(p,1,2,temp);
  pressureAsString=String(temp);

  dtostrf(d,1,0,temp);
  windDirectionAsString = String(temp);

  dtostrf(s,1,2,temp);
  windSpeedOneMinuteAsString=String(temp);

//  dtostrf(r,1,2,temp);
//  rainFallOneHourAsString=String(temp);

  String data= "T" + tempAsString;
  data += "H" + humidityAsString;
  data += "A" + airAsString;
  data += "P" + pressureAsString;
  data += "D" + windDirectionAsString;
  data += "S" + windSpeedOneMinuteAsString;
  data += "E";
  sm.print(data);
  Serial.println(data);

  mySerial.flush();
  airSerial.flush();
}

NodeMCU

#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>

const char* ssid = "ubiways";
const char* password = "123abc456d";
const char* mqtt_server = "10.66.15.150";

WiFiClient espClient;
PubSubClient client(espClient);

SoftwareSerial serial(5, 4); //RX TX

int timeBetweenRefresh = 5000;

float Temperature;
float Humidity;
float Air;
float Pressure;
float Direction;
float Speed;
String Tmp;
boolean flag;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  flag = false;
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  while(serial.available()){
    char tmp = (char)serial.read();
    char t[10];
    char h[10];
    char a[10];
    char p[10];
    char d[10];
    char s[10];
    if(tmp == 'T'){
      Tmp = "";
      flag = true;
    }else if(flag){
      if(tmp == 'H'){
        Temperature = stringToFloat(Tmp);
        dtostrf(Temperature,1,2,t);
        Tmp = "";
      }else if(tmp == 'A'){
      Humidity = stringToFloat(Tmp);
      dtostrf(Humidity,1,2,h);
      Tmp = "";
      }else if(tmp == 'P'){
        Air = stringToFloat(Tmp);
        dtostrf(Air,1,2,a);
        Tmp = "";
      }else if(tmp == 'D'){
        Pressure = stringToFloat(Tmp);
        dtostrf(Pressure,1,2,p);
        Tmp = "";
      }else if(tmp == 'S'){
        Direction = stringToFloat(Tmp);
        dtostrf(Direction,1,2,d);
        Tmp = "";
      }else if(tmp == 'E'){
        Speed = stringToFloat(Tmp);
        dtostrf(Speed,1,2,s);
        Serial.println("Temperature: " + String(t));
        Serial.println("Humidity: " + String(h));
        Serial.println("Air: " + String(a));
        Serial.println("Pressure: " + String(p));
        Serial.println("Direction: " + String(d));
        Serial.println("Speed: " + String(s));
        client.publish("Angel/T", t);
        client.publish("Angel/H", h);
        client.publish("Angel/A", a);
        client.publish("Angel/P", p);
        client.publish("Angel/WD", d);
        client.publish("Angel/WS", s);
        Serial.println("OK");
        Tmp = "";
        flag = false;
      }else{
        Tmp += tmp;
      }
    }
  }
}

float stringToFloat(String src){
  float ret = 0;
  float point = 0.1;
  boolean flag = true;
  for(int i = 0; i < src.length(); i++){
    if(src.charAt(i) == '.'){
      flag = false;
    }else if(flag){
      ret = ret * 10 + (src.charAt(i) - '0');
    }else{
      ret = ret + point * (src.charAt(i) - '0');
      point = point * 0.1;
    }
  }
  return ret;
}

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    if (client.connect("Angel/ESP8266Client")) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("Angel/Test", "Yes");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

方案二

直接使用 NodeMCU 获取传感器数据

NodeMCU 提供两个纯 GPIO 口做软串口,如果传感器仅有两个,只需要将这两个 GPIO 口都设置成 RX 即可。

同样,需要注意有些传感器的 TTL 电平是 5V,需要进行电平转换。

使用多个软串口做轮询可能会出现时间冲突,程序卡住或者数据没办法完整获取的问题。在官方的文档中给出了解决方法,当需要用到改串口时使用 listen() 方法,即可解决。然而对于 NodeMCU,SoftwareSerial 库并没有提供该方法。不能忍!暴力查看库文件(C:\Users\TheAngels\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\SoftwareSerial\SoftwareSerial.cpp)发现 SoftwareSerial 类有个方法叫做 void enableRx(boolean on),欧耶!就是这个方法!这个方法可以关闭或者打开该串口的接收监听,那不就可以模拟 listen() 方法了嘛!

样例代码

NodeMCU

#include <SoftwareSerial.h>

/*
Copyright (c) 2015 PTC Inc. 
Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
and associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software 
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies 
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT 
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 

This sketch demonstrate how to send data through REST Calls using linux processes
 on an Arduino Yún. 
 created 25 February 2015
 by Veronica MIHAI IoT Application Engineer at PTC (vmihai@ptc.com)
 */

SoftwareSerial airSerial(5, 3); //RX TX
int air[7];
SoftwareSerial mixSerial(4, 3); //RX TX
char databuffer[35];
float temp;

void setup()
{
  Serial.begin(9600);
  airSerial.begin(2400);
  mixSerial.begin(9600);
}
void loop()
{ 
  getBuffer();//Begin!
  int windDirection = WindDirection();
  float windSpeedOneMinute = WindSpeedAverage();
  float rainFallOneHour = RainfallOneHour();
  float temperature = Temperature();
  float humidity = Humidity();
  float pressure = BarPressure();
  float air = calPM(800);
  if(temperature < 0 || temperature > 100 || humidity < 0 || humidity > 100 || pressure < 0 || air < 0 || windDirection < 0 || windSpeedOneMinute < 0){
    Serial.println("Wrong!");
  }else{
    runShellCommand(temperature,humidity,air,pressure,windDirection,windSpeedOneMinute);
  }
}

void getBuffer()                                                                    //Get weather status data
{
  int index;
  mixSerial.enableRx(true);
  airSerial.enableRx(false);
  for (index = 0;index < 35;index ++)
  {
    if(mixSerial.available())
    {
      databuffer[index] = mixSerial.read();
      if (databuffer[0] != 'c')
      {
        index = -1;
      }
    }
    else
    {
      index --;
    }
  }
}

void getAirBuffer() //Get weather status data
{
  int index;
  mixSerial.enableRx(false);
  airSerial.enableRx(true);
  for (index = 0;index < 7;index ++)
  {
    if(airSerial.available())
    {
      air[index] = airSerial.read();
      if ((air[0] != 0xAA) || (air[index] == 0xFF && index != 6)){
        index = -1;
      }
    }
    else
    {
      index --;
    }
  }
}

int transCharToInt(char *_buffer,int _start,int _stop)                               //char to int)
{
  int _index;
  int result = 0;
  int num = _stop - _start + 1;
  int _temp[num];
  for (_index = _start;_index <= _stop;_index ++)
  {
    _temp[_index - _start] = _buffer[_index] - '0';
    result = 10*result + _temp[_index - _start];
  }
  return result;
}

int WindDirection()                                                                  //Wind Direction
{
  return transCharToInt(databuffer,1,3);
}

float WindSpeedAverage()                                                             //air Speed (1 minute)
{
  temp = 0.44704 * transCharToInt(databuffer,5,7);
  return temp;
}

float Temperature()                                                                  //Temperature ("C")
{
  temp = (transCharToInt(databuffer,13,15) - 32.00) * 5.00 / 9.00;
  return temp;
}

float RainfallOneHour()                                                              //Rainfall (1 hour)
{
  temp = transCharToInt(databuffer,17,19) * 25.40 * 0.01;
  return temp;
}

int Humidity()                                                                       //Humidity
{
  return transCharToInt(databuffer,25,26);
}

float BarPressure()                                                                  //Barometric Pressure
{
  temp = transCharToInt(databuffer,28,32);
  //temp = temp / 10;
  return temp / 10;
}

float calPM(float A){
  float ret = 0;
  getAirBuffer();
  float Vout = (air[1]*256+air[2])*1.0/1024*5;
  ret = Vout * A;
  return ret;
}

void runShellCommand(float t, float h, float a, float p, float d, float s){

  //create a process variable that will send the two Shell commands 
  //for setting the temperature and humidity properties to Thingworx 

 // transform float value of temperature into a String so that it can be concatenated 
 // in the setTemperature command 

  char tempAsChar[10];
  char humidityAsChar[10];
  char airAsChar[10];
  char pressureAsChar[10];
  char windDirectionAsChar[10];
  char windSpeedOneMinuteAsChar[10];
  String rainFallOneHourAsChar[10];

  dtostrf(t,1,2,tempAsChar);
  dtostrf(h,1,2,humidityAsChar);
  dtostrf(a,1,2,airAsChar);
  dtostrf(p,1,2,pressureAsChar);
  dtostrf(d,1,0,windDirectionAsChar);
  dtostrf(s,1,2,windSpeedOneMinuteAsChar);

//  dtostrf(r,1,2,temp);
//  rainFallOneHourAsString=String(temp);

  String data= "T" + String(tempAsChar);
  data += "H" + String(humidityAsChar);
  data += "A" + String(airAsChar);
  data += "P" + String(pressureAsChar);
  data += "D" + String(windDirectionAsChar);
  data += "S" + String(windSpeedOneMinuteAsChar);
  data += "E";
  Serial.println(data);

  mixSerial.flush();
  airSerial.flush();
}
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值