How to Change Image Transparency Using Ultrasonic Sensor

Hi everyone

I’m trying to make a digital poster that changes when you get closer and farther away from it using an ultrasonic sensor and arduino. My distance measuring code works, but I can’t seem to get the two images in my processing code to properly fade into each other as I increase or decrease distance.

This is the code I’m using

import processing.serial.*;  
PImage PB_100;
PImage PB_CB;
Serial myPort;  
String data="" ;
int distance;
float transparency = 1;
float increase = 2;
int white = 255;
 
 
void setup() {
  size(595, 842); // size of processing window
  PB_100 = loadImage("PB_100.png");
  PB_CB = loadImage("PB_CB.png");
  
  PB_100.resize(595, 842);
  PB_CB.resize(595, 842);
  
  background(255);
  
 
  myPort = new Serial(this, "COM7", 9600);
  myPort.bufferUntil('\n');
}
 
void draw() {
  
  println(distance);
  image(PB_100, 0, 0); // 100
  
  tint(white, transparency);
  image(PB_CB, 0, 0); // CB
  
  transparency = transparency + increase;
  
  if (distance >= 100) {
    
    if (transparency <= 0) {   
    increase = increase * -1;
  }
  }
  
  if (distance <= 99) {
    
    if (transparency >=255) {   
    increase = increase * -1;
  }
  }
}

void serialEvent(Serial myPort) {
 
  data=myPort.readStringUntil('\n');
  distance=int(trim(data));
}

At the moment, the images just automatically fade into each other once and they don’t loop. It isn’t triggered by the distance at all. Can someone please tell me what I’m doing wrong and how to fix it?

Thanks in advance!

1 Like