how to store a variable and output on next state change

Hello,

I'm trying to write some code to store a variable and output the value on the next state change of the variable.

For example. As you can see from the code below, I have a variable which will have 6 states to define 3 digital outputs (I've only shown 3 below). The problem is that I want to store the value of the variable until the state of the variable changes.

So say when my code starts and I get a variable value of 2 the outputs won't be enabled. If the variable value changes to a new number, lets say 5, I want to output the values of 2. If the next variable value is 1, I want to output the output states from 5.... and so on.

so really I just need to store the variable until the next state change.

const int output1 = 2;
const int output2 = 3;
const int output3 = 4;
int Variable = 0;

void setup() {
  
  pinMode(output1,OUTPUT);
  pinMode(output2,OUTPUT);
  pinMode(output3,OUTPUT);
}

void loop() {

  
//output state 1
if (variable == 1){
 digitalWrite(output1,HIGH); 
 digitalWrite(output2,LOW); 
 digitalWrite(output3,LOW); 
}

//output state 2
if (variable == 2){
 digitalWrite(output1,LOW);
 digitalWrite(output2,HIGH);
 digitalWrite(output3,LOW); 
}

//output state 3
if (variable == 3){
 digitalWrite(output1,HIGH);
 digitalWrite(output2,HIGH);
 digitalWrite(output3,LOW); 
}
}

if (variable = 1){
Use
if (variable == 1){

http://arduino.cc/en/Reference/If

.

Thanks for the reply,

I have used == in my code, I just missed out the extra equals sign on here!

Does anybody have any ideas of how to achieve this? I think it needs to be something like:

if (variable != new variable){
do something}

....

...

So, create a new variable to store the old value...

loop() {
  static int variable = 0;
  static int OldValue;

  OldValue = variable;
  //code which changes the value of variable

  //do something which uses the OldValue

}
if (newVariable != oldVariable) {
    oldVariable = newVariable;
    doYourStuff();
}

...R

spencerevans88:
I have used == in my code, I just missed out the extra equals sign on here!

...

Have you heard of copying and pasting? Why post different code to what you are using?