converting values and ranges

I am using a Ping sensor to send values into the arduino. At the minute i have the values constrained between 0 and 300 so that anything past 300 will be equal to 300. I now need to take this data and create a set of values that are between 0 and 255, but done in a way so that the original max value (300) now equals 255.

I then need to invert the entire data range so that 0 becomes 255 and 255 becomes 0.

I'm unsure of where to start with this so any help would be most welcome.

#include <NewPing.h>
 
#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 500
 
NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
 
void setup() {
  Serial.begin(115200);
}
 
void loop() {
  delay(50);
  int Val = sonar.ping();
  int readVal = (Val / US_ROUNDTRIP_CM);
  
  if (readVal > 300)
    {
      readVal=300;
    }
 

  Serial.print("Ping: ");
  Serial.print(readVal);
  Serial.println();
}

Take a look at this...

http://arduino.cc/en/Reference/Map

thanks! :slight_smile: