Skip to main content
added 753 characters in body
Source Link
Majenko
  • 105.9k
  • 5
  • 82
  • 139

Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

These two options look like this:

Global

long count = 0;

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

Static

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
  static long count = 0;

Both will do the same job, but the static form is preferred since it is always better to keep a variable's scope as narrow as possible. It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.

Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

These two options look like this:

Global

long count = 0;

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

Static

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
  static long count = 0;

Both will do the same job, but the static form is preferred since it is always better to keep a variable's scope as narrow as possible. It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.

Source Link
Majenko
  • 105.9k
  • 5
  • 82
  • 139

Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.