How to display random image from serial port signal

edited April 2014 in How To...

Hi!

I'm using arduino and a PIR sensor to detect motion. Sending 'A' when HIGH and 'B' when LOW through the serial port.

In processing I have a working sketch that will display an image when 'A' is being sent through. clears it and shows the background when 'B'. I want to take this a step further and have it display a random image from an array. I've been trying to plug and play with Shiffman's examples but no luck. Anyone have any tips??

this is the code that's working for me without random function. Sorry if it is sloppy.

import processing.serial.*;


PImage bg;

Serial myPort; // The serial port:
boolean drawImage;
int count;

PImage photo;
void setup() {
  size(385,351);
  bg = loadImage("yes.jpg");
  // List all the available serial ports:
  println(Serial.list());
  // Open the port you are using at the rate you want:
  myPort = new Serial(this, Serial.list()[8], 9600);
  drawImage = false;
  int count = 0;
  photo = loadImage("no1.jpg");

}

void draw() {
  background(bg);
  while (myPort.available () > 0) {
    char inByte = myPort.readChar();
    if (inByte == 'A') {
      drawImage = true;
    if (inByte == 'B') 
      drawImage = false;

    }


}


  if (drawImage) {
    count+=1;
    fill(0);
    image(photo, 0, 0);

  }

  if (drawImage && count > 120) {
    drawImage = false;
    count = 0;
  }
}

Answers

  • edited April 2014

    You could do the follwing.

    PImage images[];
    int imageIndex =0;
    
    void setup(){
    ..
    ..
    images = new PImage[10]:
    images[0] = new loadImage(".."):
    ..
    ..
    images[9] = new loadImage(".."):
    //load 10 images
    }
    
    void draw(){
    ..
    ..
      while (myPort.available () > 0) {
        char inByte = myPort.readChar();
        if (inByte == 'A') 
          imageIndex = (int)random(0, images.length -1);
     }
    
      image(images[imageIndex], 0, 0);
    }
    

    hope that you understand it, and it's what you want

    Thomas

Sign In or Register to comment.