微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何获得连续提供数据输入以输出一位整数值的输入

如何解决如何获得连续提供数据输入以输出一位整数值的输入

为简要介绍我的项目,这是一个智能停车系统,我可以在该系统中让停车用户知道停车场是否空置。我正在实现一个包含1个协调器和2个路由器的XBee网络。我有两个传感器,出口处有1个传感器,入口处有1个传感器。这两个传感器是路由器,它们收集的任何数据都将传输到协调器(输出)。这两个路由器具有相同的代码,即:

输入代码(正在发送):

#include<SoftwareSerial.h>
#define Sensor 8 

void setup() {

pinMode(Sensor,INPUT);
Serial.begin(9600);

}

void loop()
{

bool Detection = digitalRead(Sensor);
int carexit=1;

if(Detection == HIGH)
  {
  Serial.println("Car Exit");

  Serial.write(carexit);

  }
if(Detection == LOW)
  {
  Serial.println("Clear");
  }
}

这是一个非常简单的代码,可以检测到汽车进出。由于两个路由器相同,因此我们将传感器用于驶出的汽车。当我打开串行监视器时,“ Clear”(清除)一词将一直持续不间断输出,直到找到检测到为止为止,该检测将显示“ Car Exit”的输出约3秒钟,然后连续返回“ Clear”(清除)。该数据正在传输到协调器。我想做的是获取连续的数据,并让协调器处的串行监视器输入一个整数值。例如,在入口处,传感器将感应到汽车并将数据传输到协调器,并在协调器处递增。如果只有1个空位可用,结果将显示如下内容

空位:1

当汽车在出口处退出路由器时,它将向协调员发送一个递减代码

空位:0

因此,输入(路由器)将发送连续数据,而输出(发送器)将检测到该数据并将其注册一个单位的值。输出代码(接收)如下所示:

输出代码(接收中):

#include "SoftwareSerial.h"

// RX: Arduino pin 2,XBee pin DOUT.  TX:  Arduino pin 3,XBee pin DIN


void setup()
{

  Serial.begin(9600);
}
void loop()
{


  if (Serial.available() > 0)
  {
   
    Serial.write(Serial.read());

  }
}

输出代码也非常简单。让我知道是否有可能实现我想做的事情,还有遗漏的其他细节,也请告诉我。

谢谢!

解决方法

这是一个非常普遍的问题,最好从源头上解决传感器的传输代码。

//...
bool PreviousDetection = false;
void loop()
{

    bool Detection = digitalRead(Sensor);

    // do not do anything when state hasn't changed.
    if (Detection != PreviousDetection)
    {
        if (Detection)
            Serial.println("Car Exit");
        else
            Serial.println("Clear");
    }
    PreviousDetection = Detection;
}

您可能需要添加一些反跳以减少错误读数的风险。

//...
// Debounce thresholds the number depends on the frequency of readings,// speeed of cars,sensitivity and placement of your sensor...
// Dirt,sun exposure,etc... may influence readings in the long term.
const int LowDebounceThreshold = 3;
const int HighDebounceThreshold = 3;

bool PreviousDetection = false;
int DebounceCounter = 0;
bool DebouncedPreviousDetection = false;

void loop()
{

    bool Detection = digitalRead(Sensor);
    // 
    if (Detection == PreviousDetection)
        ++DebounceCounter; // this will rollover,but will not affect 
                           // DebouncedDetection in any meaningfull way.
    else
        DebounceCounter = 0;

    PreviousDetection = Detection;

    bool DebouncedDetection = PreviousDebouncedDetection;

    if (Detection && DebounceCounter >= HighDebounceThreshold)
        DebouncedDetection = true;
    else if (!Detection && DebounceCounter >= LowDebounceThreshold)
        DebouncedDetection = false;

    if (DebouncedDetection != PreviousDebouncedDetection)
    {
        PreviousDebouncedDetection = DebouncedDetection;
        if (DebouncedDetection) 
            Serial.println("Car Exit");
        else
            Serial.println("Clear");
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。