Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • The HC-SR04 ultrasonic sensor gives me "null"

    Doing tests I found this on the Arduino side:

    /* How to use the HC-SR04 Ultrasonic Sensor with Arduino 
       Dev: Michalis Vasilakis // Date: 23/7/2015 // www.ardumotive.com */
    
    //Libraries
    #include "Ultrasonic.h"
    
    //Define pins ultrasonic(trig,echo)
    Ultrasonic ultrasonic(A0,A1);
    
    //Variables
    int distance;
    
    
    void setup() {
      Serial.begin(9600);
    
    }
    
    void loop(){
      distance = ultrasonic.distanceRead(CM); //Use 'CM' for centimeters or 'INC' for inches
      //Print distance...
      //Serial.print("objeto a:");
      Serial.print(distance);
      //Serial.println("cm");
    
    }
    

    It seems that the null answer it's because the Serial.print(distance) is not continued by a Serial.println() line.

    I did the tests and it works... but the sent "val" from Arduino acummulate in the serial buffer... like if I demand that if the distance is less than 150cm the program should print "SI", but only one time (that I don't know how to declare it) but every time that the readings are less than 150cm the program prints "SISISI" or "SISISISISISISISI"

    Then, I changed this:

    if (distance <= 150) {
        Serial.println("SI");
        digitalWrite(ledPin, HIGH);
      } else {
        Serial.println("NO");
        digitalWrite(ledPin, LOW);
    }
    

    Because I don't want to see the distance readings, but if an object is inside the limit distance. And it works...BUT! this function-that is inside the serialEvent() void- doesn't works:

    if (val.equals("SI")) {
        video1.stop();
        video2.stop();
        video3.stop();
      } else {
        video1.loop();
        video2.loop();
        video3.loop();
      }
    

    What could be wrong?

    Thanks for reading and any help you could give!

  • The HC-SR04 ultrasonic sensor gives me "null"

    Thanks @kfrajer for the answer.

    When I start the sketch, the videos are running, the sensor is connected (the board LEDs show me that at least) but the null answer its printed in the processing console. :-??

    The thig is that I stablished communication with another code, and it ran perfectly giving me the distances of an object. Then I changed the text that it will be printed and the "if" statement:

    if (distance <= 150) {
        Serial.print("SI");
        digitalWrite(ledPin, HIGH);
    }
    

    I came back to the original code in arduino but keeps printing null.

    So, I don't know what It changed... :-?

  • The HC-SR04 ultrasonic sensor gives me "null"

    Hi, programmers. I have asked many questions about an art project that I'm making, but in different threads. This could be the fifth(?) but here I go...again. The thing is that I'm having troubles with my sensor and the response in Processing. I found the way to stablish communication between the two programs (Arduino and Processing) but when I wanted to execute an "if" statement the sensor doesn't work and gives me the "null" answer. It's a problem with the code in both programs or just the sensor?

    Thanks in advance!

    Here are the both codes:

    Arduino

    /* How to use the HC-SR04 Ultrasonic Sensor with Arduino 
       Dev: Michalis Vasilakis // Date: 23/7/2015 // www.ardumotive.com */
    
    //Libraries
    #include "Ultrasonic.h"
    
    //Define pins ultrasonic(trig,echo)
    Ultrasonic ultrasonic(A0,A1);
    
    //Variables
    int distance;
    int ledPin = 13;
    
    void setup() {
      Serial.begin(9600);
      pinMode (ledPin, OUTPUT);
    }
    
    void loop(){
      distance = ultrasonic.distanceRead(CM); //Use 'CM' for centimeters or 'INC' for inches
      //Print distance...
      if (distance <= 150) {
        Serial.print("SI");
        digitalWrite(ledPin, HIGH);
      } else {
        Serial.print(distance);
        digitalWrite(ledPin, LOW);
      }
    }
    

    Processing

    import processing.serial.Serial;
    import processing.video.*;
    
    Serial myPort;
    String val;   
    Movie video1, video2, video3;
    
    
    
    void setup() {
      fullScreen(SPAN);
      background(0);
      video1 = new Movie(this, "estas ahi.mp4");
      video2 = new Movie(this, "estas lejos.mp4");
      video3 = new Movie(this, "me gustaria estar aqui.mp4");
      video1.loop();
      video2.stop();
      video3.stop();
      String portName = Serial.list()[0];
      myPort = new  Serial(this, portName, 9600);
      myPort.bufferUntil('\n');
    }
    
    void serialEvent(final Serial s) {
      val = s.readString().trim();
      if (val.equals("SI")) {
        video1.stop();
        video2.loop();
        video3.loop();
      } else {
        video1.loop();
        video2.stop();
        video3.stop();
      }
    }
    
    
    void draw() {
      println(val);
      image(video1,320,120,640,480);
      image(video2,1600,200,640,480);
      image(video3,2880,235,640,480);
    
    } 
    
    void movieEvent(Movie video) {
      video.read();
    }
    
  • Connect PIR sensor to launch a webcam and a sound

    Basically, what you just posted is the same as this:

    import processing.serial.*;
    import processing.video.*;
    import ddf.minim.*;
    import ddf.minim.AudioPlayer;
    import cc.arduino.*;
    
    // Size of each cell in the grid
    int cellSize = 20;
    // Number of columns and rows in our system
    int cols, rows;
    // Variable for capture device
    Capture inputCam01;
    Movie topLayer;
    Minim minim;
    AudioPlayer song;
    Serial myPort;
    Arduino arduino;
    int ledPin = 13;
    
    
    void setup() {
      size(1280, 720);
      frameRate(30);
      cols = width / cellSize;
      rows = height / cellSize;
      colorMode(RGB, 255, 255, 255, 100);
    
      // This the default video input, see the GettingStartedCapture 
      // example if it creates an error
      inputCam01 = new Capture(this, width, height);
    
      // Start capturing the images from the camera
      inputCam01.start();  
      background(0);
    
      // we pass this to Minim so that it can load files from the data directory
      minim = new Minim(this);
    
      // loadFile will look in all the same places as loadImage does.
      // this means you can find files that are in the data folder and the 
      // sketch folder. you can also pass an absolute path, or a URL.
      song = minim.loadFile("data/untitled.wav");
      song.play();
      song.loop();
    }
    
    void movieEvent(Movie topLayer)  
    {  
      topLayer.read();
    }
    
    void draw() {
      arduino.digitalWrite(ledPin, Arduino.HIGH);
      delay(1000);
      arduino.digitalWrite(ledPin, Arduino.LOW);
      delay(1000);
    }
    

    Notice how LARGE SECTION of your code have just GONE MISSING? That's because that code is NOT inside ANY function and thus NEVER GETS CALLED.

  • Connect PIR sensor to launch a webcam and a sound

    No. If you had pressed Ctrl + t like I suggested, you would see why. Look:

    import processing.serial.*;
    import processing.video.*;
    import ddf.minim.*;
    import ddf.minim.AudioPlayer;
    import cc.arduino.*;
    
    // Size of each cell in the grid
    int cellSize = 20;
    // Number of columns and rows in our system
    int cols, rows;
    // Variable for capture device
    Capture inputCam01;
    Movie topLayer;
    Minim minim;
    AudioPlayer song;
    Serial myPort;
    Arduino arduino;
    int ledPin = 13;
    
    
    void setup() {
      size(1280, 720);
      frameRate(30);
      cols = width / cellSize;
      rows = height / cellSize;
      colorMode(RGB, 255, 255, 255, 100);
    
      // This the default video input, see the GettingStartedCapture 
      // example if it creates an error
      inputCam01 = new Capture(this, width, height);
    
      // Start capturing the images from the camera
      inputCam01.start();  
      background(0);
    
      // we pass this to Minim so that it can load files from the data directory
      minim = new Minim(this);
    
      // loadFile will look in all the same places as loadImage does.
      // this means you can find files that are in the data folder and the 
      // sketch folder. you can also pass an absolute path, or a URL.
      song = minim.loadFile("data/untitled.wav");
      song.play();
      song.loop();
    }
    
    
    //// THIS CODE IS NOT IN ANY FUNCTION! THIS CAN'T BE RIGHT.
    {
      // I know that the first port in the serial list on my mac
      // is Serial.list()[0].
      // On Windows machines, this generally opens COM1.
      // Open whatever port is the one you're using.
      String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
      myPort = new Serial(this, portName, 9600);
    }
    //// ---- TO HERE
    
    
    void movieEvent(Movie topLayer)  
    {  
      topLayer.read();
    }
    
    
    //// THIS CODE IS NOT IN ANY FUNCTION! THIS CAN'T BE RIGHT.
    {
      //println(Arduino.list());
      arduino = new Arduino(this, Arduino.list()[2], 57600);
      arduino.pinMode(ledPin, Arduino.OUTPUT);
    }
    //// ---- TO HERE
    
    void draw() {
      arduino.digitalWrite(ledPin, Arduino.HIGH);
      delay(1000);
      arduino.digitalWrite(ledPin, Arduino.LOW);
      delay(1000);
    } // End of draw()!
    
    
    //// THIS CODE IS NOT IN ANY FUNCTION! THIS CAN'T BE RIGHT.
    { 
      if (inputCam01.available()) {
        inputCam01.read();
        inputCam01.loadPixels();
        image(inputCam01, 0, 0);
    
        // Begin loop for columns
        for (int i = 0; i < cols; i++) {
          // Begin loop for rows
          for (int j = 0; j < rows; j++) {
            // Where are we, pixel-wise?
            int x = i*cellSize;
            int y = j*cellSize;
            int loc = (inputCam01.width - x - 1) + y*inputCam01.width; // Reversing x to mirror       the image
    
            float r = red(inputCam01.pixels[loc]);
            // Make a new color with an alpha component
            color c = color(r, 50, 50, 75);
    
            // Code for drawing a single rect
            // Using translate in order for rotation to work properly
            pushMatrix();
            translate(x+cellSize/2, y+cellSize/2);
            // Rotation formula based on brightness
            rotate((2 * PI * brightness(c) / 255.0));
            rectMode(CENTER);
            fill(c);
            noStroke();
            // Rects are larger than the cell for some overlap
            rect(0, 0, cellSize+6, cellSize+6);
            popMatrix();
          }
        }
      }
    }
    //// ---- TO HERE
    
  • Connect PIR sensor to launch a webcam and a sound
        import processing.serial.*;
    import processing.video.*;
    import ddf.minim.*;
    import ddf.minim.AudioPlayer;
    import cc.arduino.*;
    
    // Size of each cell in the grid
    int cellSize = 20;
    // Number of columns and rows in our system
    int cols, rows;
    // Variable for capture device
    Capture inputCam01;
    Movie topLayer;
    Minim minim;
    AudioPlayer song;
    Serial myPort;
    Arduino arduino;
    int ledPin = 13;
    
    
    void setup() 
    
    {
    size(1280, 720);
    frameRate(30);
    cols = width / cellSize;
    rows = height / cellSize;
    colorMode(RGB, 255, 255, 255, 100);
    
    // This the default video input, see the GettingStartedCapture 
    // example if it creates an error
    inputCam01 = new Capture(this, width, height);
    
    // Start capturing the images from the camera
    inputCam01.start();  
    background(0);
    
    // we pass this to Minim so that it can load files from the data directory
    minim = new Minim(this);
    
    // loadFile will look in all the same places as loadImage does.
    // this means you can find files that are in the data folder and the 
    // sketch folder. you can also pass an absolute path, or a URL.
    song = minim.loadFile("data/untitled.wav");
    song.play();
    song.loop();
    }
    {
    // I know that the first port in the serial list on my mac
    // is Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
    String portName = Serial.list()[3]; //change the 0 to a 1 or 2 etc. to match your port
     myPort = new Serial(this, portName, 9600);
    }
    void movieEvent(Movie topLayer)  
    {  
    topLayer.read();
    }
    
    {
    //println(Arduino.list());
    arduino = new Arduino(this, Arduino.list()[2], 57600);
    arduino.pinMode(ledPin, Arduino.OUTPUT);
    }
    void draw() 
    
    {
    arduino.digitalWrite(ledPin, Arduino.HIGH);
    delay(1000);
    arduino.digitalWrite(ledPin, Arduino.LOW);
    delay(1000);
    }
    { 
    if (inputCam01.available()) {
        inputCam01.read();
        inputCam01.loadPixels();
        image(inputCam01, 0, 0);
    
        // Begin loop for columns
        for (int i = 0; i < cols; i++) {
        // Begin loop for rows
        for (int j = 0; j < rows; j++) {
        // Where are we, pixel-wise?
        int x = i*cellSize;
        int y = j*cellSize;
        int loc = (inputCam01.width - x - 1) + y*inputCam01.width; // Reversing x to mirror       the image
    
        float r = red(inputCam01.pixels[loc]);
        // Make a new color with an alpha component
        color c = color(r, 50, 50, 75);
    
        // Code for drawing a single rect
        // Using translate in order for rotation to work properly
        pushMatrix();
        translate(x+cellSize/2, y+cellSize/2);
        // Rotation formula based on brightness
        rotate((2 * PI * brightness(c) / 255.0));
        rectMode(CENTER);
        fill(c);
        noStroke();
        // Rects are larger than the cell for some overlap
        rect(0, 0, cellSize+6, cellSize+6);
        popMatrix();
        }
        }
    }
    }
    
  • Connect PIR sensor to launch a webcam and a sound

    Hi again,

    I am trying to connect Arduino with Processing using a PIR Sensor. The code in Arduino is alright, however I can not synchronize both to detect the movement and open the webcam and the sound. Please, Can you help me?.

    Arduino:

    //the time we give the sensor to calibrate (10-60 secs according to the datasheet)
    int calibrationTime = 30;       
    
    //the time when the sensor outputs a low impulse
    long unsigned int lowIn;        
    
    //the amount of milliseconds the sensor has to be low
    //before we assume all motion has stopped
    long unsigned int pause = 5000; 
    
    boolean lockLow = true;
    boolean takeLowTime; 
    
    int pirPin = 3;    //the digital pin connected to the PIR sensor's output
    int ledPin = 13;
    
    
    /////////////////////////////
    //SETUP
    void setup(){
    Serial.begin(9600);
    pinMode(pirPin, INPUT);
    pinMode(ledPin, OUTPUT);
    digitalWrite(pirPin, LOW);
    
    //give the sensor some time to calibrate
    Serial.print("calibrating sensor ");
    for(int i = 0; i < calibrationTime; i++){
      Serial.print(".");
      delay(1000);
      }
    Serial.println(" done");
    Serial.println("SENSOR ACTIVE");
    delay(50);
    }
    
     ////////////////////////////
     //LOOP
     void loop(){
    
     if(digitalRead(pirPin) == HIGH){
       digitalWrite(ledPin, HIGH);   //the led visualizes the sensors output pin state
       if(lockLow){ 
         //makes sure we wait for a transition to LOW before any further output is made:
         lockLow = false;           
         Serial.println("---");
         Serial.print("motion detected at ");
         Serial.print(millis()/1000);
         Serial.println(" sec");
         delay(50);
         }        
         takeLowTime = true;
        }
    
       if(digitalRead(pirPin) == LOW){      
       digitalWrite(ledPin, LOW);  //the led visualizes the sensors output pin state
    
       if(takeLowTime){
        lowIn = millis();          //save the time of the transition from high to LOW
        takeLowTime = false;       //make sure this is only done at the start of a LOW phase
        }
       //if the sensor is low for more than the given pause,
       //we assume that no more motion is going to happen
       if(!lockLow && millis() - lowIn > pause){ 
           //makes sure this block of code is only executed again after
           //a new motion sequence has been detected
           lockLow = true;                       
           Serial.print("motion ended at ");      //output
           Serial.print((millis() - pause)/1000);
           Serial.println(" sec");
           delay(50);
           }
         }
         }
    

    Processing:

    import processing.serial.*;
    import processing.video.*;
    import ddf.minim.*;
    import ddf.minim.AudioPlayer;
    
    // Size of each cell in the grid
    int cellSize = 20;
    // Number of columns and rows in our system
    int cols, rows;
    // Variable for capture device
    Capture inputCam01;
    Movie topLayer;
    Minim minim;
    AudioPlayer song;
    Serial myPort;
    
    void setup() 
    {
    size(1280, 720);
    frameRate(30);
    cols = width / cellSize;
    rows = height / cellSize;
    colorMode(RGB, 255, 255, 255, 100);
    
    // This the default video input, see the GettingStartedCapture 
    // example if it creates an error
    inputCam01 = new Capture(this, width, height);
    
    // Start capturing the images from the camera
    inputCam01.start();  
    background(0);
    
    // we pass this to Minim so that it can load files from the data directory
    minim = new Minim(this);
    
    // loadFile will look in all the same places as loadImage does.
    // this means you can find files that are in the data folder and the 
    // sketch folder. you can also pass an absolute path, or a URL.
    song = minim.loadFile("data/untitled.wav");
    song.play();
    song.loop();
    }
    {
    // I know that the first port in the serial list on my mac
    // is Serial.list()[0].
    // On Windows machines, this generally opens COM1.
    // Open whatever port is the one you're using.
     String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
     myPort = new Serial(this, portName, 9600);
    }
    void movieEvent(Movie topLayer)  
    {  
    topLayer.read();
    }
    
    
    void draw() 
    { 
    if (inputCam01.available()) {
    inputCam01.read();
    inputCam01.loadPixels();
    image(inputCam01, 0, 0);
    
    // Begin loop for columns
    for (int i = 0; i < cols; i++) {
      // Begin loop for rows
      for (int j = 0; j < rows; j++) {
        // Where are we, pixel-wise?
        int x = i*cellSize;
        int y = j*cellSize;
        int loc = (inputCam01.width - x - 1) + y*inputCam01.width; // Reversing x to mirror       the image
    
        float r = red(inputCam01.pixels[loc]);
        // Make a new color with an alpha component
        color c = color(r, 50, 50, 75);
    
        // Code for drawing a single rect
        // Using translate in order for rotation to work properly
        pushMatrix();
        translate(x+cellSize/2, y+cellSize/2);
        // Rotation formula based on brightness
        rotate((2 * PI * brightness(c) / 255.0));
        rectMode(CENTER);
        fill(c);
        noStroke();
        // Rects are larger than the cell for some overlap
        rect(0, 0, cellSize+6, cellSize+6);
        popMatrix();
    }
    }
    }
    }
    
  • I can't connect my Perfume Dispenser to my music Visualizer . I am using an Arduino Uno.
    import cc.arduino.*;
    //import org.firmata.*;
    
    import ddf.minim.*;
    import ddf.minim.analysis.*;
    import processing.serial.*;
    
    
    
    Minim minim;
    AudioPlayer song;
    FFT fft;
    BeatDetect beat;
    BeatListener bl;
    //Serial myPort; // Create object from Serial class
    Arduino arduino;
    
    
    // Variables that define the "zones" of the spectrum
    // For example, for bass, we take only the first 4% of the total spectrum
    float specLow = 0.03; // 3%
    float specMid = 0.125; // 12.5%
    float specHi = 0.20; // 20%
    float specLLow = 0.009;
    // This leaves 64% of the possible spectrum that will not be used.
    //These values are usually too high for the human ear anyway.
    
    //Scoring values for each zone.
    float scoreLow = 0;
    float scoreMid = 0;
    float scoreHi = 0;
    
    // Previous value, to soften the reduction
    float oldScoreLow = scoreLow;
    float oldScoreMid = scoreMid;
    float oldScoreHi = scoreHi;
    
    // Softening value
    float scoreDecreaseRate = 25;
    
    // Cubes appearing in space
    int nbCubes;
    Cube[] cubes;
    
    //Lines that appear on the sides
    int nbMurs = 500;
    Mur[] murs;
    boolean isPlaying = false;
    //Arduino
    int ledPin = 11; // LED connected to digital pin 11
    float kickSize;
    
    int deltime = 15; //Time to make the relay on after a beat is detected
    boolean delayboolean = false;
    
    
    
    
    void setup()
    {
    
    //Display in 3D on the entire screen
    fullScreen(P3D);
    
    //Load the minim library
    minim = new Minim(this);
    arduino = new Arduino(this, Arduino.list()[0], 57600);
    
    Arduino.list();
    //Load song
    song = minim.loadFile("song.mp3");
    
    //Create the FFT object to analyze the song
    fft = new FFT(song.bufferSize(), song.sampleRate());
    
    //One cube per frequency band
    nbCubes = (int)(fft.specSize()*specHi);
    cubes = new Cube[nbCubes];
    println(nbCubes);
    //As many walls as we want
    murs = new Mur[nbMurs];
    println(nbMurs);
    //Create all objects
    //Create cubic objects
    for (int i = 0; i < nbCubes; i++) {
    cubes[i] = new Cube();
    
    }
    
    //Create wall objects
    //Left walls
    for (int i = 0; i < nbMurs; i+=4) {
    murs[i] = new Mur(0, height/2, 10, height); 
    }
    
    //Straight walls
    for (int i = 1; i < nbMurs; i+=4) {
    murs[i] = new Mur(width, height/2, 10, height); 
    }
    
    //Low walls
    for (int i = 2; i < nbMurs; i+=4) {
    murs[i] = new Mur(width/2, height, width, 10); 
    }
    
    //High walls
    for (int i = 3; i < nbMurs; i+=4) {
    murs[i] = new Mur(width/2, 0, width, 10); 
    }
    
    //Black background
    background(0);
    
    //Start the song
    song.play(0);
    
    // a beat detection object that is FREQ_ENERGY mode that 
    // expects buffers the length of song's buffer size
    // and samples captured at songs's sample rate
    beat = new BeatDetect(song.bufferSize(), song.sampleRate());
    // set the sensitivity to 300 milliseconds
    // After a beat has been detected, the algorithm will wait for 300 milliseconds 
    // before allowing another beat to be reported. You can use this to dampen the 
    // algorithm if it is giving too many false-positives. The default value is 10, 
    // which is essentially no damping. If you try to set the sensitivity to a negative value, 
    // an error will be reported and it will be set to 10 instead. 
    beat.setSensitivity(100); 
    kickSize= 16;
    // make a new beat listener, so that we won't miss any buffers for the analysis
    bl = new BeatListener(beat, song); 
    textFont(createFont("Helvetica", 16));
    textAlign(CENTER);
    
    arduino.pinMode(ledPin, Arduino.OUTPUT); 
    }
    
    
    void draw()
    {
    //Forward the song. One draw () for each "frame" of the song ...
    fft.forward(song.mix);
    
    //Calculation of "scores" (power) for three categories of sound
    //First, save old values
    oldScoreLow = scoreLow;
    oldScoreMid = scoreMid;
    oldScoreHi = scoreHi;
    
    //Reset values
    scoreLow = 0;
    scoreMid = 0;
    scoreHi = 0;
    
    
    
    
    //Calculate the new "scores"
    for(int i = 0; i < fft.specSize()*specLow; i++)
    { 
    scoreLow += fft.getBand(i);
    
    }
    
    for(int i = (int)(fft.specSize()*specLow); i < fft.specSize()*specMid; i++)
    {
    scoreMid += fft.getBand(i);
    
    }
    
    for(int i = (int)(fft.specSize()*specMid); i < fft.specSize()*specHi; i++)
    {
    scoreHi += fft.getBand(i);
    
    }
    
    //To slow down the descent.
    if (oldScoreLow > scoreLow) {
    scoreLow = oldScoreLow - scoreDecreaseRate;
    }
    
    if (oldScoreMid > scoreMid) {
    scoreMid = oldScoreMid - scoreDecreaseRate;
    }
    
    if (oldScoreHi > scoreHi) {
    scoreHi = oldScoreHi - scoreDecreaseRate;
    }
    
    //Volume for all frequencies at this time, with the highest sounds higher.
    //This allows the animation to go faster for more high-pitched sounds, which we would notice more.
    float scoreGlobal = 0.66*scoreLow + 0.8*scoreMid + 1*scoreHi;
    
    //subtle color background
    background(scoreLow/100, scoreMid/100, scoreHi/100);
    
    //Cube for each frequency band
    for(int i = 0; i < nbCubes; i++)
    {
    //Value of the frequency band
    float bandValue = fft.getBand(i);
    //println(bandValue);
    
    //The color is represented as: red for bass, green for medium sounds and blue for high.
    //The opacity is determined by the volume of the tape and the overall volume.
    cubes[i].display(scoreLow, scoreMid, scoreHi, bandValue, scoreGlobal);
    }
    
    //Walls lines, here we must keep the value of the previous tape and the next to connect them together
    float previousBandValue = fft.getBand(0);
    
    //Distance between each line point, negative because on the z dimension
    float dist = -25;
    
    //Multiply the height by this constant
    float heightMult = 2;
    
    //For each band
    for(int i = 1; i < fft.specSize(); i++)
    {
    //Value of the frequency band, we multiply the bands farther to make them more visible.
    float bandValue = fft.getBand(i)*(1 + (i/50));
    
    
    
    
    //Selection of the color according to the strengths of the different types of sounds.
    stroke(100+scoreLow, 100+scoreMid, 100+scoreHi, 255-i);
    strokeWeight(1 + (scoreGlobal/100));
    
    //lower left line
    line(0, height-(previousBandValue*heightMult), dist*(i-1), 0, height-(bandValue*heightMult), dist*i);
    line((previousBandValue*heightMult), height, dist*(i-1), (bandValue*heightMult), height, dist*i);
    line(0, height-(previousBandValue*heightMult), dist*(i-1), (bandValue*heightMult), height, dist*i);
    
    //upper left line
    line(0, (previousBandValue*heightMult), dist*(i-1), 0, (bandValue*heightMult), dist*i);
    line((previousBandValue*heightMult), 0, dist*(i-1), (bandValue*heightMult), 0, dist*i);
    line(0, (previousBandValue*heightMult), dist*(i-1), (bandValue*heightMult), 0, dist*i);
    
    //lower right line
    line(width, height-(previousBandValue*heightMult), dist*(i-1), width, height-(bandValue*heightMult), dist*i);
    line(width-(previousBandValue*heightMult), height, dist*(i-1), width-(bandValue*heightMult), height, dist*i);
    line(width, height-(previousBandValue*heightMult), dist*(i-1), width-(bandValue*heightMult), height, dist*i);
    
    //upper right line
    line(width, (previousBandValue*heightMult), dist*(i-1), width, (bandValue*heightMult), dist*i);
    line(width-(previousBandValue*heightMult), 0, dist*(i-1), width-(bandValue*heightMult), 0, dist*i);
    line(width, (previousBandValue*heightMult), dist*(i-1), width-(bandValue*heightMult), 0, dist*i);
    
    //Save the value for the next loop round
    previousBandValue = bandValue; 
    }
    
    //Rectangular walls
    for(int i = 0; i < nbMurs; i++)
    {
    //Each wall is assigned a band, and its strength is sent to it.
    float intensity = fft.getBand(i%((int)(fft.specSize()*specHi))); 
    murs[i].display(scoreLow, scoreMid, scoreHi, intensity, scoreGlobal);
    }
    }
    
    //Class for cubes floating in space.
    class Cube {
    //Z position of "spawn" and maximum Z position
    float startingZ = -10000;
    float maxZ = 1000;
    
    //Position values
    float x, y, z;
    float rotX, rotY, rotZ;
    float sumRotX, sumRotY, sumRotZ;
    
    //Contructor
    Cube() {
    //Make the cube appear in a random place
    x = random(0, width);
    y = random(0, height);
    z = random(startingZ, maxZ);
    
    //Give the cube a random rotation
    rotX = random(0, 1);
    rotY = random(0, 1);
    rotZ = random(0, 1);
    }
    
    void display(float scoreLow, float scoreMid, float scoreHi, float intensity, float scoreGlobal) {
    //Selection of the color, opacity determined by the intensity (volume of the band)
    color displayColor = color(scoreLow*0.67, scoreMid*0.67, scoreHi*0.67, intensity*5);
    fill(displayColor, 255);
    
    
    //Color lines, they disappear with the individual intensity of the cube
    color strokeColor = color(255, 150-(20*intensity));
    stroke(strokeColor);
    strokeWeight(1 + (scoreGlobal/300));
    
    //Creating a transformation matrix to perform rotations, enlargements
    pushMatrix();
    
    //Displacement
    translate(x, y, z); 
    
    //Calculation of the rotation according to the intensity for the cube
    sumRotX += intensity*(rotX/1000); 
    sumRotY += intensity*(rotY/1000);
    sumRotZ += intensity*(rotZ/1000); 
    
    //Application of the rotation
    rotateX(sumRotX);
    rotateY(sumRotY);
    rotateZ(sumRotY); 
    
    //Creation of the box, variable size according to the intensity for the cube
    box(100+(intensity/2));
    
    //Application of the matrix
    popMatrix();
    
    //Dislacement Z
    z+= (1+(intensity/5)+(pow((scoreGlobal/150), 2))); 
    
    //Replace the box at the back when it is no longer visible
    if (z >= maxZ) {
    x = random(0, width);
    y = random(0, height);
    z = startingZ;
    }
    }
    }
    
    
    //Class to display the lines on the sides
    class Mur {
    //Minimum and maximum position Z
    float startingZ = -10000;
    float maxZ = 50;
    
    //Values at the position
    float x, y, z; 
    float sizeX, sizeY;
    
    //Constructor
    Mur(float x, float y, float sizeX, float sizeY) {
    //Make the line appear at the specified place
    
    this.x = x;
    this.y = y;
    //random depth
    this.z = random(startingZ, maxZ); 
    
    //We determine the size because the walls on the floors have a different size than those on the sides
    this.sizeX = sizeX;
    this.sizeY = sizeY;
    }
    
    //Display function
    void display(float scoreLow, float scoreMid, float scoreHi, float intensity, float scoreGlobal) {
    //Color determined by low, medium and high sounds
    //Opacity determined by the overall volume
    color displayColor = color(scoreLow*0.67, scoreMid*0.67, scoreHi*0.67, scoreGlobal);
    
    //Make lines disappear in the distance to give an illusion of fog
    fill(displayColor, ((scoreGlobal-5)/1000)*(255+(z/25)));
    noStroke();
    
    //First band, the one that moves according to the force
    //Transformation Matrix
    pushMatrix();
    
    //Displacement
    translate(x, y, z);
    
    //extension
    if (intensity > 100) intensity = 100;
    scale(sizeX*(intensity/100), sizeY*(intensity/100), 20);
    
    //Creation of the "box"
    box(1);
    popMatrix();
    
    //Second band, the one that is still the same size
    displayColor = color(scoreLow*0.5, scoreMid*0.5, scoreHi*0.5, scoreGlobal);
    fill(displayColor, (scoreGlobal/5000)*(255+(z/25)));
    //Transformation Matrix
    pushMatrix();
    
    //Displacement
    translate(x, y, z);
    
    //Extension
    scale(sizeX, sizeY, 10);
    
    //Creation of the "box"
    box(1);
    popMatrix();
    
    //Displacemnt Z
    z+= (pow((scoreGlobal/150), 2));
    if (z >= maxZ) {
    z = startingZ; 
    
    if(beat.isKick()) {
    arduino.digitalWrite(ledPin, Arduino.HIGH); // set the LED on
    kickSize = 32;
    delayboolean = true; //Tells a later if statement to delay for long enough for the lights to light up
    }
    
    arduino.digitalWrite(ledPin, Arduino.LOW); // set the LED off
    textSize(kickSize);
    text("KICK", width/4, height/2);
    kickSize = constrain(kickSize * 0.95, 16, 32);
    
    
    // if (bandValue == 0.01) 
    //{ //if we clicked in the window
    //myPort.write('1'); //send a 1
    //println("1"); 
    // } else 
    //{ //otherwise
    //myPort.write('0'); //send a 0
    //} 
    
    //try{
    //Load band values
    // ArrayList = (ArrayList) fft.getBand();
    
    //float bandValue = fft.getBand();
    
    //get first band value
    
    // println(bandValue);
    
    // Ascertain if the top band value is new (i.e. it's new) or if it's the same, has the count changed (i.e. it's the same value again).
    
    // Update band value details.
    
    //Arduino - standard LED blinky action. 
    
    //arduino.digitalWrite(ledPin, Arduino.HIGH);
    //delay(100);
    //arduino.digitalWrite(ledPin, Arduino.LOW);
    //}
    
    // Slow everything down so you don't exceed perfume dispenser's rate limits. Check every 10 secs.
    // delay(10000);
    //} 
    
    
    }
    }
    
    }
    void mousePressed()
    {
    // if the song is already being played
    // we pause it and change the value of isPlaying variable
    if (isPlaying)
    {
    song.pause();
    isPlaying = false;
    }
    
    // and if it is paused we play it and change 'isPlaying' accordingly
    // :P pretty simple right?
    else
    {
    song.play();
    isPlaying = true;
    }}
    void stop() {
    // always close Minim audio classes when you are finished with them
    song.close();
    // always stop Minim before exiting
    minim.stop();
    // this closes the sketch
    super.stop();
    }
    void keyPressed()
    {
    if ( key == 'p' ) song.play(); // Press P to play the song.
    if ( key == 's' ) song.pause(); // Press S to pause playing.
    if ( key == 'h' ) song.rewind(); // Press H to reset to the start.
    if ( key == 'f' ) song.skip(500); // Press F to fast forward.
    if ( key == 'r' ) song.skip(-500); // Press R to rewind.
    if ( key == 'q' ) song.close(); // Press Q to quit playing.
    }
    
  • ...put two pieces of code together

    @Chrisir Thanks for your proposal. I have implement it into my code and wanted to upload it. Unfortunately it was not possible because there is not enough ram space. I have tried to use the Serial.print(F('')), to get rid of the problem, which was not enough. This is the code by now:

    int URECHO = 3;         // PWM Output 0-25000US,Every 50US represent 1cm
    int URTRIG = 5;         // PWM trigger pin
    int sensorPin = A0;     // select the input pin for the potentiometer
    int sensorValue = 0;    // variable to store the value coming from the sensor
    
    const int LEDPin = 13; // the pin that the LED is attached to
    const int LEDValueMax = 255; // the maximum value of the LED Brightness
    const int LEDValueMin = 0; // the minimum value of the LED Brightness
    int LEDValue = 255; // the start value of the LED Brightness
    int speedValue = 10; // the dimming speed value
    
    unsigned int distanceMeasured = 0;
    
    
    boolean activity; 
    
    int ledPIN = 13;
    
    
    void setup() {
      Serial.begin(9600);                        // Sets the baud rate to 9600
      pinMode(URTRIG, OUTPUT);                   // A low pull on pin COMP/TRIG
      digitalWrite(URTRIG, HIGH);                // Set to HIGH
      pinMode(URECHO, INPUT);                    // Sending Enable PWM mode command
      delay(500);
      Serial.println(F("Init the sensor"));
    
      pinMode(ledPIN, OUTPUT);
    }
    
    boolean weAreDimming = false;
    
    void loop() {
    
      PWM_Mode();
    
      if (weAreDimming) {
    
        // we dim
    
        // Decrease the LED Brightness untill it reaches minimum brightness
    
        analogWrite(ledPIN, LEDValue);
        delay(speedValue);
        LEDValue = LEDValue - 1; // in short LEDValue--;
    
        // Did we reach the minimum?
        if (LEDValue <= LEDValueMin) {
          weAreDimming = false; 
          digitalWrite(ledPIN, LOW); // set to LOW ??? Probably not necessary
        }
      } // big if 
      // -----
    
      else {
    
        // we don't dim
    
        String line = Serial.readStringUntil('\r');
        Serial.println (line);
    
        if (line.equals("on")) {
          digitalWrite(ledPIN, HIGH); //I put HIGH here instead of LOW
        } else if (line.equals("off")) {
          // turning it slowly off, aka dimming 
          // Init the dimming process 
          LEDValue = 100; // reset 
          weAreDimming = true;
        }
      } // big else
    } //function loop
    
    
    
    void PWM_Mode()                              // a low pull on pin COMP/TRIG  triggering a sensor reading
    {
    
      digitalWrite(URTRIG, LOW);
      digitalWrite(URTRIG, HIGH);               // reading Pin PWM will output pulses
    
      unsigned long LowLevelTime = pulseIn(URECHO, LOW) ;
    
      if (LowLevelTime >= 45000)              // the reading is invalid.
      {
        Serial.print(F("Invalid"));
      }
      else {
        Serial.print(F("Distance Measured="));
        distanceMeasured = LowLevelTime / 50;  // every 50us low level stands for 1cm
        Serial.print(distanceMeasured);
        Serial.println(); 
    
        if (distanceMeasured > 20) {
          activity = false;
        }
        else {
          activity = true;
        }
    
      }
    }
    

    Do you have an idea? Thanks again! F

  • ...put two pieces of code together

    in these lines, I am not sure why you say LOW when the command is "on" and vice versa:

      if (line.equals("on")) {
        digitalWrite(led, LOW);
      }
      else if (line.equals("off")) {
        digitalWrite(led, HIGH);
      }
    

    My Proposal

    My Proposal would be to have two distinct states in loop, either

    • where we dim (1) or
    • where we read the commands and switch the led on or start the dimming process (2).

    I also got rid off your while loop and instead use the looping of loop() itself

    not tested

    boolean weAreDimming = false; 
    
    void loop() {
    
    
      PWM_Mode();
    
    
    
      if (weAreDimming) {
    
        // we dim
    
        // Decrease the LED Brightness untill it reaches minimum brightness
    
        analogWrite(LEDPin, LEDValue);
        delay(speedValue);
        LEDValue = LEDValue - 1; // in short LEDValue--;
    
    
        // Did we reach the minimum?
        if (LEDValue <= LEDValueMin) {
          weAreDimming = false; 
          digitalWrite(led, LOW); // set to LOW ??? Probably not necessary
        }
      } // big if 
      // -----
    
      else {
    
        // we don't dim
    
        String line = Serial.readStringUntil('\r');
        Serial.println(line);
    
        if (line.equals("on")) {
          digitalWrite(led, HIGH);  // I put HIGH here instead of LOW
        } else if (line.equals("off")) {
          // turning it slowly off, aka dimming 
          // Init the dimming process 
          LEDValue = 100; // reset 
          weAreDimming = true;
        }
      } // big else
    } //function loop
    
  • ...put two pieces of code together

    Hello world, for my bachelor project I am busy with an audio installation, the interface is done in processing (surprise) and arduino. Enclosed you will find three pieces of code all working well on their own.

    The first part consists of two codes one is arduino and one is processing. Function: light on -the sensor catches a person comming into the room-> light out-> music on-> light on-> end/loop

    The Arduinocode:

    int URECHO = 3;         // PWM Output 0-25000US,Every 50US represent 1cm
    int URTRIG = 5;         // PWM trigger pin
    int sensorPin = A0;     // select the input pin for the potentiometer
    int sensorValue = 0;    // variable to store the value coming from the sensor
    
    
    unsigned int distanceMeasured = 0;
    
    
    boolean activity;
    
    int led = 13;
    
    
    void setup() {
      Serial.begin(9600);                        // Sets the baud rate to 9600
      pinMode(URTRIG, OUTPUT);                   // A low pull on pin COMP/TRIG
      digitalWrite(URTRIG, HIGH);                // Set to HIGH
      pinMode(URECHO, INPUT);                    // Sending Enable PWM mode command
      delay(500);
      Serial.println("Init the sensor");
    
      pinMode(led, OUTPUT);
    }
    
    void loop() {
      PWM_Mode();
    
    
    
      String line = Serial.readStringUntil('\r');
      Serial.println(line);
    
      if (line.equals("on")) {
        digitalWrite(led, LOW);
      }
      else if (line.equals("off")) {
        digitalWrite(led, HIGH);
      }
    
    
    
    
      //delay(100);
    
    //  if (activity) {
    //    digitalWrite(led, HIGH);
    //  }
    //  else {
    //    digitalWrite(led, LOW);
    //  }
    }
    
    
    void PWM_Mode()                              // a low pull on pin COMP/TRIG  triggering a sensor reading
    {
    
      digitalWrite(URTRIG, LOW);
      digitalWrite(URTRIG, HIGH);               // reading Pin PWM will output pulses
    
      unsigned long LowLevelTime = pulseIn(URECHO, LOW) ;
    
      if (LowLevelTime >= 45000)              // the reading is invalid.
      {
        Serial.print("Invalid");
      }
      else {
        Serial.print("Distance Measured=");
        distanceMeasured = LowLevelTime / 50;  // every 50us low level stands for 1cm
        Serial.print(distanceMeasured);
        Serial.println(); 
    
        if (distanceMeasured > 20) {
          activity = false;
        }
        else {
          activity = true;
        }
    
      }
    }
    

    The Processing code:

    import processing.serial.*;
    import processing.sound.*;
    
    
    int S1_WAITING_FOR_PEOPLE  = 1;
    int S2_PEOPLE_ENTERED      = 2;
    int S3_LIGHT_FADE_OUT      = 3;
    int S4_DARK                = 4;
    int S5_MUSIC               = 5;
    int S6_LIGHT_FADE_IN       = 6;
    // make sure this is the last!!!!
    int TERMINATE              = 7;
    
    int mode = S1_WAITING_FOR_PEOPLE;
    
    
    
    int no_one_when_distance_greater_then = 160; // cm
    int time_before_dim = 5000; // ms
    
    SoundFile file;
    boolean is_playing = false;
    
    Serial myPort;  
    
    int dist;
    
    boolean someone_present = false;
    int someone_present_since_time;
    
    
    int music_playing_since;
    int music_duration;
    
    int in_mode_since_ms;
    
    void setup() {
      size(640, 360);
    
      printArray(Serial.list()); // "/dev/cu.usbmodem1411" cu.usb!!!
    
      myPort = new Serial(this, Serial.list()[1], 9600);
      //myPort.readStringUntil('\n');
      myPort.bufferUntil('\n');
    
      // Load a soundfile from the data folder of the sketch and play it back in a loop
      file = new SoundFile(this, "Ex.wav");
      //file.loop();
      music_duration = (int) file.duration() * 1000;
      music_duration += 2000;
    
    }      
    
    void draw() {
      background(0);
      fill(255);
      text("frameCount: "+frameCount, 50, 25);
      text("dist: "+dist, 50, 50);
      text("mode: "+mode, 50, 75);
    
    
      if (frameCount == 180) {
        turn_on();
      } else if (frameCount > 180) {
    
        if ( mode == S1_WAITING_FOR_PEOPLE) {
    
          if (someone_present == false) {
            if (dist < no_one_when_distance_greater_then) {
              someone_present = true;
              someone_present_since_time = millis();
              change_mode(mode + 1);
            }
          }
        } else if (mode == S2_PEOPLE_ENTERED) {
          text("millis: "+millis(), 50, 100);
          text("someone_present_since_time: "+someone_present_since_time, 50, 125);
          text("time_before_dim: "+time_before_dim, 50, 150);
          if (millis() - someone_present_since_time > time_before_dim) {
            change_mode(mode + 1);
          }
        } else if (mode == S3_LIGHT_FADE_OUT) {
          turn_off();
          change_mode(mode + 1);
        } else if (mode == S4_DARK) 
        {
          change_mode(mode + 1);
        } else if (mode == S5_MUSIC) 
        {
          if (is_playing == false) {
            file.play();
            is_playing = true;
            music_playing_since = millis();
          }
          if (millis() - music_playing_since > music_duration) {
            is_playing = false;
            file.stop();
            change_mode(mode + 1);
          }
        } else if (mode == S6_LIGHT_FADE_IN) 
        {
          // todo
          if (millis() - in_mode_since_ms > 1000) {
            change_mode(mode + 1);
          }
    
        } else if (mode == TERMINATE) 
        {
          change_mode(S1_WAITING_FOR_PEOPLE);
          someone_present = false; // reset
          println("turn_on();");
          turn_on();
        }
      }
    }
    
    
    void change_mode(int m) {
      mode = m;
      in_mode_since_ms = millis();
    }
    
    
    
    void serialEvent(Serial p) { 
      String s = p.readString();
      if (s != null) {
        s = s.replace("\r\n", "");
        if (s.contains("Distance Measured")) {
          String[] tokens = split(s, "=");
          dist = int(tokens[1]);
        }
      }
    } 
    
    
    void turn_on() {
      myPort.write("on");
    }
    
    void turn_off() {
      myPort.write("off");
    }
    
    void keyPressed() {
      if (key == 'a') {
        turn_on();
      }
      if (key == 's') {
        turn_off();
      }
    }
    

    The second part is an arduino code for dimming an LED light:

    const int LEDPin = 9; // the pin that the LED is attached to
    const int LEDValueMax = 255; // the maximum value of the LED Brightness
    const int LEDValueMin = 0; // the minimum value of the LED Brightness
    int LEDValue = 255; // the start value of the LED Brightness
    int speedValue = 10; // the dimming speed value
    
    void setup() {
    
      pinMode(LEDPin, OUTPUT); // the PWM Output 
    
    }
    
    void loop() {
    
        do // Decrease the LED Brightness untill it reaches minimum brightness
        {
           analogWrite(LEDPin, LEDValue);
           delay(speedValue);
           LEDValue = LEDValue - 1;
    
        } while (LEDValue > LEDValueMin);
    
    }
    

    What I would love to fix is that in the first part where the light is turned off (int S3_LIGHT_FADE_OUT = 3;) it is going to dim the brightness as in the the code above. I am not sure how to get these two programs to talk to each other/ switching from int S3 to arduino dimming code.

    Thanks for your efforts! Faffie

  • Play video using Processing, Arduino and PIR Sensor

    Hi. A friend and I are in the middle of a video installation tests. I'm using an Arduino PIR Sensor and an Arduino Uno board.

    I need to stop a video when the PIR is "On" (Detects motion) and to play that video if the PIR is "Off".

    Checking the Processing and Arduino websites, examples and references I couldn't figured out what I'm doing wrong. Please let me know if something is missing or left. Thanks in advance for any help!

    This is the Arduino Code (copied from Arduino and Processing communication tutorials found on the web):

    /*
       PIR sensor tester
    */
    
    int ledPin = 13;                // choose the pin for the LED
    int inputPin = 2;               // choose the input pin (for PIR sensor)
    int pirState = LOW;             // we start, assuming no motion detected
    int val = 0;                    // variable for reading the pin status
    
    void setup() {
      pinMode(ledPin, OUTPUT);      // declare LED as output
      pinMode(inputPin, INPUT);     // declare sensor as input
    
      Serial.begin(9600);
    }
    
    void loop() {
      val = digitalRead(inputPin);  // read input value
      if (val == HIGH) {            // check if the input is HIGH
        digitalWrite(ledPin, HIGH);  // turn LED ON
        if (pirState == LOW) {
          // we have just turned on
          Serial.println("Motion detected!");
          // We only want to print on the output change, not state
          pirState = HIGH;
        }
      } else {
        digitalWrite(ledPin, LOW); // turn LED OFF
        if (pirState == HIGH) {
          // we have just turned of
          Serial.println("Motion ended!");
          // We only want to print on the output change, not state
          pirState = LOW;
        }
      }
    }
    

    And here is the Processing code:

    import processing.serial.*;
    import processing.video.*; 
    
    Serial myPort;
    String val;    
    
    Movie video;
    
    void setup() {
      size(640,480);
      video = new Movie(this,"sujeto1.mp4");
      video.loop();
      String portName = Serial.list()[0];
      myPort = new  Serial(this, portName, 9600);
      myPort.bufferUntil('\n');
    }
    
    void serialEvent (Serial myPort) {
      if (myPort.available() > 0) {
        val=myPort.readStringUntil('\n');
      }
      if (val=="Motion detected!") {
        video.stop();
      } else {
        video.loop();
      }
      println(val);
    
    }
    void draw() {
      background(0);
      image(video,0,0);
    
    } 
    
    void movieEvent(Movie video) {
      video.read();
    }
    
  • Problem communicate to Arduino Mega 2560

    Seems at 2011 someone else have reported such kind of phenomena.

    It will be really useful if you can provide the above link for completeness of your post. Nevertheless, I suggest you post in the arduino forum.

    I do not know much about the mega, but my first question would be if the mega and uno have the same port mapping, at least for your above example, ledPin and ledPin1? Another question is if there is any sample code that comes with the unit that you can test together with Processing?

    Kf

  • Problem communicate to Arduino Mega 2560

    ``I am trying to build a GUI for my system to communicate to Arduino Mega 2560. The testing code works on Uno board, however, it seems does not work on Mega board. Is this still a problem for processing? Seems at 2011 someone else have reported such kind of phenomena.

    The code is attached below, when it runs on Uno, there always one LED is ON, but on Mega neither of them can be switched on.

    My processing code:

    // Check if the mouse is over a rectangle and write the status to the serial port
    final String test = "Both" ; 
    
    import processing.serial.*; 
    
    Serial port;                       // Create object from Serial class
    
    void setup() { 
      size(200, 200); 
      noStroke(); 
      frameRate(10); 
      // Open the port that the board is connected to and use the same speed (9600 bps)
      port = new Serial(this,Serial.list()[0], 9600); 
      port.bufferUntil('\n');
    } 
    
    void draw() { 
      background(255); 
      if (mouseOverRect() == true)  {  // If mouse is over square,
        fill(204);                     // change color and  
        port.write('H');               // send an H to indicate mouse is over square 
      } else {                         // If mouse is not over square,
        fill(0);                       // change color and
        port.write('L');               // send an L otherwise
      } 
      rect(50, 50, 100, 100);          // Draw a square 
    } 
    
    
    boolean mouseOverRect() {        // Test if mouse is over square 
      return ((mouseX >= 50) && (mouseX <= 150) && (mouseY >= 50) && (mouseY <= 150)); 
    } 
    

    The Arduino Mega code:

        char val=0;                          // Data received from the serial port 
        int ledPin = 4;                    // Set the pin to digital I/O4
        int ledPin1 = 6;  
    
    
        void setup() { 
          pinMode(ledPin, OUTPUT);         // Set pin as OUTPUT 
          pinMode(ledPin1, OUTPUT);       
          Serial.begin(9600);              // Start serial communication at 9600 bps 
        } 
    
        void loop() { 
          if (Serial.available()) {        // If data is available to read, 
            val = Serial.read();  
        //    digitalWrite(ledPin1, HIGH);
        //    delay(500);
        //    digitalWrite(ledPin1, LOW);
            // read it and store it in val 
          } 
          //Serial.print(val);
          if (val == 'H') {                // If H was received
            digitalWrite(ledPin, HIGH);    // turn the LED on 
          } else { 
            digitalWrite(ledPin, LOW);     // Otherwise turn it OFF
          } 
           if (val == 'L') {                // If H was received
            digitalWrite(ledPin1, HIGH);    // turn the LED on 
          } else { 
            digitalWrite(ledPin1, LOW);     // Otherwise turn it OFF
          } 
          delay(100);                      // Wait 100 milliseconds for next reading 
    
    
        } 
    
  • Working on a code to take input from an Arduino and display the data using Processing.

    This is my code that sends the information to the serial monitor. If I open the serial monitor while it is running I can see each result pop up for two seconds before the next comes up.

    int ledPin = 13;
    int val = 0;
    
    void setup() {
    Serial.begin (9600);
    pinMode(ledPin, OUTPUT);
    }
    
    void loop(){
      if (val == 1){
        digitalWrite(ledPin, HIGH);
        Serial.println("LED is ON.");
        val = 0;
        delay(2000);
       }
      else if (val == 0){
        digitalWrite(ledPin, LOW);
        Serial.println("LED is OFF.");
        val = 2;
        delay(2000);
      }
      else{
        Serial.println("Invalid.");
        val = 1;
        delay(2000);
      }
    }
    
  • Questions about Processing+Arduino+Leap motion, please help!

    First, Sorry for my bad English,

    hello, I've post about this several month ago, but as I continued my project, the more I need to figure out.

    I'm doing an installation which is looped/interactive , when there's no hand detected by Leap Motion, my installation only display the looped code which is very simple delay code, (Arduino only) but if there's hand detect by Leap Motion, then convert to the code which I wrote for interactive (Processing+Arduino+leapmotion), but as the interactive part start, I want my original looped code still running,

    for example , {A} is my original looped display, {B} is Leap motion interactive code,

    {A}------(hand detected)----------------{hand removed}-----------------{A}
                                           {B}------------{B} 
    

    my original looped code don't pause or stop, just covered by the Leapmotion code.

    and here is my looped code (Arduino, nothing special, only delay) :

    int ledPin = 1;
    int ledPin2 = 2;
    int ledPin3 = 3;
    int ledPin4 = 4;
    int ledPin5 = 5;
    int ledPin6 = 6;
    int ledPin7 = 7;
    int ledPin8 = 8;
    int ledPin9 = 9;
    int ledPin10 = 10;
    int ledPin11 = 11;
    int ledPin12 = 12;
    int ledPin13 = 13;
    int ledPin14 = 14;
    
    int laser = 15;
    int laser2 = 16;
    int laser3 = 17;
    int laser4 = 18;
    int laser5 = 19;
    int laser6 = 20;
    int laser7 = 21;
    int laser8 = 22;
    
    
    
    void setup() {
    
      pinMode(ledPin, OUTPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      pinMode(ledPin4, OUTPUT);
      pinMode(ledPin5, OUTPUT);
      pinMode(ledPin6, OUTPUT);
      pinMode(ledPin7, OUTPUT);
      pinMode(ledPin8, OUTPUT);
      pinMode(ledPin9, OUTPUT);
      pinMode(ledPin10, OUTPUT);
      pinMode(ledPin11, OUTPUT);
      pinMode(ledPin12, OUTPUT);
      pinMode(ledPin13, OUTPUT);
      pinMode(ledPin14, OUTPUT);
    
      pinMode(laser, OUTPUT);
      pinMode(laser2, OUTPUT);
      pinMode(laser3, OUTPUT);
      pinMode(laser4, OUTPUT);
      pinMode(laser5, OUTPUT);
      pinMode(laser6, OUTPUT);
      pinMode(laser7, OUTPUT);
      pinMode(laser8, OUTPUT);
    
    }
    
    void loop() {
    
      // laser part 01
    
    
    
      delay(15000);
      digitalWrite(laser, HIGH);
      delay(1500);
      digitalWrite(laser, LOW);
      delay(6500);
      digitalWrite(laser3, HIGH);
      delay(1500);
      digitalWrite(laser3, LOW);
      delay(6500);
      digitalWrite(laser5, HIGH);
      delay(1500);
      digitalWrite(laser5, LOW);
      delay(6500);
      digitalWrite(laser7, HIGH);
      delay(1500);
      digitalWrite(laser7, LOW);
      delay(3000);
      digitalWrite(laser2, HIGH);
      delay(700);
      digitalWrite(laser2, LOW);
      delay(3000);
      digitalWrite(laser4, HIGH);
      delay(700);
      digitalWrite(laser4, LOW);
      delay(3000);
      digitalWrite(laser6, HIGH);
      delay(700);
      digitalWrite(laser6, LOW);
      delay(3000);
      digitalWrite(laser8, HIGH);
      delay(700);
      digitalWrite(laser8, LOW);
    
    
    
      delay(34000);
      digitalWrite(ledPin, HIGH);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin4, HIGH);
      digitalWrite(ledPin5, HIGH);
      digitalWrite(ledPin6, HIGH);
      digitalWrite(ledPin7, HIGH);
      delay(500);
      digitalWrite(ledPin, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      digitalWrite(ledPin5, LOW);
      digitalWrite(ledPin6, LOW);
      digitalWrite(ledPin7, LOW);
      delay(500);
    
      digitalWrite(laser, HIGH);
      delay(500);
      digitalWrite(laser, LOW);
    
      delay(500);
      digitalWrite(ledPin8, HIGH);
      digitalWrite(ledPin9, HIGH);
      digitalWrite(ledPin10, HIGH);
      digitalWrite(ledPin11, HIGH);
      digitalWrite(ledPin12, HIGH);
      digitalWrite(ledPin13, HIGH);
      digitalWrite(ledPin14, HIGH);
      delay(500);
      digitalWrite(ledPin8, LOW);
      digitalWrite(ledPin9, LOW);
      digitalWrite(ledPin10, LOW);
      digitalWrite(ledPin11, LOW);
      digitalWrite(ledPin12, LOW);
      digitalWrite(ledPin13, LOW);
      digitalWrite(ledPin14, LOW);
      delay(1500);
      digitalWrite(ledPin, HIGH);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin4, HIGH);
      digitalWrite(ledPin5, HIGH);
      digitalWrite(ledPin6, HIGH);
      digitalWrite(ledPin7, HIGH);
      delay(500);
      digitalWrite(ledPin, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      digitalWrite(ledPin5, LOW);
      digitalWrite(ledPin6, LOW);
      digitalWrite(ledPin7, LOW);
      delay(500);
    
      digitalWrite(laser2, HIGH);
      delay(500);
      digitalWrite(laser2, LOW);
    
      delay(500);
    
      digitalWrite(ledPin8, HIGH);
      digitalWrite(ledPin9, HIGH);
      digitalWrite(ledPin10, HIGH);
      digitalWrite(ledPin11, HIGH);
      digitalWrite(ledPin12, HIGH);
      digitalWrite(ledPin13, HIGH);
      digitalWrite(ledPin14, HIGH);
      delay(500);
      digitalWrite(ledPin, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      digitalWrite(ledPin5, LOW);
      digitalWrite(ledPin6, LOW);
      digitalWrite(ledPin7, LOW);
      delay(1500);
    
      digitalWrite(laser3, HIGH);
    
      digitalWrite(ledPin, HIGH);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin4, HIGH);
      digitalWrite(ledPin5, HIGH);
      digitalWrite(ledPin6, HIGH);
      digitalWrite(ledPin7, HIGH);
      digitalWrite(ledPin8, HIGH);
      digitalWrite(ledPin9, HIGH);
      digitalWrite(ledPin10, HIGH);
      digitalWrite(ledPin11, HIGH);
      digitalWrite(ledPin12, HIGH);
      digitalWrite(ledPin13, HIGH);
      digitalWrite(ledPin14, HIGH);
      delay(500);
    
      digitalWrite(laser3, LOW);
    
      digitalWrite(ledPin, LOW);
      digitalWrite(ledPin2, LOW);
      digitalWrite(ledPin3, LOW);
      digitalWrite(ledPin4, LOW);
      digitalWrite(ledPin5, LOW);
      digitalWrite(ledPin6, LOW);
      digitalWrite(ledPin7, LOW);
      digitalWrite(ledPin8, LOW);
      digitalWrite(ledPin9, LOW);
      digitalWrite(ledPin10, LOW);
      digitalWrite(ledPin11, LOW);
      digitalWrite(ledPin12, LOW);
      digitalWrite(ledPin13, LOW);
      digitalWrite(ledPin14, LOW);
      delay(500);
    
      digitalWrite(laser4, HIGH);
      delay(500);
      digitalWrite(laser, LOW);
    
      delay(500);
      digitalWrite(ledPin, HIGH);
      digitalWrite(ledPin2, HIGH);
      digitalWrite(ledPin3, HIGH);
      digitalWrite(ledPin4, HIGH);
      digitalWrite(ledPin5, HIGH);
      digitalWrite(ledPin6, HIGH);
      digitalWrite(ledPin7, HIGH);
      digitalWrite(ledPin8, HIGH);
      digitalWrite(ledPin9, HIGH);
      digitalWrite(ledPin10, HIGH);
      digitalWrite(ledPin11, HIGH);
      digitalWrite(ledPin12, HIGH);
      digitalWrite(ledPin13, HIGH);
      digitalWrite(ledPin14, HIGH);
      delay(500);
    
    }
    

    and this is my interactive code (Arduino) :

    int val; // Data received from the serial port
    int ledPin = 13; // Set the pin to digital I/O 13
    int ledPin2 = 12;
    int ledPin3 = 11;
    int ledPin4 = 10;
    int ledPin5 = 9;
    int ledPin6 = 8;
    
    void setup() {
      pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
      pinMode(ledPin2, OUTPUT);
      pinMode(ledPin3, OUTPUT);
      pinMode(ledPin4, OUTPUT);
      pinMode(ledPin5, OUTPUT);
      pinMode(ledPin6, OUTPUT);
      Serial.begin(9600); // Start serial communication at 9600 bps
    }
    void loop() {
      if (Serial.available())
      { // If data is available to read,
        val = Serial.read(); // read it and store it in val
      }
      if (val == 1)
      { // If 1 was received
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin2, HIGH);
        digitalWrite(ledPin3, HIGH);
        digitalWrite(ledPin4, HIGH);
        digitalWrite(ledPin5, HIGH);
        digitalWrite(ledPin6, HIGH);// turn the LED on
      } else if (val == 0) {
        digitalWrite(ledPin, LOW); // otherwise turn it off
        digitalWrite(ledPin2, LOW);
        digitalWrite(ledPin3, LOW);
        digitalWrite(ledPin4, LOW);
        digitalWrite(ledPin5, LOW);
        digitalWrite(ledPin6, LOW);
      }
      delay(10); // Wait 10 milliseconds for next reading
    } 
    

    this is my interactive code (Processing):

    import de.voidplus.leapmotion.*;
    import processing.serial.*;
    
    Serial myPort;
    
    LeapMotion leap ; 
    
    void setup () {
      size(800, 500);
      background(255);
      leap = new LeapMotion(this);
      String portName = Serial.list()[1]; //change the 0 to a 1 or 2 etc. to match your port
      myPort = new Serial(this, portName, 9600);
    }
    boolean rightHand,leftHand;
    float posy ;
    float posx ;
    void draw() {
    
        int number=0;
      for (Hand hand : leap.getHands() ) {
    
        rightHand = hand.isRight();
        posy = hand.getPosition().y;
    
        number=hand.countFingers();
    
        hand.draw();
        //println("Hand palm position: "+hand.getPalmPosition());
      }
    
      //println(number);
      println(posy);
    
      if(rightHand){
        if ((number!= 0)&&(posy < 450 && posy > 350))
        {
          timer(128);        //send a 1
          println("1");
        } else if ((number!= 0)&&(posy < 350 && posy > 250))
        {
          timer(32);
          println("2");
        } else if ((number!= 0)&&(posy < 250 && posy > 150))
        {
          timer(8);
          println("3");
        } else if ((number!= 0)&&(posy < 150 && posy > -120))
        {
          timer(4);
          println("4");
        } else 
        {                           //otherwise
          myPort.write(0);          //send a 0
        }
      }else if(leftHand){
    
    
      }
      delay(30);
    }
    
    
    
    void timer(int step) {
      if (frameCount % step ==0) {
        myPort.write(1);
      } else if (frameCount % step == step/2) {
        myPort.write(0);
      }
    }
    

    I want to put these code together as one, please help me, thank you for your reading and apologize for my bad english again.

  • Lighting up an LED from Processing to Arduino

    You need to build a second sketch were you interact directly with your arduino. In that sketch you will:

    • Configure your LED as set in the arduino
    • Test the commands you are sending to the arduino

    For the commands, you need to look at the documentation and examples related to your unit. You need to setup your own circuit (if you haven't done so) and assign it a pin. You might need to write your arduino code that fits your design. You might be able to use provided examples with some minor modifications from the arduino site. Notice your arduino code above defines a RED and GREEN pin but it doesn't manipulate them. You need to implement this part. I don't know what experience you have doing this. To make it easier for you, take my suggestion and start from a simpler sketch and some ardunino code, do some testing and take it from there.

    Check previous posts:
    https://forum.processing.org/two/search?Search=LEDs+arduino
    https://forum.processing.org/two/search?Search=ledpin

    Specifically:
    https://forum.processing.org/two/discussion/comment/95152/#Comment_95152
    https://forum.processing.org/two/discussion/comment/92348/#Comment_92348
    https://forum.processing.org/two/discussion/21768/interface-with-mux-controlled-led-rope/p1

    Kf

  • Raspberry pi with processing outputing X Y data to arduino

    Right OK, I fear I'm rapidly out of my depth so grateful for any help!

    I'm running a processing sketch on a pi 3 attached to a touch screen. As the screen is touched its drawing a line with the finger. Whilst doing that its printing the X , Y coordinates to the console in processing.

    What i'm trying to do is get these coordinates to the arduino. The arduino has an uploaded HEX file onto the onboard chip. These are controlling 2 steppers. So if you have the arduino IDE running you type X10 into the serial monitor and in drives the stepper. So, the arduino is tied up with grbl so I can't run a sketch to look for data or act on data being sent.

    I some how need to get the X Y data to the arduino. Is the best way through a USB cable? I've followed this useful link to set up the serial arduino command setup

    (http://scruss.com/blog/2014/01/07/processing-2-1-oracle-java-raspberry-pi-serial-arduino-☺/)

    and have data going from processing to arduino

    this works as a test flashing the arduino light on and off

    import processing.serial.*;
    import cc.arduino.*;
    Arduino arduino;
    int ledPin = 13;
    
    void setup()
    {
      println(Arduino.list());
      arduino = new Arduino(this, Arduino.list()[0], 9600);
      arduino.pinMode(ledPin, Arduino.OUTPUT);
    }
    
    void draw()
    {
      arduino.digitalWrite(ledPin, Arduino.HIGH);
      delay(1000);
      arduino.digitalWrite(ledPin, Arduino.LOW);
      delay(1000);
    }
    

    this is also working with my attempt to get X10 to the arduino grbl shield but no X10 going to arduino. mouse released in processing square LED on arduino blinks.

    import processing.serial.*;
    import cc.arduino.*;
    Arduino arduino;
    
    void setup()
    {
      size (200,200);
      println(Arduino.list());
      arduino = new Arduino(this, Arduino.list()[0],9600);
    }
    
    void draw() {
      background(100);
    }
    void mouseReleased(){
      arduino.digitalWrite('X', 10);
    }
    

    heres the code for the processing sketch do far it works but no data going to the serial of the arduino, should I be using digitalwrite to write the data into the arduino serial monitor, should i not be using USB but rather TX RX?

    import processing.serial.*;
    import cc.arduino.*;
    Arduino arduino;
    
    void setup()
    {
      size (200,200);
      println(Arduino.list());
      arduino = new Arduino(this, Arduino.list()[0],9600);
    }
    void setup() 
    {
      size(200,200); //make our canvas 200 x 200 pixels big
      String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
      myPort = new Serial(this, portName, 9600);
    }
    
    void draw() {
      stroke(255);
      if (mousePressed == true) {
        line(mouseX, mouseY, pmouseX, pmouseY);
      }
    }
    void mousePressed ()
    {
        println("PRESSED x:" +mouseX + " y:" + mouseY);
    }
    void mouseDragged ()
    {
      println("G01 x" +mouseX + " y" + mouseY + " F100");
    }
    

    Thankyou in advance for any help. Loving the whole coding hardware... but struggling with the depth of knowledge required and coding logic!

  • visualization Arduino programm via processing - read serial Input doesnt work

    Hello, Me and a friend are absolute noobs in programming but try to create a bop it like game. To realize the project we are using Arduino and Processing. The Arduino Code runs the time, counts the points, etc. The Arduino part works, but now we want to use processing to visualize everything. Therefore we connect the Arduinoboard via USB to the Computer, but we have serious problems to read the serial data. In the Console we can see there is something in the Buffer, but we cant seperate the data or save it in our proseccing variables!

    The question now is, how do we read the serial data correctly, how do we save the data for player 1 in the variable of the processing programm and seperate it from the data of the random number and the data of player2 and vice versa? Is there a better way than our actual code?

    Nothing we found on the internet could help us yet, hopefully somebody here can!

    Arduino Part:

    #define DEBUG 1
    
             int ledPin = 13;
             int Buzzer = 2;
             int Spieler1Taster1 = 3;
             int Spieler1Taster2 = 4;
             int Spieler1Taster3 = 5;
             int Spieler2Taster1 = 6;
             int Spieler2Taster2 = 8;
             int Spieler2Taster3 = 9;
             int threshold= 800;                                   //the microphone threshold sound level at which the LED will turn on
             int Zufall1 = 10;
             int Zufall2 = 11;
             int Zufall3 = 12;
    
             int Spieler1Taster1HIGH = 0;
             int Spieler1Taster2HIGH = 0;
             int Spieler1Taster3HIGH = 0;
             int Spieler2Taster1HIGH = 0;
             int Spieler2Taster2HIGH = 0;
             int Spieler2Taster3HIGH = 0;
             int buttonState;
             int ledState = HIGH;
             int zufall = 0;
             int counter1 = 0;
             int counter2 = 0;
             int sample;                                          //the variable that will hold the value read from the microphone each time
             int n = 0;
             int halt = 0;
             int y;
             int counter1x;
    
    unsigned long previousMillis = 99999999999;
    unsigned long previousMillis_Reset = 0;
       const long interval = 10000;
       const long interval_Reset = 100;
       const long reset = 3000;
    
    void setup()
    {
         Serial.begin(9600);
         pinMode(13, OUTPUT);
         pinMode(12, OUTPUT);
         pinMode(11, OUTPUT);
         pinMode(10, OUTPUT);
         pinMode(9, INPUT);
         pinMode(8, INPUT);
         pinMode(6, INPUT);
         pinMode(5, INPUT);
         pinMode(4, INPUT);
         pinMode(3, INPUT);
         pinMode(2, INPUT);
    }
    void loop()   
    {
    
         unsigned long currentMillis = millis();
    
         buttonState = digitalRead(Buzzer);
      if (buttonState == HIGH)                                            
      {
         previousMillis = currentMillis;  
         counter1 = 0;
         counter2 = 0;  
      }
      if ( currentMillis - previousMillis < interval)                     
    {
         //Serial.print("Zeit ");
         //Serial.println((currentMillis - previousMillis)/1000);
         digitalWrite(13, HIGH);
         zufall = random(3) + 1;
    
    
      if (DEBUG)
      {
         }
    
         //delay(100);
    
      if (zufall == 1)        
      {
         digitalWrite(10, HIGH); // set the LED on
         digitalWrite(11, LOW); // set the LED off
         digitalWrite(12, LOW); // set the LED off
      }
      if (zufall == 2)
      {
         digitalWrite(10, LOW); // set the LED on
         digitalWrite(11, HIGH); // set the LED off
         digitalWrite(12, LOW); // set the LED off
      }
      if (zufall == 3)
      {
         digitalWrite(10, LOW); // set the LED on
         digitalWrite(11, LOW); // set the LED off
         digitalWrite(12, HIGH); // set the LED off
      }
      if (zufall == 4)
      {
    
      }  
         Serial.print("Zufallszahl: ");
         Serial.println(zufall, DEC);
    
    
         buttonState = digitalRead(Spieler1Taster1);
      if (buttonState == HIGH)
      {
         Spieler1Taster1HIGH = 1;
      }  
      if (buttonState == LOW && Spieler1Taster1HIGH == 1)
      {
         counter1++;
         Spieler1Taster1HIGH = 0;
      }    
    
         buttonState = digitalRead(Spieler1Taster2);
      if (buttonState == HIGH)
      {
         Spieler1Taster2HIGH = 1;
      }
      if (buttonState == LOW && Spieler1Taster2HIGH == 1)
      {
         counter1++;
         Spieler1Taster2HIGH = 0;
      }    
    
         buttonState = digitalRead(Spieler1Taster3);
      if (buttonState == HIGH)
      {
         Spieler1Taster3HIGH = 1;
      }
      if (buttonState == LOW && Spieler1Taster3HIGH == 1)
      {
         counter1++;
         Spieler1Taster3HIGH = 0;
      }
    
         buttonState = digitalRead(Spieler2Taster1);
      if (buttonState == HIGH)
      {
         Spieler2Taster1HIGH = 1;
      }
      if (buttonState == LOW && Spieler2Taster1HIGH == 1)
      {
         counter2++;
         Spieler2Taster1HIGH = 0;
      }
    
         buttonState = digitalRead(Spieler2Taster2);
      if (buttonState == HIGH)
      {
         Spieler2Taster2HIGH = 1;
      }
      if (buttonState == LOW && Spieler2Taster2HIGH == 1)
      {
         counter2++;
         Spieler2Taster2HIGH = 0;
      }
    
         buttonState = digitalRead(Spieler2Taster3);
      if (buttonState == HIGH)
      {
         Spieler2Taster3HIGH = 1;
      }
      if (buttonState == LOW && Spieler2Taster3HIGH == 1)
      {
         counter2++;
         Spieler2Taster3HIGH = 0;
      }
         delay(100);
         Serial.print("Spieler: ");    
         Serial.println(counter1, DEC);
         Serial.print("Spieler2: ");
         Serial.println(counter2, DEC);
         y = 0;                                                                                   //Gewinner Abfrage
         auswerten(zufall);
    }
    }
    
      else
      {   
         digitalWrite(13, LOW);
         digitalWrite(10, LOW);
         digitalWrite(11, LOW);
         digitalWrite(12, LOW);
      }
    
    
    
    
       if (buttonState == HIGH)
    {
         long x = (currentMillis);
       if ((x + reset) < currentMillis)
       {
         reset;
         digitalWrite(13, LOW);
         digitalWrite(10, LOW);
         digitalWrite(11, LOW);
         digitalWrite(12, LOW);
         counter1 = 0;
         counter2 = 0;
       }
    
       if (n = 0)
       {
         x = currentMillis;
         n = 1;
       }
    
       else
       {
         x = 0;
         n = 0;
       }
       Serial.println (x);
    }
    
    
    
    
    }
        int auswerten(int zufall)
    {
    
    
        int ende  = 0;
        int endex = 0; //endex =  digitalRead(Spieler1Taster1) + digitalRead(Spieler1Taster2) + digitalRead(Spieler1Taster3) + digitalRead(Spieler2Taster1) + digitalRead(Spieler2Taster2) + digitalRead(Spieler2Taster3);
      do
    {
      if (zufall == 1 && digitalRead (Spieler1Taster1))
      {
         ende = 1;
      }
      if (zufall == 1 && digitalRead (Spieler2Taster1))
      {
         ende = 1;
      }
      if (zufall == 2 && digitalRead (Spieler1Taster2))
      {
         ende = 1;
      }
      if (zufall == 2 && digitalRead (Spieler2Taster2))
      {
         ende = 1;
      }
      if (zufall == 3 && digitalRead (Spieler1Taster3))
      {
         ende = 1;
      }
      if (zufall == 3 && digitalRead (Spieler2Taster3))
      {   
         ende = 1;
    }
    }
      while (!ende);
    
     unsigned long currentMillis = millis();
    
          if (currentMillis - previousMillis >= interval)
         {
            if (y == 0)
          {
              if (counter1 > counter2)
              {
               Serial.println("Der Gewinner ist Spieler 1");
               y = 1;
              }     
              if (counter1 < counter2)
              {
               Serial.println("Der Gewinner ist Spieler 2");
               y = 1;
              }
              if ((counter1 == counter2) && ((counter1 || counter2) > 0))
              {
              Serial.println("Unentschieden");
              y = 1;
              }    
           }
         }
    
      return 0;
    }
    

    Processing Part:

    import processing.serial.*;
      Serial myPort;
    
      String counter1;
      String counter2;
      String Zufall;
    
    
      //Hintergrundbild
      PImage bg;
    
      int begin;
      int duration = 30;
      int time = 30;
    
      // Schriftband
      int band1x, band2x;
      int verlosungszeit;
      int Zeitvormittags;
      int Zeitnachmittags;
    
    
      float mill = 0;
      int prevSec = 0;
    
      float Zaehler1;
      float Zaehler2;
      float Zahl;
    
    
    void setup()
    {
    //keine Maus
      noCursor();
    
    
    //Programm Bildschiurmgröße zuweisen
      size(1920, 1080);
    
    
    //Hintergrundbild größe zuweisen und Bild auswählen
      background(300);
      size(1920, 1080);
      bg = loadImage("pc-kabel.jpg");
    
    
      //Bilder pro Sekunde
      frameRate(50);
    begin = millis();
      // Schriftband
      band1x = width;
      band2x = band1x + width;
      Zeitvormittags = 13;
      Zeitnachmittags = 17;
    
    
      // Zuweisung serielle Schnittstelle
      String portName = Serial.list()[0];
      myPort = new Serial(this, "COM3", 9600);
      myPort.bufferUntil('\n');
    println(Serial.list());
    }
    //Vollbild
         boolean sketchFullScreen()
      {
        return true;
      }
    
    void serialEvent(Serial myPort)
    {
      counter1 = myPort.readStringUntil(',');
      counter2 = myPort.readStringUntil(';');
      Zufall = myPort.readStringUntil('!');
    
      //counter1 = counter1.substring(0, counter1.length() - 1);
      //counter2 = counter2.substring(0, counter2.length() - 1);
      //Zufall = Zufall.substring(0, Zufall.length() - 1);
    
      Zaehler1 = float(counter1);
      Zaehler2 = float(counter2);
      Zahl = float(Zufall);
    }
    
      void draw()
      {
        //Hintergrundbild ausführen
        background(bg);
      Zeit();
        //Schriftzug ausführen
      Banner();
        //ermpfangene Werte Anzeigen
      Anzeige();
        //Zähler Spieler 1
      //Zähler1();
        //Zähler Spieler 2
      //Zähler2();
    }
    
    
    void Anzeige()
    {
      {
      String inBuffer = myPort.readString();
    if (inBuffer != null)
    {
      println(Zaehler1);
      println(Zaehler2);
      text(Zaehler1, 200, 800); // Text ausgebe
      text(Zaehler2, 1520, 800); // Text ausgeben
    }
    else
    {
    
    }
    print(counter1); //print it out in the console
      textSize (50);
      text("Spieler 1", 200, 200);
      text("Spieler 2", 1520, 200);
    }
    }
    
    
    
    
                //****** EIGENE FUNKTIONEN ******//
      //Zähler
      void Zeit()
    {
      if (time > 0){  
        time = duration - (millis() - begin)/1000;
         textSize(200);
         text(time, 850, 200); // Text ausgeben
    }
    }
    
    // Schriftband Verlosungstermine
    void Banner()
    {
      // Zeitbestimmung
      int stunde;
      String morgen;
    
      morgen = "";
      stunde = hour();
      if(stunde < Zeitvormittags)
        verlosungszeit = Zeitvormittags;
        else
        {
          if(stunde < Zeitnachmittags)
            verlosungszeit = Zeitnachmittags;
            else
            {
            morgen = "morgen ";
            verlosungszeit = Zeitvormittags;
            }
        }
    
      // Schriftbänder einblenden
      textSize(50);
      fill(92, 172, 238);
      textAlign(LEFT, CENTER);
      text("Nächste Gutscheinverlosung "+ morgen + "um " + verlosungszeit +" Uhr", band1x, 40);
      text("Nächste Gutscheinverlosung "+ morgen + "um " + verlosungszeit +" Uhr", band2x, 40);
    
      if(band2x < 0 && band1x < 0)
         band1x =  width;
    
         band1x = band1x - 2;
    
      if(band1x < 0 && band2x < 0)
         band2x = width;
    
         band2x = band2x - 2;
    }
    
  • Processing Android Mode + Android Device + Bluetooth + Arduino

    Indicated below are the processing codes that run on processing 2.0b7. By this codes, you could create your own custom GUI that communicates with arduino. Just in case you would be able to recreate the code with just using imports in processing android, using almost the same as the the indicated codes.

    Processing Android Mode Codes:

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.widget.Toast;
    import android.view.Gravity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import java.util.UUID;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import android.os.Handler;
    import android.os.Message;
    import android.util.Log;
    import android.bluetooth.BluetoothServerSocket;
    import android.bluetooth.BluetoothSocket;
    
    public BluetoothSocket scSocket;
    
    // *** GUI Initialization *** //
    int i = 150;
    int j = 150;
    int Mode = 1;
    
    int numFrames = 12;
    int frame = 0;
    PImage[] images = new PImage[numFrames];
    
    int circleX1, circleY1; 
    int circleX2, circleY2; 
    int circleSize1 = 100;
    int circleSize2 = 100;
    boolean circleOver1 = false;
    boolean circleOver2 = false;
    
    PImage img1;
    PImage img2;
    
    boolean foundDevice=false;
    boolean BTisConnected=false;
    String serverName = "ArduinoBasicServer";
    
    // *** For GUI Communicaion *** //
    public static final int MESSAGE_WRITE = 1;
    public static final int MESSAGE_READ = 2;
    String readMessage="";
    //String sendLetter="";
    SendReceiveBytes sendReceiveBT=null;
    
    // *** For Bluetooth Features *** //
    BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      if(requestCode==0) {
      if(resultCode == RESULT_OK) {
      background(0);
      ToastMaster ("Bluetooth has been switched ON");
      ToastMaster("Please Reload Application to Connect to Device");
      ToastMaster("Please Reload Application to Connect to Device");
      ToastMaster("Please Reload Application to Connect to Device");
      } else {
      background(0);
      ToastMaster("You need to turn Bluetooth ON !!!");
      ToastMaster("You need to turn Bluetooth ON !!!");
      ToastMaster("You need to turn Bluetooth ON !!!");
      }
      }
    }
    
    BroadcastReceiver myDiscoverer = new myOwnBroadcastReceiver();
    BroadcastReceiver checkIsConnected = new myOwnBroadcastReceiver();
    
    // *** For GUI Communication *** //
    private final Handler mHandler = new Handler() {
      @ Override
      public void handleMessage(Message msg) {
      switch (msg.what) {
      case MESSAGE_WRITE:
      break;
      case MESSAGE_READ:
      byte[] readBuf = (byte[]) msg.obj;
      readMessage = new String(readBuf, 0, msg.arg1);
      break;
      }
      }
    };
    
    // *** For GUI Setup *** //
    void setup() {
      background(0);
      orientation(PORTRAIT);
      size(displayWidth,displayHeight); //Resolution Size
      frameRate(12);
    
      circleX1 = width/2;
      circleY1 = (height/2)+55;
      circleX2 = width/2;
      circleY2 = (height/2)-55;
      ellipseMode(CENTER);
    
      images[0] = loadImage("Loader.1.png");
      images[1] = loadImage("Loader.2.png");
      images[2] = loadImage("Loader.3.png");
      images[3] = loadImage("Loader.4.png");
      images[4] = loadImage("Loader.5.png");
      images[5] = loadImage("Loader.6.png");
      images[6] = loadImage("Loader.7.png");
      images[7] = loadImage("Loader.8.png");
      images[8] = loadImage("Loader.9.png");
      images[9] = loadImage("Loader.10.png");
      images[10] = loadImage("Loader.11.png");
      images[11] = loadImage("Loader.12.png");
    
      img1 = loadImage("SwitchOff.png");
      img2 = loadImage("SwitchOn.png");
    
      background(0);
    
    // *** For Bluetooth Features *** // 
      if (!bluetooth.isEnabled()) {
      Intent requestBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
      startActivityForResult(requestBluetooth, 0);
      }
    
      if (bluetooth.isEnabled()) {
      registerReceiver(myDiscoverer, new IntentFilter(BluetoothDevice.ACTION_FOUND));
      registerReceiver(checkIsConnected, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    
      if (!bluetooth.isDiscovering()) {
      bluetooth.startDiscovery();
      }
      }
    }
    
    // *** GUI Proper Draw Setup *** //
    void draw() {
       if(foundDevice) {
      if(BTisConnected){
      update(mouseX, mouseY);
      background(0);
    
      if(circleOver1 && mousePressed == true){
        Mode = 1;
        byte[] myByte = stringToBytesUTFCustom("B");
        sendReceiveBT.write(myByte);
      } else if(circleOver2 && mousePressed == true){
        Mode = 2;
        byte[] myByte = stringToBytesUTFCustom("A");
        sendReceiveBT.write(myByte);
      }
    
      if (Mode == 1) {
        image(img1,(width/2)-60,(height/2)-120);
      } else if (Mode == 2) {
        image(img2,(width/2)-60,(height/2)-120);
      }
    
      } else {
    
      if (j == 0) {
      background(0);  
      text("Target Device not Found", (width/2)-80, height/4);
      } else {
      background(0);
      frame = (frame+1) % numFrames;
      image(images[frame],(width/2)-80,(height/2)-80);
      text("Searching for Target Device", (width/2)-70, height/4);
      j = j-1;
      }
    
      }
      } else {
    
      if (i == 0) {
      background(0);  
      text("No Bluetooth Device Found", (width/2-70), height/4);
      } else {
      background(0);
      frame = (frame+1) % numFrames;
      image(images[frame],(width/2)-80,(height/2)-80);
      text("Searching for Bluetooth Device", (width/2)-70, height/4);
      i = i-1;
      }
    
      }
    }
    
    // *** For Bluetooth Features *** //
    public class myOwnBroadcastReceiver extends BroadcastReceiver {
      ConnectToBluetooth connectBT;
      @Override
      public void onReceive(Context context, Intent intent) {
      String action=intent.getAction();
    
      if(BluetoothDevice.ACTION_FOUND.equals(action)){
      String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
      BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
      foundDevice=true;
    
      if(discoveredDeviceName.equals("HMSoft")) {//name of device 
      ToastMaster("Connecting you Now !!!");
      unregisterReceiver(myDiscoverer);
      connectBT = new ConnectToBluetooth(discoveredDevice);
      new Thread(connectBT).start();
      } else { 
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      ToastMaster("Please Turn on Target Device");
      }
      }
    
      if(BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
      ToastMaster("Already CONNECTED with Target Device");
      int counter=0;
      while(scSocket==null){
      }
      BTisConnected=true;
      if(scSocket!=null){
      sendReceiveBT = new SendReceiveBytes(scSocket);
      new Thread(sendReceiveBT).start();
      String red = "r";
      byte[] myByte = stringToBytesUTFCustom(red);
      sendReceiveBT.write(myByte);
      }
      }
      }
    }
    
    // *** for Communication NEW *** //
    public static byte[] stringToBytesUTFCustom(String str) {
      char[] buffer = str.toCharArray();
      byte[] b = new byte [buffer.length << 1];
      for (int i = 0; i < buffer.length; i++) {
      int bpos = i << 1;
      b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
      b[bpos + 1] =(byte) (buffer[i]&0x00FF);
      }
      return b;
    }
    
    public class ConnectToBluetooth implements Runnable{
      private BluetoothDevice btShield;
      private BluetoothSocket mySocket = null;
      private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    
      public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
      btShield = bluetoothShield;
    
      try{
      mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
      }
      catch(IOException createSocketException){
      Log.e("ConnectToBluetooth", "Error with Socket");
      }
      }
    
      public void run() {
      bluetooth.cancelDiscovery();
    
      try{
      mySocket.connect();
      scSocket=mySocket;
      } catch (IOException connectException){
      Log.e("ConnectToBluetooth", "Error with Socket Connection");
    
      try{
      mySocket.close();
      }
      catch(IOException closeException){
      }
      return;
     }
     }
    
      public BluetoothSocket getSocket() {
      return mySocket;
      }
    
      public void cancel() {
      try {
      mySocket.close();
      } catch (IOException e) {
      }
      }
    }
    
    // *** For GUI Communication *** //
    private class SendReceiveBytes implements Runnable {
      private BluetoothSocket btSocket;
      private InputStream btInputStream = null;
      //;
      private OutputStream btOutputStream = null;
      String TAG = "SendReceiveBytes";
      public SendReceiveBytes(BluetoothSocket socket) {
      btSocket = socket;
      try {
      btInputStream = btSocket.getInputStream();
      btOutputStream = btSocket.getOutputStream();
      }
      catch (IOException streamError) {
      Log.e (TAG, "Error when getting input or output Stream");
      }
      }
    
      public void run () {
      byte[] buffer = new byte [1024];
      int bytes;
      while (true) {
      try {
      bytes = btInputStream.read(buffer);
      mHandler.obtainMessage (MESSAGE_READ, bytes, -1, buffer)
      .sendToTarget();
      }
      catch (IOException e) {
      Log.e(TAG, "Error reading from btInputStream");
      break;
      }
      }
      }
      public void write(byte[] bytes) {  
      try {
      btOutputStream.write(bytes);
      }
      catch (IOException e) {
      Log.e(TAG, "Error when writing to btOutputStream");
      }
      }
      public void cancel() {
      try {
      btSocket.close();
      }
      catch (IOException e) {
      Log.e(TAG, "Error when closing the btSocket");
      }
      }
    }
    
    void ToastMaster(String textToDisplay) {
      Toast myMessage = Toast.makeText(getApplicationContext(),
      textToDisplay,
      Toast.LENGTH_LONG);
      myMessage.setGravity(Gravity.CENTER, 0, 0);
      myMessage.show();
    }
    
    // *** GUI Proper --- Ending Codes --- *** //
    void update(int x, int y) {
      if( overCircle(circleX1, circleY1, circleSize1)) {
        circleOver1 = true;
        circleOver2 = false;
      } else if( overCircle(circleX2, circleY2, circleSize2)) {
        circleOver1 = false;
        circleOver2 = true;
      } else {
        circleOver1 = false;
        circleOver2 = false;
      }
    }
    
    boolean overCircle(int x, int y, int diameter) {
      float disX = x - mouseX;
      float disY = y - mouseY;
      if(sqrt(sq(disX) + sq(disY)) < diameter/2) {
        return true;
      } else {
        return false;
      }
    }
    

    Arduino Codes:

    #include <SoftwareSerial.h>
    
    #define RxPin 4
    #define TxPin 2
    #define DEBUG_ENABLED 1
    
    SoftwareSerial BTSerial(RxPin, TxPin);
    
    int ledPin = 13;
    int Mode = 1;
    
    void setup()
     {
     Serial.begin(9600);
     pinMode(RxPin, INPUT);
     pinMode(TxPin, OUTPUT);
    
     pinMode(ledPin, OUTPUT);
    
     BTSerial.begin(9600);
     }
    
    void loop() {
      char val;
      if (BTSerial.available());{
        val = BTSerial.read();
        if (val == 'A') {
          Mode = 2;
         } else if (val == 'B') {
          Mode = 1;
         } 
      }
        if (Mode == 1){
          digitalWrite(ledPin, LOW);
        } else if (Mode == 2) {
          digitalWrite(ledPin, HIGH);     
      }
        delay(10);
    }
    

    The GUI is executed and tested on a samsung galaxy android phone and is used to turn on a diode connected to pin D13 of an arduino uno. Communication was done via bluetooth via a seeed studion bluetooh shield version 2. If there are any information that you need to know, as long as I know about it, I would be glad to share it.

    Files can be downloaded from my google drive containing the codes but unfortunately I am having a hardttime uploading processing version 2.0b7 where I could run the codes. Link: https://drive.google.com/drive/folders/0B23a7LuYxuDLR0F5UXMyVDZMeFE