0

Currently I'm controlling an RGB LED with my Arduino Nano.

I'm mixing the colors using analogWrite

Though, the LED's don't light up at all for low analogwrite values and the difference between the levels is not visible (to me).

I'm using 100 Ohms resistors between the LED's, using a 680Ohms didn't seem to make a difference.

Analogwrite is working by toggling the LED's fast (PWM)? So not by lowering voltage? This is why I think it's weird that they don't light up at all, on low write values.

My sketch below:

#include <SoftwareSerial.h>

int r, g, b = 0;
String command = "";
const byte rxPin = 11;
const byte txPin = 10;

SoftwareSerial blueTooth (rxPin, txPin);

void handleCommand() {
  r = rgbFromCommand("r=",";");
  g = rgbFromCommand("g=",";");
  b = rgbFromCommand("b=",";");

  if(r != -1){
    analogWrite(A2,r);
  }
  if(g != -1){
    analogWrite(A1,g);
  }
  if(b != -1){
    analogWrite(A0,b);
  }
}

int rgbFromCommand(String prefix, String postfix) {
  int idx = command.indexOf(prefix);
  int endIdx = command.indexOf(postfix,idx);
  if(idx>=0 && endIdx>=0){
    idx+=2;
    return command.substring(idx,endIdx).toInt();
  }
  return -1;
}


void setup() {
  pinMode(rxPin,INPUT);
  pinMode(txPin,OUTPUT);
  Serial.begin(9600);
  blueTooth.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
    // read the incoming byte:
    char incomingByte = Serial.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
  if(blueTooth.available() > 0){
        // read the incoming byte:
    char incomingByte = blueTooth.read();

    if(incomingByte == '\n'){
      handleCommand();
      command = "";
    }else{
      command += incomingByte;
    }
  }
}

1 Answer 1

2

Analog pins aren't PWM pins. Instead you have to use the pins marked with a ~

Pins that aren't PWM pins will be off with a value of 0-127 and on with a value between 128 and 255.

2
  • Ah, analogWrite and analog pin caused the confusion! Also, I find it rather weird that it doesn't cause (atleast) a warning. I'm using an Arduino Nano, and the silkscreen on it is also rather unreadable. I thought it could be the resolution of the analogWrite, as it did work in native C++ (because I did use the hardware PWM and pins (as at that point it made sense to read the datasheet ;) ))
    – aaa
    Commented Dec 22, 2015 at 22:07
  • Yup, found the right pins, now works like a charm (youtube.com/watch?v=iJPvMaQH3D4) many thanks!
    – aaa
    Commented Dec 22, 2015 at 22:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.