|
Main Links:
Final Projects
|
Main /
RangingExampleint potPin = 0; // Analog input pin that the potentiometer is attached to int potValue = 0; // value read from the pot int led = 9; // PWM pin that the LED is on. n.b. PWM 0 is on digital pin 9 int led2 = 10; int rangedValue = 0; void setup() { // initialize serial communications at 9600 bps: Serial.begin(9600); } void loop() { potValue = analogRead(potPin); // read the pot value
analogWrite(led, potValue/4); // PWM the LED with the pot value (divided by 4 to fit in a byte)
Serial.print("potValue = "); // print the pot value back to the debugger pane
Serial.print(potValue); // print the pot value back to the debugger pane
// rangedValue = intRanger(originalMinimum,originalMaximum,newMinimum,newMaximum,valueToBeRanged) rangedValue = intRanger(320,840,0,255,potValue);
analogWrite(led2, rangedValue); // PWM the LED with the pot value (divided by 4 to fit in a byte)
Serial.print(" rangedValue = "); // print the pot value back to the debugger pane
Serial.print(rangedValue); // print the pot value back to the debugger pane
Serial.print("\n");
delay(10); // wait 10 milliseconds before the next loop
} int intRanger( int originalMin, int originalMax, int newMin, int newMax, int currentValue) { long zeroRefOriginalMax =0;
long zeroRefNewMax = 0;
long zeroRefCurVal = 0;
int rangedValue = 0;
// Check for out of range currentValues
if (currentValue < originalMin) {
currentValue = originalMin;
}
if (currentValue > originalMax) {
currentValue = originalMax;
}
// Zero Refference the values
zeroRefOriginalMax = originalMax - originalMin;
zeroRefNewMax = newMax - newMin;
zeroRefCurVal = currentValue - originalMin;
// Check for negative values and 0 max ranges
if ( (zeroRefNewMax < 1) || (zeroRefOriginalMax < 1) || (originalMin < 0) || (originalMax < 1) || (newMin < 0) || (newMax < 1) || (currentValue < 0) ) {
return 0;
}
rangedValue = ( (zeroRefCurVal * zeroRefNewMax) / zeroRefOriginalMax ) + newMin ;
return rangedValue;
} |