简体   繁体   中英

Arduino variable usage

I'm a newbie when it comes to Arduino and C++.

I'm trying to write a program that reads the input data from analog pin zero (a 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. 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);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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