Quantcast
Channel: Arduino - Processing 2.x and 3.x Forum
Viewing all 747 articles
Browse latest View live

If serial isn't available on startup

$
0
0

I've been thinking about this problem for a couple weeks, came up with several possible solutions, but none have worked, so I'm looking for suggestions, ideas, or a good general direction to start thinking along.

I wrote a rather large applet that does a couple different things; sometimes, but not always, it will be connecting to an arduino via an HC-06 bluetooth module (the code is exactly the same as using serial through USB) . Sometimes I will need to run the program without connecting to serial. If I use Serial.list() it doesn't choose the right port, if the port is not available, the program doesn't run at all.
I need a method that connects if the port is available, but just ignores it and runs the program if it is not. Is there a function I can use to check the port before initializing, that way if it's not there i can tell my program not to use any of the portions that require serial communication? Thanks -J


serial communication with 4 sensor

$
0
0

have 4 Hc-sr04 sensor i use newping library

I have 4 Hc-sr04 sensor I use newping library. I try to printnl the data in processing. I don't know what i did wrong.

I have number in processing but not the good one and they repeat forever.

s1_101 s2_110 s3_115 s0_111
s1_114 s2_50 s3_58 s0_32
s1_48 s2_99 s3_109 s0_13
s1_10 s2_115 s3_101 s0_110
s1_115 s2_111 s3_114 s0_51
s1_58 s2_32 s3_48 s0_99
s1_109 s2_13 s3_10 s0_115
s1_101 s2_110 s3_115 s0_111

Maybe it a simple mistake or I am totally wrong ?

arduino

#include <NewPing.h>
#define TRIGGER_PIN1  2  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN1     3  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define TRIGGER_PIN2  4  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN2     5
#define TRIGGER_PIN3  6  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN3     7
#define TRIGGER_PIN4  8  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN4     9

#define MAX_DISTANCE  30 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar0(TRIGGER_PIN1, ECHO_PIN1, MAX_DISTANCE); // NewPing setup of pins and maximum distance.
NewPing sonar1(TRIGGER_PIN2, ECHO_PIN2, MAX_DISTANCE);
NewPing sonar2(TRIGGER_PIN3, ECHO_PIN3, MAX_DISTANCE);
NewPing sonar3(TRIGGER_PIN4, ECHO_PIN4, MAX_DISTANCE);

int inByte = 0; // incoming serial byte

void setup() {
  Serial.begin(115200); // Open serial monitor at 115200 baud to see ping results.
  while (!Serial) {
 ; // wait for serial port to connect. Needed for Leonardo only
 }
  establishContact(); // send a byte to establish contact until receiver
  // responds
}
void loop() {
  if (Serial.available() > 0) {
inByte = Serial.read();

    int d = 500;
    delay(d);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
    int uS0 = sonar0.ping(); // Send ping, get ping time in microseconds (uS).
    Serial.print("sensor0: ");
    Serial.print(sonar0.convert_cm(uS0)); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)
    Serial.println("cm");

    delay(d);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
    int uS1 = sonar1.ping(); // Send ping, get ping time in microseconds (uS).
    Serial.print("sensor1: ");
    Serial.print(sonar1.convert_cm(uS1)); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)
    Serial.println("cm");

    delay(d);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
    int uS2 = sonar2.ping(); // Send ping, get ping time in microseconds (uS).
    Serial.print("sensor2: ");
    Serial.print(sonar2.convert_cm(uS2)); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)
    Serial.println("cm");

    delay(d);                                 // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
    int uS3 = sonar3.ping(); // Send ping, get ping time in microseconds (uS).
    Serial.print("sensor3: ");
    Serial.print(sonar3.convert_cm(uS3)); // Convert ping time to distance and print result (0 = outside set distance range, no ping echo)
    Serial.println("cm");

   // Serial.write(sonar0);
   // Serial.write(sonar1);
   // Serial.write(sonar2);
   // Serial.write(sonar3);

  }
}
void establishContact() {
 while (Serial.available() <= 0) {
 Serial.print('A'); // send a capital A
 delay(300);
 }>
}

processing

import processing.serial.*;

Serial myPort;                       // The serial port
int[] serialInArray = new int[4];    // Where we'll put what we receive
int serialCount = 0;                 // A count of how many bytes we receive
int sensor0,sensor1,sensor2,sensor3;
//int sensor1;
//int sensor2;
//int sensor3; // Sensor
boolean firstContact = false;        // Whether we've heard from the microcontroller

void setup() {
  size(256, 256);  // Stage size
  noStroke();      // No border on the next thing drawn
  // Print a list of the serial ports, for debugging purposes:
  //println(Serial.list());

  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[2];
  myPort = new Serial(this, portName , 115200);
  //"/dev/cu.wchusbserialfa140"
}

void draw() {
  background(000000);
}

void serialEvent(Serial myPort) {
  // read a byte from the serial port:
  int inByte = myPort.read();
  // if this is the first byte received, and it's an A,
  // clear the serial buffer and note that you've
  // had first contact from the microcontroller.
  // Otherwise, add the incoming byte to the array:
  if (firstContact == false) {
    if (inByte == 'A') {
      myPort.clear();          // clear the serial port buffer
      firstContact = true;     // you've had first contact from the microcontroller
      myPort.write('A');       // ask for more
    }
  } else {
    // Add the latest byte from the serial port to array:
    serialInArray[serialCount] = inByte;
    serialCount++;

    // If we have 4 bytes:
    if (serialCount > 3 ) {
      sensor0 = serialInArray[0];
      sensor1 = serialInArray[1];
      sensor2 = serialInArray[2];
      sensor3 = serialInArray[3];

      // print the values (for debugging purposes only):
      println ( " s0_"+ sensor0);
      print ( " s1_"+ sensor1);
      print ( " s2_"+ sensor2);
      print ( " s3_"+ sensor3);

      // Send a capital A to request new sensor readings:
      myPort.write('A');
      // Reset serialCount:
      serialCount = 0;
    }
  }
}
`

peak detection

Processing script (Minim example with serial stuff shoved in) displaying 'Null' input from arduino

$
0
0

I'm trying to control the gain value of a song that's playing by using inputs from an arduino (0 or 1) I tested the arduino code with the general processing serial comm example and it works fine. I also tested my processing script with an arduino code that generates just 0s and 1s and that also works okay

Here's the processing script I'm using:

` /** * This sketch demonstrates how to play a file with Minim using an AudioPlayer.
* It's also a good example of how to draw the waveform of the audio. Full documentation * for AudioPlayer can be found at http://code.compartmental.net/minim/audioplayer_class_audioplayer.html *

* For more information about Minim and additional features, * visit http://code.compartmental.net/minim/ / import processing.serial.; import ddf.minim.*;

Serial myPort;
String val;
int a;

Minim minim;
AudioPlayer player;

void setup()
{

  myPort = new Serial(this, "COM3", 115200);

  size(512, 200, P3D);

  // 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.
  player = minim.loadFile("Highway to Hell.wav");
}

void draw()
{
  if ( myPort.available() > 0)
  {  // If data is available,
  val =  (myPort.readStringUntil('\n'));
     if (val != null) {
       val =trim(val);
     a = Integer.parseInt(val);
     }
     }
 if(a==1)
 {
  player.setGain(0);
 }
 else if(a==0)
 {
   player.setGain(-30);
 }
  //println(val);
   if (mousePressed == true)
  {                           //if we clicked in the window
   myPort.write('1');         //send a 1
   println("1");
  } else
  {                           //otherwise
  myPort.write('0');          //send a 0
  }


  background(0);
  stroke(255);

  // draw the waveforms
  // the values returned by left.get() and right.get() will be between -1 and 1,
  // so we need to scale them up to see the waveform
  // note that if the file is MONO, left.get() and right.get() will return the same value
  for(int i = 0; i < player.bufferSize() - 1; i++)
  {
    float x1 = map( i, 0, player.bufferSize(), 0, width );
    float x2 = map( i+1, 0, player.bufferSize(), 0, width );
    line( x1, 50 + player.left.get(i)*50, x2, 50 + player.left.get(i+1)*50 );
    line( x1, 150 + player.right.get(i)*50, x2, 150 + player.right.get(i+1)*50 );
  }

  // draw a line to show where in the song playback is currently located
  float posx = map(player.position(), 0, player.length(), 0, width);
  stroke(0,200,0);
  line(posx, 0, posx, height);

  if ( player.isPlaying() )
  {
    text("Press any key to pause playback.", 10, 20 );
  }
  else
  {
    text("Press any key to start playback.", 10, 20 );
  }


if (keyPressed)
{
  {if(key == 'b')
  if ( player.isPlaying() )
  {
    player.pause();

  }

  // if the player is at the end of the file,
  // we have to rewind it before telling it to play again
  else if ( player.position() == player.length() )
  {
    player.rewind();
    player.play();
  }
  else
  {
    player.play();
  }
  }}}`

and the Arduino script I used to generate the 0s and1s:

`Serial.begin(115200);

}

// the loop routine runs over and over again forever:
void loop() {
  if (Serial.available())
   { // If data is available to read,
     val = Serial.read(); // read it and store it in val
   }
   if (val == '1')
   {
  // read the input pin:

  // print out the state of the button:
  Serial.println("0");
  delay(1000);        // delay in between reads for stability
  Serial.println("1");
  delay(1000);
  Serial.println("0");
  delay(1000);        // delay in between reads for stability
  Serial.println("1");
  delay(1000);
  Serial.println("0");
  delay(1000);        // delay in between reads for stability
  Serial.println("1");
  delay(1000);Serial.println("0");
  delay(1000);        // delay in between reads for stability
  Serial.println("1");
  delay(1000);
   }


}
`

I'm using an input from processing ( a mouse click right now) to initialize the arduino code that does the 0s and 1s.

I then tried using the processing script with my actual arduino code:

` #include "eott.h"
  boolean Button1flag= LOW; // these are flags... I don't know why these are here
  boolean Button2flag= LOW;
  boolean Button3flag= LOW;

  int Buttonstate1 ; // these are the button states, read from the arduino
  int Buttonstate2 ;
  int Buttonstate3 ;


  int A=0;
  int B=0;
  int C=0;

  int i=0; // i will drive the array row change


  /* this is the array that would correspond to the song, a poor substitute for a MIDI file but simple. every row is a 25 ms block of the song.
  This is a test , ideally the array would be stored outside the code so I can call different 'songs'*/




  long Delay= 137.6121539054329; //this is the delay, and the duration for which each loop will run
  long t=0; // millis wil keep track of the time

void setup() {

// First define all the inputs and outputs
  pinMode(11,INPUT); // Pins 2,3,4 are the inputs where the buttons will be connected
  pinMode(12,INPUT);
  pinMode(13,INPUT);
  pinMode(2,OUTPUT); // Pins 11,12,13 are the outputs where the vibration motors will be connected (and mounted to the vibrators)
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(8,OUTPUT);
  Serial.begin(115200); // start the serial code at 9600 bpa
}

void loop() {
    if (i<=167)
 {
  i++;
 }
else {i=0;}//{while(1);}
 A= array[i][0];
 B= array[i][1];
 C= array[i][2];
   digitalWrite(2,A);
   digitalWrite(3,B);
   digitalWrite(4,C);
   digitalWrite(8,LOW);


  // put your main code here, to run repeatedly:
while (millis()<=t+Delay) // run the loop while the current value of millis is less than the sum of the previous time and the delay value
{
   Buttonstate1 = digitalRead(11); // these are the button states, read from the arduino
   Buttonstate2 = digitalRead(12);
   Buttonstate3 = digitalRead(13);

  if (Buttonstate1==A) //first condition: is button1 equal to the corresponding array value?
      {if (Buttonstate2==B) // second condition
          {if  (Buttonstate3==C) // basically if all three conditions are not met, the output is false
              {
                Serial.println("1"); // send a signal to processing to increase the volume of the song to signify success
                digitalWrite(8,HIGH);
                }
              }


  }
  else {
        Serial.println("0"); // this will tell processing to reduce the volume of the song, signifying failure.
        digitalWrite(8, LOW);
        }
  }
  t=millis();

/*
Serial.print(A);{0,0,0},

Serial.print("\t");
Serial.print(B);
Serial.print("\t");
Serial.print(C);
Serial.print("\t");
*/
}

`

This code takes an array (stored in eott.h) and outputs the array values to LEDs, while looking for input from buttons corresponding to the LEDs. if all three buttons match with the array value, it prints a "1" to the serial port, else it prints a "0".

but in this case , the code shows me an error NumberFormatException for input string "00" the values inside the quotes keeps changing every time I try to run the program. It then proceeds to crash.

Any help would be greatly appreciated, Thank you!

Procesing with Jfree Chart

$
0
0

Hi,

I saw video on internet where they are receiving serial data & plotting a graph using Java & Jfree Chart.

Here is the link of video. Source code is open.

image

Here is the source code link.

https://www.youtube.com/redirect?q=http://www.farrellf.com/arduino/SensorGraph.java&amp;redir_token=n6DitzxrIYtUbj3AGqFq9PO8z3J8MTQ0OTI5NTU0NEAxNDQ5MjA5MTQ0

Main beauty of graph is zoom in , zoom out, print & save option, which you can see at the end of video.

I want to make same type chart with processing.

Can some one help me.

Arduino PID Font end

$
0
0

Alright so I am not really sure how to word this issue. But I am trying to use a arduino for PID control. The code for this has been done and seems to work well, The dev of this code also did a Front end to tune the PID in real time. All that info can be found here http://playground.arduino.cc/Code/PIDLibrary the issue is with his front end. When using the newer 3.0 and 3.0.1 I get a size error. Using the older 1.5.1 I get a "The function valueLabel() does not exist". And I can't find a answer to this. And I also cant seem to find much info on how to run the older alpha stuff to see if that can work. I have tried to contact the dev but to no avail. And as far as I can tell i have the controlP5 and processing.serial installed in the correct location. I am a total noob to coding but I can get by just fine for most things. This is beyond what I know or really even how to figure out a solution to this. As i have no experiance in coding. Any help would be absolutely amazing. Thanks

My sketch reads one pixel from arduino, then gives me an ArrayIndexOutOfBoundsException

$
0
0

Dear Forum,

I'm building a drawbot that draws bitmaps. I'm almost there -thanks to the good people here-, but I can't get my head around this issue here.

I have a code that can parse coordinates from a string from my arduino, display the corresponding pixel on screen and send the brightness of that pixel back to the arduino. Then I have an arduino code that can move to the next pixel and send its location coordinates as a string.

This seems to work, but only for one pixel. Then processing sends me and ArrayIndexOutOfBoundsException. I guess I need to flush a string somewhere. But I don't know which one. The debuggerer somehow gets stuck on my sketch too. So some advice would be really helpful.

Here's the Processing sketch:

    import processing.serial.*; //import the Serial library

    Serial myPort;  //the Serial port object
    String strIn = "";  //Declare a string with name strIn, this will store the coordinates received from the arduino
    String strOut = "";  //Declare a string with name strOut, this will store the coordinates and corrseponding geryvalue of a pixel in the bitmap.
    String portName = "";  //apparently this is necessary
    String coordinates;
    int locX= 0;
    int locY= 0;

    PImage img;

    void setup()
    {

      size(182, 262);  //This is the size of the canvas and the range of the printer //<>//
      // Make a new instance of a PImage by loading an image file
      img = loadImage("parel.bmp");
      tint(255, 100);
      image (img, 0, 0);
      String portName = Serial.list()[0];
      myPort = new Serial(this, portName, 9600);
    }


    void draw()
    {
      if (myPort.available() > 0)                     // If data is available,
      {
        strIn = myPort.readStringUntil('\n');         // read it and store it in a string called strIn
        String[] coordinates = split(strIn, ",");
        //Cut the strIn string at the comma into two strings called coordinates.
        //We expect a message coming in something like "XXX,YYY"
        int locX = int(trim(coordinates[0]));        //This says that the first string is an integer called LocX
        int locY = int(trim(coordinates[1]));       //This says that the next string is an integer called LocX
        color pix = img.get(locX, locY);             //look up the colour of the requested pixel
        stroke(pix);                                 //show the pixel on the canvas on screen
        point(locX, locY);
        int Bright = round(brightness(pix));        //sending pix will send a large negative string, so we will just send the brightness
        strOut = locX + "," + locY + "," + Bright + "L" + "\n";  //put all the needed values into a string called strOut
        myPort.write(strOut);                                    //send it over serial port to the arduino to parse
        }
    }

And here's the arduino sketch:

// Jerry Wirerammer lives!

unsigned int xPos ;           //this integer sets the X position of the robot
unsigned int yPos   ;         //this integer sets the Y position of the robot
unsigned int xGoal  ;        //this integer sets the X location of the pixel where the mothership thinks the robot is. If the Robot is in position, it can put a dot.
unsigned int yGoal   ;       //this integer sets the X location of the pixel where the mothership thinks the robot is. If the Robot is in position, it can put a dot.
unsigned int GreyValue ;
char val;
int CanvasWidth = 182;
int CanvasHeight = 263;
String received ;

void setup() {

  Serial.begin(9600);                             //Serial communication, we are using it


  goHome();        //move to the 0,0 position.
}



void loop() {


  Serial.print(xPos);
  Serial.print(",");
  Serial.println(yPos);


  if ( Serial.available() ) // if data is available to read
  {
    val = Serial.read();    // read it and store it in 'val'
    if ( val != 'L' ) {     // if not an 'L'
      received += val;          // add it to the received string
    }

    else {
      // if 'L' was received (our designated termination char)
      //Look for the location of the first comma
      int commaIndex = received.indexOf(',');
      //  Search for the next comma just after the first
      int secondCommaIndex = received.indexOf(',', commaIndex + 1);

      String firstValue = received.substring(0, commaIndex);  //the first series of characters before the first comma
      String secondValue = received.substring(commaIndex + 1, secondCommaIndex); //the next series of characters between the first and second comma
      String thirdValue = received.substring(secondCommaIndex); //the final series of characters before the L that we didn't add to the "received" string

      xGoal = firstValue.toInt();
      yGoal = secondValue.toInt();
      GreyValue = thirdValue.toInt();

/*    debugging purposes only:
      Serial.print("received:");
      Serial.println(received);
      Serial.print("xGoal =");
      Serial.println(xGoal);
      Serial.print("yGoal =");
      Serial.println(yGoal);
      Serial.print("xPos =");
      Serial.println(xPos);
      Serial.print("yPos =");
      Serial.println(yPos);
*/

      received = "";                // Flush the string so we can receive new data
    }
  }
  else {
    delay (1000); // wait a bit and try again
  }


  if (xGoal == xPos) {
    if (yGoal == yPos) {
      MoveOn();
    }
  }
}


void MoveOn() //this subroutine tells the robot how to move to the next position.
{
  if (xPos != CanvasWidth) {   //if we are not at the end of the x axis
    xPos = xPos + 1;          //and adjust x position by increasing by one
  }
  else if (yPos != CanvasHeight) { //if we are not at the end of the y axis
    xPos = 0;           //and adjust x position to its starting value
    yPos = yPos + 1;                  //and adjust y position by increasing by one
  }
  else {
    delay(1);                       //Do nothing. This will make the robot print the last pixel over and over again.
  }
}




void goHome() //this subroutine tells the robot how to move to position 0,0
{
  while (xPos != 0) {         //if we are not x position 0
    xPos = xPos - 1;          //and adjust x position by increasing by one
    //this will repeat until we are at position x=0
  }

  while (yPos != 0) {         //if we are not x position 0
    yPos = yPos - 1;          //and adjust x position by increasing by one
  }
}

FFT code for audio spectrum analyzer

$
0
0

Hey, I'm currently making the spectrum analyzer off this website. http://www.instructables.com/id/Arduino-Processing-Audio-Spectrum-Analyzer/ I'm using a different LED screen, Mine is a 16x32 from adafruit. I've changed and got my arduino portion of the code to work but I'm getting an error that I'm unfamiliar with from processing. I read some people had issues with this project trying to upload the code to processing 3 because originally it was programmed on processing 1. Im running 1.5.1.

Any help is much appreciated!

The line of code causing the problem is:

port = new Serial(this, Serial.list()[1],9600); //set baud rate

This is the error I'm receiving:

WARNING: RXTX Version mismatch Jar version = RXTX-2.2pre1 native lib Version = RXTX-2.2pre2 Exception in thread "Animation Thread" java.lang.ArrayIndexOutOfBoundsException: 1 at Audio_Spectrum_to_Arduino3216_doublebar_pde.setup(Audio_Spectrum_to_Arduino3216_doublebar_pde.java:68) at processing.core.PApplet.handleDraw(Unknown Source) at processing.core.PApplet.run(Unknown Source) at java.lang.Thread.run(Thread.java:662)

Here is the entire code:

                            import ddf.minim.analysis.*;
                            import ddf.minim.*;
                            import processing.serial.*; //library for serial communication

                            Serial port; //creates object "port" of serial class

                            Minim minim;
                            AudioInput in;
                            FFT fft;
                            float[] peaks;

                            int peak_hold_time = 1;  // how long before peak decays
                            int[] peak_age;  // tracks how long peak has been stable, before decaying

                            // how wide each 'peak' band is, in fft bins
                            int binsperband = 5;
                            int peaksize; // how many individual peak bands we have (dep. binsperband)
                            float gain = 40; // in dB
                            float dB_scale = 2.0;  // pixels per dB

                            int buffer_size = 1024;  // also sets FFT size (frequency resolution)
                            float sample_rate = 44100;

                            int spectrum_height = 176; // determines range of dB shown

                            int[] freq_array = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
                            int i,g;
                            float f;


                            float[] freq_height = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};  //avg amplitude of each freq band

                            void setup()
                            {
                              size(200, 200);

                              minim = new Minim(this);
                              port = new Serial(this, Serial.list()[1],9600); //set baud rate

                              in = minim.getLineIn(Minim.MONO,buffer_size,sample_rate);

                              // create an FFT object that has a time-domain buffer
                              // the same size as line-in's sample buffer
                              fft = new FFT(in.bufferSize(), in.sampleRate());
                              // Tapered window important for log-domain display
                              fft.window(FFT.HAMMING);

                              // initialize peak-hold structures
                              peaksize = 1+Math.round(fft.specSize()/binsperband);
                              peaks = new float[peaksize];
                              peak_age = new int[peaksize];
                            }


                            void draw()
                            {
                            for(int k=0; k<16; k++){
                            freq_array[k] = 0;
                            }

                              // perform a forward FFT on the samples in input buffer
                              fft.forward(in.mix);

                            // Frequency Band Ranges
                              freq_height[0] = fft.calcAvg((float) 0, (float) 50);
                              freq_height[1] = fft.calcAvg((float) 51, (float) 69);
                              freq_height[2] = fft.calcAvg((float) 70, (float) 94);
                              freq_height[3] = fft.calcAvg((float) 95, (float) 129);
                              freq_height[4] = fft.calcAvg((float) 130, (float) 176);
                              freq_height[5] = fft.calcAvg((float) 177, (float) 241);
                              freq_height[6] = fft.calcAvg((float) 242, (float) 331);
                              freq_height[7] = fft.calcAvg((float) 332, (float) 453);
                              freq_height[8] = fft.calcAvg((float) 454, (float) 620);
                              freq_height[9] = fft.calcAvg((float) 621, (float) 850);
                              freq_height[10] = fft.calcAvg((float) 851, (float) 1241);
                              freq_height[11] = fft.calcAvg((float) 1242, (float) 1600);
                              freq_height[12] = fft.calcAvg((float) 1601, (float) 2200);
                              freq_height[13] = fft.calcAvg((float) 2201, (float) 3000);
                              freq_height[14] = fft.calcAvg((float) 3001, (float) 4100);
                              freq_height[15] = fft.calcAvg((float) 4101, (float) 5600);


                            // Amplitude Ranges  if else tree
                              for(int j=0; j<16; j++){
                                if (freq_height[j] < 200000 && freq_height[j] > 200){freq_array[j] = 16;}
                                else{ if (freq_height[j] <= 300 && freq_height[j] > 150){freq_array[j] = 15;}
                                else{ if (freq_height[j] <= 250 && freq_height[j] > 125){freq_array[j] = 14;}
                                else{ if (freq_height[j] <= 200 && freq_height[j] > 100){freq_array[j] = 13;}
                                else{ if (freq_height[j] <= 160 && freq_height[j] > 90){freq_array[j] = 12;}
                                else{ if (freq_height[j] <= 150 && freq_height[j] > 75){freq_array[j] = 11;}
                                else{ if (freq_height[j] <= 140 && freq_height[j] > 65){freq_array[j] = 10;}
                                else{ if (freq_height[j] <= 120 && freq_height[j] > 50){freq_array[j] = 9;}
                                else{ if (freq_height[j] <= 50 && freq_height[j] > 45){freq_array[j] = 8;}
                                else{ if (freq_height[j] <= 45 && freq_height[j] > 40){freq_array[j] = 7;}
                                else{ if (freq_height[j] <= 40 && freq_height[j] > 35){freq_array[j] = 6;}
                                else{ if (freq_height[j] <= 35 && freq_height[j] > 30){freq_array[j] = 5;}
                                else{ if (freq_height[j] <= 30 && freq_height[j] > 15){freq_array[j] = 4;}
                                else{ if (freq_height[j] <= 15 && freq_height[j] > 10){freq_array[j] = 3;}
                                else{ if (freq_height[j] <= 10 && freq_height[j] > 5){freq_array[j] = 2;}
                                else{ if (freq_height[j] <= 5 && freq_height[j] >= 1 ){freq_array[j] = 1;}
                                else{ if (freq_height[j] < 1 ){freq_array[j] = 0;}
                              }}}}}}}}}}}}}}}}}

                              //send to serial
                              port.write(0xff); //write marker (0xff) for synchronization

                              for(i=0; i<16; i++){
                                port.write((byte)(freq_array[i]));
                              }
                              //delay(2); //delay for safety
                            }


                            void stop()
                            {
                              // always close Minim audio classes when you finish with them
                              in.close();
                              minim.stop();

                              super.stop();
                            }

I can't get processing to respond on my arduino input

$
0
0

Hello, For a project I'm trying to make a game with processing and arduino. I'm making a game where you can move a basketball hoop to the left and right off the screen to catch falling basketballs. I'm trying to get the hoop to move to the right when the button is pressed and to the left when it isn't. For my arduino i'm using the 'button' code from the examples library.

My problem is that the hoop only moves to the left and doesn't move to the right when I press the button. Can somebody please see what I'm doing wrong?

my processing code is as follows:

///////////////////////////////////////////////////////////////////////

import processing.serial.*;
import cc.arduino.*;

Arduino arduino;


int buttonPin = 2;

int buttonState = 0;

int Xbas = 0;  // X coördinate for basket



void setup() {
  size(1350, 900);
  smooth();
  arduino = new Arduino(this, Arduino.list()[0], 100);
  arduino.pinMode(buttonState, Arduino.INPUT);
}

void Basket (int x, int y) {
  background(100);
  strokeWeight(1);
  pushMatrix();
  translate(width/2, height);
  for (int i = Xbas - 100; i <= Xbas + 40; i += 20) {
    line(i, -150, i + 30, -10);
  }
  for (int i = Xbas - 40; i <= Xbas + 100; i += 20) {
    line(i, -150, i - 30, - 10);
  }
  line(Xbas + 60, - 150, Xbas + 80, - 70);
  line(Xbas + 80, - 150, Xbas + 90, - 110);
  line(Xbas - 60, - 150, Xbas - 80, - 70);
  line(Xbas - 80, - 150, Xbas - 90, - 110);
  fill(#CE3419);
  ellipse(Xbas, -150, 200, 30);
  fill(100);
  ellipse(Xbas, -150, 130, 10);
  popMatrix();
}


void draw() {

  Basket (0, 0);


  if (arduino.digitalRead(buttonState) == Arduino.LOW) {
    Xbas += 2;
  } else if (arduino.digitalRead(buttonState) == Arduino.HIGH) {
    Xbas -= 2;
  }
}

//////////////////////////////////////////////////////////////////

Why does my laptop not connect to my other laptop?

$
0
0

So I have this code, and it doesn't want to connect to my server file. It should be able to switch two LED's on and off..

Client:

import processing.net.*; import processing.serial.*; Client c; Serial port; int incomingbyte; void setup() { c = new Client(this, "127.0.0.1", 12345); port = new Serial(this, Serial.list()[0], 9600); } void draw() { if (c.available()>0) { incomingbyte = c.read(); port.write(incomingbyte); println(incomingbyte); } }

Server: import processing.net.*; Server s; void setup() { size(400,400); rectMode(RADIUS); s = new Server(this, 12345); } void draw() { background(0); if (mouseX > 0 && mouseX < 200 && mouseY > 0 && mouseY < 400) { fill(0,200,0); rect(0,0,200,400); s.write('H'); } else{ s.write("L"); } if (mouseX > 200 && mouseX < 400 && mouseY > 0 && mouseY < 400) { fill(200,0,0); rect(300,0,100,400); s.write('K'); } else { s.write('J'); } if (mousePressed){ s.write('H'); s.write('K'); } }

Arduino: const int ledPin = 8; // the pin that the LED is attached to const int ledPin1 = 7; int incomingByte; // a variable to read incoming serial data into void setup() { // initialize serial communication: Serial.begin(9600); // initialize the LED pin as an output: pinMode(ledPin, OUTPUT); pinMode(ledPin1, OUTPUT); } void loop() { // see if there's incoming serial data: if (Serial.available() > 0) { incomingByte = Serial.read(); if (incomingByte == 'H') { digitalWrite(ledPin, HIGH); } if (incomingByte == 'L') { digitalWrite(ledPin, LOW); } if (incomingByte == 'K') { digitalWrite(ledPin1, HIGH); } if (incomingByte == 'J') { digitalWrite(ledPin1, LOW); } } }

Trying to make my countdown faster in Processing Photo Booth

$
0
0

Please help. I am a total noob, and I need to make the countdown faster in processing + it doesn't capture everything. Some shots are missing/not taken.

import cc.arduino.*;
import org.firmata.*;


import processing.video.*;
import processing.serial.*;
Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

Capture video;


int a = 1024; // width of window
int b = 768;  // height of window
int x = 100;  // x- position text
int y = 700; // y- position text
int capnum = 0;
int countdowntimer = 10;
int globalframecount = 0;
PImage aj;
PImage bj;
PImage cj;
PImage dj;
color black = color(0);
color white = color(255);
int numPixels;

void setup() {
  String portName = Serial.list () [2];
  myPort = new Serial (this, portName, 9600);
  print(Serial.list ());
  frameRate (25);
  size(1024, 768); // Change size to 320 x 240 if too slow at 640 x 480
  strokeWeight(5);

  // This the default video input, see the GettingStartedCapture
  // example if it creates an error
  video = new Capture(this, width, height, 30);

  // Start capturing the images from the camera
  video.start();

  numPixels = video.width * video.height;
  noCursor();
  smooth();
}

void draw() {
  if ( myPort.available() > 0) {
    val = myPort.read();
  }
  if (val>0) {
    globalframecount = 1;
  }
  println(val);
  if (video.available()) {
    video.read();
    video.loadPixels();
    int threshold = 127;
    float pixelBrightness;
    loadPixels();
    for (int i = 0; i<numPixels; i++) {
      pixelBrightness = brightness(video.pixels[i]);
      if (pixelBrightness > threshold) {
        pixels [i] = white;
      } else {
        pixels[i] = black;
      }
    }
    updatePixels();
    int testValue = get(mouseX, mouseY);
    float testBrightness = brightness(testValue);
    if (testBrightness > threshold) { // If the test location is brighter than
      fill(black); // the threshold set the fill to black
    } else { // Otherwise,
      fill(white); // set the fill to white
    }
  }



  PFont fontA = loadFont("Serif-48.vlw");
  textFont(fontA);


  noFill();

  switch(val) {

  case 's':
    globalframecount = 1;
    //  background(0);

    break;

  case 't':
    //null
    break;
  default:
    //println("Zulu");   // Prints "Zulu"
    break;
  }

  if (globalframecount == 25) {
    countdowntimer = 9;
  }
  if (globalframecount == 50) {
    countdowntimer = 8;
  }
  if (globalframecount == 75) {
    countdowntimer = 7;
  }
  if (globalframecount == 100) {
    countdowntimer = 6;
  }
  if (globalframecount == 125) {
    countdowntimer = 5;
  }
  if (globalframecount == 150) {
    countdowntimer = 4;
  }
  if (globalframecount == 175) {
    countdowntimer = 3;
  }
  if (globalframecount == 200) {
    countdowntimer = 2;
  }
  if (globalframecount == 225) {
    countdowntimer = 1;
  }
  //    image (video, 0, 0);

  if ((globalframecount < 250) & (globalframecount > 0)) {
    textFont(fontA, 30);
    fill(0);
    text ("Preview! Get ready for your photo in "+str(countdowntimer), x+2, y);
    text ("Preview! Get ready for your photo in "+str(countdowntimer), x, y+2);
    text ("Preview! Get ready for your photo in "+str(countdowntimer), x-2, y);
    text ("Preview! Get ready for your photo in "+str(countdowntimer), x, y-2);
    textFont(fontA, 30);
    fill(255);
    text ("Preview! Get ready for your photo in "+str(countdowntimer), x, y);
    //text (countdowntimer, width-250, y);
    globalframecount++;
  }

  if ((globalframecount >= 250) & (globalframecount < 500)) {
    // image (video, 0, 0);

    if ((globalframecount > 250) & (globalframecount < 311))
    {
      textFont(fontA, 100);
      fill(0);
      text (str(countdowntimer), width/2+2, height/2);

      text (str(countdowntimer), width/2, height/2+2);

      text (str(countdowntimer), width/2-2, height/2);

      text (str(countdowntimer), width/2, height/2-2);

      fill(255);
      text (str(countdowntimer), width/2, height/2-2);
    }
    if (globalframecount == 250)
    {
      countdowntimer = 3;
    }

    if (globalframecount == 270)
    {
      countdowntimer = 2;
    }

    if (globalframecount == 290)
    {
      countdowntimer = 1;
    }

    if (globalframecount == 312) {
      background(255);
    }
    if (globalframecount == 313) {
      saveFrame(capnum+".jpeg");
      aj = loadImage(capnum+".jpeg");
      capnum++;
    }

    if ((globalframecount > 314) & (globalframecount < 373))
    {
      textFont(fontA, 100);
      fill(0);
      text (str(countdowntimer), width/2+2, height/2);

      text (str(countdowntimer), width/2, height/2+2);

      text (str(countdowntimer), width/2-2, height/2);

      text (str(countdowntimer), width/2, height/2-2);

      fill(255);
      text (str(countdowntimer), width/2, height/2-2);
    }
    if (globalframecount == 314)
    {
      countdowntimer = 3;
    }

    if (globalframecount == 335)
    {
      countdowntimer = 2;
    }

    if (globalframecount == 355)
    {
      countdowntimer = 1;
    }

    if (globalframecount == 374) {
      background(255);
    }

    if (globalframecount == 375) {
      saveFrame(capnum+".jpeg");
      bj = loadImage(capnum+".jpeg");
      capnum++;
    }

    if ((globalframecount > 375) & (globalframecount < 436))
    {
      textFont(fontA, 100);
      fill(0);
      text (str(countdowntimer), width/2+2, height/2);

      text (str(countdowntimer), width/2, height/2+2);

      text (str(countdowntimer), width/2-2, height/2);

      text (str(countdowntimer), width/2, height/2-2);

      fill(255);
      text (str(countdowntimer), width/2, height/2-2);
    }
    if (globalframecount == 376)
    {
      countdowntimer = 3;
    }

    if (globalframecount == 401)
    {
      countdowntimer = 2;
    }

    if (globalframecount == 420)
    {
      countdowntimer = 1;
    }

    if (globalframecount == 438) {
      background(255);
    }

    if (globalframecount == 439) {
      saveFrame(capnum+".jpeg");
      cj = loadImage(capnum+".jpeg");
      capnum++;
    }

    if ((globalframecount > 440) & (globalframecount < 497))
    {
      textFont(fontA, 100);
      fill(0);
      text (str(countdowntimer), width/2+2, height/2);

      text (str(countdowntimer), width/2, height/2+2);

      text (str(countdowntimer), width/2-2, height/2);

      text (str(countdowntimer), width/2, height/2-2);

      fill(255);
      text (str(countdowntimer), width/2, height/2-2);
    }
    if (globalframecount == 440)
    {
      countdowntimer = 3;
    }

    if (globalframecount == 460)
    {
      countdowntimer = 2;
    }

    if (globalframecount == 480)
    {
      countdowntimer = 1;
    }

    if (globalframecount == 497) {
      background(255);
    }

    if (globalframecount == 498) {
      saveFrame(capnum+".jpeg");
      dj = loadImage(capnum+".jpeg");
      capnum++;
    }

    if (globalframecount == 499) {
      fill(255);
      background(0);
      rect(width/11, height/10, (width-240), (height-100));
      image(aj, width/8, height/8, width/3, height/3);
      image(bj, 4*(width/8), height/8, width/3, height/3);
      image(cj, width/8, 4*(height/8), width/3, height/3);
      image(dj, 4*(width/8), 4*(height/8), width/3, height/3);
      fill(0);
      text ("take a picture it will last longer", x, y);
      saveFrame("multipage"+capnum+".jpeg");
      globalframecount = -1;
    }


    //delay(50);
    globalframecount++;
  }
}

How to verify the Serial.list()

$
0
0

Hi guys, i'm trying to figure out how can i know what are the ports in the serial array. I'm using this code:

    while(i<Serial.list().length&&!trovato){
              if((Serial.list()[i]=="COM1")||(Serial.list()[i]=="COM2")||(Serial.list()[i]=="COM3")||(Serial.list()[i]=="COM4")||(Serial.list()[i]=="COM5"))

The if condition is always false, but if i print the Serial.list() array i can see that i have a COM4 and the lenght is 1. I need to use that because i don't know if arduino will be connected on another COM on an other PC.

The full if is

        int i=0;
                while(i<Serial.list().length&&!trovato){
                  if((Serial.list()[i]=="COM1")||(Serial.list()[i]=="COM2")||(Serial.list()[i]=="COM3")||(Serial.list()[i]=="COM4")||(Serial.list()[i]=="COM5")){
                    pos=i;
                    trovato=true;
                  }
                  else
                  i++;
                }
                if(trovato){
                  porta= new Serial(this, Serial.list()[pos], 9600);
                  porta_connessa=true;
                }
                else
                  porta_connessa=false;

Thanks

Save input text via GUI Builder in a way that i can use it with a Arduino

$
0
0

I need your help! I'm sittin on a project for university. I have build a gui with the g4p guibuilder in processing. What i want, is that the text you enter in a textfield is saved somewhere in a way that you can use it via a arduino? How can i do that?

Sending a numerical variable from Processing to Arduino

$
0
0

I'm new in this world, and I'd know how to send a numerial variable Processing-->Arduino (not Arduino-->Processing!!).

I've got the programme for send only a letter, but i don't know hoy to send a number (0-100).

Thanks!

2 Microcontrollers in Arduino IDE, getting strange output on Processing

$
0
0

Hello, so i'm working on a project with 2 arduinos and processing. The code works fine coming from 1 arduino bu when I integrate the processing to use 2 serial connects with if statements For processing forum processing forum not working

IN the strange one I am using buttons Processing Code

import processing.serial.*; Serial myPort, myPort2, myPort3, myPort4, myPort5; // The serial port int xPos = 400; // horizontal position of the graph float inByte = 0; int lastxPos=401; int lastheight=700; int lastheight2=700; float inByte2 =0; int rectX, rectY; // Position of square button int rectX2, rectY2; // Postion of second Square button int rectX3, rectY3; int rectX4, rectY4; int rectX5, rectY5; int rectSize = 20; // Diameter of rect int rectSize2 = 20; int rectSize3 = 20; int rectSize4 = 20; int rectSize5 = 20; color rectColor,baseColor; color rectHighlight; color currentColor; boolean rectOver = false; boolean rectOver2 = false; boolean rectOver3 = false; boolean rectOver4 = false; boolean rectOver5 = false; void setup() { size(1024, 700); //rectColor = color(0); //rectHighlight = color(0); rectX = width-250-rectSize-10; rectY = height/3-rectSize/2; rectX2 = width-200-rectSize2-10; rectY2 = height/3-rectSize2/2; rectX3 = width-150-rectSize3-10; rectY3 = height/3-rectSize3/2; rectX4 = width-100-rectSize4-10; rectY4 = height/3-rectSize4/2; rectX5 = width-50-rectSize5-10; rectY5 = height/3-rectSize5/2; myPort = new Serial(this, "COM10", 115200); myPort2 = new Serial(this, "COM12", 9600); myPort.bufferUntil('\n'); myPort2.bufferUntil('\n'); background(0,0,0); } void draw() { } void update(int x, int y) { if (overRect(rectX, rectY, rectSize, rectSize)) { rectOver = true; rectOver2 = rectOver3 = rectOver4= rectOver5 = false; } else if (overRect2(rectX2, rectY2, rectSize2, rectSize2)) { rectOver2 = true; rectOver = rectOver3 = rectOver4= rectOver5 = false; } else if (overRect3(rectX3, rectY3, rectSize3, rectSize3)) { rectOver3 = true; rectOver = rectOver2 = rectOver4= rectOver5 = false; } else if (overRect4(rectX4, rectY4, rectSize4, rectSize4)) { rectOver4 = true; rectOver = rectOver2 = rectOver3 = rectOver5 = false; } else if (overRect5(rectX5, rectY5, rectSize5, rectSize5)) { rectOver5 = true; rectOver = rectOver2 = rectOver3 = rectOver4 = false; } else { rectOver = rectOver2 = rectOver3 = rectOver4= rectOver5 = false; } } /* void mousePressed() { if (rectOver) { // currentColor = rectColor; // serialEvent(myPort); } } */ boolean overRect(int x, int y, int width, int height) { if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) { return true; } else { return false; } } boolean overRect2(int x, int y, int width, int height) { if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) { return true; } else { return false; } } boolean overRect3(int x, int y, int width, int height) { if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) { return true; } else { return false; } } boolean overRect4(int x, int y, int width, int height) { if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) { return true; } else { return false; } } boolean overRect5(int x, int y, int width, int height) { if (mouseX >= x && mouseX <= x+width && mouseY >= y && mouseY <= y+height) { return true; } else { return false; } } void serialEvent (Serial Port) { // get the ASCII string: strokeWeight(10); fill(255,255,255); textSize(15); text("Module 1, IR1-Foyer", 50 ,80); text("Module 2, IR1-Reception", 50, 120); update(mouseX,mouseY); textSize(15); fill(255,255,255); textSize(15); text("Full ------------------------------", 200, 20); text("Empty ----------------------------", 200, 690); text(" 75% -----------------------------", 200, 175); text(" 50% -----------------------------", 200, 350); text(" 25% -----------------------------", 200, 525); text("Water levels tank 1", 650, 690); text("Volume measure 07/12/2015", 700,20); strokeCap(SQUARE); stroke(200,200,200); strokeWeight(10); line(320, 1023, 320, 1); line(480,1023,480, 1); rect(rectX, rectY, rectSize, rectSize); rect(rectX2, rectY2, rectSize2, rectSize2); rect(rectX3, rectY3, rectSize3, rectSize3); rect(rectX4, rectY4, rectSize4, rectSize4); rect(rectX5, rectY5, rectSize5, rectSize5); strokeWeight(150); if (Port == myPort) { String inString = myPort.readStringUntil('\n'); if (inString != null) { inString = trim(inString); inByte = float(inString); inByte = map(inByte, 0, 1023, 0, height); if(rectOver == true){ textSize(15); fill(255,255,0); text("Module 1, IR1-Foyer", 50 ,80); strokeWeight(150); if ( int(height-inByte) >= (lastheight)) { stroke(0,0,0); line(lastxPos, lastheight, xPos, height - inByte); delay(10); if(lastheight > 525) { textSize(18); fill(255,0,0); text(" <----------- Warning!", 500, 525); } else if(lastheight < 525) { textSize(18); fill(0,0,0); text(" <----------- Warning!", 500, 525); } } else if ( int(height-inByte) <= (lastheight)) { stroke(0,0,200); line(lastxPos, lastheight, xPos, height - inByte); if(lastheight > 525) { textSize(18); fill(255,0,0); } else if(lastheight < 525) { textSize(18); fill(0,0,0); text(" <----------- Warning!", 500, 525); } } // } } } } // String inString = Port.readStringUntil('\n'); else if (Port == myPort2) { String inString = myPort2.readStringUntil('\n'); if (inString != null) { inString = trim(inString); inByte = float(inString); inByte = map(inByte, 0, 1023, 0, height); // if(mousePressed){ if(rectOver2 == true){ textSize(15); fill(255,255,0); text("Module 1, IR1- reception", 50 ,120); if ( int(height-inByte) >= (lastheight)) { stroke(0,0,0); line(lastxPos, lastheight, xPos, height - inByte); delay(10); if(lastheight > 525) { textSize(18); fill(255,0,0); text(" <----------- Warning!", 500, 525); } else if(lastheight < 525) { textSize(18); fill(0,0,0); text(" <----------- Warning!", 500, 525); } } else if ( int(height-inByte) <= (lastheight)) { stroke(0,0,200); line(lastxPos, lastheight, xPos, height - inByte); if(lastheight > 525) { textSize(18); fill(255,0,0); } else if(lastheight < 525) { textSize(18); fill(0,0,0); text(" <----------- Warning!", 500, 525); } } } else { // stroke(0,0,0); //line(700, 1023, 700, height); } lastxPos=xPos; lastheight= int(height-inByte); } // } } else { // stroke(0,0,0); //line(700, 1023, 700, height); } }

Thanks in advance


Interactive 3D

$
0
0

Hi there,

I'm creating an Interactive 3D prototype for a client which involves Arduino connected buttons launching individaul webpages in a PC browser using Processing

I'm working with the Arduino and about 50 buttons. When I press one of the buttons I want (on the pc side) a specific webpage, which displays a 3d file to load. There are 52 of these "Arduino" buttons and 52 associated webpages showing 3d.

I ONLY require the Processing to load and display the webpages (any demo webpages will do to get it working). However the Processing is giving me two hurdles I'm stuck with

1) The Processing will only launch the first wepage on the list - regardless of which of the 50 buttons is pressed on the Arduino side (button associated LEDS seem to indicate it is a Processing mistake I'm making).

2) Processing launches a new tab on the Internet browser every time a button is pressed, whereas I only want it to load in the same Tab.

Processing Code

import processing.serial.*; Serial myPort; int houseID=0;

String listHouseURLs[] = { "http://" + "showroom.cosmotiles.co.uk/black/black-wall-tiles/bohemia-negro", // this is the first house, it's ID is 0 "http://" + "showroom.cosmotiles.co.uk/white-ivory/white-ivory-wall-tiles/tuareg-arena", // this is the second house, it's ID is 1 "http://" + "showroom.cosmotiles.co.uk/brown-tiles/brown-tiles-wall-tiles/bohemia-moka", // third house, 2 "http://" + "showroom.cosmotiles.co.uk/blue-grey/blue-grey-wall-floor-tiles/gambini-argyle", // fourth house, 3 "http://" + "showroom.cosmotiles.co.uk/mixed-colours/mixed-colours-wall-tiles/planet-azul" // fifth house, 4. };

void setup() { println(Serial.list()); String portnum=Serial.list()[0]; // replace 0 with 1 if you have to myPort= new Serial(this, portnum, 9600); myPort.buffer(16); }

void draw() { // empty function }

void serialEvent(Serial myPort){ String inputString= myPort.readString(); houseID = int(inputString); link(listHouseURLs[houseID]); }

Any assistance is resolving this would be gratefully appreciated, it's all new stupp to me and I've hit a bit of a wall.

Thanks

Cathal Brennan

Serial port gets disabled then null (Windows 10)

$
0
0

Strange, never seen this before. I am on a WIndows 10/Arduino Uno/Mega system where things work fine, in particular with respect to using the plainDSP shield along with its C++ library. I generate data on Arduino, transfer it to processing on my PC - via COM6 -> perfect.

On a new project, using PID to develop a flight controller, I donwloaded the PID_Front_End_v03 and the control IP5 librairies. On the Arduino side things work fine. On the processing side after fixing a valueValue() function call which should really be getValueLabel(), I get this cryptic error COM5 for the UNO, COM6 for the Mega : Error, disabling serialEvent() for COM5 null The serial port does get opened but some time before Inside the draw loop, I get the close port message. I tried debugging the program however the Processing debugger seems to have a mind of its own. Stepping does not really work and break points seem to get ignored. The draw function has simple code : void draw() { int counter; counter = 0; background(200); drawGraph(); drawButtonArea(); counter++; }

My idea was to step donw each line one at a time, see where the problem occurs, and then redo and step into the naughty function. That's assuing the debugger works as it should. But no. I manage to stop at background(200); but the if I try to step down one line at a time, does not do anything. If I put break points on each of the lines and do GO, stops at background(200); but not at the others. Furthermore, the close port message does not occur systematically on a first call to a function. I can stop several times at background(200); before it occurs.

There it is. Any ideas ???

Michèle

How to draw a complete color wheel?

$
0
0

Hello people,

I'm trying to create a program that I can use to control the LED strips inside my PC using Arduino. I currently have communication and a lot of other parts working already, but I am stuck on a small problem.

I am able to draw a color wheel or rectangle in this case that should represent all colors available. The program looks at the value under the mouse while it is pressed, and sends this to the Arduino. The problem I am having is that the colors nearest to the edge are not picked up as pure red (255,0,0), green or blue. The closest value I can get is: (255,32,32).

What I have tried so far is changing the size of the rectangle to exclude the missing colors being rendered off-screen. I have found that the code reading the color value under the cursor is correct - I did this by drawing a plain pure red rectangle in the corner, which returned the correct value (255,0,0). I also found that simply subtracting 32 from the values is incorrect, as on pure white you will find the value to be (223,223,223).

This causes significant problems with my LEDs, as a value of 32 on the PWM pin will light the corresponding color up by quite a bit because of the non-linear relationship between LED volt and brightness.

So to reiterate my question: how do I draw a color circle or rectangle from which I can get 100% red, blue and green as well?

Here is my code:

import processing.serial.*;

Serial myPort;    // The serial port
String inString;  // Input string from serial port
int lf = 10;      // ASCII linefeed
int[] rgb = new int[3];
PImage m;

void setup(){
  size(400,400);
  frameRate(120);
  smooth(4);
  ellipseMode(CENTER);
  background(255);

  colorMode(HSB, 400);
  for (int i = 0; i < 400; i++) {
    for (int j = 0; j < 400; j++) {
      stroke(i, j, 400);
      point(i, j);
    }
  }
  m=get();

  myPort = new Serial(this, Serial.list()[1], 9600);
  myPort.bufferUntil(lf);
}

void draw(){
  image(m,0,0);
  if(mousePressed){
    color c = get(mouseX,mouseY);
    fill(c);
    stroke(0);
    ellipse(mouseX,mouseY,30,30);
    rgb[0] = c >> 16 & 0xFF;
    rgb[1] = c >> 8 & 0xFF;
    rgb[2] = c & 0xFF;

    fill(0);
    text(rgb[0], 10,70);
    text(rgb[1], 10,90);
    text(rgb[2], 10,110);

    String test = ",";
    test += str(rgb[0]);
    test += "+";
    test += str(rgb[1]);
    test += "+";
    test += str(rgb[2]);
    test += "\n";

    myPort.write(test);
  }
  fill(0);
  text("Received: " + inString, 10,50);
}

void serialEvent(Serial p) {
  inString = p.readString();
}

How to use PC sounds to FFT for LEDs control with arduino?

$
0
0

Hello, i'm new to Processing and all of this.

I have been trying to make some LEDs react to sound. At the begining i started to use mp3 files and i got it to work, now i want to use real time sound coming from the PC to control those LEDs. So i used AudioInput instead of AudioPlayer and when i try to run it gives me the following error:

`==== JavaSound Minim Error ==== ====Unable to return TargetDataline: unsupported format - PCM_SIGNED 44100.0 Hz, 16 bit, stereo, 4 bytes/frame, little-endian

=== Minim Error === === Minim.getLineIn: attempt failed, could not secure an AudioInput. `

After some search i tried to enable Stereo Mix through the Sound options of Windows, and the error persists. Then for no much reason i connected my headphones to the front audio jack of my PC and hit run again, no errors were shown and everything was working as expected (besides the fact that i had to scale all the frequency bands so i didn't have to have the volume almost at max). But when i disconnect the headphones the LEDs stop reacting, and if i restart the program the errors are showed again.

Can anyone help me with this? Thank your very much.

P.S.: Don't know if it matters, but i have on my PC a Realtek integrated sound card a Nvidea graphics card connected with a HDMI cable to an Asus LCD monitor which has integrated speakers (so the sound comes from the monitor). The code i'm using is the following;

`import ddf.minim.*;
import ddf.minim.analysis.*; import processing.serial.*; import cc.arduino.*;

Arduino arduino;

Minim minim; AudioInput sound; FFT fft;

int redPin1 = 8; int greenPin1 = 7; int bluePin1 = 6;

int redPin2 = 2; int greenPin2 = 3; int bluePin2 = 4;

int redPin3 = 11; int greenPin3 = 12; int bluePin3 = 13;

int color_id = 0;

int common_cathode = 1;

void setup() { size(800, 600);

arduino = new Arduino(this, Arduino.list()[1], 57600);
for (int i = 0; i <= 13; i++) arduino.pinMode(i, Arduino.OUTPUT);
for (int i = 0; i <= 13; i++) arduino.digitalWrite(i,arduino.HIGH);

minim = new Minim(this);
sound = minim.getLineIn();
fft = new FFT(sound.bufferSize(), sound.sampleRate());

}

void draw() {
background(#151515);

fft.forward(sound.mix);

for (int i = 0; i < 513; i++){
  fft.scaleBand(i, 15);
}

strokeWeight(1.3);
stroke(#FFF700);

// frequency
pushMatrix();
  translate(250, 0);

  for(int i = 0; i < 0+fft.specSize(); i++) {
    line(i, height*4/5, i, height*4/5 - fft.getBand(i)*4);
    if(i%100==0) text(fft.getBand(i), i, height*4/5+20);
    if(i==200) {
      if(fft.getBand(i)>2) {
        setColor1(255,255,0);
        setColor3(255,255,0);
      }
      else if(fft.getBand(i)>1) {
        setColor1(255,0,255);
        setColor3(255,0,255);
      } else {
        setColor1(255,255,255);
        setColor3(255,255,255);
      }
    }
    if(i==50) {
      if(fft.getBand(i)>5) {
        color_id = (color_id+1)%4;
      } else if(fft.getBand(i)>3) {
        if(color_id==0) setColor2(0,255,0);
        else if(color_id==1) setColor2(0,255,255);
        else if(color_id==2) setColor2(0,0,255);
        else setColor2(255,0,0);
      } else if (fft.getBand(i) > 1){
       setColor1(0,255,255);
       setColor3(0,255,255);
      }
      else {
        setColor2(255,255,255);
      }
    }
  }
popMatrix();

stroke(#FF0000);

//waveform
for(int i = 250; i < sound.left.size() - 1; i++) {
  line(i, 50 + sound.left.get(i)*50, i+1, 50 + sound.left.get(i+1)*50);
  line(i, 150 + sound.right.get(i)*50, i+1, 150 + sound.right.get(i+1)*50);
  line(i, 250 + sound.mix.get(i)*50, i+1, 250 + sound.mix.get(i+1)*50);
}

noStroke();
fill(#111111);
rect(0, 0, 250, height);

textSize(24);
fill(#046700);
text("left amplitude", 10, 50);
text("right amplitude", 10, 150);
text("mixed amplitude", 10, 250);
text("frequency", 10, height*4/5);

}

void stop() { for (int i = 0; i <= 13; i++) arduino.digitalWrite(i,arduino.HIGH); sound.close();
minim.stop(); super.stop(); } void setColor1(int red, int green, int blue) { if(common_cathode==1) { red = 255-red; green = 255-green; blue = 255-blue; } arduino.digitalWrite(redPin1, red); arduino.digitalWrite(greenPin1, green); arduino.digitalWrite(bluePin1, blue);
} void setColor2(int red, int green, int blue) { if(common_cathode==1) { red = 255-red; green = 255-green; blue = 255-blue; } arduino.digitalWrite(redPin2, red); arduino.digitalWrite(greenPin2, green); arduino.digitalWrite(bluePin2, blue);
} void setColor3(int red, int green, int blue) { if(common_cathode==1) { red = 255-red; green = 255-green; blue = 255-blue; } arduino.digitalWrite(redPin3, red); arduino.digitalWrite(greenPin3, green); arduino.digitalWrite(bluePin3, blue);
}`

no Graph with data from Arduino?

$
0
0

tried a simple example to draw a Graph from arduino data. No graph visible? Running on Windows 10

import processing.serial.*;

Serial myPort; // The serial port int xPos = 0; // horizontal position of the graph

void setup () { // set the window size: size(400, 600);

// List all the available serial ports println(Serial.list());

// open Serial.list()[0]. // Open whatever port is the one you're using. myPort = new Serial(this, Serial.list()[1], 9600); // myPort = new Serial(this, "COM8", 9600);

// don't generate a serialEvent() unless you get a newline character: myPort.bufferUntil('\n'); // set inital background: //background(0); schwarzer Hintergrund background (100,100,255); } void draw () { // everything happens in the serialEvent() }

void serialEvent (Serial myPort) { // get the ASCII string: String inString = myPort.readStringUntil('\n');

if (inString != null) { // trim off any whitespace: inString = trim(inString); // convert to an int and map to the screen height: float inByte = float(inString);

inByte = map(inByte, 0, 1023, 0, height); println(inString); // to see if datas are incoming

// draw the line: stroke(0,0,0); line(xPos, height, xPos, height - inByte);

// at the edge of the screen, go back to the beginning: if (xPos >= width) { xPos = 0; background(0); //background (216,225,165); } else { // increment the horizontal position: xPos++; } } }

Viewing all 747 articles
Browse latest View live