Variables Initialized to Sensor Readings

I am trying to initialize global variables to sensor readings so that my students and I don’t have to continually write out SensorValue(sensorName) whenever a conditional or reading is required. I have attached a short code sample of what I am trying to do. It seems as though when the code is compiled the variable is set to the current reading and then never updated. Please explain how to fix this and accomplish what I am setting out to do. Thank you.

**Update
I was able to make it work by creating a task that continually refreshes. I’m assuming that in version 1 when the variable is first declared and initialized it is never updated again and therefore never changes value. Version 2 seems kind of clunky to me; is there a better way to do what I am trying to accomplish?
Capture.JPG
Capture.JPG

When assigning any value to a variable, the variable only changes at the time of the assignment. Assigning the value of a sensor using the SensorValue function to a variable will only happen when that line of code is executed. You have a couple of choices that would allow you to achieve what you are trying to do.

  1. Assign to your S1 variable at the beginning of your while loop.
#pragma config(Sensor, dgtl1,  buttonOne,      sensorTouch)
#pragma config(Motor,  port1,           motorOne,      tmotorVex393_HBridge, openLoop)
//*!!Code automatically generated by 'ROBOTC' configuration wizard               !!*//

int S1;
int M1;

task main()
{
    while(1)
    {
      S1 = SensorValue buttonOne ];
      motor motorOne ] = M1;
      
      if( S1 == 1 )
      {
        M1 = 60;
        wait1Msec(200);
      }
      else
        M1 = 0;
      
     wait1Msec(25);  
    }
}
  1. Use a macro, a macro allows substitution within the code, use with care.
#define S1  SensorValue buttonOne ]
int  M1;

task main()
{
    while(1)
    {
      motor motorOne ] = M1;
      
      if( S1 == 1 )
      {
        M1 = 60;
        wait1Msec(200);
      }
      else
        M1 = 0;
      
     wait1Msec(25);  
    }
}
  1. Use a function to retrieve the value of the sensor.
int  M1;

int S1()
{
  return( SensorValue buttonOne ] );
}
task main()
{
    while(1)
    {
      motor motorOne ] = M1;
      
      if( S1() == 1 )
      {
        M1 = 60;
        wait1Msec(200);
      }
      else
        M1 = 0;
      
     wait1Msec(25);  
    }
}

Personally I would stick to using SensorValue in the code where needed or use a descriptive function name like this (same as the previous code with a different name for S1)

int  M1;

int getButtonSensor()
{
  return( SensorValue buttonOne ] );
}
task main()
{
    while(1)
    {
      motor motorOne ] = M1;
      
      if( getButtonSensor() == 1 )
      {
        M1 = 60;
        wait1Msec(200);
      }
      else
        M1 = 0;
      
     wait1Msec(25);  
    }
}