Passing a Variable outside an if statement

Hi everyone ,

In my code I am trying to pass the value of int node1, node2, node3 in texts as you can see in void draw.

import java.util.Arrays;
import processing.serial.*;
import http.requests.*;


PImage bg;
int address;
int value;
String read;
String list;
String hex;
int node1;
int node2;
int node3;
int lf = 10;
Serial COMPort;
String[] validaddresses={"0x1","0x2","0x3","0x4"};


void setup() {
  size(1280, 720);
  
  bg = loadImage("some photo.jpg");
  
  
  String portName = Serial.list()[0];
  COMPort = new Serial(this, portName, 9600);
  COMPort.bufferUntil(lf);

  textSize(30);
  
}

void draw() {
  background(bg);
  int node1=0;
  int node2=0;
  int node3=0;
  text("The value is " + node1, 250, 250);
  text("The value is " + node2, 450, 350);
  text("The value is " + node3, 450, 450);
}
  void serialEvent(Serial COMPort)  
  {  
    
    read = trim(COMPort.readString());  // read and store it to string read 
    String[] list=split(read," ");
    
    if (list[0].equals(validaddresses[0])) {
      int node1 = Integer.parseInt(list[1]);
      System.out.println(node1);
      
      }
     if (list[0].equals(validaddresses[1])) {
       int node2 = Integer.parseInt(list[1]);
       System.out.println(node2);
      
      } 
    if (list[0].equals(validaddresses[2])) {
      int node3 = Integer.parseInt(list[1]);
      System.out.println(node3);
      
      }
      
  delay(100);
 
    }

Is there an easy way to solve with this issue? Not sure what I have to try.

I think the problem here is that you say int node1 in all places. This declares a new variable node1. Since you do this in a function, this variable is seen as local (known only within the function) and over shadowing the global variable node1 (declared before setup()).

So before setup() your code is correct:

int node1;
int node2;
int node3;

To make sure that every time you use node1, you are in fact referring to this node1, you have to remove the int (which declares a variable) from the other places :

in draw() :

I would delete this totally since it kills the values from serialEvent to 0 (((or say

  node1=0;  // still a bad idea since draw() runs on an on
  node2=0;
  node3=0;

)))

And in serialEvent

      int node1 = Integer.parseInt(list[1]);  // declaring a new local variable 

must be

      node1 = Integer.parseInt(list[1]);  // setting the old global variable (before setup and in draw) to a new value 
2 Likes

It’s not working. Value displayed in text keeps remaining 0. What I need is when code reads new serial data which is like"0x1 78" or β€œ0x3 105” to test first column and pass the value of the 2nd column to texts.

please post your entire code

definitely remove this from draw()

Yes . I killed it from draw totally as you mentioned earlier and it works. Thank you a lot.

1 Like