1

I am attempting to write a small sketch with the Arduino IDE (1.8.10) to set the colour of an RGB LED, however my function for setting the colour of the LED is behaving strangely.

Here is the full sketch code:

#define RED 9
#define GREEN 10
#define BLUE 11

void setup()
{
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
  digitalWrite(RED, LOW);
  digitalWrite(GREEN, LOW);
  digitalWrite(BLUE, LOW);
  Serial.begin(9600);
}

int gRed = 20;
int gGreen = 21;
int gBlue = 22;

void setRGB(int r, int g, int b)
{
  Serial.println(r);
  Serial.println(g);
  Serial.println(b);
  analogWrite(RED, r);
  analogWrite(GREEN, g);
  analogWrite(BLUE, b);
}

void loop()
{  
  //setRGB(gRed, gGreen, gBlue); // WORKS - White-ish
  setRGB(20, 21, 22); // DOESN'T WORK - Blue =/
}

As you may tell from the comments, when I pass "global" variables in to setRGB() the LED lights up the expected colour. But, when I pass literals in it does not.

The Serial monitor shows the following output when using the literals:

20
21⸮20
21
20
21
20
21⸮
etc....

Can anybody help me figure out what I'm doing wrong?

Board in use is a Mega2560.

3
  • Comments are not for extended discussion; this conversation has been moved to chat.
    – VE7JRO
    Commented Nov 30, 2019 at 14:37
  • the conclusion in chat was a compiler problem (it over-optimized). with AVR core 1.6.21 which uses older version of avr-gcc the code worked
    – Juraj
    Commented Dec 1, 2019 at 19:40
  • I'd add some delay between calls. Or even change the values by analogWrite when they changes only.
    – KIIV
    Commented Dec 1, 2019 at 20:38

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.