Ex: Blinker / Dimmer in Serial Connection





The Arduino Code:


 const int ledPin = 9;      // pin that the LED is attached to
 byte brightness = 0;
 byte blink_rate = 0;
 byte checkbit = 0;

 int state = 0;

 int ledState = LOW;        // to store LED states
 long previousMillis = 0;   // to store last time LED was updated


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

 void loop()
 {
   unsigned long currentMillis = millis();

   // check if data has been sent from the computer:
   if (Serial.available())
   {
     // read the most recent byte (from 0 to 255):
    checkbit = Serial.read();
    if (state == 2)
    {
      blink_rate = checkbit;
      state = 3;
    }
    if (state == 1)
    {
      brightness = checkbit;    
      state = 2;
    }
    if (checkbit == 255)
    {
        state = 1;
    }
   } 
  

  if(currentMillis - previousMillis > blink_rate)
  {
    // save the last time you blinked the LED
    previousMillis = currentMillis;  
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
    {
       ledState = HIGH;
       analogWrite(ledPin, brightness);
    }
    else
    {
        ledState = LOW;
        analogWrite(ledPin, 0);
    }
  }
}

........................................................................................
Processing code:



  import processing.serial.*;
  Serial port;
//  byte start;
 
  void setup()
  {
  size(254, 150);
 
  println("Available serial ports:");
  println(Serial.list());
 
  // Uses the second port in this list (number 1). 
  port = new Serial(this, Serial.list()[1], 9600); 
  }
 
  void draw()
  {
  // draw a gradient from black to white
  for (int i = 0; i < 254; i++) {
  stroke(i);
  line(i, 0, i, 150);
  }
 
  // write the current X & Y-position of the mouse to the
  // serial port as a single byte




    port.write(255);
    port.write(mouseX); println("X: " + mouseX);
    port.write(mouseY); println("Y: " + mouseY);
  }
 

No comments:

Post a Comment