【问题标题】:Why does the ledstrip stop partway and then go all the way and can I make this more efficient为什么ledstrip中途停止然后一直走,我可以让这个更有效率吗
【发布时间】:2020-12-31 21:25:13
【问题描述】:

所以我需要一些帮助来查看和编辑下面的代码。有没有办法让它比我做的更有效?另外,有没有更好的方法来做我做过的一些方法?非常感谢答案(我对 Arduino 还很陌生)。

下面的代码是一个走廊灯带,当 Arduino 上的距离传感器检测到附近某个距离以下的任何物体时,它会亮起(是的,我想过使用运动传感器,但我手头只有距离传感器)。

const int trigPin = 9;
const int echoPin = 10;

float duration, distance;
#include <FastLED.h>
#define LED_PIN     6
#define NUM_LEDS    60
int timingnum = 0;
//#define BRIGHTNESS  bright
int bright = 100;///the brightness of the leds
int lednum = 60;///the number of leds available
int timer;
CRGB leds[NUM_LEDS];

void setup() {
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  Serial.begin(9600);
  FastLED.addLeds<WS2812, LED_PIN, GRB>(leds, NUM_LEDS);
  // FastLED.setBrightness(  BRIGHTNESS );
}

void loop() {
  lights();
}
        
void sensor() { ///THIS IS CLEAN
  digitalWrite(trigPin, LOW);
  delayMicroseconds(timingnum);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(timingnum);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration*.0343)/2;
  Serial.print("Distance: ");
  Serial.println(distance);
}

// in the lights the reason why it wouldnt output the data for the 
// represented while loops is because the while loop continued running 
// without the data from the distance and thus it needs to constantly 
// be updated in the while loop conditional statments
void lights() { 
  sensor(); //data update
  while (distance <= 10) {
    for (int x = 0; x <= 60; x++) {
      leds[x] = CRGB(255,255,255);
      FastLED.show();
      sensor(); //sensor update
    }
    for (timer = 0; timer <=800; timer++) {
      sensor();
    }
    sensor(); //replaces the data updates above
  }
  sensor(); //sensor update
  while (distance >= 11) {
    for (int x = 0; x <= 60; x++) {
      leds[x] = CRGB(0,0,0);
      FastLED.show();
    }
    sensor(); //data update
  }
}

【问题讨论】:

    标签: arduino sensors led


    【解决方案1】:

    我很想创建一个小函数来设置 LED 灯条的 RGB 颜色:void fillup(byte r, byte g, byte b)。然后你会在两个地方调用它:fillup(0,0,0)fillup(127,127,127)(是的,不是 100% 开启)。

    另外,我很困惑为什么在第一个 while 循环中有这么多 sensor() 调用。似乎您只需要在需要更新 distance 的值时调用它一次。

    此外,sensor 调用中的 cmets 令人困惑……阅读它们后,我不知道 sensor 应该做什么。我倾向于在描述其功能的函数之前添加注释,并在代码中添加独立注释来解释下一个“段落”的功能。而且我避免使用横幅 - 它们会妨碍您。

    您希望FastLED.show() 在更新颜色的循环中吗?或者只是在循环之后,在阵列更改后更新硬件? IDK,只是问问。

    我通常不介意全局变量,但在这种情况下,您最好让sensor 返回距离。然后你可以while ( sensor() &lt;= 10 )。如果你想保持全局,或者使用do.. while 循环并在底部调用sensor

    我也会尝试摆脱浮点...只需计算原始回波值中的阈值,然后使用它们。我们真的关心内部度量单位是什么吗?

    抱歉拖了这么久……你的东西没有问题。

    【讨论】:

    • 所以我考虑了您所说的,并纠正了有关传感器更新的令人困惑的部分,一切正常。感谢您的帮助!
    • 不客气!感谢您慷慨地听取我挑剔的建议!玩得开心!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多