Trying to update a local var based on newest can bus data in if loop

I have my arduino picking up CAN data and then converting it for another use but i seem to have made 2 variables with the same name instead of updating the variable i made outside of the receiving portion of code. i tried making it a static int but i cant seem to get this to work.

void loop()
{

 static int mapcan ;

{ CAN_FRAME incoming;

    if (Can0.available() > 0) { //  CAN BUS INCOMING TRAFFIC
      Can0.read(incoming);
 	if (incoming.id == 0x7e8)   // RESPONSE PID = 0x7e8. USED FOR MAP DATA (this is a customizable based on sent data on 0x7e0)
      {
        //MAP
        int MAPS = (incoming.data.bytes[4] + .05) * 100; // from gm  //multiplied by 100 for higher resolution      
        int mapout = map(MAPS, -1125, 31250, 0, 500); // ( -11.25- 312.5 kpa converted to 0-5v ref)
        static int mapcan = ((mapout * 819) / 100); /// this wont update my variable???
}}}

uint8_t Byte1map = (mapcan) >> 8;
  uint8_t Byte2map = (mapcan);

 CAN_FRAME outgoing;
    outgoing.id = 0x2C0;
    outgoing.extended = false;
    outgoing.priority = 0; //0-15 lower is higher priority
    outgoing.length = 2;
    outgoing.data.byte[0] = Byte1map;
    outgoing.data.byte[1] = Byte2map;
}

Remove static int. What you have done here is declared a static variable local to the if statement code block and it cannot be accessed outside of that block.

Scope of Variables in C++

okay that makes sense. Could I declare it static at the top of the loop to keep the variable active every loop. then refer to it inside the if loop as just int or will that still make 2 separate variables?

Yes.

If you precede an identifier by a data type that is a declaration and the compiler reserves storage and determines the scope.

Consider the following:

int foo;                   // global variable foo
const int bar = 7; // global constant bar

void setup()
{
    foo = 7;    // this sets the global foo
}

void loop()
{
  int temp = 3;
  static int foo = 0;   // static variable foo which is local to the loop() function
  const int bar = 8;   // constant variable bar which is local to the loop() function

  if (temp == 3)
  {
      int foo = bar;         // variable foo local to this if block is set to loop() const bar
      // Because you declared foo here there is NO WAY to get to the static foo or the global foo!
  }

  foo++;  // this increments the static foo.  There is no way to get to the global foo!!!
}

I GOT IT! I had to remove all declaration inside if block and just make it mapcan=
thanks for your help!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.