mardi 22 septembre 2020

Can I make an image sequence in processing move/play with an Arduino ultrasonic sensor?

This is my first post so I apologize in advance if anything is unclear and I will try to learn quickly. I am also a newbie when it comes to programming. Using Arduino Uno, Ultrasonic Sensor HC-SR04, Processing3.5.3

In the processing and Arduino sketches I have provided I am able to play an image sequence, and when the ultrasonic sensor picks up the distance of an object a "1" is printed in the processing console.

I am wondering if I can use this "1" to make an if statement. If the console prints a number larger than 0, then have the image sequence play--else, only one image will be drawn (The gif will pause). I have tried a couple versions of this, but I don't want to pretend like I know what I am doing.

Any leads for me to follow would be wonderful! Or tutorials online!

I feel like there is something incredibly simple that I am just missing... I guess nothing is ever that simple. Thank you for your time :))

ARDUINO CODE:

#define trigPin 9
#define echoPin 10

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop() {
  long distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);           //CHANGE THIS??
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  distance = pulseIn(echoPin, HIGH);

  if (distance <= 2000){ //raise this number to raise the distance to wave hand
    Serial.print("1");
  }
  else {
    Serial.print("0");
  }
  delay(500);  
}

PROCESSING

import processing.serial.*;

int numFrames = 22; //number of frames in animation
int currentFrame = 0;
PImage[] image = new PImage[22];
Serial myPort; 
String instring = ""; 

void setup() {
  myPort = new Serial(this, Serial.list()[1], 9600);  
  myPort.bufferUntil('\n');                                                                             
  size(1600, 900);                                    
  frameRate(30);                                      
  background(0);
  
  //Load images below
 for(int i = 0; i<image.length; i++)
   { 
     image[i] = loadImage("PatMovingFace" + i + ".png");
   }    

}

void draw() {
   //ALL BELOW connects to arduino sensor
  while (myPort.available () > 0){
    instring = myPort.readString();
    println(instring);
    int sensorAct = Integer.parseInt(instring, 10); 
  }
    playGif();   
}
  
 // ALL BELOW will make the pic array animate! Image moves! 

void playGif(){
      currentFrame = (currentFrame+1) % numFrames; //use % to cycle through frames!
      int offset = 0;

      for (int i = 0; i < image.length; i++)
      {
          //image(image[i] % numFrames), 0, 0); 
          image(image[(currentFrame + offset) % numFrames], 0, 0);
          offset += 0;
          image(image[(currentFrame + offset) % numFrames], 0, 0);
          offset+= 0; 
      }   
}

Aucun commentaire:

Enregistrer un commentaire