Search code examples
arduinoprocessingarduino-unoled

Arduino & Processing 3: "Dimmer" Built-In Example


Okay, so I'm using an Arduino Uno on a Windows 10 PC, as well as Processing 3. I'm attempting to follow the directions on the Arduino website for controlling the brightness of an LED by moving my across the PC screen, by having the Arduino software cooperate w/ Processing. (Here's the link to the project I'm talking about: https://www.arduino.cc/en/Tutorial/Dimmer) It seems so simple, yet it's not quite working. The LED will glow, but its brightness won't vary with the mouse's X position, and its glow is flickering. I get no error codes.

As regards the circuit, I have an LED connected to PWM pin 9, with a 200-ohm resistor to ground; I am certain that the polarity of the LED is correctly set up. The website isn't clear how exactly Processing & the Arduino software should collaborate to make this happen. (So I would greatly appreciate an explanation thereof if possible.) The Arduino & Processing codes are below. I don't understand what I'm doing wrong?

Here is my Arduino code:

const int ledPin = 9;      // the pin that the LED is attached to

void setup() {
  // initialize the serial communication:
  Serial.begin(9600);
  // initialize the ledPin as an output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  byte brightness;

  // check if data has been sent from the computer:
  if (Serial.available()) {
    // read the most recent byte (which will be from 0 to 255):
    brightness = Serial.read();
    // set the brightness of the LED:
    analogWrite(ledPin, brightness);
  }
}

Here's my Processing code:

import processing.serial.*;

import cc.arduino.*;

Arduino arduino;

void setup() {
  size(256, 150);

  arduino = new Arduino(this, "COM3", 9600);

}

void draw() {
  background(constrain(mouseX, 0, 255));

  arduino.analogWrite(9, constrain(mouseX, 0, 255)); // 

}

Solution

  • For those of you who wish to know, here is my functional code:

    Arduino portion:

    const int ledPin = 9;      // the pin that the LED is attached to
    
    void setup() {
      // initialize the serial communication:
      Serial.begin(9600);
      // initialize the ledPin as an output:
      pinMode(ledPin, OUTPUT);
    }
    
    void loop() {
      int brightness;
    
      // check if data has been sent from the computer:
      if (Serial.available()) {
        // read the most recent byte (which will be from 0 to 255):
        brightness = Serial.read();
        // set the brightness of the LED:
        analogWrite(9, brightness);
      }
    
      delay(10);
    }
    

    Processing portion (on Processing 3):

    import processing.serial.*;
    
    import cc.arduino.*;
    
    Serial arduino;
    
    void setup() {
      size(256, 150);
    
      arduino = new Serial(this, "COM3", 9600);
    
    }
    
    void draw() {
      background(constrain(mouseX, 0, 255));
    
      arduino.write(constrain(mouseX, 0, 255)); //  
    }