Changing colors on a rectangle


#1

THE FOLLOWING CODE IS WRITTEN ON PROCESSING. I NEED THE CODE TO CHANGE THE COLOR OF A RECTANGLE WHEN THE VARIABLE B CHANGES ITS VALUE. WHEN D>20 THE RECTANGLE SHOULD BE GREEN, WHEN 20>D>10 IT SHOULD BE YELLOW, AND WHEN D<10 SHOULD BE RED. SO FAR I ONLY GET RED. THANKS FOR YOUR HELP

import processing.serial.*;
Serial port;
void setup() {
  port = new Serial(this, "/dev/cu.usbserial-DN02SMXZ", 9600);
  fullScreen();
}
void draw() {
  background(50);
  if (port.available() &gt; 
  0) {
    String a = port.readStringUntil(10);
    if (a != null) {
      text(a, 80, 80);

      a = trim(a);
      int b = int(a);

      if (b &gt; 
      20)
      {
        fill(0, 255, 0);
        rect(b*2, 100, 100, 300);
        delay(500);
      } else if (b&gt;
      10)
      {
        fill(255, 155, 0);
        rect(b*2, 100, 100, 300);
        delay(500);
      } else if (b &lt; 
      10)
      {
        fill(255, 0, 0);
        rect(b*2, 100, 100, 300);
        delay(500);
      }
    }
  }
}

#2

The basic code should work, however I note the following:
else if (b < 10)
I think should just be else, otherwise the value of 10 paints nothing.

If a contains any characters other than numerics and whitespace, the result will be red, since int("10j"), or any other random string with alphas is 0.

I tested the code with a = “5\n”, “15\n”, and “50\n”, in all three cases the color was as expected.

So my best guess is your serial input contains more than numerics and whitespace.


#3

The code it was supposed to display a Box changing colors. The box remains Red at all times.


#4

Example:

float b;

void setup(){
  size(200,200);
  textSize(32);
}

void draw(){
  b = map(mouseX, 0, width, 0, 30);
  background(0);
  if( b > 20 ){
    fill(0,255,0);
  } else if ( b > 10 ){
    fill(255,255,0);
  } else {
    fill(255,0,0);
  }
  rect(10,10,180,180);
  fill(0);
  text( int(b), 50, 100);
}

Notice the complete lack of calls to delay(). Unless you know exactly what you’re doing and what that function does, you probably don’t need them.