简体   繁体   English

Arduino变量用法

[英]Arduino variable usage

I'm a newbie when it comes to Arduino and C++. 对于Arduino和C ++,我是新手。

I'm trying to write a program that reads the input data from analog pin zero (a POT). 我正在尝试编写一个从模拟引脚零(POT)读取输入数据的程序。 after the value is read I want it to print to the serial monitor, but only once. 读取值后,我希望它打印到串行监视器,但只打印一次。 if the value of from analog pin zero changes I want it to print the new value to the serial monitor. 如果模拟引脚零值的值发生变化,我希望它将新值打印到串行监视器。 I'm trying to use global variables, but to no avail. 我正在尝试使用全局变量,但无济于事。 any help would be greatly appreciated! 任何帮助将不胜感激!

int entered=0;
int flag;

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

void loop() {

int potValue=analogRead(A0);

if (!entered){
entered=1;
Serial.println(potValue);

}
int flag=potValue;

if (flag!=flag){
entered=0;
}
 }

That is really close. 那真的很接近。 This line is your mistake 这条线是你的错

int flag=potValue;

As written, that creates a new local variable flag . 如上所述,这会创建一个新的局部变量标志 The local variable hides the global variable. 局部变量隐藏全局变量。 So the comparison is always to itself and never fails. 因此,比较始终是对自己的,永远不会失败。 Change the line to : 将行更改为:

flag=potValue;

and your program will function as desired. 并且您的程序将按照需要运行。

You can save some memory and code space like this: 您可以像这样保存一些内存和代码空间:

int g_lastValue = 0;

void loop() {

  int nowValue = analogRead(A0);

  if (nowValue != g_lastValue) {
    Serial.println(nowValue);
    g_lastValue = nowValue;
  }
  ...
}

The use of g_ as name prefix is a cue that a variable is global. 使用g_作为名称前缀是变量是全局的提示。 I use this naming convention as it helps when reading a function to know variables that are not local. 我使用这个命名约定,因为它有助于在读取函数时知道非本地变量。 Without a name cue, you need to scan the entire function body to see if there is a variable declaration present, and only by looking through the function and not finding a declaration can you know the variable must be global. 如果没有名称提示,则需要扫描整个函数体以查看是否存在变量声明,并且只有通过查看函数而不查找声明才能知道变量必须是全局的。 On small functions, not really an issue, but as your code grows, you may want some self documentation a naming convention provides. 在小函数上,并不是真正的问题,但随着代码的增长,您可能需要一些命名约定提供的自我文档。

You're on your way but you are getting tangled a bit in variables. 你正在路上,但你在变量方面有点纠结。

It can be simpler: just one global variable and one conditional check. 它可以更简单:只需一个全局变量和一个条件检查。

int lastRead = -1; // init to value outside of possible range

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

void loop() {

  // get current value
  int currentRead = analogRead(0);

  //compare and only print if !=
  if (currentRead != lastRead){
   lastRead = currentRead; // store
   Serial.println(lastRead);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM