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

data transfering from processing to arduino

$
0
0

Hi all,

I'm beginner to processing and arduino. i intend to transfer a series data ( e.g. a series number) from processing to arduino. this **numbers ** will turn a servo. i mean i want to send a series number from processing to arduino that these numbers control my servo position. I write two sketch, one of them for processing and another for arduino. but it seems processing does not sent any data to arduino or arduino unable to read data. i don't know what happens. please help. thanks a lot. Farrokh

===================================== Processing sketch : import processing.serial.*; Serial myPort; int i;

void setup(){ printArray(Serial.list()); myPort = new Serial(this, Serial.list()[0], 9600); }

void draw (){ for (i=0; i < 150 ; i+=10){ myPort.write(80); }

}

Arduino sketch:

include <Servo.h>

Servo myservo;
int pos = 0;

void setup() { Serial.begin(9600); myservo.attach(9); myservo.write(5); }

void loop() { while(!Serial.available()); myservo.write(Serial.read()); delay (100); }


Can arduino using processing be a joystick?

$
0
0

I've made a joystick and I made a test program on processing. My question is: can I play games with that joystick by programing it with processing?

Photo from webcam upload to twitter keeps posting same photo rather than new

$
0
0

`import twitter4j.conf.*; import twitter4j.*; import twitter4j.auth.*; import twitter4j.api.*;

import java.util.*; import processing.video.*;

import processing.serial.*;

int picCount = 0; Capture webcam; Twitter twitter;

Serial myPort; // The serial port String inString; // Input string from serial port int lf = 10; // ASCII linefeed

void setup() {

size(640, 480); webcam = new Capture(this, 640, 480);
String[] devices = Capture.list(); println(devices); webcam.start();

ConfigurationBuilder cb = new ConfigurationBuilder(); cb.setOAuthConsumerKey("****"); cb.setOAuthConsumerSecret("****"); cb.setOAuthAccessToken("****"); cb.setOAuthAccessTokenSecret("****");

TwitterFactory tf = new TwitterFactory(cb.build());

twitter = tf.getInstance();

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

void draw() {

if (webcam.available() == true) { webcam.read(); image(webcam, 0, 0); }

if (inString != null) {

inString = inString.trim();

int val = int(inString);



if (val == 1) {

  println("saving...");
  save("cam" + picCount + ".png");
  picCount++;

  //send tweet
  File file = new File("C:\\Users\\Jake\\Documents\\Processing\\Twitter test 2\\Twittertest2\\cam" + picCount + ".png");

  delay (3000);
  tweetPic(file, "");
}

} }

void testPassingFile(File _file) { println(_file.exists()); println(_file.getName()); println(_file.getPath()); println(_file.canRead()); }

void tweetPic(File _file, String theTweet) { try { StatusUpdate status = new StatusUpdate(theTweet); status.setMedia(_file); twitter.updateStatus(status); } catch (TwitterException te) { println("Error: "+ te.getMessage()); } }

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

How to control the user's keyboard

$
0
0

Hello, I'm currently trying to make an Arduino-based game controller, which will be composed of an Arduino sketch, and a Processing sketch. What I'm trying to do right now is to get the processing sketch to send keyboard signals to a computer, so it is as if a key actually were being pressed. Does anybody know a function or something else that I can use to do this? Thanks, ChopinCJ

adding background image

$
0
0

hello this is an open source program created by mr. choi im having trouble adding the background image in this program please help thank you expecting EOF found oscp5

/** --- PRE SETUP --- */
import processing.video.*;
import processing.serial.*;
import cc.arduino.*;
import controlP5.*;
import oscP5.*;
import netP5.*;

boolean initialized = false;
int w = 1280, h = 480;

//Open Sound Control Variables
OscP5 oscP5;

//controlP5 variables
ControlP5 cp5;
DropdownList serialPortDL, webcamLDL, webcamRDL;
int serialPortWidth = 100;
int webcamWidth = 250;
int itemHeight = 20;
int elements = 20;
int margins = 20;

//Arduino variables
Arduino arduino;
String serialPorts[];
boolean arduinoConnected = false;
int xPin = 9; int yPin = 8; int zPin = 10;
float xRot, yRot, zRot = 90.0; //y = base, x = mid, z = top

//Webcam variables
Capture webcamL;
Capture webcamR;
String camList[];
boolean webcamLConnected = false;
boolean webcamRConnected = false;

/** ----- SETUP ----- */

PImage bg;
int y;

void setup () {
  //set up screen
  w = displayWidth; h = displayHeight;
  size (w, h);
  bg = loadImage("ics.jpg");
}

void draw() {
  background(bg);

  stroke(226, 204, 0);
  line(0, y, width, y);

  y++;
  if(y > height) {
    y = 0;
  }
}


  //---create osc comms---\\
  oscP5 = new OscP5(this,5000);

  //---create GUI---\\
  cp5 = new ControlP5(this);
  //setup Arduino
  serialPorts = Arduino.list();
  serialPortDL = cp5.addDropdownList("Serial Port");
  serialPortDL.setPosition((w-serialPortWidth)/2, margins);
  serialPortDL.setItemHeight(itemHeight);
  serialPortDL.setSize(serialPortWidth,itemHeight*elements);
  for(int i=0; i < serialPorts.length; ++i) {
    serialPortDL.addItem(serialPorts[i], i);
  }
  //setup cameras
  camList = Capture.list();
  webcamLDL = cp5.addDropdownList("Left Camera");
  webcamLDL.setPosition(margins,margins);
  webcamLDL.setItemHeight(itemHeight);
  webcamLDL.setSize(webcamWidth,itemHeight*elements);
  webcamRDL = cp5.addDropdownList("Right Camera");
  webcamRDL.setPosition(w-webcamWidth-margins, margins);
  webcamRDL.setItemHeight(itemHeight);
  webcamRDL.setSize(webcamWidth,itemHeight*elements);
  for(int i = 0; i < camList.length; ++i) {
    webcamLDL.addItem(camList[i],i);
    webcamRDL.addItem(camList[i],i);
  }
}

/** --- MAIN LOOP --- */
void draw () {
  if(!initialized) {
    initialized = true;
    frame.setLocation(0,0);
  }
  background(130);

  //---update webcam info---\\
  if(webcamLConnected) {
    if (webcamL.available()) { webcamL.read(); }
    image (webcamL, w*.25, h/2, w/2, h);
  }
  if(webcamRConnected) {
    if (webcamR.available()) { webcamR.read(); }
    image (webcamR, w*.75, h/2, w/2, h);
  }
  //---update servo info---\\
  if(arduinoConnected) {
    arduino.servoWrite(xPin,int(xRot));
    arduino.servoWrite(yPin,int(yRot));
    arduino.servoWrite(zPin,int(zRot));
  }
}

/** ---- HELPERS ---- */
void oscEvent(OscMessage oscMessage) {
  xRot = oscMessage.get(0).floatValue();
  yRot = oscMessage.get(1).floatValue();
  zRot = oscMessage.get(2).floatValue();
}
void controlEvent(ControlEvent event) {
  // check if the Event was triggered from a ControlGroup
  if (event.isGroup()) {
    println("event from group : "+event.getGroup().getValue()+" from "+event.getGroup());
  } else if (event.isController()) {
    int val = int(event.getController().getValue());
    String controller = event.getController().getName();
    //get the arduino
    if (controller.equals("Serial Port")) {
      arduino = new Arduino(this, serialPorts[val], 57600);
      println("Arduino connected at "+serialPorts[val]);
      arduino.pinMode(xPin, Arduino.SERVO);
      arduino.pinMode(yPin, Arduino.SERVO);
      arduino.pinMode(zPin, Arduino.SERVO);
      arduinoConnected = true;
    }
    //get the left webcam
    if (controller.equals("Left Camera")) {
      webcamL = new Capture(this, camList[val]);
      println("Left Webcam is "+camList[val]);
      webcamLConnected = true;
      webcamL.start();
    }
    //get the right webcam
    if (controller.equals("Right Camera")) {
      webcamR = new Capture(this, camList[val]);
      println("Right Webcam is "+camList[val]);
      webcamRConnected = true;
      webcamR.start();
    }
  }
}

Difference in framerate between USB serial com port and bluetooth?

$
0
0

Why would there be a difference in framerate speed when using the USB serial port versus using a JY_MCU Bluetooth serial device?

Here is part of my code:

_String portName = Serial.list()[0]; //element 0 typically is my Bluetooth device, 2 is my USB serial port

_ myPort = new Serial(this, portName, 9600);

_ frameRate(100);

I am using the following to actually send data to my Arduino either on USB serial or Bluetooth serial:

_myPort.write(pwmOutArray[pwmWriteIndex]);

When I run this with my USB serial com port, I get a framerate of about 100. However, when I run this same code using the Bluetooth serial device, the framerate is much slower: typically 20-35 frames per second, so the Bluetooth slows down code execution.

Can anyone explain this? Thanks for your help.

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();
                            }

How to filter specific messages coming from arduino, and log them into an CSV?

$
0
0

Hello, glad to meet you all, this is my first post. I'm trying to setup a CSV file logging, in order to record some reaction time responses coming from arduino. So far i've managed to tweak some codes i've found in the internets and managed to get them to work sepparately: the first one (arduino side) measures the reaction time and prints it in the serial ("Your reaction time was:"). A different, processing code receives some data (button pressed or not) and logs it into a CSV file. The problem is, that this code will write ANY line that comes from the serial, which leaves no room for me to send useful message to the user (like "you pressed the button too early!").

**tl;dr **

Is there a way that I can modify the processing code to filter just the seconds of the reaction time instead of every line that comes from the serial?

Below there are 3 blocks of code:

1) the arduino code that i want to implement,

2) the processing code,

3) and the original arduino code meant for the processing code.

Arduino code so far:

(more readable pastebin here http://pastebin.com/Ej6jt6RZ)


 /* REACTION TIME (with 2 leds) v1.1
  *  Luis Andrés Gonzalez
  * Reaction time original version from http://www.instructables.com/id/Arduino-Reaction-Time-Tester/?ALLSTEPS
  * Send data to processing via the Serial Port original from By Elaine Laguerta http://url/of/online/tutorial.cc
 */
 int switchPin = 6;  // pin where the button will be connected
 int ledPin1 = 2 ;   // LED that signals starting of the game
 int ledPin2 = 8 ;   // LED that lights to test the reaction time

 // declare some variables:
 boolean lastButton = LOW;
 boolean currentButton = LOW;
 boolean Started = false;
 boolean timer = false;
 long startTime;
 long endTime;
 int randomTime;
 long beginTime;
 float elapsedTime;


 void setup()
 {
   // Setup button and LEDs:
   pinMode(switchPin, INPUT);
   pinMode(ledPin1, OUTPUT);
   pinMode(ledPin2, OUTPUT);

   // Begin serial communication
   Serial.begin(9600);
 }
 boolean debounce(boolean last)
 {
   boolean current = digitalRead(switchPin);
   if(last != current)
   {
     delay(5);
     current = digitalRead(switchPin);
   }
   return current;
 }


 void loop()
 {
   // see if button pressed
   currentButton = debounce(lastButton);
   if(lastButton == LOW && currentButton == HIGH)
   {
     if(Started==false){
       Started=true;
       randomTime = random(4,10);
       randomTime = randomTime*1000;
       Blink();
       beginTime=millis();

     }
     else{
       if((millis()-beginTime)>=randomTime){
           Stop();
           Started=false;
           timer=false;
       }

       else{
         Started=false;
         timer=false;
         Serial.println("You pressed the button too soon !");
         for(int i=0; i<3; i++){
           Blink();
         }
       }
     }
   }

   lastButton = currentButton;

   if(Started == true && (millis()-beginTime)>=randomTime && timer==false){
     Serial.println("Start");
     timer=true;
     Start();
   }
 }






 void Start(){
   startTime = millis();
   digitalWrite(ledPin1, HIGH);
 }

 void Blink(){
   digitalWrite(ledPin2, HIGH);
   delay(100);
   digitalWrite(ledPin2, LOW);
   delay(100);
 }

 void Stop(){
   endTime = millis();
   elapsedTime = (endTime - startTime)+5;
   elapsedTime = elapsedTime/1000;
   Serial.print("Time Seconds: ");
   Serial.println(elapsedTime);
   digitalWrite(ledPin1, LOW);

 }

Processing code:

(http://pastebin.com/EjEcuqct)


 /*
   Saving Values from Arduino to a .csv File Using Processing - Pseduocode

   This sketch provides a basic framework to read data from Arduino over the serial port and save it to .csv file on your computer.
   The .csv file will be saved in the same folder as your Processing sketch.
   This sketch takes advantage of Processing 2.0's built-in Table class.
   This sketch assumes that values read by Arduino are separated by commas, and each Arduino reading is separated by a newline character.
   Each reading will have it's own row and timestamp in the resulting csv file. This sketch will write a new file a set number of times. Each file will contain all records from the beginning of the sketch's run.
   This sketch pseduo-code only. Comments will direct you to places where you should customize the code.
   This is a beginning level sketch.

   The hardware:
   * Sensors connected to Arduino input pins
   * Arduino connected to computer via USB cord

   The software:
   *Arduino programmer
   *Processing (download the Processing software here: https://www.processing.org/download/
   *Download the Software Serial library from here: http://arduino.cc/en/Reference/softwareSerial

   Created 12 November 2014
   By Elaine Laguerta
   http://url/of/online/tutorial.cc

 */

 import processing.serial.*;
 Serial myPort; //creates a software serial port on which you will listen to Arduino
 Table table; //table where we will read in and store values. You can name it something more creative!

 int numReadings = 5; //keeps track of how many readings you'd like to take before writing the file.
 int readingCounter = 0; //counts each reading to compare to numReadings.

 String fileName;
 void setup()
 {
   String portName = Serial.list()[1];
   //CAUTION: your Arduino port number is probably different! Mine happened to be 1. Use a "handshake" sketch to figure out and test which port number your Arduino is talking on. A "handshake" establishes that Arduino and Processing are listening/talking on the same port.
   //Here's a link to a basic handshake tutorial: https://processing.org/tutorials/overview/

   myPort = new Serial(this, portName, 9600); //set up your port to listen to the serial port
   table = new Table();
   table.addColumn("id"); //This column stores a unique identifier for each record. We will just count up from 0 - so your first reading will be ID 0, your second will be ID 1, etc.

   //the following adds columns for time. You can also add milliseconds. See the Time/Date functions for Processing: https://www.processing.org/reference/
   table.addColumn("year");
   table.addColumn("month");
   table.addColumn("day");
   table.addColumn("hour");
   table.addColumn("minute");
   table.addColumn("second");

   //the following are dummy columns for each data value. Add as many columns as you have data values. Customize the names as needed. Make sure they are in the same order as the order that Arduino is sending them!
   table.addColumn("sensor1");

 }

 void serialEvent(Serial myPort){
   String val = myPort.readStringUntil('\n'); //The newline separator separates each Arduino loop. We will parse the data by each newline separator.
   if (val!= null) { //We have a reading! Record it.
     val = trim(val); //gets rid of any whitespace or Unicode nonbreakable space
     println(val); //Optional, useful for debugging. If you see this, you know data is being sent. Delete if  you like.
     int sensorVals = int(val); //parses the packet from Arduino and places the valeus into the sensorVals array. I am assuming floats. Change the data type to match the datatype coming from Arduino.

     TableRow newRow = table.addRow(); //add a row for this new reading
     newRow.setInt("id", table.lastRowIndex());//record a unique identifier (the row's index)

     //record time stamp
     newRow.setInt("year", year());
     newRow.setInt("month", month());
     newRow.setInt("day", day());
     newRow.setInt("hour", hour());
     newRow.setInt("minute", minute());
     newRow.setInt("second", second());

     //record sensor information. Customize the names so they match your sensor column names.
     newRow.setInt("sensor1", sensorVals);


     readingCounter++; //optional, use if you'd like to write your file every numReadings reading cycles

     //saves the table as a csv in the same folder as the sketch every numReadings.
     if (readingCounter % numReadings ==0)//The % is a modulus, a math operator that signifies remainder after division. The if statement checks if readingCounter is a multiple of numReadings (the remainder of readingCounter/numReadings is 0)
     {
       //saveTable(table, "data/new.csv");
       fileName = "data/" + str(year()) + str(month()) + str(day()) + str(table.lastRowIndex()) + ".csv"; //this filename is of the form year+month+day+readingCounter
       saveTable(table, fileName); //Woo! save it to your computer. It is ready for all your spreadsheet dreams.
     }
    }
 }

 void draw()
 {
    //visualize your sensor data in real time here! In the future we hope to add some cool and useful graphic displays that can be tuned to different ranges of values.
 }

The original Arduino code meant for the processing code above:

(http://pastebin.com/qQF7YbYN)

/*
Sending Data to Processing via the Serial Port
This sketch provides a basic framework to send data from Arduino to Processing over a Serial Port. This is a beginning level sketch.

Hardware:
* Sensors connected to Arduino input pins
* Arduino connected to computer via USB cord

Software:
*Arduino programmer
*Processing (download the Processing software here: https://www.processing.org/download/

Additional Libraries:
*Read about the Software Serial library here: http://arduino.cc/en/Reference/softwareSerial

Created 12 November 2014
By Elaine Laguerta
http://url/of/online/tutorial.cc
*/

/*To avoid overloading the Arduino memory, and to encourage portability to smaller microprocessors, this sketch
does not timestamp or transform data. In this tutorial, timestamping data is handled on the processing side.

Whether you process data on the Arduino side is up to you. Given memory limitations of the Arduino, even a few computations and mapping of values can
max out the memory and fail. I recommend doing as little as possible on the Arduino board.*/

//#include SoftwareSerial.h

/*Declare your sensor pins as variables. I'm using Analog In pins 0 and 1. Change the names and numbers as needed
Pro tip: If you're pressed for memory, use #define to declare your sensor pins without using any memory. Just be careful that your pin name shows up NOWHERE ELSE in your sketch!
for more info, see: http://arduino.cc/en/Reference/Define
*/
int sensor1Pin = 6;


/*Create an array to store sensor values. I'm using floats. Floats use 4 bytes to represent numbers in exponential notation. Use int if you are representing whole numbers from -32,768 to 32,767.
For more info on the appropriate data type for your sensor values, check out the language reference on data type: http://arduino.cc/en/Reference/HomePage
Customize the array's size to be equal to your number of sensors.
*/
/*
 * Prueba de dejar esto afuera
 float sensorVals[] = {0,0,0}
*/
/*Pro tip: if you have a larger number of sensors, you can use a for loop to initialize your sensor value array. Here's sample code (assuming you have 6 sensor values):
float sensorVals[6];
int i;
for (i=0; i<6; i++)
{
sensorVals[i] = 0;
}
*/

void setup(){
Serial.begin(9600); //This line tells the Serial port to begin communicating at 9600 bauds
}

//
void loop(){
//read each sensor value. We are assuming analog values. Customize as nessary to read all of your sensor values into the array. Remember to replace "sensor1Pin" and "sensor2Pin" with your actual pin names from above!
int sensorVal = digitalRead(sensor1Pin);

/*If you are reading digital values, use digitalRead() instead. Here's an example:
sensorVal[0] = digitalRead(sensor1Pin);
*/

//print over the serial line to send to Processing. To work with the processisng sketch we provide, follow this easy convention: separate each sensor value with a comma, and separate each cycle of loop with a newline character.
//Remember to separate each sensor value with a comma. Print every value and comma using Serial.print(), except the last sensor value. For the last sensor value, use Serial.println()
//Serial.print(sensors[0]);
//Serial.print(",");
//Serial.print(sensors[1]);
//Serial.print(",");
Serial.println(sensorVal);
delay(1000);
}

Controlling Multi Motors w/Muli ControlP5 Knobs (differentiating serial data) & Reading Applet Page

$
0
0

Hi,
Operating System: Windows 7 professional service pack 1
Arduino Uno with arduino software version: 1.6.6
Processing Software version: 3.101 32 bit

Goal: create 55 ControlP5 knobs that correspond to 55 electric motors using the Arduino UNO. To be able to adjust all the knobs individually and then start/stop all the motors at once using one master button.

What I have so far: I have successfully controlled one motor with one knob, and I have already posted this on this forum here.
LINK- https://forum.processing.org/two/discussion/14006/example-code-controlling-electric-motors-with-a-controlp5-knob-and-adafruit-motor-shield-boards#latest

CODE-
Processing:

    import processing.serial.*;
    import controlP5.*; // import library for knob

    Serial port;        // Create serial port object
    ControlP5 cp5;      // defines the type "cp5" as a variable "type" defined in ControlP5  for knob

    int myColorBackground = color(0,0,0);
    int knobValue = 100;

    Knob myKnobA;
    Knob myKnobB;

    void setup() {

      port = new Serial(this, 9600);
      size(700,400);
      smooth();
      noStroke();

      cp5 = new ControlP5(this);  //object created from library (what is this exactly?)

      myKnobA = cp5.addKnob("knob")  // "method" is add(ControllerInterface<?> theElement)
                   .setRange(0,255)
                   .setValue(50)
                   .setPosition(100,70)
                   .setRadius(50)  // for knob
                   .setDragDirection(Knob.VERTICAL)
                   ;
    }

    void draw() {

      background(myColorBackground);
      fill(knobValue);
      rect(0,height/2,width,height/2);
      fill(0,100);
      rect(80,40,140,320);
    }

    void knob(int theValue) {
      myColorBackground = color(theValue);
      println("a knob event. setting background to "+theValue);
      port.write(theValue);
    }

Arduino:

    #include <Wire.h>
    #include <Adafruit_MotorShield.h>
    #include "utility/Adafruit_PWMServoDriver.h"

    // Create the motor shield object with the default I2C address
    // Adafruit_MotorShield AFMS = Adafruit_MotorShield();
    // DONT USE THIS ONE IF RUNNING MULIPLE MOTORS
    // Or, create it with a different I2C address (say for stacking)
    Adafruit_MotorShield AFMS = Adafruit_MotorShield(0X60);  // 1st board if stacking

    // Select which 'port' M1, M2, M3 or M4. In this case, M1
    Adafruit_DCMotor *myMotor1 = AFMS.getMotor(1); // 1st board, M1

    char val;             // Data received from the serial port

    void setup() {
      Serial.begin(9600);                  // Start serial communication at 9600 bps

      AFMS.begin();  // create with the default frequency 1.6KHz, this connects to the
                 // controller- need one for each motor? nope.
    }

    void loop() {
      if (Serial.available()) {            // If data is available,
        val = Serial.read();               // read it and store it in val
      }
      myMotor1->setSpeed(val);
      myMotor1->run(FORWARD);
      delay(100);                          // Wait 100 milliseconds for next reading
    }

I have made the following approaches and have tried the following things:

1) I attempted make a multiple knob GUI (2 knobs) that control 2 different motors, but have no way of assigning each knob to each motor because It I am unclear on how to differentiate serial data from one ControlP5 knob to another ControlP5 knob. The two knobs individually control the speed for the two motors simultaneously, as if they were the same motor. so in other words if you adjust the speed of one knob both motors will change speed and it doesn't matter which knob you change speed with. here is the code:

CODE-

Processing Side:

    // Write data to the serial port according to the status of 2 ControlP5 Knob controlled
    // by the mouse, and differenetiate the data between the two knobs when sending serially.
    // Uses values from 0-255.

    import processing.serial.*;
    import controlP5.*; // import library for knob

    Serial port;        // Create serial port object
    ControlP5 cp5;      // defines the type "cp5" as a variable "type" defined in ControlP5  for knob

    int myColorBackground = color(0,0,0);
    int knobValue = 100;
    int knobValue1 = 100;  //for the second knob

    Knob myKnobA;
    Knob myKnobB;

    void setup() {

      port = new Serial(this, 9600);
      size(1000,1000);
      smooth();
      noStroke();

      cp5 = new ControlP5(this);  //object created from library (what is this exactly?)

      myKnobA = cp5.addKnob("knob")  // "method" is add(ControllerInterface<?> theElement)
                   .setRange(0,255)
                   .setValue(50)
                   .setPosition(100,70)
                   .setRadius(50)  // for knob
                   .setDragDirection(Knob.VERTICAL)
                   ;

      myKnobB = cp5.addKnob("knob1")  // "method" is add(ControllerInterface<?> theElement)
                   .setRange(0,255)   // for second knob
                   .setValue(50)      // for second knob
                   .setPosition(300,1)      // for second knob
                   .setRadius(50)  // for knob
                   .setDragDirection(Knob.VERTICAL)      // for second knob
                   ;                  // for second knob
    }

    void draw() {

      background(myColorBackground);
      fill(knobValue);
      rect(0,height/2,width,height/2);
      fill(knobValue1);    // was (0,100)
     // rect(knobValue1);  // was (80,40,140,320)
    }

    void knob(int theValue) {
      myColorBackground = color(theValue);
      println("a knob event. setting background to "+theValue);
      port.write(theValue);
    }
    void knob1(int theValue1) {      // for second knob
      myColorBackground = color(theValue1);    // for second knob
      println("a knob event1. setting background to "+theValue1);  // for second knob
      port.write(theValue1);      // for second knob
    }

Arduino Side:

    // Read data from the serial and turn a DC motor on or off according to the value. with adafruit motor driver
    // board code included

    #include <Wire.h>     // ADAFruit
    #include <Adafruit_MotorShield.h> // ADAFruit
    #include "utility/Adafruit_PWMServoDriver.h"  // ADAFruit

    // Create the motor shield object with the default I2C address
    // Adafruit_MotorShield AFMS = Adafruit_MotorShield(); // DONT USE THIS ONE IF RUNNING MULIPLE MOTORS //ADAFruit
    // Or, create it with a different I2C address (say for stacking)   // ADAFruit
    Adafruit_MotorShield AFMS = Adafruit_MotorShield(0X60);  // 1st board   // ADAFruit

    // Select which 'port' M1, M2, M3 or M4. In this case, M1 // ADAFruit
    Adafruit_DCMotor *myMotor1 = AFMS.getMotor(1); // 1st board, M1 // ADAFruit
    Adafruit_DCMotor *myMotor2 = AFMS.getMotor(2); // 2nd board, M2 // ADAFruit

    char val1;             // Data received from the serial port
    char val2;
    void setup() {
      Serial.begin(9600);                  // Start serial communication at 9600 bps

      AFMS.begin();  // create with the default frequency 1.6KHz, this connects to the  // ADAFruit
                     // controller- need one for each motor? nope.   // ADAFruit
    }

    void loop() {
      if (Serial.available()) {            // If data is available,
        val1 = Serial.read();               // read it and store it in val
      }
      myMotor1->setSpeed(val1); // ADAFruit
      myMotor1->run(FORWARD); // ADAFruit
      delay(100);                          // Wait 100 milliseconds for next reading

      if (Serial.available()) {
        val2 = Serial.read();
      }
      myMotor2->setSpeed(val2);
      myMotor2->run(FORWARD);
      delay(100);
      }

2) Searched and Studied passing strings through serial thinking that was a way to do it. I think I see how to pass a string serially but not how to differentiate data from one knob to one motor. does anyone know a good tutorial related to what I am doing?

3) Studying the applet page on the ControlP5 Page (http://www.sojamo.de/libraries/controlP5/). I think there is something I do not understand about reading the applet page of the conrolP5 website. I noticed they have the methods listed with no description.
Question1: How do you know how to use the code with all the methods listed?
Question2: How do you know what each Method does?
i was thinking getAddress, setAddress, & getValue would allow me to assign each knob to each motor. But I have not found how to implement them, an example, or able to decipher the Applet page for ControlP5.
LINK- http://www.sojamo.de/libraries/controlP5/

4) I studied the "SerialCalResponse" of the "Serial" examples built in to processing. It was not clear to me if:
Question1: Do I need 55 Serial Ports?
Question2: How do I differentiate the data coming from each object (ControlP5 knob) and then tell the arduino which motor corresponds to which knob. I will use a "case" function to differentiate but what am I differentiating?
Question3: Can I set up a monitoring command to tell the difference between the data coming from each knob or will it just display the value of the knob (0-255)?

5) I attempted to make an array of objects in order to generate the two knobs with one constructor but failed. it only generates one knob.
CODE-

// Create an array of 2 ControlP5 Knobs controlled
// by the mouse. uses values from 0-255.

import processing.serial.*;  //import library for serial communication
import controlP5.*; // import library for knob

Serial port;        // Create serial port object
ControlP5 cp5;      // defines the type "cp5" as a variable "type" defined in ControlP5  for knob

int myColorBackground = color(0,0,0);  // for GUI
int knobValue = 100;                   // for GUI

final int KNOB_NUMB = 2;               // number of knobs for i for loop below

// Knob myKnobA;
// Knob myKnobB;
Knob[] myKnob = new Knob [KNOB_NUMB];  // attempting to use Knob as a data type


void setup() {

  port = new Serial(this, 9600);
  size(1000,1000);
  smooth();
  noStroke();

  cp5 = new ControlP5(this);  //object created from library (what is this exactly?)
              // Initialize the balls' data

  for (int i = 0; i < KNOB_NUMB; i++)
  {
  myKnob[i] = cp5.addKnob("knob")  // "method" is add(ControllerInterface<?> theElement) the following indexes are per the object cp5
               .setRange(0,255)
               .setValue(50)
               .setPosition(100+i*10,70)
               .setRadius(50)  // for knob
               .setDragDirection(Knob.VERTICAL)
               ;
  }  // for
          }  // for setup()
void draw() {

  background(myColorBackground);
  fill(knobValue);
  rect(0,height/2,width,height/2);
  fill(0,100);
  rect(80,40,140,320);
}
/*
void knob(int theValue) {
  myColorBackground = color(theValue);
  println("a knob event. setting background to "+theValue);
  port.write(theValue);
}
*/

Question 1: Is only one knob showing up in the window because of how I am using the setPosition function above?

Please Post your answers here for the benefit of everyone

Problem with Serial on Windows 64-Bit

$
0
0

Need help using processing to use arduino. My serial library for 64-bits windows is missing. How can I get it? or How can I get my Serial functions to work on my 64 -bit windows?

I got this error when I use a Serial example from the Arduino (FIRMATA) library.

> serial is only compatible with the 32-bit download of Processing.
> serial does not run in 64-bit mode.
> processing.app.SketchException: serial is only compatible with the 32-bit download of Processing.
        at
> processing.mode.java.runner.Runner.(Runner.java:108)
    at
> processing.mode.java.JavaMode.handleRun(JavaMode.java:122)
    at
> processing.mode.java.JavaEditor$20.run(JavaEditor.java:480)
    at java.lang.Thread.run(Thread.java:662)

myPort.available always 0

$
0
0

Hy,

I'm on Linux kubuntu. I would like receive data from an arduino nano (3 axis motion for head tracking). The arduino code works because I can read data with Pure Data (Pd). The arduino is on port [32] (/dev/ttyUSB0)

I use the common code:

// Example by Tom Igoe

import processing.serial.*;

int lf = 10;    // Linefeed in ASCII
String myString = null;
Serial myPort;  // The serial port

void setup() {
  // List all the available serial ports
  printArray(Serial.list());
  // Open the port you are using at the rate you want:
  myPort = new Serial(this, Serial.list()[32], 9600);
  myPort.clear();
  // Throw out the first reading, in case we started reading
  // in the middle of a string from the sender.
  myString = myPort.readStringUntil(lf);
  myString = null;
}

void draw() {
  println(myPort.available());

  while (myPort.available() > 0) {
    myString = myPort.readStringUntil(lf);
    if (myString != null) {
      println(myString);
    }
  }
}

But myPort.available is always 0. I can't read anything.

Can someone help me ?

thanks

Fonction typeof in processing

$
0
0

Hello, I’m a 16 years old student in a French High School working on a project at school: how to simulate a retinal implant with photoresistances, a screen and an Arduino board. At this moment, I wrote a program for an Arduino uno board that measures the quantity of lights picked up by photoresistances, and interpretes it in a 10 bits data integer.

Now I have to realize a second program on Processing which interprets this data gathered from photoresistances to create a 2x3 matrix (the number of sensors) with a contrast of black on each, representing the quantity of light. I’m at the debugging stage of my programming, and have eliminated most errors in my program. However, there’s one still resisting me: the program on Processing is supposed to read a string data feed containing the interger data. Here’s an example of said feed: nullnullnullnullnullnull235,235,235,236,234,203,223…

I however have a problem: I can’t cut this string to get only the integer data. I’ve used several instructions advised on the Arduino website, but all failed.

So I’m turning to you people to get some help, please. You can see enclosed with this message both programs. Thank you very much,

mateobae

I reading wrong data serial port

$
0
0

I'm sending values(0-11) from Arduino Serial port but i reading wrong datas( like 48,49,50...) in processing..

//processing code

int gelenindex=12;
  while(myport.available()>0)
  {
    gelenindex=(int)(myport.read());//porttan gelenrenk index aldik
    println((int)myport.read()+"*");// i send 3 but get data result: 13* and -1*
  }

Reaction time game. How to solve infinite loop.

$
0
0

I'm programming my arduino to make a reaction time game as a sketch for a more serious scientific study. It works like this

  1. you press a button once, and a led blinks indicating the game begins
  2. after a random lapse, the led lights up, and a clock starts to measure the time until you press the button again
  3. if you do, it shows the reaction time in seconds
  4. if you press before the led lights up, it blinks three times and the game ends
  5. if you don't press the button after a tame, the led blinks twice and the game ends
  6. once the game ends, it only begins again if you press the button again.

I've managed to work ok all steps from 1 through 5, but I cannot see how to get to work step 6. The way the code is written, after 5 it loops back to 1, infinitely. Any ideas on how to solve this?

/* REACTION TIME (with 2 leds) v2.1 beta
    Luis Andrés Gonzalez
   Reaction time original version from http://www.instructables.com/id/Arduino-Reaction-Time-Tester/?ALLSTEPS
   Send data to processing via the Serial Port original from By Elaine Laguerta http://url/of/online/tutorial.cc
*/
const int switchPin = 6;  // pin where the button will be connected
const int ledPin1 = 2 ;   // Left LED
const int ledPin2 = 8 ;   // Middle LED
const int ledPin3 = 12;   // Right LED

// declare some variables:
boolean lastButton = LOW;
boolean currentButton = LOW;
boolean gameStarted = false;  // true if game has started
boolean timerFlag = false;    // true if timer is running
long startTime;
long endTime;
int randomSeconds;
long beginTime;
float elapsedTime;
int maxTimer = 5 * 1000;
float totalTime;



void setup() {
  // Setup button and LEDs:
  pinMode(switchPin, INPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(ledPin3, OUTPUT);

  // Begin serial communication
  Serial.begin(9600);
}

void loop() {
  // Check https://www.arduino.cc/en/Tutorial/StateChangeDetection to understand the following code.
  if ((millis() - beginTime) > (randomSeconds + maxTimer)) {
    Stop();

    //resets game:
    gameStarted = false;
    timerFlag = false;
    currentButton = LOW;
    lastButton = LOW;


    Blink(2);
    Serial.println("message");

  }
  // read the pushbutton input pin in the current loop:
  currentButton = buttonPressed(lastButton);

  // if there's a change from low to high (comparing last and current loop) then the following is true
  if (currentButton == HIGH && lastButton == LOW) {   // outer IF

    if (gameStarted == false) {                       // middle IF. starts the game
      gameStarted = true;
      randomSeconds = random(2, 5) * 1000; // generates a random number of seconds between 3 and 8
      Blink(1);
      Serial.println("9090"); // signal code for start sound
      beginTime = millis();
    } else {

      if ((millis() - beginTime) >= randomSeconds) {
        Stop();
        gameStarted = false;
        timerFlag = false;

      } else if ((millis() - beginTime) < randomSeconds ) {
        gameStarted = false;
        timerFlag = false;
        Serial.println("1010"); // signal code for early response
        Blink(3);
      }

    }
  }                             // end outer if

  // save the current state as the last state,
  //for next time through the loop
  lastButton = currentButton;




  // If true, starts the response time timer and lights up the LED
  if (gameStarted == true && (millis() - beginTime) >= randomSeconds && timerFlag == false) {
    timerFlag = true;

    Start();

  }

} // end void loop

//===========================================================================================

boolean buttonPressed(boolean last) {       //button debouncing function
  boolean current = digitalRead(switchPin);
  if (last != current) {
    delay(5);
    current = digitalRead(switchPin);
  }
  return current;
}

void Start() {

  startTime = millis();
  Light(ledPin1, "on");

}

void Stop() {
  if ( (millis() - beginTime) 

Can I use two ports in arduino at the same time?

$
0
0

I am using bitVoicer for speech recognition and communicate with processing. But once I use a port to control arduino with this library, my processing stops working and indicates "Port busy".

I am wondering if I can use two ports, one of which send and receive data from processing (or use firmata) and the other receives data from bitVoicer software to control the arduino with words.

I tried the example in arduino tutorial website "https://www.arduino.cc/en/Tutorial/SoftwareSerialExample", which does not work for me as well.

Thank you very much.


Sending a number through serial to arduino with ControlListener(library controlP5)

$
0
0

I'm trying to send a number to an arduino through controlListener that monitors a dropdown menu.

Here's the code:

class MyControlListener implements ControlListener {
  int mode ;
  public void controlEvent(ControlEvent theEvent) {

    println((int)theEvent.getController().getValue()+1);  //debug
    mode = (int)theEvent.getController().getValue()+1;

    myPort.write(mode);

  }
}

The problem is that apparently, arduino doesn't receive the appropriate data type because when I check what it has received it shows a blank space. If I press the number with the keyboard it receives it ok. Here's an attempt to use the menu and with the keyboard:

ControlP5 2.2.5 infos, comments, questions at http://www.sojamo.de/libraries/controlP5
Enter Test mode:
Press 1 for random mode
Press 2 for fixed time mode
2
I received:
Invalid optionI received: 2
Game mode selected = Fixed time mode

Here is the complete code:

/**
 REACTION TIME GAME v 1.0
 Adapted by code made by Elaine Laguerta
 by Luis Andrés Gonzalez, January 2016

 Reads reaction time from Arduino over the serial port and save it to .csv file on your computer.
 The .csv file will be saved in the same folder as your Processing sketch.
 This sketch assumes that values read in seconds by Arduino are separated by a newline character.
 Special code numbers are specified to signal the game start, success and failure of accomplishing the task.
 Each reading will have it's own row and timestamp in the resulting csv file. This sketch will write a new file each day.

 The hardware:
 * A pushbutton connected to Arduino input pins
 * Arduino connected to computer via USB cord

 The software:
 *Arduino IDE
 *Processing (download the Processing software here: https://www.processing.org/download/
 *The corresponding arduino code

 */

// ==== Libraries and instantiations ====
import processing.serial.*;
Serial myPort; //creates a software serial port on which you will listen to Arduino

import ddf.minim.*;
import ddf.minim.ugens.*;
Minim minim;
AudioOutput out;

import controlP5.*;
import java.util.*;

ControlP5 cp5;
MyControlListener myListener;

Table table; //table where we will read in and store values. You can name it something more creative!

int numReadings = 1; //keeps track of how many readings you'd like to take before writing the file.
int readingCounter = 0; //counts each reading to compare to numReadings.

// Serial code numbers for specific events
int startCode = 9090; // code for game start
int earlyCode = 1010; // code for early button press
int lateCode = 7777; // code for late button press
String fillColor;
char letter;
String fileName;
String words;
boolean startLogging;


void setup() {
  size(500, 700);
  String portName = Serial.list()[1];
  //CAUTION: your Arduino port number is probably different! Mine happened to be 1. Use a "handshake" sketch to figure out and test which port number your Arduino is talking on. A "handshake" establishes that Arduino and Processing are listening/talking on the same port.
  //Here's a link to a basic handshake tutorial: https://processing.org/tutorials/overview/

  // SOUND setup:
  minim = new Minim(this);
  out = minim.getLineOut();
  out.setTempo( 80 );
  out.pauseNotes();
  // end SOUND setup.

  myPort = new Serial(this, portName, 9600); //set up your port to listen to the serial port

  table = new Table();
  table.addColumn("id"); //This column stores a unique identifier for each record. We will just count up from 0 - so your first reading will be ID 0, your second will be ID 1, etc.

  //the following adds columns for time. You can also add milliseconds. See the Time/Date functions for Processing: https://www.processing.org/reference/
  table.addColumn("year");
  table.addColumn("month");
  table.addColumn("day");
  table.addColumn("hour");
  table.addColumn("minute");
  table.addColumn("second");

  //the following are dummy columns for each data value. Add as many columns as you have data values. Customize the names as needed. Make sure they are in the same order as the order that Arduino is sending them!
  table.addColumn("sensor1");

  cp5 = new ControlP5(this);
  List modes = Arrays.asList("Random time mode", "Fixed time mode");
  /** add a ScrollableList, by default it behaves like a DropdownList */
  cp5.addScrollableList("Select session mode")
    .setPosition(200, 50)
    .setSize(250, 100)
    .setBarHeight(20)
    .setItemHeight(20)
    .addItems(modes)
    .setType(ScrollableList.DROPDOWN) // currently supported DROPDOWN and LIST
    ;
  myListener = new MyControlListener();
  cp5.getController("Select session mode").addListener(myListener);
} // void setup

void serialEvent(Serial myPort) {

  String val = myPort.readStringUntil('\n'); //The newline separator separates each Arduino loop. We will parse the data by each newline separator.

  if (val!= null) { //We have a reading! Record it.

    val = trim(val); //gets rid of any whitespace or Unicode nonbreakable space
    float sensorVal = float(val); //parses the packet from Arduino and places the valeus into the sensorVals array. I am assuming floats. Change the data type to match the datatype coming from Arduino.
    if (sensorVal == 0000) {
      println("Logging started");
      startLogging = true;
    }
    if (float(val) == startCode) {
      out.playNote( 0.0, 0.4, "C3" );
      out.playNote( 0.2, 0.2, "C4" );
      out.resumeNotes();
      fillColor="green";
    } else if (float(val) == earlyCode) {
      println("You pressed the button too early!");
      fillColor="red";
      out.playNote( 0, 2, "A1");
      out.resumeNotes();
    } else if (float(val) == lateCode) {
      println("You pressed the button too late!");
      fillColor="red";
      out.playNote( 0, 2, "A1");
      out.resumeNotes();
    } else if (!Float.isNaN(sensorVal)){
      print("Your reaction time was: ");
      println(val);
      out.playNote( 0, 0.2, "C4");
      out.playNote( 0.2, 0.2, "C4");
      out.playNote( 0.4, 0.2, "C4");
      out.resumeNotes();
      fillColor="yellow";
    } else {
      println(val);
    }



    if (sensorVal != startCode && !Float.isNaN(sensorVal) ) { // if it's NOT the start number but it IS a number
    //if (sensorVal != startCode && startLogging == true) { // if it's NOT the start number but it IS a number
      TableRow newRow = table.addRow(); //add a row for this new reading
      newRow.setInt("id", table.lastRowIndex());//record a unique identifier (the row's index)

      //record time stamp
      newRow.setInt("year", year());
      newRow.setInt("month", month());
      newRow.setInt("day", day());
      newRow.setInt("hour", hour());
      newRow.setInt("minute", minute());
      newRow.setInt("second", second());

      //record sensor information. Customize the names so they match your sensor column names.

      if (sensorVal == earlyCode) {
        newRow.setString("sensor1", "early");
      } else if (sensorVal == lateCode) {
        newRow.setString("sensor1", "late");
      } else if (Float.isNaN(sensorVal)) {
        // if its not a number, don't log it
      } else {
        newRow.setFloat("sensor1", sensorVal);
      }

      readingCounter++; //optional, use if you'd like to write your file every numReadings reading cycles
    }
    //saves the table as a csv in the same folder as the sketch every numReadings.
    if (readingCounter % numReadings ==0) {//The % is a modulus, a math operator that signifies remainder after division. The if statement checks if readingCounter is a multiple of numReadings (the remainder of readingCounter/numReadings is 0)
      fileName = "data/" + str(year()) + str(month()) + str(day()) /**+" - " + str(table.lastRowIndex())*/ + ".csv"; //this filename is of the form year+month+day+readingCounter
      saveTable(table, fileName); //Woo! save it to your computer. It is ready for all your spreadsheet dreams.
    }
  }
} // void serialevent


void draw()
{
  if (fillColor == "red") {              // If the serial value is 0,
    fill(255, 0, 0);                   // set fill to black
  } else if (fillColor == "green") {                       // If the serial value is not 0,
    fill(0, 255, 0);                 // set fill to light gray
  } else if (fillColor =="yellow") {
    fill(255, 255, 0);
  }
  background(240);
  rect(50, 50, 99, 99);
}

void keyTyped() {
  // The variable "key" always contains the value
  // of the most recent key pressed.
  if ((key >= '0' && key 

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

Same Old question as new????

$
0
0

Hi Everyone, I'm New to processing. Can i control real time applications using processing in Arduino or raspberry pi or visual studio etc????

More specific regarding the question, I wanna make an app for controlling Arduino motors using processing software? Is it possible???

I will appreciate your time, Thank You

My serial data doesn't show up in processing

$
0
0

Hi, I'm new here and I already have a question.

It's about my serial port. I have an Arduino attached to my mac, and it sends data (from 2 potentiometers) to the serial port. I know this works fine because I can see this data in both the Arduino IDE Serial Monitor as well as in terminal. I know my Arduino is on port 9. I have this coded in Processing, and it worked all fine, until a few days ago.

Since then every program in Processing I start which has something to do with reading data from this port fails, and I get this message: NullPointerException. I then figured out that Processing thinks there's is no data at all from my serial port. (Even a simple example program from this site fails)

How can I fix this? I really have no idea anymore and I'm a bit desperate , so any help is welcome. Thanks in advance, Susan X_X

USB dashboard

$
0
0

I have an arduino running a bunch of process equipment that I want to visualize using processing. I have done this very successfully in the past using Processing on OSX, but now I want to visualize it on a touch screen built into the equipment and not on a laptop. I have an .SVG flow diagram of the equipment that I want to populate with temperatures, pressures, etc coming off the arduino.

I have spent the day looking at different options and want to just sanity check what I have found.

First, I want to have a nice looking process flow diagram that is populated with the state points of the equipment. I can definitely connect a screen to the arduino, but I could not use any kind of drawn image there.

Second, there are a million different IOT apps that will let you drag and drop a dashboard together and use a bunch of servers. I don't want to do that either because A) I want it to be a physical connections and B) I want to create a custom diagram.

So now I am thinking that either a windows 10 or android tablet is the best way to go. These tablets are just as cheap as the screens they are replacing at the size I want (7-10"). Furthermore, they can all talk to each other over USB serial.

This seems absolutely crazy to me, but after lots of looking it seems like the easiest way to get it to work. What do you think? Is there a better solution I am just not seeing?

Viewing all 747 articles
Browse latest View live