Parsing a string to an integer

Hello everyone, I wrote a processing program where and array of png’s animate with the system variable mouseY using the map function. It works, but now I want to change the mouseY and animate with the ultrasonic data coming in. The Arduino code is as follows:

const int pingPin = 9;
void setup() {
  Serial.begin(9600);
}

void loop() {
  long duration, inches, cm;

  pinMode(pingPin, OUTPUT);
  
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  pinMode(pingPin, INPUT);
  
  duration = pulseIn(pingPin, HIGH);

  cm = microsecondsToCentimeters(duration);

  int val = map(cm, 0, 1023, 0, 255); 
  Serial.println(cm);                                    
  delay(100);
}

I want to map from far to near, between the first to last image (I have 32 images, but I am declaring only 6 here) .

import processing.serial.*;

Serial myPort;
String val;

PImage[] artboard = new PImage[6];

int counter = 0;
PImage img;

void setup () {
  size(767, 600);
  
  String portName = Serial.list()[2];
  myPort = new Serial(this, portName, 9600);
  
  frameRate(60);

  artboard[0]=loadImage("Artboard_1.png");
  artboard[1]=loadImage("Artboard_2.png");
  artboard[2]=loadImage("Artboard_3.png");
  artboard[3]=loadImage("Artboard_4.png");
  artboard[4]=loadImage("Artboard_5.png");

}

void draw() {
  background(255,255,255);
  
  if ( myPort.available() > 0 ){
     val = myPort.readStringUntil('\n');
  }
  println(val);
  
  int yPos;
  
 for( yPos = 0; yPos<0; yPos++){
   yPos = Integer.parseInt(val);
 } 
  
  
  int frame = (int)map(yPos, 0, 600, 0, 6);
  if (frame < 0) {
    frame = 0;
  }
  if (frame > 32) {
    frame = 32;
  }
  image(artboard[frame], 0, 0);
  
}

Thank youuu

1 Like
  cm = microsecondsToCentimeters(duration);

//  int val = map(cm, 0, 1023, 0, 255); // <--- have a look at the map function  
 // if your range is from 10 to 400 cm 
int val = map(cm, 0, 400, 0, 32); // map range from 0 to 400 to 0 to 32 (number of pictures) 
// Serial.println(cm);   // <------- send val, you send  cm   
Serial.println(val);

Adopt your processing code accordingly.

3 Likes

Thank you and I fixed the parsing like this

void serialEvent (Serial myPort) {
  yPos  =  float (myPort.readStringUntil ( '\n' ) ) ;  
} 
1 Like