0

Mega 2560

I am reading in values from 3 pots then mapping them to values between 0 - 255

#define REDPIN   7
#define GREENPIN 8
#define BLUEPIN  9

int red_pot   = A0;  // analog pin used to connect the potentiometer
int green_pot = A1;
int blue_pot  = A3;


void setup() {

  pinMode(REDPIN,   OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN,  OUTPUT);

  Serial.begin(38400); //Debug port
  Serial.setTimeout(50);
}


void loop() {

  int red, green, blue; 

  red   = analogRead(red_pot);
  green = analogRead(green_pot);
  blue  = analogRead(blue_pot);

  Serial.print(" r = ");
  Serial.print(red);

  Serial.print(" b = ");
  Serial.print(blue);

  Serial.print(" g = ");
  Serial.print(green);
  Serial.print("\n\n\n");


  // map values
  red   = map(red,   20, 650, 0, 255);     
  green = map(green, 20, 570, 0, 255);
  blue  = map(blue,  20, 570, 0, 255);


  Serial.print("red map : ");
  Serial.print(red);

  Serial.print(" green map : ");
  Serial.print(green);

  Serial.print(" blue map : ");
  Serial.print(blue);
  Serial.print('\n\n\n');

  analogWrite(REDPIN,   red); 
  analogWrite(GREENPIN, green);
  analogWrite(BLUEPIN,  blue);    
}

red & green behave as expected but blue is not, from the serial monitor...

When blue is at its lowest value,

enter image description here

When blue is at its highest value,

enter image description here

I have changed blue's analog pin assignment but the same issue.

Any clues what's happening?

EDIT #1

I thought it might be some int sign error so I changed the map operation to,

blue  = map(abs(blue), 20, 670, 0, 255);

It made no difference.

DrBwts
  • 161
  • 1
  • 9

1 Answers1

1

Note that the Arduino function "map" is really this:

long map(long x, long in_min, long in_max, long out_min, long out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

...so, if you pass a "minimum from" value which is less than the actual value you are mapping from you will get a negative number given your "minimum out" is zero.

In several of your examples you have set the minimum to 20 but pass a value of 19. If your program is intolerant of negative numbers (for instance, how would a negative number effect the PWM hardware), consider testing for lower than minimum and higher than maximum values before using the map function.

st2000
  • 7,513
  • 2
  • 13
  • 19