We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am working on a simple project which is a bit challenging for a beginner like me. It is a project with processing and Arduino. In general, I made two buttons, A and B, in Arduino. Once the button A is pressed, Arduino will send a serial number to processing, and an image A will be displayed until the button B is pressed, which will make Arduino send another serial number to processing to display image B.
Here comes my question. I want to make an effect that** if none of buttons has been pressed for a while, the window of processing will automatically return to its background**. I have been stuck in this problem for long.. Now I have no clue about it.
This is my code for Arduino:
int switchPin2 =2;
int switchPin3 =3;
void setup() {
pinMode(switchPin2, INPUT);
pinMode(switchPin3, INPUT);
Serial.begin(9600);
}
void loop() {
if(digitalRead(switchPin2)==HIGH && digitalRead(switchPin3)==LOW)
{
Serial.write(2);
delay(1000);
}
else if(digitalRead(switchPin3)==HIGH && digitalRead(switchPin2)==LOW)
{
Serial.write(3);
delay(1000);
}
delay(100);
}
This is my code for processing:
import processing.serial.*;
Serial port;
PImage img2;
PImage img3;
int val=0;
void setup(){
size(400,400);
img2=loadImage("a.jpg");
img3=loadImage("b.jpg");
port= new Serial(this,"/dev/cu.usbmodem1451", 9600);
}
void draw(){
background(255);
if(0<port.available()){
val=port.read();
}
if(val==2){
image(img2,0,0);
}
if(val==3){
image(img3,0,0);
}
}
I long for some hints ! Thank you in advance!
Answers
This is untested code but it should do the trick.
Kf
@ckuoping --
Setting aside the serial communication, consider this very simple case of an event timer (of the kind that @kfrajer shared). Any time it is activated, it sets an expire-time in the future. The event is then true until the expire time passes -- the event then becomes false.
@kfrajer Thank u so much. It is really well activated.
@kfrajer Thank you so much! it works pretty well! awesome!! and also thank @jeremydouglass it is good for me to realise Kfrajer's code with your clear explanation! There is one thing left I want to ask again: what is the function/meaning behind the script: val=-1. Is it just a random number or must it be set to -1?
If you check the code, the value of val drives the action in draw. If val is 2 or 3, it will display the respective image. Now, when the time runs out, we want to "not" show an image at all. For that, we need to change val to a different value. I choose this negative value assuming val will not take any negative value but only in this case, when no images are displayed. To make my code clear I could have use this next definition in a global scope in the code::
final int SHOW_BACKGROUND = -1;
and then:
Kf
@kfrajer! thanks again! Now everything is clear!