Toggle variable not working in subroutine

I'm trying to toggle a variable so that every 1s I can take a distance reading, then compare the two. This worked as its own sketch the only problem is when I incorporate it into the "stopcheck" subroutine it won't toggle the variable "ReadToggle"

Why is this happening and how can I fix it?

Code for full program and isolated sketch shown below in that order.

//SETTINGS
const byte stopdistance = 50;             //Car stop distance
const long SCinterval = 1000;            // time between stop checks

// defines pin numbers
const int trigPin = 2;                   //Sensor - TRIG pin
const int echoPin = 8;                   //Sensor - ECHO pin
const int StopledPin = 13;               //LED - Stop led

// defines constants
const long blinkInterval = 300;          // Stopled Blink Interval
unsigned long previousMillis = 0;        // will store last time LED was updated

unsigned long SCprevMillis = 0;          // will store last time stopcheck occured in during autobrake



// defines variables
long duration;                           //duration of received pulse
int distance;                            //distance from sensor in cm
bool StopledState = 1;                    //ledState used to set the LED
bool autostopOverride = 0;                //autobraking system override
bool autostopFlash  = 0;                  //flash led to signal autostop engaged

void setup() {
  pinMode(StopledPin, OUTPUT);          //Set ledPin as Output
  pinMode(trigPin, OUTPUT);             // Sets the trigPin as an Output
  pinMode(echoPin, INPUT);              // Sets the echoPin as an Input
  Serial.begin(9600);                   // Starts the serial communication

}

void loop()
{
  distancecheck();                      //Checks distance between sensor and object
  brakingtrigger();                     //triggers autobrake at stopping distance
}

void distancecheck()
{
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2;
}

void brakingtrigger()
{
  if (distance <= stopdistance)             //if distance is equal or less than set distance
  {
    autostop();                             //call autostop
  }
  else
  {
    digitalWrite(StopledPin, 1);  //turn on LED
  }
}

void autostop()
{
  blinkStopLED();                               //Blinks stopLED
  stopcheck();                                  //checks distance every 1s
}


void stopcheck()
{
  //vars
  unsigned long SCcurrentMilis = millis();      //var for StopCheck
  int ReadToggle = 0;                           // ReadToggle used to set which read var to write
  int prevdist1;                                 //distance captured alternating interval
  int prevdist2;                                 //distance captured alternating interval
  int stopped;

  if (SCcurrentMilis - SCprevMillis >= SCinterval)
  {
    SCprevMillis = SCcurrentMilis;          //save last time reading was taken
    ReadToggle = !ReadToggle;               //toggle distance read 1 or 2
    //check whether car is stopped every SCinterval

    Serial.println(ReadToggle);

  }
}

void blinkStopLED()
{
  unsigned long currentMillis = millis();   //var for StopledBlink

  if (currentMillis - previousMillis >= blinkInterval)
  {
    previousMillis = currentMillis;             //every interval
    StopledState = !StopledState;               //toggle StopledState
    digitalWrite(StopledPin, StopledState);     //write StopledState to StopledPin
  }
}
/*
  Blink without Delay

  Turns on and off a light emitting diode (LED) connected to a digital pin,
  without using the delay() function. This means that other code can run at the
  same time without being interrupted by the LED code.

  The circuit:
  - Use the onboard LED.
  - Note: Most Arduinos have an on-board LED you can control. On the UNO, MEGA
    and ZERO it is attached to digital pin 13, on MKR1000 on pin 6. LED_BUILTIN
    is set to the correct LED pin independent of which board is used.
    If you want to know what pin the on-board LED is connected to on your
    Arduino model, check the Technical Specs of your board at:
    https://www.arduino.cc/en/Main/Products

  created 2005
  by David A. Mellis
  modified 8 Feb 2010
  by Paul Stoffregen
  modified 11 Nov 2013
  by Scott Fitzgerald
  modified 9 Jan 2017
  by Arturo Guadalupi

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

// Variables will change:
int ReadToggle = 0;             // ReadToggle used to set which read var to write


// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long SCprevMillis = 0;          // will store last time stopcheck occured in during autobrake

// constants won't change:
const long SCinterval = 1000;            // time between stop checks

void setup() {
  Serial.begin(9600);                   // Starts the serial communication
}

void loop() {
  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long SCcurrentMilis = millis();      //var for StopCheck

  if (SCcurrentMilis - SCprevMillis >= SCinterval)
  {
    SCprevMillis = SCcurrentMilis;          //save last time reading was taken
    ReadToggle = !ReadToggle;               //toggle distance read 1 or 2
                                            //check whether car is stopped every SCinterval
    if (ReadToggle == 1)
    {

      Serial.print("Prev Distance1: ");
      Serial.println(ReadToggle);
    }
    else if (ReadToggle == 0)
    {

      Serial.print("Prev Distance2: ");
      Serial.println(ReadToggle);
    }
  }
}

Okay, after a bit of trial and error it seems it is because I was using ReadToggle as a locally define variable instead of a globally defined variable. Not entirely sure why that should matter but at least it works.

Sketco:
Okay, after a bit of trial and error it seems it is because I was using ReadToggle as a locally define variable instead of a globally defined variable. Not entirely sure why that should matter but at least it works.

Check the post at the top of the Forum and look for the topic on Scope. You need to understand it.

Thanks econjack. I appreciate you pointing me to things one stumbling block at a time :smiley:

Every time you executed stopcheck, ReadToggle was being reset to zero.

Yep. That's what I gleaned from the reading. Thanks to you both!

If you only use ReadToggle in one function, the best solution is to add the 'static' keyword to the declaration:

static int ReadToggle = 0;

This tells the compiler to keep the value of ReadToggle (like it does with global variables). The variable is still local, which makes it easier to understand the code.

If ReadToggle is only used to hold 0 and 1 it would be better to declare it 'boolean' instead of 'int'. That makes it half the size and the code will know that it shouldn't have a value other than 0/false/LOW or 1/true/HIGH.