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

Looping recorded sounds with minim...

$
0
0

Hi I want to record sounds (multiple sounds which should be stored in a folder) with a microphone and loop it with the other sounds I have added - song, song 2 and song 3. The problem is I want the software to initialize and loop the recorded sound by itself, so even if I shut down the program and start it up again, it should continue from where I left. Thanks in advance.

`import processing.serial.*; //Importing serial library import ddf.minim.*; //Importing minim library. Minim is the library we are using for sound-related activities, such as record and playback.

Serial myPort;

Minim minim;

AudioPlayer song; AudioPlayer song2; AudioPlayer song3;

AudioInput in; AudioRecorder recorder;

int countname; //change the name int name = 000000; int startGain = 0;

void newFile() {
countname = (name + 1); recorder = minim.createRecorder(in, "Rec" + countname + ".wav", true); }

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

//println(Serial.list()); myPort = new Serial(this, Serial.list()[0], 9600); myPort.bufferUntil('\n');

minim = new Minim(this);

in = minim.getLineIn(Minim.STEREO, 2048); newFile();//go to change file name

song = minim.loadFile("beyonce.mp3"); song2 = minim.loadFile("dajam.wav"); song3 = minim.loadFile("Rec1.wav"); }

void draw() { background(0); stroke(255);

if ( recorder.isRecording() ) { text("Currently recording...", 5, 15); ellipse(60,60,55,55); fill(255,0,0); } else { text(" Not recording.", 5, 15); ellipse(60,60,55,55); fill(0,255,0); } }

void serialEvent (Serial myPort) { String inString = myPort.readStringUntil('\n');

if (inString != null) { inString = trim (inString);

float inByte = float(inString);
println(inByte);

if (inByte == 1){
  song.loop();
  song2.loop();
  song3.loop();
  song.rewind();
  song2.rewind();
  song3.rewind();
}

if (inByte == 0){
  song.pause();
  song2.pause();
  song3.pause();
  song.rewind();
  song2.rewind();
  song3.rewind();
}

if (inByte == 2){ if ( recorder.isRecording() ) {
recorder.endRecord();

  name++;
  recorder.save();
  println("Done saving.");
  println(name);
  }
  else
  {
  newFile();
  recorder.beginRecord();
  }
}

if (inByte == 3){ song.setGain(startGain++ * 2); song2.setGain(startGain++ * 2); song3.setGain(startGain++ * 2); }

if (inByte == 4){
 song.setGain(startGain-- * 2);
 song2.setGain(startGain-- * 2);
 song3.setGain(startGain-- * 2);
}

} }

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

super.stop(); }`


null pointer exception processing error

$
0
0

Hello i am currently working my thesis (creation of BCI with emotiv, arduino,servo and processing). My goal is to send r and l keystrokes to move the servo right or left with emotiv. For start i have create a code in processing (actually i try to combine things that i found here in the forum) and to arduino. I get a null pointer exception error on valtowrite when i try to hit r or l keystrokes. The goal is to identify automatically the port .Please advise.

Here is the processing code:

import processing.serial.*;

Serial ser_port;                // for serial port
PFont fnt;                      // for font
int num_ports;
boolean device_detected = false;
String[] port_list;
String detected_port = "";

void setup() {
    size(400, 200);                         // size of application window
    background(0);                          // black background
    fnt = createFont("Arial", 16, true);    // font displayed in window

    println(Serial.list());

    // get the number of detected serial ports
    num_ports = Serial.list().length;
    // save the current list of serial ports
    port_list = new String[num_ports];
    for (int i = 0; i < num_ports; i++) {
        port_list[i] = Serial.list()[i];
    }
}

void draw()
{
    background(0);
    // display instructions to user
    textFont(fnt, 14);
    text("1. Arduino or serial device must be unplugged.", 20, 30);
    text("   (unplug device and restart this application if not)", 20, 50);
    text("2. Plug the Arduino or serial device into a USB port.", 20, 80);

    // see if Arduino or serial device was plugged in
    if ((Serial.list().length > num_ports) && !device_detected) {
        device_detected = true;
        // determine which port the device was plugge into
        boolean str_match = false;
        if (num_ports == 0) {
            detected_port = Serial.list()[0];
        }
        else {
            // go through the current port list
            for (int i = 0; i < Serial.list().length; i++) {
                // go through the saved port list
                for (int j = 0; j < num_ports; j++) {
                    if (Serial.list()[i].equals(port_list[j])) {
                        break;
                    }
                    if (j == (num_ports - 1)) {
                        str_match = true;
                        detected_port = Serial.list()[i];
                    }
                }
            }
        }
    }
    // calculate and display serial port name
    if (device_detected) {
        text("Device detected:", 20, 110);
        textFont(fnt, 18);
        text(detected_port, 20, 150);
        textFont(fnt, 14);
        text("3.  Now think Right or Left in this Window",20,190);

    }
}

char valToWrite = 'r' & 'l'; //a value to send as a single byte

void keyPressed(){
  valToWrite = key;
  ser_port.write(valToWrite);
}

void keyReleased(){
  valToWrite = 'r' & 'l';
  ser_port.write(valToWrite);
}

AND here is the arduino code:

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

#define SERVO_PIN 9


int pos = 0;    // variable to store the servo position
int lastMotionMillis = 0;

void setup() {
  Serial.begin(9600);
  myservo.attach(SERVO_PIN);  // attaches the servo on pin 9 to the servo object
  delay(300);
  myservo.write(90);
}

void loop() {
   if (Serial.available() ) {
     char c = Serial.read();
     if (c=='r') {
       pos = pos +25;
       myservo.write(pos);
       lastMotionMillis = millis();
     }
     if (c=='l') {
       pos = pos -25;
       myservo.write(pos);
       lastMotionMillis = millis();
     }

     }
   }

playing multiple tracks at the same time and adjusting volume

$
0
0

This is for an art project. I'm trying to play 4 wav. files on an infinite loop at the volume 0. when I press a button, the volume should rise up to 100. each button is connected with a wav. file, so when I press button A, file A's volume would rise to 100. I hope this makes things clear enough?

This is the ARDUINO code, I only have 2 wav files at the moment.

  int ledPin = 2;
  int ledPin3 = 3;
  int value = 0;

  void setup()
{
  Serial.begin(9600);
  pinMode(ledPin, INPUT);
  pinMode(ledPin3, INPUT);

}

void loop()
{
  if (digitalRead(ledPin) == HIGH)
  {
    Serial.println("1");
    delay (50);
  }
  else
  {
   Serial.println("2");
   delay (50);
  }

    if (digitalRead(ledPin3) == HIGH)
  {
    Serial.println("3");
    delay (50);
  }
  else
  {
   Serial.println("4");
   delay (50);
  }


}

This is the PROCESSING file, also with two files.

import ddf.minim.*;
import processing.serial.*;

Serial port;
float value = 0;
float old = 0;

Minim minim;
AudioPlayer player;



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

  minim = new Minim(this);
  player = minim.loadFile("harp.wav");
  player.play();
  player.shiftGain(-80,-80,100);
  player.rewind();


  port = new Serial(this, "/dev/cu.usbmodem1421", 9600);
  port.bufferUntil('\n');
}

void draw()
{
  background(0);
  if ((value == 1) || (value == 2))
  {
  if (value != old)
  {
  if (value == 1)
  {
    //volume up
    player.shiftGain(-80, 0, 100);

  }
 else if (value == 2)
 {
   //volume down
   player.shiftGain(0,-80,100);

 }

  }
 old = value;

}
}
void serialEvent (Serial port)
{
  value = float(port.readStringUntil('\n'));
}`


This is PROCESSING file version B,

`import ddf.minim.*;
import processing.serial.*;

Serial port;
float value = 0;

Minim minim;
Minim minim2;
AudioPlayer player;
AudioPlayer player2;


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

  minim = new Minim(this);
  player = minim.loadFile("basses.wav");
  player.play();
  player.mute();
  player.rewind();

  minim2 = new Minim(this);
  player2 = minim2.loadFile("harp.wav");
  player2.play();
  player2.mute();
  player2.rewind();


  port = new Serial(this, "/dev/cu.usbmodem1421", 9600);
  port.bufferUntil('\n');
}

void draw()
{
  background(0);
  if (value == 2)
  {
    player.unmute();
    delay(3000);

  }
 if (value == 1);
 {
   player.mute();
   delay(3000);

 }

   if (value == 4)
  {
    player2.unmute();
    delay(3000);

  }
 if (value == 3);
 {
   player2.mute();
   delay(3000);

 }

}


void serialEvent (Serial port)
{
  value = float(port.readStringUntil('\n'));
}

The problem is that a) files are not playing at the same time b) it's clicking when the button is pressed c) overall, it's not really responding to the button, just playing on and off by itself. Any ideas or an easier way to do this maybe? I really appreciate it.

How to use ultrasonic sensor to trigger a video ? (Arduino+processing)

$
0
0

Hey ! First time I'm using Arduino and Processing at the same time and I'm completely lost ! I'm designing an interactive installation, and I need the trigger the position in a video with the distance : as we get closer to the sensor, the video will move. I've set up a code for Arduino which gives the distance. For processing, I found a code which triggers the position with the webcam (and the size of the head of the spectator, as he gets closer, his head become bigger, and the position moves forward). Do you have any idea/ thoughts about how I can modify this code ? It's the same idea, with arduino instead of the webcam but I don't know where to start...

Thank you very much !

Arduino :

#include <NewPing.h>
#include <Servo.h>


#define TRIGGER_PIN  12  // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     11  // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

int LEDpin = 13;
Servo myservo;
int val;

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
  Serial.begin(9600); // Open serial monitor at 115200 baud to see ping results.
  pinMode(LEDpin, OUTPUT);
  myservo.attach(9);// attaches servo to pin 9

}

void loop() {
  delay(400);                      // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
  unsigned int uS = sonar.ping(); // Send ping, get ping time in microseconds (uS).
  //Serial.print("Ping: ");
  Serial.println(uS / US_ROUNDTRIP_CM); // Convert ping time to distance in cm and print result (0 = outside set distance range)
  //Serial.println("cm");
  //if(uS / US_ROUNDTRIP_CM < 100) {digitalWrite(LEDpin, HIGH);}
  //else if (uS / US_ROUNDTRIP_CM > 100) {digitalWrite(LEDpin, LOW);}
 // else if (uS / US_ROUNDTRIP_CM > 100) {digitalWrite(LEDpin, LOW);}
  //delay (200);

  val = (uS / US_ROUNDTRIP_CM);
  val = map(val, 0, 172, 15, 180);
  myservo.write(val);
  delay (150);


}

PROCESSING

import gab.opencv.*;
import processing.video.*;
import java.awt.*;
//-------------------------------------------------
/*


*/
//-------------------------------------------------
Capture video;
OpenCV opencv;
//---
Movie monSuperFilm;// déclaration du film
float positionDuFilmEnSecondes;//position ds le film
Integer surfaceVisages,surfaceMin,surfaceMax;
//-------------------------------------------------
/*


*/
//-------------------------------------------------
void setup() {
  //----------------
  size(1080, 720);//dimensions de votre film en pixels; mettre la définition de votre film
  //-----------------
  // partie video cam
  //-----------------
  video = new Capture(this, 640/2, 480/2);
  opencv = new OpenCV(this, 640/2, 480/2);
  opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE);
  video.start();
  //-----------------
  // partie film
  //-----------------
    monSuperFilm = new Movie(this,"pattern1080-6low-1.mov");// chargement du film ; mettre le nom de votre film qui est dans le dossier data
    monSuperFilm.loop();
  //-----------------
  // partie visages
  //-----------------
  // plus la surface du visage est grande dans l'image retournée par la caméra du mac et plus on est près
  // le programme cumule les surfaces de tous les visages capturés par la caméra; à essayer à plusieurs devant le mac !
    surfaceMin=400;// min 0 //surface du visage sur la camera qui correspond au début du film
    surfaceMax=1500;// max 640x480=307200 //surface du visage sur la camera qui correspond à la fin du film
}
//-------------------------------------------------
/*


*/
//-------------------------------------------------
void draw() {
  //background(255);
  //scale(2);
  opencv.loadImage(video);

  //image(video, 0, 0 );

  //noFill();
  stroke(0, 255, 0);
  strokeWeight(3);
  Rectangle[] faces = opencv.detect();
  println(faces.length);
//---------------------------------------------
// calcul de la surface occupée par les visages
//---------------------------------------------
surfaceVisages=0;
  for (int i = 0; i < faces.length; i++) {
    //println(faces[i].x + "," + faces[i].y);
    //rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height);
    surfaceVisages=surfaceVisages+faces[i].width*faces[i].height;
  }
  fill(0);
  text(str(surfaceMin)+" / "+str(surfaceVisages)+" / "+str(surfaceMax),10,50);
   monSuperFilm.read();//on lit l'image du film
  positionDuFilmEnSecondes=map(surfaceVisages,surfaceMin,surfaceMax,0,monSuperFilm.duration());
  monSuperFilm.jump(positionDuFilmEnSecondes);// on se déplace dans le film
  image(monSuperFilm, 0, 0);//on affiche l'image courante du film

}
//-------------------------------------------------
/*


*/
//-------------------------------------------------
void captureEvent(Capture c) {
  c.read();
}

How do I fix port busy?

$
0
0

I am trying to install the Processing.org(Processing) code on an Arduino Mega 2560 board with A sample program for the MPU5060("MPU5060_DMP6.ino"). Everything seems to be fine, except that I get the message that the port(COM5) is busy. If I clear COM5 and run MPU5060_DMP6.ino, then Processing("MPUTeapot") states that COM5 is busy. If I clear COM5 and run MPUTeapot, then the MPU5060_DPM6.ino states that COM5 is busy. The sample code is altered as instructed and checked. I can not find a problem. The customized sample code for both MPU5060_DMP6.ino and MPUTeapot are included. Can someone please show me what is wrong.

The Arduino sketch(MPU5060_DMP6.ino) executes in "Arduino IDE". The Processing.org sketch("MPUTeapot" is also written in Arduino C++ but executes in a separate IDE specifically for Processing.

"MPU5060_DMP6.ino"

    #include "I2Cdev.h"

    #include "MPU6050_6Axis_MotionApps20.h"
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        #include "Wire.h"
    #endif

    MPU6050 mpu;
    //MPU6050 mpu(0x69); // <-- use for AD0 high

    #define OUTPUT_TEAPOT



    #define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards  --  and Mega 2560
    #define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
    bool blinkState = false;

    // MPU control/status vars
    bool dmpReady = false;  // set true if DMP init was successful
    uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
    uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
    uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
    uint16_t fifoCount;     // count of all bytes currently in FIFO
    uint8_t fifoBuffer[64]; // FIFO storage buffer

    // orientation/motion vars
    Quaternion q;           // [w, x, y, z]         quaternion container
    VectorInt16 aa;         // [x, y, z]            accel sensor measurements
    VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
    VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
    VectorFloat gravity;    // [x, y, z]            gravity vector
    float euler[3];         // [psi, theta, phi]    Euler angle container
    float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

    // packet structure for InvenSense teapot demo
    uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };

    volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
    void dmpDataReady() {
        mpuInterrupt = true;
    }

    void setup() {
        // join I2C bus (I2Cdev library doesn't do this automatically)
        #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
            Wire.begin();
            Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
        #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
            Fastwire::setup(400, true);
        #endif

        // initialize serial communication
        // (115200 chosen because it is required for Teapot Demo output, but it's
        // really up to you depending on your project)
        Serial.begin(115200);
        while (!Serial); // wait for Leonardo enumeration, others continue immediately

        // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
        // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
        // the baud timing being too misaligned with processor ticks. You must use
        // 38400 or slower in these cases, or use some kind of external separate
        // crystal solution for the UART timer.

        // initialize device
        Serial.println(F("Initializing I2C devices..."));
        mpu.initialize();
        pinMode(INTERRUPT_PIN, INPUT);

        // verify connection
        Serial.println(F("Testing device connections..."));
        Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

        // wait for ready
        Serial.println(F("\nSend any character to begin DMP programming and demo: "));
        while (Serial.available() && Serial.read()); // empty buffer
        while (!Serial.available());                 // wait for data
        while (Serial.available() && Serial.read()); // empty buffer again

        // load and configure the DMP
        Serial.println(F("Initializing DMP..."));
        devStatus = mpu.dmpInitialize();

        // supply your own gyro offsets here, scaled for min sensitivity
        mpu.setXGyroOffset(220);
        mpu.setYGyroOffset(76);
        mpu.setZGyroOffset(-85);
        mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

        // make sure it worked (returns 0 if so)
        if (devStatus == 0) {
            // turn on the DMP, now that it's ready
            Serial.println(F("Enabling DMP..."));
            mpu.setDMPEnabled(true);

            // enable Arduino interrupt detection
            Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
            attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
            mpuIntStatus = mpu.getIntStatus();

            // set our DMP Ready flag so the main loop() function knows it's okay to use it
            Serial.println(F("DMP ready! Waiting for first interrupt..."));
            dmpReady = true;

            // get expected DMP packet size for later comparison
            packetSize = mpu.dmpGetFIFOPacketSize();
        } else {
            // ERROR!
            // 1 = initial memory load failed
            // 2 = DMP configuration updates failed
            // (if it's going to break, usually the code will be 1)
            Serial.print(F("DMP Initialization failed (code "));
            Serial.print(devStatus);
            Serial.println(F(")"));
        }

        // configure LED for output
        pinMode(LED_PIN, OUTPUT);
    }



    // ================================================================
    // ===                    MAIN PROGRAM LOOP                     ===
    // ================================================================

    void loop() {
        // if programming failed, don't try to do anything
        if (!dmpReady) return;
        }

        // reset interrupt flag and get INT_STATUS byte
        mpuInterrupt = false;
        mpuIntStatus = mpu.getIntStatus();

        // get current FIFO count
        fifoCount = mpu.getFIFOCount();

        // check for overflow (this should never happen unless our code is too inefficient)
        if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
            // reset so we can continue cleanly
            mpu.resetFIFO();
            Serial.println(F("FIFO overflow!"));

        // otherwise, check for DMP data ready interrupt (this should happen frequently)
        } else if (mpuIntStatus & 0x02) {
            // wait for correct available data length, should be a VERY short wait
            while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

            // read a packet from FIFO
            mpu.getFIFOBytes(fifoBuffer, packetSize);

            // track FIFO count here in case there is > 1 packet available
            // (this lets us immediately read more without waiting for an interrupt)
            fifoCount -= packetSize;


            #ifdef OUTPUT_READABLE_EULER
                // display Euler angles in degrees
                mpu.dmpGetQuaternion(&q, fifoBuffer);
                mpu.dmpGetEuler(euler, &q);
                Serial.print("euler\t");
                Serial.print(euler[0] * 180/M_PI);
                Serial.print("\t");
                Serial.print(euler[1] * 180/M_PI);
                Serial.print("\t");
                Serial.println(euler[2] * 180/M_PI);
            #endif




            #ifdef OUTPUT_TEAPOT
                // display quaternion values in InvenSense Teapot demo format:
                teapotPacket[2] = fifoBuffer[0];
                teapotPacket[3] = fifoBuffer[1];
                teapotPacket[4] = fifoBuffer[4];
                teapotPacket[5] = fifoBuffer[5];
                teapotPacket[6] = fifoBuffer[8];
                teapotPacket[7] = fifoBuffer[9];
                teapotPacket[8] = fifoBuffer[12];
                teapotPacket[9] = fifoBuffer[13];
                Serial.write(teapotPacket, 14);
                teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
            #endif

            // blink LED to indicate activity
            blinkState = !blinkState;
            digitalWrite(LED_PIN, blinkState);
        }
    }

Following is the code for MPUTeapot

"MPUTeapot"

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

    // NOTE: requires ToxicLibs to be installed in order to run properly.
    // 1. Download from http://toxiclibs.org/downloads
    // 2. Extract into [userdir]/Processing/libraries
    //    (location may be different on Mac/Linux)
    // 3. Run and bask in awesomeness

    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(300, 300, 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 = "COM5";

        // 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);
        float[] axis = quat.toAxisAngle();
        rotate(axis[0], -axis[1], axis[3], axis[2]);

        // draw main body in red
        fill(255, 0, 0, 200);
        box(10, 10, 200);

        // draw front-facing tip in blue
        fill(0, 0, 255, 200);
        pushMatrix();
        translate(0, 0, -120);
        rotateX(PI/2);
        drawCylinder(0, 20, 20, 8);
        popMatrix();

        // draw wings and tail fin in green
        fill(0, 255, 0, 200);
        beginShape(TRIANGLES);
        vertex(-100,  2, 30); vertex(0,  2, -80); vertex(100,  2, 30);  // wing top layer
        vertex(-100, -2, 30); vertex(0, -2, -80); vertex(100, -2, 30);  // wing bottom layer
        vertex(-2, 0, 98); vertex(-2, -30, 98); vertex(-2, 0, 70);  // tail left layer
        vertex( 2, 0, 98); vertex( 2, -30, 98); vertex( 2, 0, 70);  // tail right layer
        endShape();
        beginShape(QUADS);
        vertex(-100, 2, 30); vertex(-100, -2, 30); vertex(  0, -2, -80); vertex(  0, 2, -80);
        vertex( 100, 2, 30); vertex( 100, -2, 30); vertex(  0, -2, -80); vertex(  0, 2, -80);
        vertex(-100, 2, 30); vertex(-100, -2, 30); vertex(100, -2,  30); vertex(100, 2,  30);
        vertex(-2,   0, 98); vertex(2,   0, 98); vertex(2, -30, 98); vertex(-2, -30, 98);
        vertex(-2,   0, 98); vertex(2,   0, 98); vertex(2,   0, 70); vertex(-2,   0, 70);
        vertex(-2, -30, 98); vertex(2, -30, 98); vertex(2,   0, 70); vertex(-2,   0, 70);
        endShape();

        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);
                    */
                }
            }
        }
    }

    void drawCylinder(float topRadius, float bottomRadius, float tall, int sides) {
        float angle = 0;
        float angleIncrement = TWO_PI / sides;
        beginShape(QUAD_STRIP);
        for (int i = 0; i < sides + 1; ++i) {
            vertex(topRadius*cos(angle), 0, topRadius*sin(angle));
            vertex(bottomRadius*cos(angle), tall, bottomRadius*sin(angle));
            angle += angleIncrement;
        }
        endShape();

        // If it is not a cone, draw the circular top cap
        if (topRadius != 0) {
            angle = 0;
            beginShape(TRIANGLE_FAN);

            // Center point
            vertex(0, 0, 0);
            for (int i = 0; i < sides + 1; i++) {
                vertex(topRadius * cos(angle), 0, topRadius * sin(angle));
                angle += angleIncrement;
            }
            endShape();
        }

        // If it is not a cone, draw the circular bottom cap
        if (bottomRadius != 0) {
            angle = 0;
            beginShape(TRIANGLE_FAN);

            // Center point
            vertex(0, tall, 0);
            for (int i = 0; i < sides + 1; i++) {
                vertex(bottomRadius * cos(angle), tall, bottomRadius * sin(angle));
                angle += angleIncrement;
            }
            endShape();
        }
    }

Please and Thank You for solving such a "First Grade"(beginner) problem

Thank You for the input. This Post has been edited for readability.

Game Control Plus processing sketch stops when loses windows focus.

$
0
0

I posted a question earlier but it was really poorly written. Hopefully this is clear. Game Control Plus is a fantastic library that allows you to easily write a processing sketch that captures a windows 10 joystick movement. But a problem I am having is that I need to run a driving simulation at the same time as the sketch so I can capture the joystick movements. Whenever I focus on the driving simulation window, the GC+ sketch stops. Focus on the Processing sketch window the GC+ joystick sketch restarts and the driving simulation stops. I understand in previous windows versions you could have two active windows. (XP??) Any help would be so gratefully appreciated. (I posted example code from GC+ library.)

/**
 Basic demonstration of using a joystick.

 When this sketch runs it will try and find
 a game device that matches the configuration
 file 'joystick' if it can't match this device
 then it will present you with a list of devices
 you might try and use.

 The chosen device requires 2 sliders and 2 buttons.
 */

import org.gamecontrolplus.gui.*;
import org.gamecontrolplus.*;
import net.java.games.input.*;

ControlIO control;
ControlDevice stick;
float px, py;
boolean trailOn;

ArrayList<PVector>  shadows = new ArrayList<PVector>();
ArrayList<PVector>  trail = new ArrayList<PVector>();

public void setup() {
  size(400, 400);
  // Initialise the ControlIO
  control = ControlIO.getInstance(this);
  // Find a device that matches the configuration file
  stick = control.getMatchedDevice("joystick");
  if (stick == null) {
    println("No suitable device configured");
    System.exit(-1); // End the program NOW!
  }
  // Setup a function to trap events for this button
  stick.getButton("SHADOW").plug(this, "dropShadow", ControlIO.ON_RELEASE);
}

// Poll for user input called from the draw() method.
public void getUserInput() {
  px = map(stick.getSlider("X").getValue(), -1, 1, 0, width);
  py = map(stick.getSlider("Y").getValue(), -1, 1, 0, height);
  trailOn = stick.getButton("TRAIL").pressed();
}

// Event handler for the SHADOW button
public void dropShadow() {
  // Make sure we have the latest position
  getUserInput();
  shadows.add(new PVector(px, py, 40));
}

public void draw() {
  getUserInput(); // Polling
  background(255, 255, 240);
  // Draw shadows
  fill(0, 0, 255, 32);
  noStroke();
  for (PVector shadow : shadows)
    ellipse(shadow.x, shadow.y, shadow.z, shadow.z);
  // Add to trail if appropriate trail
  if (trailOn)
    trail.add(new PVector(px, py));
  else
    trail.clear();
  // If there is a trail then draw it
  if (trail.size() > 1) {
    stroke(132, 0, 0);
    for (int n = 1; n < trail.size(); n++) {
      PVector v0 = trail.get(n-1);
      PVector v1 = trail.get(n);
      line(v0.x, v0.y, v1.x, v1.y);
      v0 = v1;
    }
  }
  // Show position
  noStroke();
  fill(255, 64, 64, 64);
  ellipse(px, py, 20, 20);
}

Is Arduino 1.6.13 stable? or Did my MPU6050 just break?

$
0
0

I just upgraded to Arduino 1.6.13 I am using a Mega 2560, so I changed the #include, but noticed that the MeGyro example only works for a few seconds. I question if my MPU6050 broke on the same day that I upgraded the software. Is there a workaround that fixes the problem?

Solved This Arduino program executes 3 lines of code and then restarts itself just becauseitwantsto!

$
0
0
int Segment, n, Compare;
double ANGLE                      [300] ;
double DISTANCE                   [300] ;
double XX                         [300] ;
double YY                         [300] ;
double Correlation           [20 ] = {1,9,2,8,3,7,2,6,5};
double Sorted_Correlation    [20 ] = {1,2,2,3,7,8,9,5,6};
bool   Matched               [20 ] = {0,0,0,0,0,0,0,0,0};
int    Backward_Index        [20 ] = {1,1,1,1,1,1,1,1,1};
double rotation, newangle, oldangle;
int Creatures = 7;
bool Searching = 1;
double angle_rad = PI / 180.;
double angle_deg = 180.0 / PI;
double speed;
double Distance;
int x, count=1, size_of_array=0, Segment0, MinPower ;
boolean Left = 1, Turning, Confident ;


void setup() {
  //Set Pwm 8KHz
  TCCR1A = _BV(WGM10);
  TCCR1B = _BV(CS11) | _BV(WGM12);
  TCCR2A = _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS21);


  int n = 6,k, temp, Heading ;
  REAL x ;
  REAL y;
  REAL m,b,r;

  Serial.begin(9600);
  Serial.println(" \n");
  Serial.println("Room_Map_MAM_10.ino") ;
  Serial.println("Start Setuuuup");
  gyro.begin();
  Serial.println("asdfasf");
  _delay(1);

And the output is:

Room_Map.ino
Start Setup


Room_Map.ino
Start Setup

btw I just upgraded to Arduino IDE 1.6.13 if that makes a difference. I never had this problem before the upgrade.

Answer: Be careful with the phrase "Start Setup" in Arduino IDE 1.6.13 It is actionable!

No, that is not it. Something is wrong with "gyro.begin()"

No, that is not it. And the moral of the story is ... Do not assign variables more memory space than you have memory space.

Yes, THAT is it.

SOLVED!


Control P5 inside a class?

$
0
0

Hello,

I'm building an interface using controlp5 for an Arduino with some sensors attached to it. I want to have many sensors, so I am trying to build the interface in a modular fashion so that I can just instantiate as many control panels as I have sensors, and update all the panels at once when my hardware sends a telemetry packet.

I have made something that kind of works and draws the widgets, but it appears that my callback functions are not being triggered - for example, when one of the buttons in the code below is pressed, the corresponding serial printout does not happen. Also, the println(channelOne.currentGain); in the main sketch always prints 0, no matter what the gain slider is doing.

I don't do much Java, so I am sure that I am missing something basic here about how the class and its variables are declared, any pointers on how to set this up correctly would be much appreciated!

Here is my main program:

import processing.core.PApplet;

SensorChannel channelOne;

void setup()
{
  size(800, 450);
  smooth();

  channelOne = new SensorChannel(this, 30, 30);
}

void draw()
{
  background(0);

  println(channelOne.currentGain);
  delay(20);
}

And here is the class definition for a SensorChannel:

import processing.core.PApplet;
import controlP5.*;

class SensorChannel {
  PApplet app;
  ControlP5 cp5;

  //Moving line graph
  Chart chart;

  //CheckBox buttons;
  boolean triggered;
  boolean manualOverride;
  boolean calibrateBaseline;
  boolean calibrateGain;
  boolean calibrateTrigger;
  boolean selfControl;

  //Sliders
  int currentGain;
  int currentBalance;
  int currentReading;
  int currentTrigger;

  SensorChannel(PApplet papp, int x, int y)
  {

    app = papp;
    cp5 = new ControlP5(papp);

    println("hello!");

    //Line graph
    chart = cp5.addChart("sensorChart")
    .setPosition(x+0, y+0)
    .setSize(306, 220)
    .setRange(0, 1024)
    .setView(Chart.LINE) // use Chart.LINE, Chart.PIE, Chart.AREA, Chart.BAR_CENTERED
    .setStrokeWeight(1.5)
    .setColorCaptionLabel(color(40))
    ;

    chart.addDataSet("sensorReading");
    chart.setData("sensorReading", new float[100]);
    chart.setColors("sensorReading", color(240));

    chart.addDataSet("sensorReading");
    chart.setData("sensorReading", new float[100]);
    chart.setColors("sensorReading", color(140));

    //Reading (10bits)
    //Trigger point (10bits)

    //Balancing digipot setting (1 byte)
    cp5.addSlider("currentBalance")
    .setLabel("Balance Pot")
    .setPosition(x+0,y+284)
    .setSize(306,20)
    .setRange(0,255)
    ;
    //Gain setting (1 byte)
    cp5.addSlider("currentGain")
    .setLabel("Gain")
    .setPosition(x+0,y+263)
    .setSize(306,20)
    .setRange(0,255)
    ;

    //Current Sensor Reading (1 byte)
    cp5.addSlider("currentReading")
    .setLabel("Sensor Reading")
    .setPosition(x+0,y+221)
    .setSize(306,20)
    .setRange(0,255)
    ;

    //Trigger Point (1 byte)
    cp5.addSlider("currentTrigger")
    .setLabel("Trigger Point")
    .setPosition(x+0,y+242)
    .setSize(306,20)
    .setRange(0,255)
    ;

    //Misc. Settings Toggles
    cp5.addToggle("triggered")
    .setLabel("Trigger")
    .setPosition(x+0,y+305)
    .setSize(50,20)
    ;

    cp5.addToggle("manualOverride")
    .setLabel("Override")
    .setPosition(x+51,y+305)
    .setSize(50,20)
    ;

    cp5.addToggle("calibrateBaseline")
    .setLabel("C. Baseline")
    .setPosition(x+102,y+305)
    .setSize(50,20)
    ;

    cp5.addToggle("calibrateGain")
    .setLabel("C. Gain")
    .setPosition(x+153,y+305)
    .setSize(50,20)
    ;

    cp5.addToggle("calibrateTrigger")
    .setLabel("C. Trig")
    .setPosition(x+204,y+305)
    .setSize(50,20)
    ;

    cp5.addToggle("selfControl")
    .setLabel("S. Control")
    .setPosition(x+255,y+305)
    .setSize(50,20)
    ;

  }

  void triggered(boolean theFlag)
  {
    println("Trigger status: " + theFlag);
  }

  void manualOverride(boolean theFlag)
  {
    println("Manual Override status: " + theFlag);
  }

  void calibrateBaseline(boolean theFlag)
  {
    println("Calibrate Baseline status: " + theFlag);
  }

  void calibrateGain(boolean theFlag)
  {
    println("Calibrate Gain status: " + theFlag);
  }

  void calibrateTrigger(boolean theFlag)
  {
    println("Calibrate Trigger status: " + theFlag);
  }

  void selfControl(boolean theFlag)
  {
    println("Self Control status: " + theFlag);
  }

}

This programs jams when it executes "gyro.begin()" Solution?

$
0
0

This programs jams when it executes "gyro.begin()" Is there a solution?

int Segment, n, Compare;
double ANGLE                 [100];
double DISTANCE              [100] ;
double XX                    [100] ;
double YY                    [100] ;
double Correlation           [20 ] = {1,9,2,8,3,7,2,6,5};
double Sorted_Correlation    [20 ] = {1,2,2,3,7,8,9,5,6};
bool   Matched               [20 ] = {0,0,0,0,0,0,0,0,0};
int    Backward_Index        [20 ] = {1,1,1,1,1,1,1,1,1};
double rotation, newangle, oldangle;
int Creatures = 7;
bool Searching = 1;
double angle_rad = PI / 180.;
double angle_deg = 180.0 / PI;
double speed;
double Distance;
int x, count=1, size_of_array=0, Segment0, MinPower ;
boolean Left = 1, Turning, Confident ;


void setup() {
  //Set Pwm 8KHz
  TCCR1A = _BV(WGM10);
  TCCR1B = _BV(CS11) | _BV(WGM12);
  TCCR2A = _BV(WGM21) | _BV(WGM20);
  TCCR2B = _BV(CS21);


  int n = 6,k, temp, Heading ;
  REAL x ;
  REAL y;
  REAL m,b,r;

  Serial.begin(9600);
  Serial.println(" \n");
  Serial.println("Room_Map.ino") ;
  Serial.println("Start Setuuuup");
  gyro.begin();
  Serial.println("asdfasf");

And the output is:

Room_Map.ino
Start Setuuuup

The port name?

$
0
0
arduino = new Arduino(this, "/dev/name/COM3", 57600);

Presentation1222

What port do I use. I have tried COM1/2/3/4/5

How do I get Jeff Rowberg's MPU6050 software to run.

$
0
0

I am trying to get Jeff Rowberg's software for the Invensense MPU6050 to run. (Arduino's MPU6050.ino and Processing's MPUTeapot.ino) But MPU6050.ino and MPUTpot.ino do not talk to each other. MPU6050.ino hangs (malfunctions?) while waiting for an interrupt from MPUTeapot.ino that never happens. I have to break out of his wait loop. I have the Arduino Mega 2560, which should have the correct interrupt pin. (as follows)

  NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
       depends on the MPU-6050's INT pin being connected to the Arduino's
       external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
       digital I/O pin 2.

This should be taken care of as follows:

 #define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards

But, I have to add a break as follows:

   // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt && fifoCount < packetSize) {
            // other program behavior stuff here
            // .
            // .
            // .
            // if you are really paranoid you can frequently test in between other
            // stuff to see if mpuInterrupt is true, and if so, "break;" from the
            // while() loop to immediately process the MPU data
            // .
            // .
            // .
            Break;

Do I actually have to add a wire?

Jeff Rowberg's MPU6050.ino code follows"

// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg <jeff@rowberg.net>
// Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
//
// Changelog:
//      2013-05-08 - added seamless Fastwire support
//                 - added note about gyro calibration
//      2012-06-21 - added note about Arduino 1.0.1 + Leonardo compatibility error
//      2012-06-20 - improved FIFO overflow handling and simplified read process
//      2012-06-19 - completely rearranged DMP initialization code and simplification
//      2012-06-13 - pull gyro and accel data from FIFO packet instead of reading directly
//      2012-06-09 - fix broken FIFO read sequence and change interrupt detection to RISING
//      2012-06-05 - add gravity-compensated initial reference frame acceleration output
//                 - add 3D math helper file to DMP6 example sketch
//                 - add Euler output and Yaw/Pitch/Roll output formats
//      2012-06-04 - remove accel offset clearing for better results (thanks Sungon Lee)
//      2012-06-01 - fixed gyro sensitivity to be 2000 deg/sec instead of 250
//      2012-05-30 - basic DMP initialization working

/* ============================================
I2Cdev device library code is placed under the MIT license
Copyright (c) 2012 Jeff Rowberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/

// I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
// for both classes must be in the include path of your project
#include "I2Cdev.h"

#include "MPU6050_6Axis_MotionApps20.h"
//#include "MPU6050.h" // not necessary if using MotionApps include file

// Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
// is used in I2Cdev.h
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    #include "Wire.h"
#endif

// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for SparkFun breakout and InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu;
//MPU6050 mpu(0x69); // <-- use for AD0 high

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

/* =========================================================================
   NOTE: Arduino v1.0.1 with the Leonardo board generates a compile error
   when using Serial.write(buf, len). The Teapot output uses this method.
   The solution requires a modification to the Arduino USBAPI.h file, which
   is fortunately simple, but annoying. This will be fixed in the next IDE
   release. For more info, see these links:

   http://arduino.cc/forum/index.php/topic,109987.0.html
   http://code.google.com/p/arduino/issues/detail?id=958
 * ========================================================================= */



// uncomment "OUTPUT_READABLE_QUATERNION" if you want to see the actual
// quaternion components in a [w, x, y, z] format (not best for parsing
// on a remote host such as Processing or something though)
//#define OUTPUT_READABLE_QUATERNION

// uncomment "OUTPUT_READABLE_EULER" if you want to see Euler angles
// (in degrees) calculated from the quaternions coming from the FIFO.
// Note that Euler angles suffer from gimbal lock (for more info, see
// http://en.wikipedia.org/wiki/Gimbal_lock)
//#define OUTPUT_READABLE_EULER

// uncomment "OUTPUT_READABLE_YAWPITCHROLL" if you want to see the yaw/
// pitch/roll angles (in degrees) calculated from the quaternions coming
// from the FIFO. Note this also requires gravity vector calculations.
// Also note that yaw/pitch/roll angles suffer from gimbal lock (for
// more info, see: http://en.wikipedia.org/wiki/Gimbal_lock)
#define OUTPUT_READABLE_YAWPITCHROLL

// uncomment "OUTPUT_READABLE_REALACCEL" if you want to see acceleration
// components with gravity removed. This acceleration reference frame is
// not compensated for orientation, so +X is always +X according to the
// sensor, just without the effects of gravity. If you want acceleration
// compensated for orientation, us OUTPUT_READABLE_WORLDACCEL instead.
//#define OUTPUT_READABLE_REALACCEL

// uncomment "OUTPUT_READABLE_WORLDACCEL" if you want to see acceleration
// components with gravity removed and adjusted for the world frame of
// reference (yaw is relative to initial orientation, since no magnetometer
// is present in this case). Could be quite handy in some cases.
//#define OUTPUT_READABLE_WORLDACCEL

// uncomment "OUTPUT_TEAPOT" if you want output that matches the
// format used for the InvenSense teapot demo
//#define OUTPUT_TEAPOT



#define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno & most boards
#define LED_PIN 13 // (Arduino is 13, Teensy is 11, Teensy++ is 6)
bool blinkState = false;

// MPU control/status vars
bool dmpReady = false;  // set true if DMP init was successful
uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
uint16_t fifoCount;     // count of all bytes currently in FIFO
uint8_t fifoBuffer[64]; // FIFO storage buffer

// orientation/motion vars
Quaternion q;           // [w, x, y, z]         quaternion container
VectorInt16 aa;         // [x, y, z]            accel sensor measurements
VectorInt16 aaReal;     // [x, y, z]            gravity-free accel sensor measurements
VectorInt16 aaWorld;    // [x, y, z]            world-frame accel sensor measurements
VectorFloat gravity;    // [x, y, z]            gravity vector
float euler[3];         // [psi, theta, phi]    Euler angle container
float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector

// packet structure for InvenSense teapot demo
uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' };



// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}



// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // join I2C bus (I2Cdev library doesn't do this automatically)
    #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
        Wire.begin();
        Wire.setClock(400000); // 400kHz I2C clock. Comment this line if having compilation difficulties
    #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
        Fastwire::setup(400, true);
    #endif

    // initialize serial communication
    // (115200 chosen because it is required for Teapot Demo output, but it's
    // really up to you depending on your project)
    Serial.begin(115200);
    while (!Serial); // wait for Leonardo enumeration, others continue immediately

    // NOTE: 8MHz or slower host processors, like the Teensy @ 3.3v or Ardunio
    // Pro Mini running at 3.3v, cannot handle this baud rate reliably due to
    // the baud timing being too misaligned with processor ticks. You must use
    // 38400 or slower in these cases, or use some kind of external separate
    // crystal solution for the UART timer.

    // initialize device
    Serial.println(F("Initializing I2C devices..."));
    mpu.initialize();
    pinMode(INTERRUPT_PIN, INPUT);

    // verify connection
    Serial.println(F("Testing device connections..."));
    Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));

    // wait for ready
    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
    while (Serial.available() && Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() && Serial.read()); // empty buffer again

    // load and configure the DMP
    Serial.println(F("Initializing DMP..."));
    devStatus = mpu.dmpInitialize();

    // supply your own gyro offsets here, scaled for min sensitivity
    mpu.setXGyroOffset(220);
    mpu.setYGyroOffset(76);
    mpu.setZGyroOffset(-85);
    mpu.setZAccelOffset(1788); // 1688 factory default for my test chip

    // make sure it worked (returns 0 if so)
    if (devStatus == 0) {
        // turn on the DMP, now that it's ready
        Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(digitalPinToInterrupt(INTERRUPT_PIN), dmpDataReady, RISING);
        mpuIntStatus = mpu.getIntStatus();

        // set our DMP Ready flag so the main loop() function knows it's okay to use it
        Serial.println(F("DMP ready! Waiting for first interrupt..."));
        dmpReady = true;

        // get expected DMP packet size for later comparison
        packetSize = mpu.dmpGetFIFOPacketSize();
    } else {
        // ERROR!
        // 1 = initial memory load failed
        // 2 = DMP configuration updates failed
        // (if it's going to break, usually the code will be 1)
        Serial.print(F("DMP Initialization failed (code "));
        Serial.print(devStatus);
        Serial.println(F(")"));
    }

    // configure LED for output
    pinMode(LED_PIN, OUTPUT);
}



// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop() {
    // if programming failed, don't try to do anything
    if (!dmpReady) return;

    // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {
        // other program behavior stuff here
        // .
        // .
        // .
        // if you are really paranoid you can frequently test in between other
        // stuff to see if mpuInterrupt is true, and if so, "break;" from the
        // while() loop to immediately process the MPU data
        // .
        // .
        // .
    }

    // reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    // get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
        Serial.println(F("FIFO overflow!"));

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
    } else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            Serial.print("quat\t");
            Serial.print(q.w);
            Serial.print("\t");
            Serial.print(q.x);
            Serial.print("\t");
            Serial.print(q.y);
            Serial.print("\t");
            Serial.println(q.z);
        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

        // blink LED to indicate activity
        blinkState = !blinkState;
        digitalWrite(LED_PIN, blinkState);
    }
}

Arduino to Processing with push button and LEDs

$
0
0

I have created a program that allows you to use processing to communicate to LEDs connected to a nano. The processing code allows the user to select an LED colour and how many times the LED will flash. Now, I have to connect a push button to the circuit. This is what I'm struggling with. When I push the button, it is supposed to bring the processing screen back to its original state and turn off all the LEDs. I have put the code in Arduino for the button push, but I have no idea what kind of code I need to communicate this back to Processing. I haven't put any code into Processing yet for the push button. Any help would be greatly appreciated.

Processing code...

PFont jpFont, ebFont;
int iLED=0, iCount=0, iData=0;
import processing.serial.*;
Serial rrSerial;

void setup()
{
  size(1000,500);
  jpFont=loadFont("Tahoma-48.vlw");
  ebFont=loadFont("Tahoma-Bold-48.vlw");
  println(Serial.list()[2]);
  rrSerial=new Serial(this, Serial.list()[2],9600);
  rrSerial.write(0x83);
}

void draw()
{
   background(100);

   fill(255,0,0);
   stroke(0);
   strokeWeight(10);
   ellipse(width/2-350,height/2+100,200,200);

   fill(0,255,0);
   stroke(0);
   strokeWeight(10);
   ellipse(width/2-125,height/2+100,200,200);

   fill(0,0,255);
   stroke(0);
   strokeWeight(10);
   ellipse(width/2+100,height/2+100,200,200);

   fill(247,142,12);
   stroke(0);
   strokeWeight(10);
   ellipse(width/2+325,height/2+100,200,200);

   if(iLED==1)
   {
     textFont(ebFont);
     textSize(75);
     fill(#F7F70C);
     text(""+iCount,125,375);
   }

   if(iLED==2)
   {
     textFont(ebFont);
     textSize(75);
     fill(#F7F70C);
     text(""+iCount,350,375);
   }

  if(iLED==3)
  {
     textFont(ebFont);
     textSize(75);
     fill(#F7F70C);
     text(""+iCount,575,375);
  }

   if(iLED==4)
   {
     textFont(ebFont);
     textSize(75);
     fill(#F7F70C);
     text(""+iCount,800,375);
   }

   iData=iLED<<4|iCount&0x0F;
}

void keyPressed()
{
   if(keyCode==RIGHT&&iLED<5)
   {
     iLED++;
     iCount=0;
     if(iLED==5)iLED=0;
   }

   if(keyCode==LEFT&&iLED>0)
   {
     iLED--;
     iCount=0;
     if(iLED==0)iLED=5;
   }

   if(keyCode==UP&&iCount<10)
   {
     iCount++;
     if(iCount==10)iCount=0;
   }

   if(keyCode==DOWN&&iCount>-1)
   {
     iCount--;
     if(iCount==-1)iCount=9;
   }

   if(key==ENTER)rrSerial.write(iData);

   if(key=='q')exit();
}

Now Arduino...

boolean bToggle=0;
int iButton;

void setup()
{
  Serial.begin(9600);
  pinMode(3,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(9,OUTPUT);
  pinMode(11,INPUT);
  digitalWrite(3,LOW);
  digitalWrite(5,LOW);
  digitalWrite(9,LOW);
  digitalWrite(11,HIGH);
}

void loop()
{
  if(Serial.available()>0)
  {
    int iInput=Serial.read();
    int iWhich_Led=iInput>>4;
    int iFlash_Count=iInput&0x0f;

    if(iWhich_Led==1)LED_burst(3,iFlash_Count);

    if(iWhich_Led==2)LED_burst(5,iFlash_Count);

    if(iWhich_Led==3)LED_burst(9,iFlash_Count);

    if(iWhich_Led==4)LED_sequence(iFlash_Count);
  }

  iButton=digitalRead(11);

  if(iButton==0)
  {
    while(digitalRead(11)==0);
    bToggle=!bToggle;
  }

  if(bToggle==1)
  {
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);
    digitalWrite(9,LOW);
  }
}

void LED_burst(int iLED,int iCount)
{
  for(int iX=0;iX<iCount;iX++)
  {
    digitalWrite(iLED,HIGH);
    delay(100);
    digitalWrite(iLED,LOW);
    delay(100);
  }
}

void LED_sequence(int iCountx)
{
  for(int iY=0;iY<iCountx;iY++)
  {
    digitalWrite(3,HIGH);
    delay(50);
    digitalWrite(3,LOW);
    delay(50);
    digitalWrite(5,HIGH);
    delay(50);
    digitalWrite(5,LOW);
    delay(50);
    digitalWrite(9,HIGH);
    delay(50);
    digitalWrite(9,LOW);
    delay(50);
  }
}

changing video in processing using arduino and button

$
0
0

I want to changing video in processing. Before push the button, we can see video 'A'. After push the button, we can see video 'B'.

//this is my arduino code.

int switchPin=7; int LEDPin=13;

void setup() { // put your setup code here, to run once: pinMode(switchPin, INPUT); pinMode(LEDPin, OUTPUT); Serial.begin(9600); }

void loop() { // put your main code here, to run repeatedly: if(digitalRead(switchPin) == HIGH){ Serial.write(2); digitalWrite(LEDPin,HIGH); } else { Serial.write(1); digitalWrite(LEDPin,LOW); } delay(100); }

//here is processing code

import processing.serial.*; import processing.video.*;

Serial port; int val = 0; int oldval = 0; int frame = 0; int numFrames = 15;

Movie Ch1,Ch2; int t=0; Movie Chapter = Ch1;

void setup(){ size(740,405);

Ch1 = new Movie(this, "A.mov"); Ch2 = new Movie(this, "B.mp4");

Ch1.loop(); Ch2.loop();

println(Serial.list()); port = new Serial(this, "/dev/cu.usbmodem1411"); }

void draw(){

   if (0 < port.available()) {
 val = port.read();
}

if (val != oldval && val== 2){ if(frame<numFrames-1){ frame = (frame+1 ); }else{ frame = 1; } } image (Ch1,0,0); image (Ch2,0,0);

oldval = val;

}

void movieEvent(Movie m){ if (m== Ch1){ Ch1.read(); }else if (m== Ch2){ Ch2.read(); } }

The output is that screen shows video'B' and audio shows video'A'. And it makes the button useful:( I don't want it.. I want [ video'A' -> push button -> video'B' ]

how to delete the previous frame?

$
0
0

hello I am new to processing and I'm working on a code to create a simple compass using the arduino. this is my current code:

PFont f;
import processing.serial.*;
Serial myPort;
String val;
int angle;

void setup()
{
  /**connects to the arduino**/
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 115200);
  myPort.bufferUntil('\n');

  /**draws the compass**/
  size(200, 200);
  ellipse(100, 100, 200, 200);
    fill(#000000);
  ellipse(100, 100, 5, 5);
  f = createFont("Arial",16,true);
  textFont(f,16);
  fill(0);
  text("N", 95, 20);
  text("S", 95, 195);
  text("E", 180, 104);
  text("W", 5, 104);
}

void draw()
{
   if ( myPort.available() > 0)
  {
    val = myPort.readStringUntil('\n');
   angle = int(val);
  }
println(angle);

   pushMatrix();
   translate(100, 100);
   rotate(radians(angle));
   arrow(0, 50, 0, 0);
   popMatrix();
   delay(500);
}

//the arrow draw function
void arrow(int x1, int y1, int x2, int y2)
{
  line(x1, y1, x2, y2);
  pushMatrix();
  translate(x1, y1);
  float a = atan2(x1-x2, y2-y1);
  rotate(a);
  line(0, 0, -10, 10);
  line(0, 0, 10, 10);
  popMatrix();
}

my problem is that when the arrow changes it's position, the previous frame doesn't disappear.

I added a photo to explain what I mean...

what do I need to do to resolve this?

compass


Coming to an end with this assignment. Just cannot make the text appear on the screen.

$
0
0
int pageNumber = 1;
//Variables for falling ball
float y0 = 0;
float x0 = random (width);
float y0_speed=3;

PImage bot;
PImage gift;
PImage img;
PImage img2;

int quantity = 300;
float [] xPosition = new float[quantity];
float [] yPosition = new float[quantity];
int [] flakeSize = new int[quantity];
int [] direction = new int[quantity];
int minFlakeSize = 1;
int maxFlakeSize = 5;
int sceneNumber = 1;

PFont f; // Global font variable
float x; // Horizontal location
int index = 0;

String[] headlines = {
  "Merry Christmas!!! ",
  "and",
  "Happy New Year!!!",
};

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

Arduino arduino;

//declare the potentiometer
TKPotentiometer pot;

float minVal = 1023;
float maxVal = 0;

void setup() {
size(800,600);
  arduino = new Arduino(this, Arduino.list()[3], 57600);

   img=loadImage("Fullpage.png");
   img2=loadImage("800-600pixels.jpg");
   gift=loadImage("gift2.png");
   bot=loadImage("santasmall.png");
  //for every tinkerkit component we have to pass
  //the arduino and the port
  pot = new TKPotentiometer(arduino, TK.I0);

  noStroke();

  frameRate(30);
  noStroke();
  smooth();
    for(int i = 0; i < quantity; i++) {
    flakeSize[i] = round(random(minFlakeSize, maxFlakeSize));
    xPosition[i] = random(0, width);
    yPosition[i] = random(0, height);
    direction[i] = round(random(0, 1));
  }
}
void draw (){
if (pageNumber == 1) {
  // background(0);
 imageMode(CORNER);
image(img, 0, 0, 800, 600);
}
{
  img = loadImage("Full-page.png");
    f = createFont( "American Typewriter", 70);
  textFont(f, 50);
  fill(255, 255, 255);
  textAlign (LEFT);


if (pageNumber == 2) {
   imageMode(CORNER);
  image(img2, 0, 0);
  // Display headline at x location

//get the potentiometer values
  float val = pot.read();

  //calibration
  if (val < minVal) minVal = val;
  if (val > maxVal) maxVal = val;

  //map the values of the potentiometer
  //on the width of the window
  val = map(val, minVal, maxVal, 100, 700);

  imageMode(CENTER);
  image(bot, val, height-115);

  //print the potentiometer values
  println(val);

   for(int i = 0; i < xPosition.length; i++) {

    ellipse(xPosition[i], yPosition[i], flakeSize[i], flakeSize[i]);

    if(direction[i] == 0) {
      xPosition[i] += map(flakeSize[i], minFlakeSize, maxFlakeSize, .1, .5);
    } else {
      xPosition[i] -= map(flakeSize[i], minFlakeSize, maxFlakeSize, .1, .5);
    }

    yPosition[i] += flakeSize[i] + direction[i];

    if(xPosition[i] > width + flakeSize[i] || xPosition[i] < -flakeSize[i] || yPosition[i] > height + flakeSize[i]) {
      xPosition[i] = random(0, width);
      yPosition[i] = -flakeSize[i];
    }

  }
   //Blank out the background
  fill(255,0);
  rect(0,0,width,height);

  //Check if the ball is off the screen
  if(y0 > height+15)  //15 is the radius of the ball
  {
    y0 = -15; //Move it back to just above the screen
    x0 = random(width); //Pick a new random horizontal location on the canvas
    y0_speed = random(3, 7); //Pick a new random speed between 3 and 7
  }

  //Move the ball
  y0 += y0_speed; //Increase the balls y value by the variable
                  //y0_speed each time through the loop

  //Draw the ball
  fill(255,255,255);
  image (gift, x0, y0, 30, 30);
}
void keyPressed(){
  if (key == '1'){
   pageNumber = 1;
  }
   if (key == '2'){
   pageNumber = 2;
  }

}

Transfer file from PC to Arduino SD card

$
0
0

Hi,

I am looking for an example that shows how to transfer a file from my PC to the SD card of my Arduino. I have searched the Internet and your forum but I could not find anything. I would be very grateful if you could help me.

Kind regards

Text- to Speech: How to implement read out function of Sketch to Terminal?

$
0
0

Hello,

I am quite new in the field of programming and for a university project I would be very happy to receive some help from advanced people in this field ;)

I just came recently across this Processing- Code about Text-to-Speech with Terminal on Mac. ( http://www.frontiernerds.com/text-to-speech-in-processing#comments ) Great thing! Which I would need for my project. The sketch in Processing: I have a analog book with conductive ink (connected to arduino) , that is flipping through a projection that is referring to a .txt- file. The projection of the single text parts works but it would be great if the texts could not only be projected but also read out from Terminal. But I don't really get how to tell the programm to read out the shown text. I would be very happy if someone could have a look into it and help me!

Thank you very much in advance!

This is my processing code:

import processing.serial.*;

Serial myPort; String val; String[] lines; StringList pages = new StringList(); PFont f;

int counter = 0;

int boxWidth = 1000;

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

lines = loadStrings("text_try.txt");

pages.append("");

for(int i = 0; i < lines.length; i++){ if(lines[i].equals("")){ counter++; pages.append(""); } else { pages.set(counter, pages.get(counter).concat(lines[i])); } }

println(pages.get(0));

f = createFont("FuturaLight",37,true);

fullScreen(); background(0); }

void draw () {

if ( myPort.available() > 0) { val = myPort.readStringUntil('\n'); try { String tempString = val.substring(0, val.length() - 2); int tempInt = parseInt(tempString);

  newText(tempInt);

} catch (Exception e) {
  //println("failed");
}

}

}

void newText (int pageNumber){

if (pageNumber > 0) { background(0);

textFont(f);
fill(255);
textAlign(CENTER, CENTER);
text(pages.get(pageNumber - 1), (width/2) - (boxWidth/2), 0, boxWidth, height);

} else { background(0); }

}

How to remove ghosting on resistor array

$
0
0

Hi, I have a resistor array 4*4 . I send 5V pulses to each column separately, and I read data from rows. now I need to remove ghostinguntitled

on the plot I have static resistance (blue line) and when i change resistance of another resistor (red line) the resistance is changed.

I must find some algorithm to eliminate this ghosting and I just don't know how can I do that. Thanks for help

How to count rectangular signals and calculate signal/minute?

$
0
0

Hello! I have little expierence with programming and I had followed some instructions to make a light sensitive counter that would peak every time there's a sufficient change in ambient or artificial lighting. I took an example build of a heartrate sensor and adapted it for this purpose.

I was wondering If there's a way for processing to count signal position and display a calculated minute average of signals. For example 25 signals in 10 seconds multiplied by 6 to get signals per minute.

Example signal would be

LightSensor

The processing code i'm using is taken from an example about a heartrate sensor.

How would I go about making the code detect a signal like this and count it once it goes over a certain treshold?

import processing.serial.*;

Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph
float oldHeartrateHeight = 0; // for storing the previous reading

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

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

  // Setup which serial port to use.
  // This line might change for different computers.
  myPort = new Serial(this, Serial.list()[1], 9600);

  // set inital background:
  background(0);
}

void draw () {
}

void serialEvent (Serial myPort) {
  // read the string from the serial port.
  String inString = myPort.readStringUntil('\n');

  if (inString != null) {
    // trim off any whitespace:
    inString = trim(inString);
    // convert to an int
    println(inString);
    int currentHeartrate = int(inString);

    // draw the Heartrate BPM Graph.
    float heartrateHeight = map(currentHeartrate, 0, 1023, 0, height);
    stroke(0,255,0);
    line(xPos - 1, height - oldHeartrateHeight, xPos, height - heartrateHeight);
    oldHeartrateHeight = heartrateHeight;
    // at the edge of the screen, go back to the beginning:
    if (xPos >= width) {
      xPos = 0;
      background(0);
    } else {
      // increment the horizontal position:
      xPos++;
    }
  }
}
Viewing all 747 articles
Browse latest View live