如何获取连续给出数据的输入以输出一位整数值

问题描述 投票:0回答:1

简单总结一下我的项目,这是一个智能停车系统,我可以让停车用户知道停车场是否空置。我正在实现一个包含 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());

  }
}

输出代码也非常简单。让我知道是否有任何可能的方法来实现我正在尝试做的事情,如果我遗漏了任何其他细节,也请告诉我。

c++ arduino xbee
1个回答
0
投票

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

//...
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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.