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

Non-Linear/Exponential Sound

$
0
0

Hi,

How do I create non-linear/exponential sound with sinewave code. Below is the code I am currently working with. The frequency is very choppy.

Thanks

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

    Arduino arduino;
    SinOsc sine;

    int total1;
    //int total2;
    //int total3;

    float freq=400;
    float amp=0.5;
    float pos;

    void setup() {
      // window size
      size(470, 280);
      background(0);
      // print out all the device connected to serial ports
      println(Arduino.list());

      arduino = new Arduino(this, Arduino.list()[1], 57600);

       // Create and start the sine oscillator.
       sine = new SinOsc(this);

       //Start the Sine Oscillator.
       sine.play();

    }

    void draw() {
      fill(0,0,0,5);
      rect(0,0,width,height);


     // read capacitive sensor value sent via firmata
      total1=arduino.analogRead(8) ;

     print("total1 : ");
     print(total1);
     println();

    if (total1 >=40 && total1 <=1200){
    // Map from 0.0 to 1.0 for amplitude
      amp=map(total1, 40, 1200, 0.0, 1.0);
      sine.amp(amp);
    } else if (total1 <=40) {
      amp = 0;
      sine.amp(amp);
    }
      println(total1);

      if (total1 >=40 && total1 <=1200){

    // Map from 20Hz to 1000Hz for frequency
        freq=map(total1, 40, 1200, 500.0, 1000.0);
        sine.freq(freq);

      }

      // Map from -1.0 to 1.0 for left to right
      pos=0.0;//map(mouseX, 0, width, -1.0, 1.0);
      sine.pan(pos);

    } // end draw

Converting GIF to Sketch: selectFolder and (String, String) not working

$
0
0

Hi there, getting told my method "selectFolder(String) in the type PApplet is not applicable for the arguments (String, String)" Not related to this error, but I'm trying to be able to change it to work with 15 x 15 or 24 x 24 GIF sizes. Super fun if we can figure this out. HERE IS THE LINK TO THE GITHUB RESOURCE: https://github.com/MeULEDs

See my issue below:

....

Public void OutputSelect() {
  m("Select an output Folder:", "OutputProcess");
}

void OutputProcess(File selection) {
  if (selection == null) {
    OutputPath = "None Chosen";
  } else {
    OutputPath = selection.getAbsolutePath();
  }

}

public void Run() {


  String ArduinoFileName = cp5.get(Textfield.class,"ArduinoName").getText();
  String thePattern = "[^A-Za-z0-9]+";
  String [] m = match(ArduinoFileName, thePattern);

....

Unexpected behavior with basic excercise Processing and Arduino

$
0
0

Hi. I'm new with Arduino / Processing, so i'm making a basic workshop that is a blink led with an Arduino Uno board and Processing 3.0.1.

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


Arduino arduino;
int ledPin = 13;

void setup(){
  // println(Arduino.list().length);
  arduino = new Arduino(this, Arduino.list()[Arduino.list().length - 1], 57600);
  arduino.pinMode(ledPin, Arduino.OUTPUT);
}

void draw(){
  println("Turn on led Pin "+ledPin);
  arduino.digitalWrite(ledPin, Arduino.HIGH);
  delay(1000);
  println("Turn off led Pin "+ledPin);
  arduino.digitalWrite(ledPin, Arduino.LOW);
  delay(1000);
}

Arduino.list()[Arduino.list().length - 1] is my the usb port that connects with my arduino

I have the led in pin 13 to possitive and pin ground with negative.

The problem here is that the led doesn't change, just stay turned on without changes.

Thanks

How can my Processing sketch know which Serial port is Arduino?

$
0
0

As the title. I want for my Processing sketch to know which Serial port is Arduino, so that I will not need to re - compile everything to match the Arduino's Serial port.

I have no clue, so I need guidance.

Button in processing pilot Relay in arduino

$
0
0

I would use four buttons made by processing and G4p Gui to drive 4 relays (software selection) connected to Arduino UNO (output 13, 12, 11 and 10) to replace a rotary switch 4-way (hardware selection) in order to manage everything through the Internet.

This is GUI code: https://justpaste.it/r6t9

Controlling Arduino with Processing through Bluetooth

$
0
0

Hi all,

I'm looking to use an evolutionary algorithm to control a small robot built with Arduino.

I need to get feedback from the sensors attached to Arduino as fast as possible into Processing. And once processed give some instructions back to the Arduino.

Is it possible to control Arduino from processing wirelessly?

Thanks, Charles

Combining x2 Processing sketches to be triggered by an Arduino sensor.

$
0
0

Hi,

Mac OS 10.11.1 Processing 3.0

In the processing sketch below I am creating a graph thats triggered by an Arduino proximity sensor, as I move closer to the sensor, the graph displays the peaks and troughs in the processing display window.

In the 2nd Processing sketch I am creating a series of lines that draw themselves, this is nothing to do with an Ardunino.

So what I am trying to do is combine the 2 sketches, so that when I trigger the Arduino sensor it draws the series of lines (from the 2nd processing sketch) in Processing, not the basic graph.

Is this even possible? I have been tried various combinations of code but always resulting in a curly bracket errors. any help appreciated.

thanks


1ST PROCESSING SKETCH


import processing.serial.*;

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

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

  println(Serial.list());
  myPort = new Serial(this, Serial.list()[3], 9600);

  // don't generate a serialEvent() unless you get a newline character:
  myPort.bufferUntil('\n');

  // set inital background:
  background(0);
}
void draw () {
  // draw the line:
  stroke(127, 34, 255);
  line(xPos, height, xPos, height - inByte);

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


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:
    inByte = float(inString);
    println(inByte);
    inByte = map(inByte, 0, 1023, 0, height);
  }
}


2ND PROCESSING SKETCH


Part[] allParts;
int numParts = 10;
boolean isPaused = false;

Part part;

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

  println(Serial.list());
  myPort = new Serial(this, Serial.list()[3], 9600);

  // don't generate a serialEvent() unless you get a newline character:
  myPort.bufferUntil('\n');

  // set inital background:
  background(0);
}
void draw () {
  // draw the line:
  stroke(127, 34, 255);
  line(xPos, height, xPos, height - inByte);

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

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:
    inByte = float(inString);
    println(inByte);
    inByte = map(inByte, 0, 1023, 0, height);
  }
}

how can I let a video triggerd by arduino not to loop, but when after delay triggerd again play?

$
0
0

this is the code i've been using

import processing.serial.*; import processing.video.*; Movie myMovie; Serial myPort; String val; boolean SpeelAf = false;

int x = 0;

void setup() { fullScreen(); background(0); noStroke(); fill(102); String portName = Serial.list()[0]; //verander de 0 in een 1 of 2 enzo., zo

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

myMovie = new Movie(this, "F:/Droombus.mp4"); //zet hier het ju

myMovie.play(); } void draw() { println(SpeelAf); if ( myPort.available() > 0) { // Als er data is, if (SpeelAf == false) {

  val = myPort.readStringUntil('\n');  //alleen uitlezen als film

  println(val);
 SpeelAf = true;
 println(SpeelAf);

} } if (SpeelAf == true) { myMovie.loop(); // afspelen tot het einde } else { myMovie.pause(); // afspelen tot het einde SpeelAf=false; } if (myMovie.available() == true) { myMovie.read(); // SpeelAf=true; } else { //SpeelAf=false; } image(myMovie, 0, 0); //dit is de grootte van het filmpje. Aan }


[Fixed] Strong delay when reading Serial Input

$
0
0

Problem solved by using serialEvent(), parsing the data and storing it in an array within serialEvent and then looping through that array and sending values to firmata in the draw() loop.

*

Hi Everyone, I'm in a bit of a time-crunch, so I'm hoping someone here can help me.

I need to read data from Arduino_1, check if values are higher than a threshold and then send them to another Arduino_2. Arduino_1is running code that I cannot change (it is also doing other things, I do not have whatever code is running on it, and I am worried I might break things if I start messing with it). Arduino_2 is running standard Firmata.

The problem I have is that currently there is a really high delay caused by the way I am Parsing the data. (I know its my parsing, because I have seen this work perfectly and the only thing that has changed is the code I am trying to recreate right now).

The incoming datastream from Arduino_1 looks like this (copy+paste form Arduino IDE):

...
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 2,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 1,
3, 2, 2, 2, 2, 2, 1, 2,
...

Its at 9700 Baud and I guess (but honestly have no idea) that there are 10ms delays between each line.

I am parsing it like so:

 if ( serial.available() > 0)
  {  // If data is available,
    val = serial.readStringUntil('\n');
    if (val!=null) {
      motorStates = split(val, ',');
      if (motorStates.length == 9) { //I don't understand why its 9. But it works.
        for (int i = 0; i<motorStates.length; i++) {
          if (int(trim(motorStates[i]))>3) {
            binaryMotorStates[i]=1;
          } else {
            binaryMotorStates[i]=0;
          }
        }
      }
     send();  //send values to Arduino
    }

The send function either uses Firmata directly, or sends out an OSC message to a second sketch which then writes to the Arduino using Firmata (using seperate sketches for sending and receiving has fixed some timing errors for me in the past). The check for the length of the array is only necessary if I have this code snippet running in the draw function. I have tried this both within serial.event as well as in draw and I get the same delays.

Any suggestions on what to try next, or better ways of parsing my data stream? I'm pretty sure that I'm making a mess of the parsing, I'd love alternate suggestions on how to do that.

Large Delay when using Serial data from Arduino

$
0
0

Hello,

I am having trouble getting my sketch to respond to my ardunio in actual time. There is about a 30 second delay. The delay gets longer as the sketch continues to run.

My goal: under certain conditions from the Arduino a sprite will play in processing. There are 4 condition (1 0, 1 1, 2 0, 2 1).

Code:

int numFrames = 7; int currentFrame = 0; PImage[] images = new PImage[numFrames];

import processing.serial.*; Serial myPort;
String val;

void setup() { size(1000,600); frameRate(5);

images[0] = loadImage("images/heart(1).gif"); images[1] = loadImage("images/heart(2).gif"); images[2] = loadImage("images/heart(3).gif"); images[3] = loadImage("images/heart(4).gif"); images[4] = loadImage("images/heart(5).gif"); images[5] = loadImage("images/heart(6).gif"); images[6] = loadImage("images/heart(7).gif");

String portName = Serial.list()[1]; myPort = new Serial(this, portName, 9600);

}

void draw() { background(255);

//Display Serial Data if (myPort.available() > 0) { if ( (val = myPort.readStringUntil(ENTER)) != null ) val = trim(val); else return; if (val != null) { println(val); } }

//control sketch currentFrame = (currentFrame+1) % numFrames; // Use % to cycle through frames int offset = 0;

if ("1 1".equals(val)) {
image(images[(currentFrame+offset) % numFrames], 333, 200);
offset+=2;

}

if("2 1".equals(val)){
image(images[(currentFrame+offset) % numFrames], 666, 200);
offset+=2;
player.play();
}

}

Any help is greatly appreciated!

Problem with save data from serial port

$
0
0

Hi guys I'm new with Processing development and I having some problems. here's the issue: I'm using an Arduino to measuere temperature and just wanna to send it to Processing by serial communication and store it in to a .txt file. I have already searched a solution in Processing tutorials and in this forum, but didn't find yet. Any help is welcome!! Here is my code (the comments are in Portuguese):

//Ler os dados da porta serial e salvar num arquivo .txt

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

Serial portaCOM5; //Cria um objeto da classe Serial
String dados, COM5; //Dados em ASCII recebidos do Arduino
int val ;// Dados recebidos pela porta serial

//Banco de dados
PrintWriter arquivo;

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


   println(Serial.list ()); //Lista no Prompt de Comando todas as portas seriais disponíveis

   COM5 = Serial.list()[0]; //Recebe a porta USB escolhida
   portaCOM5= new Serial(this, "COM5", 9600); //taxa de transfarencia 9600bps
   portaCOM5.bufferUntil('\n');

        //Banco de dados:
   arquivo = createWriter("temperaturas"+"_"+month()+"-"+day()+"-"+year()+"_"+hour()+"-"+minute()+"-"+
            second()+".txt"); //cria um arquivo para armazenar as temperaturas

    arquivo.print("Monitoramento de Temperatura DHT11");
    arquivo.println();

}

void draw()
{
  background (255); //Ajusta cor de fundo como branca

  }

void serialEvent(Serial portaCOM5)
{

     COM5= Serial.list()[0]; //Recebe a porta USB escolhida


  while (portaCOM5.available()>0)
  {
     val = portaCOM5.readString();
     arquivo.println();
  }

  arquivo.flush(); // Writes the remaining data to the file
  arquivo.close(); // Finishes the file

}

PS: When I check the monitor serial from Arduino, the data are there, so I believe anything here is wrong.

Thanks!!!!

Unterminated string constant error

$
0
0

I've made a laser scanner and I'm using Processing and an Arduino to run it. The Processing code has quite a few files in it and I'm having trouble with one of them. It's showing me the error but not showing me which line it's on. Here is the error it's throwing:

processing.app.SketchException: Unterminated string constant
at processing.mode.java.preproc.PdePreprocessor.checkForUnterminatedMultilineComment(PdePreprocessor.java:440)
at processing.mode.java.preproc.PdePreprocessor.write(PdePreprocessor.java:515)
at processing.mode.java.JavaBuild.preprocess(JavaBuild.java:277)
at processing.mode.java.JavaBuild.preprocess(JavaBuild.java:192)
at processing.mode.java.JavaBuild.build(JavaBuild.java:151)
at processing.mode.java.JavaBuild.build(JavaBuild.java:130)
at processing.mode.java.JavaMode.handleRun(JavaMode.java:120)
at processing.mode.java.JavaEditor$23.run(JavaEditor.java:697)
at java.lang.Thread.run(Thread.java:745)

Here is a pastebin link to my code (it's too long to post here): http://pastebin.com/RUUc9rxr

Help is appreciated!

If you need any of the other files let me know.

Arbitrary Audio Output on a Sample-by-Sample Basis

$
0
0

I would like to control my computer's audio output to display images on an oscilloscope. My project would be almost trivial if there were some sort of function (or method, I guess) that treats the sound card digital to analog converter more like the way it's done on an Arduino. That is, if analogWrite(LEFT_SPEAKER, outputValue); or something similar were in a Processing library, everything would be perfect.

As far as I have been able to determine so far, it seems that I need to fill an array and play that array with one of the audio libraries. I would fill the array with whatever I calculate I need for the oscilloscope display and keep it filled as I go.

It seems like this shouldn't be an unusual task, but I haven't been able to find much information (or I have been looking in the wrong places). Has anyone out there come across something like this before and can point me to it?

Thanks for your help.

Having problems with sketching the heart rate signal of AD8232.

$
0
0

Hello everyone, I am using AD8232 to sketch a heart rate signal. I am getting the serial data however I can't sketch it through the processing software. At least, it should sketch a blue flat line but it only pops a white screen.

Drawing of graphs from I2C IMU

$
0
0

Hello guys here is my code. I have tried to draw 3 graphs from arduino. I am reading angle by meaning inegration gyro angle , accelerometer angle and their complementary filter. But i get the message "Error, disabling serialEvent() for COM5 null"

import processing.serial.*;
Serial port;
float currentAngle ;
float pitchacc ;
float pitch ;
int gyro = 1;
int accel = 2;
int xn = 0;
float yn1 = 250;
float yn2 = 250;
float yn3 = 250;
int xk = 0;
void setup ()
{
  size (500,500);
  background (0);
  port = new Serial ( this, "COM5", 9600);
  port.bufferUntil ('\n');
}
void draw ()
{
fill(255);
stroke(255);
line (xn, yn1, xk, currentAngle);
line (xn, yn2, xk, pitchacc);
line (xn, yn3, xk, pitch);
if (xk > 500) {
background(0);
xk=0;
}
xn=xk;
yn1 = currentAngle;
yn2 = pitchacc;
yn3 = pitch;
xk++;
}

void serialEvent (Serial port)
{

  currentAngle = float(port.readStringUntil(gyro));
  pitchacc = float(port.readStringUntil(accel));
  pitch = float(port.readStringUntil('\n'));
}

Is there any way to playing a web-based game with Processing

$
0
0

Hi guys,

I have a project that playing a flash game which include mouse clicks with my hand moves and I want to use processing. I mean there is a game which I have to click on images and I want to click this images with my hand moves. I did Arduino part and connection part but I couldn't do the processing part. I cannot click on a webpage becuase if I click once, then the processing window goes back and doesn't work. Can you help me?

Sorry for bad English

Processing Signal in Arduino is not working

$
0
0

I am controlling Arduino motors on Proteus with serial communication between Arduino and Processing. Signal is receiving on COMPIM Arduino, but the motor is not working. Just want you to check my programming that is their any fault in it.

Arduino Programming

int motor1pin1=10; int val=0; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode (motor1pin1, OUTPUT); }

void loop() { while (Serial.available()){ val=Serial.read(); } if (val == '1'){ digitalWrite(motor1pin1,HIGH); } else{ digitalWrite(motor1pin1,LOW); } delay(100); // put your main code here, to run repeatedly: }

Processing programming part

case UP: println("UP!"); fill(255,0,0); triangle(100, 440, 160, 440, 130, 400); myPort.write('1'); break;

two buttons in the same place that act like a switch.

$
0
0

I am trying to build a login interface for an arduino that has several sensors, I was trying to create a button that would allow me to record and log to file and when clicked the button would become hidden run the associated code then the STOP button would become visible. Once that is clicked the logging would stop, hide the button and bring the REC button to the front.

The code kind of works but I am getting a bunch of errors. Here is a copy of what I have so far.

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


ControlP5 cp5;

Chart myChart1;
Chart myChart2;
Chart myChart3;
Chart myChart4;

Button b1;
Button b2;

Textlabel b1Lbl;
boolean logging = false;
String bevent;

void setup() {
  size(800, 600);
  cp5 = new ControlP5(this);

  List l = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "h");
  /* add a ScrollableList, by default it behaves like a DropdownList */
  cp5.addScrollableList("SELECT COM PORT")
     .setPosition(10, 10)
     .setSize(200, 100)
     .setBarHeight(20)
     .setItemHeight(20)
     .addItems(l)
     .close()
     // .setType(ScrollableList.LIST) // currently supported DROPDOWN and LIST
     ;
  // create a new button with name 'REC'
  b1 = cp5.addButton("REC")
     .setValue(0)
     .setPosition(740,10)
     .setSize(50,20)
//     .setLabel("REC")
     .setVisible(true)
     ;

  b2 = cp5.addButton("STOP")
     .setValue(0)
     .setPosition(740,10)
     .setSize(50,20)
//     .setLabel("STOP")
     .setVisible(false)
     ;

  myChart1 = cp5.addChart("sensor1")
     .setPosition(10, 40)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart1.addDataSet("sensin1");
//  myChart1.setData("sensein1", new float[100]);

  myChart2 = cp5.addChart("sensor2")
     .setPosition(405, 40)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart2.addDataSet("sensin2");
//  myChart2.setData("sensin2", new float[100]);

  myChart3 = cp5.addChart("sensor3")
     .setPosition(10, 250)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart3.addDataSet("sensin3");
//  myChart3.setData("sensein3", new float[100]);

  myChart4 = cp5.addChart("sensor4")
     .setPosition(405, 250)
     .setSize(385, 200)
     .setRange(-10, 120)
     .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
     .setStrokeWeight(1.5)
     .setColorCaptionLabel(color(40))
     .setLabel("")
     ;

//  myChart4.addDataSet("sensin4");
//  myChart4.setData("sensin4", new float[100]);
}

void draw() {
  background(240);
}

public void REC(){
  b1.hide();
  b2.show();
  b2.bringToFront();
  logging = true;
  println("Logging Data to File");
}

public void STOP(){
  b2.hide();
  b1.show();
  b1.bringToFront();
  logging = false;
  println("Stop Logging Data");
}

void dropdown(int n) {
  /* request the selected item based on index n */
  println(n, cp5.get(ScrollableList.class, "dropdown").getItem(n));

  /* here an item is stored as a Map  with the following key-value pairs:
   * name, the given name of the item
   * text, the given text of the item by default the same as name
   * value, the given value of the item, can be changed by using .getItem(n).put("value", "abc"); a value here is of type Object therefore can be anything
   * color, the given color of the item, how to change, see below
   * view, a customizable view, is of type CDrawable
   */

   CColor c = new CColor();
  c.setBackground(color(255,0,0));
  cp5.get(ScrollableList.class, "dropdown").getItem(n).put("color", c);

}

void keyPressed() {
  switch(key) {
    case('1'):
    /* make the ScrollableList behave like a ListBox */
    cp5.get(ScrollableList.class, "dropdown").setType(ControlP5.LIST);
    break;
    case('2'):
    /* make the ScrollableList behave like a DropdownList */
    cp5.get(ScrollableList.class, "dropdown").setType(ControlP5.DROPDOWN);
    break;
    case('3'):
    /*change content of the ScrollableList */
    List l = Arrays.asList("a-1", "b-1", "c-1", "d-1", "e-1", "f-1", "g-1", "h-1", "i-1", "j-1", "k-1");
    cp5.get(ScrollableList.class, "dropdown").setItems(l);
    break;
    case('4'):
    /* remove an item from the ScrollableList */
    cp5.get(ScrollableList.class, "dropdown").removeItem("k-1");
    break;
    case('5'):
    /* clear the ScrollableList */
    cp5.get(ScrollableList.class, "dropdown").clear();
    break;
  }
}`

The errors I am getting are as follows...

Feb 22, 2016 9:16:32 PM controlP5.ControlBroadcaster printMethodError
SEVERE: An error occured while forwarding a Controller event, please check your code at REC
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at controlP5.ControlBroadcaster.invokeMethod(Unknown Source)
    at controlP5.ControlBroadcaster.callTarget(Unknown Source)
    at controlP5.ControlBroadcaster.broadcast(Unknown Source)
    at controlP5.Controller.broadcast(Unknown Source)
    at controlP5.Button.setValue(Unknown Source)
    at TemperatureGUI_001.setup(TemperatureGUI_001.java:67)
    at processing.core.PApplet.handleDraw(PApplet.java:2377)
    at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1527)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)
Caused by: java.lang.NullPointerException
    at TemperatureGUI_001.REC(TemperatureGUI_001.java:140)
    ... 13 more
Feb 22, 2016 9:16:32 PM controlP5.ControlBroadcaster printMethodError
SEVERE: An error occured while forwarding a Controller event, please check your code at STOP
java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at controlP5.ControlBroadcaster.invokeMethod(Unknown Source)
    at controlP5.ControlBroadcaster.callTarget(Unknown Source)
    at controlP5.ControlBroadcaster.broadcast(Unknown Source)
    at controlP5.Controller.broadcast(Unknown Source)
    at controlP5.Button.setValue(Unknown Source)
    at TemperatureGUI_001.setup(TemperatureGUI_001.java:75)
    at processing.core.PApplet.handleDraw(PApplet.java:2377)
    at processing.awt.PSurfaceAWT$12.callDraw(PSurfaceAWT.java:1527)
    at processing.core.PSurfaceNone$AnimationThread.run(PSurfaceNone.java:316)
Caused by: java.lang.NullPointerException
    at TemperatureGUI_001.STOP(TemperatureGUI_001.java:148)
    ... 13 more

The unusual thing is that the code actually seems to work and the button acts the way I would have expected it but would rather not have the errors.

Having issues pixelating a video with Arduino input

$
0
0

I'm trying to create a pixelated video where the greater the distance from the arduino distance sensor (4 pin) the greater the size of pixels and vice versa. However so far I can run both and hear the audio playing but no video appears in processing window. I know that Processing is receiving the right data from arduino because it prints correctly in the console.

Arduino code int trigger=7; int echo=6; long time=0; long dist=0;

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


pinMode(trigger, OUTPUT); pinMode(echo, INPUT);
}


void loop()
{
digitalWrite(trigger, LOW); delay(5); digitalWrite(trigger, HIGH); delay(10); digitalWrite(trigger, LOW); time = pulseIn(echo, HIGH);
dist = (time/2) / 29.1;

if (
Serial.println(dist);



delay(1000);
}

Processing Code import processing.serial.*; import processing.video.*;

int numPixelsWide, numPixelsHigh;
int blockSize = 0;
Movie mov;
color movColors[];

Serial myPort;  // Create object from Serial class
String val;     // Data received from the serial port

void setup() {

  size(1200,700);

  noStroke();
  mov = new Movie(this, "MVI_3468.MOV");
  mov.loop();


  //println(Serial.list());
  String portName = Serial.list()[7]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);

}

void draw()
{
  if ( myPort.available() > 0)
  {  // If data is available,
  val = myPort.readStringUntil('\n');         // read it and store it in val
  }
  println(val); //print it out in the console

  if (val == null) {}

  else {
     blockSize = int(val);
  }


  if (blockSize == 0)
  {}

 else{

   //println(blockSize);

  numPixelsWide = width / blockSize;
  numPixelsHigh = height / blockSize;

  movColors = new color[numPixelsWide * numPixelsHigh];



   if (mov.available() == true) {
    mov.read();
    mov.loadPixels();
    int count = 0;
    for (int j = 0; j < numPixelsHigh; j++) {
      for (int i = 0; i < numPixelsWide; i++) {
        movColors[count] = mov.get(i*blockSize, j*blockSize);
        count++;
      }
    }
  }

  background(255);
  for (int j = 0; j < numPixelsHigh; j++) {
    for (int i = 0; i < numPixelsWide; i++) {
      fill(movColors[j*numPixelsWide + i]);
      rect(i*blockSize, j*blockSize, blockSize, blockSize);
    }
  }
 }
}

Any help would be welcomed, I am new to Processing so forgive me if there are obvious mistakes.

Arduino Processing with TeapotPacket, Rotation of a Box

$
0
0

Hi,

First time I'm working with arduino processing. Now I was playing arround with the Arduino MPU 6050 gyroscopic sensor. For this I used the Teapot libarary to rotate a box. This box rotates arround his gravity of center. Now I would like to change this So it doesn't rotate arround it center of gravity but arround 1 of his sides.

Does anybody know how to change this?

Attached is the code. Kind regards

import processing.serial.*; import processing.opengl.*; import toxi.geom.*; import toxi.processing.*;

ToxiclibsSupport gfx;

Serial port; // The serial port char[] teapotPacket = new char[14]; // InvenSense Teapot packet int serialCount = 0; // current packet byte position int synced = 0; int interval = 0;

float[] q = new float[4]; Quaternion quat = new Quaternion(1, 0, 0, 0);

float[] gravity = new float[3]; float[] euler = new float[3]; float[] ypr = new float[3];

void setup() { // 300px square viewport using OpenGL rendering size(1920, 600, OPENGL); gfx = new ToxiclibsSupport(this);

// setup lights and antialiasing
lights();
smooth();

// display serial port list for debugging/clarity
println(Serial.list());

// get the first available port (use EITHER this OR the specific port code below)
//String portName = Serial.list()[0];

// get a specific serial port (use EITHER this OR the first-available code above)
String portName = "COM3";

// open the serial port
port = new Serial(this, portName, 115200);

// send single character to trigger DMP init/start
// (expected by MPU6050_DMP6 example Arduino sketch)
port.write('r');

}

void draw() { if (millis() - interval > 1000) { // resend single character to trigger DMP init/start // in case the MPU is halted/reset while applet is running port.write('r'); interval = millis(); }

// black background
background(0);

// translate everything to the middle of the viewport
pushMatrix();
translate(width/2, height/2);

// 3-step rotation from yaw/pitch/roll angles (gimbal lock!)
// ...and other weirdness I haven't figured out yet
//rotateY(-ypr[0]);
//rotateZ(-ypr[1]);
//rotateX(-ypr[2]);

// toxiclibs direct angle/axis rotation from quaternion (NO gimbal lock!)
// (axis order [1, 3, 2] and inversion [-1, +1, +1] is a consequence of
// different coordinate system orientation assumptions between Processing
// and InvenSense DMP)
float[] axis = quat.toAxisAngle();
rotate(axis[0], -axis[1], axis[3], axis[2]);

// Box
fill(255,0,0,200);
box(10,10,200);

popMatrix();

}

void serialEvent(Serial port) { interval = millis(); while (port.available() > 0) { int ch = port.read();

    if (synced == 0 && ch != '$') return;   // initial synchronization - also used to resync/realign if needed
    synced = 1;
    print ((char)ch);

    if ((serialCount == 1 && ch != 2)
        || (serialCount == 12 && ch != '\r')
        || (serialCount == 13 && ch != '\n'))  {
        serialCount = 0;
        synced = 0;
        return;
    }

    if (serialCount > 0 || ch == '$') {
        teapotPacket[serialCount++] = (char)ch;
        if (serialCount == 14) {
            serialCount = 0; // restart packet byte position

            // get quaternion from data packet
            q[0] = ((teapotPacket[2] << 8) | teapotPacket[3]) / 16384.0f;
            q[1] = ((teapotPacket[4] << 8) | teapotPacket[5]) / 16384.0f;
            q[2] = ((teapotPacket[6] << 8) | teapotPacket[7]) / 16384.0f;
            q[3] = ((teapotPacket[8] << 8) | teapotPacket[9]) / 16384.0f;
            for (int i = 0; i < 4; i++) if (q[i] >= 2) q[i] = -4 + q[i];

            // set our toxilibs quaternion to new data
            quat.set(q[0], q[1], q[2], q[3]);

            /*
            // below calculations unnecessary for orientation only using toxilibs

            // calculate gravity vector
            gravity[0] = 2 * (q[1]*q[3] - q[0]*q[2]);
            gravity[1] = 2 * (q[0]*q[1] + q[2]*q[3]);
            gravity[2] = q[0]*q[0] - q[1]*q[1] - q[2]*q[2] + q[3]*q[3];

            // calculate Euler angles
            euler[0] = atan2(2*q[1]*q[2] - 2*q[0]*q[3], 2*q[0]*q[0] + 2*q[1]*q[1] - 1);
            euler[1] = -asin(2*q[1]*q[3] + 2*q[0]*q[2]);
            euler[2] = atan2(2*q[2]*q[3] - 2*q[0]*q[1], 2*q[0]*q[0] + 2*q[3]*q[3] - 1);

            // calculate yaw/pitch/roll angles
            ypr[0] = atan2(2*q[1]*q[2] - 2*q[0]*q[3], 2*q[0]*q[0] + 2*q[1]*q[1] - 1);
            ypr[1] = atan(gravity[0] / sqrt(gravity[1]*gravity[1] + gravity[2]*gravity[2]));
            ypr[2] = atan(gravity[1] / sqrt(gravity[0]*gravity[0] + gravity[2]*gravity[2]));

            // output various components for debugging
            //println("q:\t" + round(q[0]*100.0f)/100.0f + "\t" + round(q[1]*100.0f)/100.0f + "\t" + round(q[2]*100.0f)/100.0f + "\t" + round(q[3]*100.0f)/100.0f);
            //println("euler:\t" + euler[0]*180.0f/PI + "\t" + euler[1]*180.0f/PI + "\t" + euler[2]*180.0f/PI);
            //println("ypr:\t" + ypr[0]*180.0f/PI + "\t" + ypr[1]*180.0f/PI + "\t" + ypr[2]*180.0f/PI);
            */
        }
    }
}

}

Viewing all 747 articles
Browse latest View live