Use the Arduino Processing Interface

Hello everyone,

I can not transmit or receive PWM information, sent with analogWrite from Arduino and find it in Processing.

I used the Arduino Input example in Processing and I can get the information from the Arduino analog input and the Arduino digital outputs (the Arduino program is based on the standardFirmata skecth). But I can not get the PWM information from the Arduino output 9. I just receive the data 0.

Thank you for your lights!

Processing Program

import processing.serial.*;

import cc.arduino.*;

Arduino arduino;

color off = color(4, 79, 111);
color on = color(84, 145, 158);

void setup() {
  size(470, 280);

  // Prints out the available serial ports.
  println(Arduino.list());
  
  // Modify this line, by changing the "0" to the index of the serial
  // port corresponding to your Arduino board (as it appears in the list
  // printed by the line above).
  arduino = new Arduino(this, Arduino.list()[4], 57600);
  
  // Alternatively, use the name of the serial port corresponding to your
  // Arduino (in double-quotes), as in the following line.
  //arduino = new Arduino(this, "/dev/tty.usbmodem621", 57600);
  
  // Set the Arduino digital pins as inputs.
  for (int i = 0; i <= 13; i++)
    arduino.pinMode(i, Arduino.INPUT);
}

void draw() {
  background(off);
  stroke(on);
  
  // Draw a filled box for each digital pin that's HIGH (5 volts).
  for (int i = 0; i <= 13; i++) {
    if (arduino.digitalRead(i) == Arduino.HIGH)
      fill(on);
    else
      fill(off);
      
    rect(420 - i * 30, 30, 20, 20);
  }

  // Draw a circle whose size corresponds to the value of an analog input.
  noFill();
  for (int i = 0; i <= 5; i++) {
    ellipse(280 + i * 30, 240, arduino.analogRead(i) / 16, arduino.analogRead(i) / 16);
    ellipse(50, 240, arduino.analogRead(9) / 16, arduino.analogRead(9) / 16);
    println(arduino.analogRead(9));
  }
}

Arduino Program (just the end)

 a=a+1;
  float b = a/100;
   int sensorValue = analogRead(A0);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5/ 1023.0);

  int phi= map (voltage, 0, 5, 0, 180);
//// Converts the potar value as phase shift of the cosine wave

  
//TEST OUTPUT VALUE
 
  digitalWrite (3, HIGH);
  digitalWrite (8, HIGH);
  
  analogWrite (ledPin, abs (100*cos (2*PI*b/10)));
  analogWrite (ledPin2, abs (200*cos (2*PI*b/10-phi)));

  Serial.println (b);
  Serial.println (phi);
  
  Serial.print ("fonction cos "); Serial.println(abs (100*cos (2*PI*b/100)));
  Serial.print ("fonction lag "); Serial.println(abs (100*cos (2*PI*b/100- phi)));
1 Like

pls. can you first confirm that
-a- if you load up to Arduino the Standard Firmata example
! without change one line
-b- load on processing the firmata example for analog read

that this combination works.

for me it looks that you know about firmata,
and you say you used the firmata arduino sketch

  • and that includes the firmata protocol / also used by the processing firmata lib
import cc.arduino.*;

so you should use firmata as it is:

means NO

  • Serial.println from arduino to processing
  • digitalWrite and analogWrite to pins what are handled by firmata
    ( and add you in processing declared as inputs ?? )

so actually it looks like you NOT want to use firmata ( what is ok )
only if you not use the firmata lib cc.arduino and not use the firmata sketch


but if you use firmata ( as you have not to deal with serial coding… )
that part what you program in arduino is supposed to be in processing

    • analog read ?potentiometer?
    • calc some trig. function
    • write to PWM outputs

With a unchanged firmata in arduino.

( i hope i got your situation correctly / sorry if i am OFF )

Hi .

Thanks for your answer.

I am not sure to have well understood what you told me ( English is not my maternal language).

So I have found an other solution to receive two data from Arduino to Processing

And I have found those programs for Processing and Arduino

First Processing Program

// import the Processing serial library
import processing.serial.*;    
Serial myPort; // The serial port
 
// Test values
int v1 =0;
int v2 = 255;
int x;
 
void setup() {
  size(640,480);
  // Open serial port
  //printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[0], 9600);
 
  // Read bytes into a buffer until you get a linefeed (ASCII 10):
  myPort.bufferUntil('\n');
 
  //draw with smooth edges:
  //smooth();
  background(255);
}
 
void draw() {
 
  // Draw circles
  fill(#ff0000);
  ellipse(x, v1, 5, 5);
  fill(#00ff00);
  ellipse(x, v2, 5, 5);
 
  // Update x position
  x++;
 
  // Refresh screen
  if (x > 600) {
    background(255);
    x = 0;
  }
}
 
// serialEvent  method is run automatically by the Processing applet
// whenever the buffer reaches the byte value set in the bufferUntil()
// method in the setup():
void serialEvent(Serial myPort) {
 
  // read the serial buffer:
  String myString = myPort.readStringUntil('\n');
 
  // if you got any bytes other than the linefeed:
  myString = trim(myString);
 
  // split the string at the commas
  // and convert the sections into integers:
  int values[] = int(split(myString, ','));
 
  if (values.length > 0) {
    v1 = values[0];
    v2 = values[1];
    //println(v2);
  }
}

and this one for Arduino but it doesn’t seem to work.

// Send serial data to Processing
// Data are separated by a ",", so you could send any number of data
 
int firstSensor = 0;    // first analog sensor
int secondSensor = 255;   // second analog sensor
 
void setup() {
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}
 
void loop() {
 
    // Update Data with linear values
    firstSensor += 10; 
    secondSensor -= 20;
    if (secondSensor < 0)  secondSensor = 255;
    if (firstSensor > 255)  firstSensor = 0;
 
    // Send Data
    Serial.print(firstSensor);
    Serial.print(","); // séparateur
    // Avec println on ferme le paquet de valeur, car "ln"
    Serial.println(secondSensor); 
 
    // Sampling rate
    delay(5);
}

I have got two lines who go straight on

ahm, so after i recommended to use the firmat ( upload firmata standard example unchanged to arduino )
and do all the coding in processing,
you do the exact opposite, not use firmata, and play serial sending.
OK

what is the problem with this code?
first time you try serial communication and you send 200 lines per second?

how does it look from arduino IDE monitor ( terminal?)
pls show the printout.

and in processing, after

  myString = trim(myString);

pls do a print and show the result here.


i tested the whole thing here ( Raspberry Pi /usb/ Arduino Leonardo )
clean up / make real slow…


arduino code:

// Send serial data to Processing
// Data are separated by a ",", so you could send any number of data
 
int firstSensor = 0;    // first analog sensor
int secondSensor = 255;   // second analog sensor
 
void setup() {
  Serial.begin(9600);
  while (!Serial) { ; }                // wait for serial port to connect. Needed for native USB port only
  }
 
void loop() { 
    
    firstSensor += 1;                  // Update Data with linear values
    if (firstSensor > 255)  firstSensor = 0;

    secondSensor -= 2;
    if (secondSensor < 0)  secondSensor = 255;
    //                                      Send Data
    Serial.print(firstSensor);
    Serial.print(",");                      // séparateur
    Serial.println(secondSensor);           // Avec println on ferme le paquet de valeur, car "ln"
 
  
    delay(500);        //5);                 // Sampling rate
}

/*  see monitor:
127,1
128,255
129,253
130,251
131,249
132,247
133,245
134,243
135,241
136,239
137,237
138,235
139,233

 */

processing code:

// https://discourse.processing.org/t/use-the-arduino-processing-interface/9409/3

import processing.serial.*;      // import the Processing serial library
Serial myPort;                   // The serial port
// Test values
int v1 = 0;
int v2 = 0;
int x;

void setup() {
  size(640,480);
  // Open serial port
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[1], 9600);
  myPort.bufferUntil('\n');          // Read bytes into a buffer until you get a linefeed (ASCII 10):
  background(255);
}
 
void draw() {
  // Draw circles
  fill(#ff0000);
  ellipse(x, v1, 5, 5);
  fill(#00ff00);
  ellipse(x, v2, 5, 5);
  x++;                         // Update x position
  if (x > 600) {
    background(255);            // Refresh screen
    x = 0;
  }
}
 
// serialEvent  method is run automatically by the Processing applet // whenever the buffer reaches the byte value set in the bufferUntil() method in the setup():
void serialEvent(Serial myPort) {                     // read the serial buffer:
  String myString = myPort.readStringUntil('\n');
  myString = trim(myString);                          // if you got any bytes other than the linefeed:
  println(myString);
  int values[] = int(split(myString, ','));                 // split the string at the commas// and convert the sections into integers:
  if (values.length > 0) {
    v1 = values[0];
    v2 = values[1];
  }
}

1 Like

Thanks u. It works perfectly now.

I was tired yesterday night and I have changed this line
if (values.length >0 {

with this line
if (values.length >2 {

If there is a better and simpler solution to use FIRMATA library?

that i write above and you possibly did not try.
( you might have got a feeling what fits more. )

sorry, i can not say what way is better without fully understanding what your project is about.

your basic question ( besides coding ) was
how to get arduino PWM output to processing
and that not makes sense in case
you send the PWM setpoint from processing to arduino.

in case you want read a potentiometer from arduino Ain
and set a arduino PWM output,
that can work inside arduino ( and no PC / USB / processing … required )
so pls tell us more what for you want use processing in that project?
( besides learning )

Yes it works too.

I will add the program we made above inside the firmata example for analog read.

In this way, it should work great, i will control Processing, with numerical data AND analogic data from Arduino.

Later, I will synthetize a sound in Processing with numerical data from Arduino, and I will add a filter to this sound with Processing. Last, with those data (of filter sound) that I will send to Arduino, I will control the speed of one motor.

I’m sure I can make it directly in Arduino, but It’s great to visualize data on screen and transform it in a wave.

Thanks again. Maybe I will need you soon.

Sincerly.

Hi,

I just checked the code above and it displays 2 constant lines.
I would like to take 2 signals from the Arduino’s analog pins and display them on Processing in a similar way as in the Arduino’s IDE serial plotter.
I appreciate your help.

Regards,

please post your code ( using </> Preformatted text )
and also the console print out.


minimal arduino code

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print( analogRead(0) );          // A0
  Serial.print(",");
  Serial.print( analogRead(1) );          // A1
  Serial.println(",");
  delay(1000);                            // every second
}


/* if A0 at 5V see on arduino monitor
1023,868,
1023,867,
1023,866,
1023,865,
1023,866,
1023,866,
1023,867,

*/

minimal processing code

import processing.serial.*;

Serial myPort; 
String data;

void setup_serial() {                                 // USB arduino..
  printArray(Serial.list());
  String portName = Serial.list()[1]; 
  myPort = new Serial(this, portName, 9600);
  myPort.clear();
  myPort.bufferUntil('\n');
  println("try connect to "+portName);
}

void serialEvent(Serial p) {                          // handle serial data
  data = trim(p.readStringUntil('\n'));
  if (data != null) {
    println(data);            // print every GOOD line
  }
}

void setup() {
  size(640, 360);
  setup_serial();
}

void draw(){}

/*

[0] "COM1"
[1] "COM7"
try connect to COM7
1023,869,
1023,833,
1023,862,
1023,866,
1023,866,

*/

with a arduino leonardo on USB COM7
of a Win 10 / Processing 3.5.3 /

1 Like

Hi,

Thanks for replying.

My Arduino code looks just like yours, except that use float values and only one comma to separate the data.

void setup() {
  Serial.begin(9600);
}

void loop() {
  Serial.print( (float)analogRead(0) );          // A0
  Serial.print(",");
 Serial.println( (float)analogRead(1) );          // A1
  
  delay(100);                            // every second
}

The Processing code is similar too and i can also get the Arduino values on the console.
Now I would like to graph them on Processing as on Arduino’s serial plotter

sorry, but float not makes sense for analog sampling data from INT 0 … 1023
as you just add ‘.00’ characters to the serial transport.

if you later need to interpret that in engineering values:
1023 as 5.00V or 273.00 square pound/cubic feet
do that in the latest moment in processing

  • after transport serial
  • after store in a array ( long == canvas width for plot example )
  • or anything required for data reduction for “historic data collection”

so very good, your communication works.
now could take the string ( from one arduino line ) and make it to 2 numbers


can you give a example or photo,
as it looks like i not know the Arduino IDE that well.

my understanding is that already now the
Arduino IDE serial monitor outprint
and the Processing console outprint
looks same,
if you mean that you want the processing canvas shows the arduino lines? use
https://processing.org/reference/text_.html

or you want it like this?