<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
      <title>Tagged with digitalwrite() - Processing 2.x and 3.x Forum</title>
      <link>https://forum.processing.org/two/discussions/tagged/feed.rss?Tag=digitalwrite%28%29</link>
      <pubDate>Sun, 08 Aug 2021 18:38:32 +0000</pubDate>
         <description>Tagged with digitalwrite() - Processing 2.x and 3.x Forum</description>
   <language>en-CA</language>
   <atom:link href="/two/discussions/taggeddigitalwrite%28%29/feed.rss" rel="self" type="application/rss+xml" />
   <item>
      <title>Connect RGB led on arduino to mouseclick on processing.</title>
      <link>https://forum.processing.org/two/discussion/25045/connect-rgb-led-on-arduino-to-mouseclick-on-processing</link>
      <pubDate>Thu, 16 Nov 2017 11:56:58 +0000</pubDate>
      <dc:creator>DeDaymar</dc:creator>
      <guid isPermaLink="false">25045@/two/discussions</guid>
      <description><![CDATA[<p>Hello,</p>

<p>Im working on a project with arduino and processing. On my UNO board I have an RGB led. On my processing screen I have the colors Red Green and Blue by a mouseclick. So when I click the screen it goes from red to green and when I click again it goes to blue etc. The processing part works, thanks to <a href="/two/profile/GoToLoop">@GoToLoop</a>. For the connection from processing to arduino I used an example from processing called arduino_output. So I have both parts, seperately, but now I have to put them together. First I just put both completely together and that kinda worked but not good. I hope someone with a sharp eye can point out to me what to do. Btw, for arduino code I use the Standardfirmata code. Also, in the example arduino_output you have to click once to turn the led on and once to turn it off. In my program I just want that when I click it lights up and when I click again it just changes to the next color.</p>

<p>Processing code combined with arduino_output program :</p>

<pre><code>import processing.serial.*;
import cc.arduino.*;

Arduino arduino;

static final color[] KLEUREN = { #FF0000, #008000, #0000FF };
int kleurindex;
int[] values = { Arduino.LOW, Arduino.LOW, Arduino.LOW };

void setup() {
  size(300, 200);
  noLoop();
  colorMode(RGB);
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  for (int i = 0; i&lt;=13; i++)
      arduino.pinMode(i, Arduino.OUTPUT);
}

void draw() {
  final color c = KLEUREN[kleurindex];
  background(c);
  /*for (int i = 0; i &lt;= 13; i++) {
    if (values[i] == Arduino.HIGH)
      fill(on);
    else
       fill(off); }*/

}

void mousePressed() {
  kleurindex = (kleurindex + 1) % KLEUREN.length;
  redraw();
  int pin = (450 - mouseX) / 30;        //this is still of the part where you have to click in a box to change color. don't know how to change that part.
   if (values[pin] == Arduino.LOW) {
    arduino.digitalWrite(pin, Arduino.HIGH);
    values[pin] = Arduino.HIGH;
  } else {
    arduino.digitalWrite(pin, Arduino.LOW);
    values[pin] = Arduino.LOW;
  }

}
</code></pre>

<p>ps. where you read 'kleuren' or something with 'kleur'  it means color.</p>
]]></description>
   </item>
   <item>
      <title>When button clicked, let something move</title>
      <link>https://forum.processing.org/two/discussion/22561/when-button-clicked-let-something-move</link>
      <pubDate>Sat, 13 May 2017 13:48:29 +0000</pubDate>
      <dc:creator>Ditger</dc:creator>
      <guid isPermaLink="false">22561@/two/discussions</guid>
      <description><![CDATA[<p>So i build something so that when you push a button, an LED is going to light up</p>

<p>Now the issue that I'm having is that when i click the button, it doesn't do anything</p>

<p>this is my code in processing</p>

<pre><code>import processing.serial.*;
import cc.arduino.*;

Arduino arduino;
int BUTTON1 = 11;
int BUTTON2 = 10;
int BUTTON3 = 9;
int BUTTON4 = 8; 


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


}

void draw()
{   
  int x = 150;
  int y = 150;
  ellipse(x,y,50,50);
   if(arduino.digitalRead(BUTTON1) == Arduino.HIGH) {
     x = x + 50;
   }
}
</code></pre>

<p>I hope that someon can help me</p>
]]></description>
   </item>
   <item>
      <title>Arduino MQ-3 sensor sending signal input to p5.js</title>
      <link>https://forum.processing.org/two/discussion/22348/arduino-mq-3-sensor-sending-signal-input-to-p5-js</link>
      <pubDate>Tue, 02 May 2017 18:10:45 +0000</pubDate>
      <dc:creator>jstate1</dc:creator>
      <guid isPermaLink="false">22348@/two/discussions</guid>
      <description><![CDATA[<p>I am making a breathlyzer for a project using Arduino uno and p5.js. When I blow into the arduino sensor, it should display random circles on computer screen in p5.js. I am having problems with signal communication from my Arduino to p5.js. The connection is working, but the random circles are not displaying on my screen. Here is my code.</p>

<p>project.ino</p>

<pre><code>int level;
int LEDgreen2 = 2;
int LEDgreen3 = 3;
int LEDgreen4 = 4;
int LEDred7 = 7;
int LEDblue13 = 13;



void setup()
{ 
  Serial.begin(9600);
  pinMode(LEDgreen2, OUTPUT);
  pinMode(LEDgreen3, OUTPUT);
  pinMode(LEDgreen4, OUTPUT);
  pinMode(LEDred7, OUTPUT);
  pinMode(LEDblue13, OUTPUT);               
}

void loop()
{
    for(int time = 0;time &lt;= 3000;time++) //blow for 3 seconds
    {      
      digitalWrite(LEDblue13, HIGH);                          
      level = analogRead(A0);
      delay(1);
    }

digitalWrite(LEDblue13, LOW); 

if ( level &gt; 200) //no alch
{
  digitalWrite(LEDgreen2, HIGH); 
  digitalWrite(LEDgreen3, HIGH); 
  digitalWrite(LEDgreen4, HIGH);
}
else 
{
  digitalWrite(LEDred7, HIGH);
  Serial.println(level); 
}

delay(2000); //Wait 2 seconds to start over 
digitalWrite(LEDblue13,HIGH); //TURN ON BLUE LIGHT (START OVER)
digitalWrite(LEDgreen2, LOW); //turn off green LED
digitalWrite(LEDgreen3, LOW); //turn off green LED
digitalWrite(LEDgreen4, LOW); //turn off green LED
digitalWrite(LEDred7, LOW);//turn off red LED
}
</code></pre>

<p>p5.js</p>

<pre><code>var serial;
var inByte = 0;



function setup() {
  createCanvas(windowWidth, windowHeight);
  serial = new p5.SerialPort();
  serial.on('data', serialEvent)
  serial.open("COM3");
}

function draw() {

}


function serialEvent() {
 var inString = serial.readStringUntil('\r\n'); 
 inString = inString.trim();

 if (inString.length &gt; 0) {
   inByte = Number(inString);
   print(inByte);
 }
 if(inByte&gt;200){
   var x = random(width);
   var y = random(height);

   var r = random(255);
   var g = random(255);
   var b = random(255);

   fill(r, g, b, 100);
   ellipse(x, y, 50, 50);
 }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Arduino -&gt; Processing conversion: creating mux channels</title>
      <link>https://forum.processing.org/two/discussion/21737/arduino-processing-conversion-creating-mux-channels</link>
      <pubDate>Fri, 31 Mar 2017 19:15:14 +0000</pubDate>
      <dc:creator>narner</dc:creator>
      <guid isPermaLink="false">21737@/two/discussions</guid>
      <description><![CDATA[<p>As the title alludes to, I'm in the process of converting an Arduino sketch to a Processing sketch. So far, mostly pretty straightforward.</p>

<p>I'm running into an issue with creating an array of ints for the channels for two muxers. Below is the code that I currently have working for the Arduino sketch:</p>

<pre><code>int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

  int muxChannel[20][8]={
    //Mux 1 
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  }; 

  //loop through the 4 sig
  for(int i = 0; i &lt; 8; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //write the value at the SIG pin
  analogWrite(SIG_pin, testValue);  

  //return the value
  return 0;
}
</code></pre>

<p>Below is the slightly varied version that I'm using for my Processing-equivelent sketch.</p>

<pre><code>int readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[20][8]={
    //Mux 1 
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  }; 


  //loop through the 4 sig
  for(int i = 0; i &lt; 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //write the value at the SIG pin
  arduino.analogWrite(SIG_pin, testValue);  

  int val = 0;
  return val;
}
</code></pre>

<p>I'm currently getting an error of unexpected token: int error at the following line:</p>

<pre><code>  int muxChannel[20][8]={
</code></pre>

<p>And, an error of <code>The type of expression must be an array type but it resolved to int at this line</code>:</p>

<pre><code>digitalWrite(controlPin[i], muxChannel[channel][i]);
</code></pre>

<p>I'm by no means a Java expert, so I'm not exactly sure what's going on. Anyone able to offer some insight?</p>

<p>Thank you!</p>
]]></description>
   </item>
   <item>
      <title>GPIO Pins not receiving signal</title>
      <link>https://forum.processing.org/two/discussion/19434/gpio-pins-not-receiving-signal</link>
      <pubDate>Wed, 30 Nov 2016 19:19:13 +0000</pubDate>
      <dc:creator>pas54</dc:creator>
      <guid isPermaLink="false">19434@/two/discussions</guid>
      <description><![CDATA[<p>I'm working on a project that uses GPIO output. The pins aren't getting power. Here's that part of the code:</p>

<pre><code>import processing.io.*;

void setup()
{
GPIO.pinMode(5, GPIO.OUTPUT);
}

void draw()
{
GPIO.digitalWrite(5, GPIO.HIGH);
}
</code></pre>

<p>I know the code doesn't do much, but from what I understand, there should be 3.3 volts coming from pin 5 as a result of that code. The 5V power pins aren't even getting power. What's going on here?</p>
]]></description>
   </item>
   <item>
      <title>How do I get Jeff Rowberg's MPU6050 software to run.</title>
      <link>https://forum.processing.org/two/discussion/19483/how-do-i-get-jeff-rowberg-s-mpu6050-software-to-run</link>
      <pubDate>Sat, 03 Dec 2016 00:28:28 +0000</pubDate>
      <dc:creator>CLplaneGuy</dc:creator>
      <guid isPermaLink="false">19483@/two/discussions</guid>
      <description><![CDATA[<p>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)</p>

<pre><code>  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.
</code></pre>

<p>This should be taken care of as follows:</p>

<pre><code> #define INTERRUPT_PIN 2  // use pin 2 on Arduino Uno &amp; most boards
</code></pre>

<p>But, I have to add a break as follows:</p>

<pre><code>   // wait for MPU interrupt or extra packet(s) available
        while (!mpuInterrupt &amp;&amp; fifoCount &lt; 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;
</code></pre>

<p>Do I actually have to add a wire?</p>

<p>Jeff Rowberg's MPU6050.ino code follows"</p>

<pre><code>// I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class using DMP (MotionApps v2.0)
// 6/21/2012 by Jeff Rowberg &lt;jeff@rowberg.net&gt;
// Updates should (hopefully) always be available at <a href="https://github.com/jrowberg/i2cdevlib" target="_blank" rel="nofollow">https://github.com/jrowberg/i2cdevlib</a>
//
// 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); // &lt;-- 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:

   <a href="http://arduino.cc/forum/index.php/topic,109987.0.html" target="_blank" rel="nofollow">http://arduino.cc/forum/index.php/topic,109987.0.html</a>
   <a href="http://code.google.com/p/arduino/issues/detail?id=958" target="_blank" rel="nofollow">http://code.google.com/p/arduino/issues/detail?id=958</a>
 * ========================================================================= */



// 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
// <a href="http://en.wikipedia.org/wiki/Gimbal_lock" target="_blank" rel="nofollow">http://en.wikipedia.org/wiki/Gimbal_lock</a>)
//#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: <a href="http://en.wikipedia.org/wiki/Gimbal_lock" target="_blank" rel="nofollow">http://en.wikipedia.org/wiki/Gimbal_lock</a>)
#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 &amp; 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() &amp;&amp; Serial.read()); // empty buffer
    while (!Serial.available());                 // wait for data
    while (Serial.available() &amp;&amp; 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 &amp;&amp; fifoCount &lt; 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 &amp; 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 &amp; 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount &lt; packetSize) fifoCount = mpu.getFIFOCount();

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

        // track FIFO count here in case there is &gt; 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(&amp;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(&amp;q, fifoBuffer);
            mpu.dmpGetEuler(euler, &amp;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(&amp;q, fifoBuffer);
            mpu.dmpGetGravity(&amp;gravity, &amp;q);
            mpu.dmpGetYawPitchRoll(ypr, &amp;q, &amp;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(&amp;q, fifoBuffer);
            mpu.dmpGetAccel(&amp;aa, fifoBuffer);
            mpu.dmpGetGravity(&amp;gravity, &amp;q);
            mpu.dmpGetLinearAccel(&amp;aaReal, &amp;aa, &amp;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(&amp;q, fifoBuffer);
            mpu.dmpGetAccel(&amp;aa, fifoBuffer);
            mpu.dmpGetGravity(&amp;gravity, &amp;q);
            mpu.dmpGetLinearAccel(&amp;aaReal, &amp;aa, &amp;gravity);
            mpu.dmpGetLinearAccelInWorld(&amp;aaWorld, &amp;aaReal, &amp;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);
    }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>What port name do I use?</title>
      <link>https://forum.processing.org/two/discussion/18803/what-port-name-do-i-use</link>
      <pubDate>Mon, 31 Oct 2016 05:13:31 +0000</pubDate>
      <dc:creator>Sean02</dc:creator>
      <guid isPermaLink="false">18803@/two/discussions</guid>
      <description><![CDATA[<p>I have got his code of someone else as i am a beginner. I am using a windows computer. I not sure what the port name is.
This is the line of my code that isn't working.  **  arduino = new Arduino(this, "/dev/com5", 57600.  Line 34 is the one i need help with.</p>

<pre><code>import cc.arduino.*;
import org.firmata.*;

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

Arduino arduino;

Minim minim;  
AudioPlayer song;
FFT fft;

int redPin1 = 12;
int greenPin1 = 11;
int bluePin1 = 10;

int redPin2 = 9;
int greenPin2 = 7;
int bluePin2 = 8;

int redPin3 = 6;
int greenPin3 = 4;
int bluePin3 = 5;

int color_id = 0;

int common_cathode = 0;

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

    arduino = new Arduino(this, "/dev/com5", 57600);
    for (int i = 0; i &lt;= 13; i++) arduino.pinMode(i, Arduino.OUTPUT);
    for (int i = 0; i &lt;= 13; i++) arduino.digitalWrite(i,arduino.HIGH);

    minim = new Minim(this);  
    song = minim.loadFile("fugly.mp3");
    song.play();
    fft = new FFT(song.bufferSize(), song.sampleRate());    
}

void draw() {    
    background(#151515);

    fft.forward(song.mix);

    strokeWeight(1.3);
    stroke(#FFF700);

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

    stroke(#FF0000);

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

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

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

void stop()
{
    for (int i = 0; i &lt;= 13; i++) arduino.digitalWrite(i,arduino.HIGH);
    song.close();  
    minim.stop();
    super.stop();
}
void setColor1(int red, int green, int blue)
{
  if(common_cathode==1) {
    red = 255-red;
    green = 255-green;
    blue = 255-blue;
  }
  arduino.digitalWrite(redPin1, red);
  arduino.digitalWrite(greenPin1, green);
  arduino.digitalWrite(bluePin1, blue);  
}
void setColor2(int red, int green, int blue)
{
  if(common_cathode==1) {
    red = 255-red;
    green = 255-green;
    blue = 255-blue;
  }
  arduino.digitalWrite(redPin2, red);
  arduino.digitalWrite(greenPin2, green);
  arduino.digitalWrite(bluePin2, blue);  
}
void setColor3(int red, int green, int blue)
{
  if(common_cathode==1) {
    red = 255-red;
    green = 255-green;
    blue = 255-blue;
  }
  arduino.digitalWrite(redPin3, red);
  arduino.digitalWrite(greenPin3, green);
  arduino.digitalWrite(bluePin3, blue);  
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>7 Segment Up/Down Counter controlled by Processing Program</title>
      <link>https://forum.processing.org/two/discussion/18716/7-segment-up-down-counter-controlled-by-processing-program</link>
      <pubDate>Wed, 26 Oct 2016 03:48:27 +0000</pubDate>
      <dc:creator>lucassantos212</dc:creator>
      <guid isPermaLink="false">18716@/two/discussions</guid>
      <description><![CDATA[<p>Hi! The activity involves me having to create an up/down counter using an Arduino and controlled by processing. My idea is that there are buttons in the processing program that when hovered over, sends a signal to the arduino program signifying a process. So hovering over the first square, makes it count down, the second square, stop, and the last square resets it. If it is not over any square, it sends a '0', making it continue counting up.</p>

<p>This is the working arduino code. I have pushbuttons that does the processes mentioned.</p>

<pre><code>    `

    unsigned char digit_1 = 7;
    unsigned char digit_2 = 8;
    unsigned char digit_3 = 10;

    int num1 = 0;
    int num2 = 0;
    int num3 = 0;
    int state = 0;
    int halt = 0;
    char val; //data received from serial port
    void setup()
    {
      Serial.begin(9600);
      for (int x = 11; x &lt; 19; x++)
      {
        pinMode (x, OUTPUT);
      }

      pinMode (digit_1, OUTPUT);
      pinMode (digit_2, OUTPUT);
      pinMode (digit_3, OUTPUT);
     //  attachInterrupt(0, s1_press, RISING);
     //  attachInterrupt(1, s2_press, RISING);

    }


    void loop()
    {
      while (Serial.available())
      { val = Serial.read();
      }
      if (val == 1)
      {
        state = 1;
      }
      else //if (val == 0)
      {
        state = 0;
        halt = 0;
      }
      if (val == 2)
      {
        halt = 1;
      }
      else
      {
        state = 0;
        halt = 0;
      }

      if (halt == 0) {
        if (state == 0) {
          num3++;
          if (num3 == 10) {
            num3 = 0;
            num2++;
          }
          if (num2 == 10) {
            num2 = 0;
            num1++;
          }
          if (num1 == 10) {
            num1 = 0;
            num2 = 0;
            num3 = 0;
          }
        }

        if (state == 1) {
          num3--;
          if (num3 == -1) {
            num3 = 9;
            num2--;
          }
          if (num2 == -1) {
            num2 = 9;
            num1--;
          }
          if (num1 == -1) {
            num3 = 9;
            num2 = 9;
            num1 = 9;
          }
        }
      }
      for (int x = 0; x &lt; 80; x++) {
        digitalWrite (digit_3, HIGH);
        digitalWrite (digit_2, LOW);
        digitalWrite (digit_1, LOW);
       display_ (num1);
        delay(1);
        digitalWrite (digit_3, LOW);
        digitalWrite (digit_2, HIGH);
        digitalWrite (digit_1, LOW);
        display_ (num2);
        delay(1);
        digitalWrite (digit_3, LOW);
        digitalWrite (digit_2, LOW);
        digitalWrite (digit_1, HIGH);
        display_ (num3);
        delay(1);
      }

    }




    void display_ (unsigned char num)
    {
      switch (num)
      {
        case 0:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, HIGH);
            digitalWrite (17, LOW);
            digitalWrite (18, LOW);

            break;
          }
        case 1:
          {
            digitalWrite (11, LOW);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, LOW);
            digitalWrite (15, LOW);
            digitalWrite (16, LOW);
            digitalWrite (17, LOW);
            digitalWrite (18, LOW);

            break;
          }
        case 2:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, LOW);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, LOW);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);
             break;
          }
        case 3:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, LOW);
            digitalWrite (16, LOW);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);
           break;
          }
        case 4:
          {
            digitalWrite (11, LOW);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, LOW);
            digitalWrite (15, LOW);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 5:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, LOW);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, LOW);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 6:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, LOW);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 7:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, LOW);
            digitalWrite (15, LOW);
            digitalWrite (16, LOW);
            digitalWrite (17, LOW);
            digitalWrite (18, LOW);


            break;
          }
        case 8:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, HIGH);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
        case 9:
          {
            digitalWrite (11, HIGH);
            digitalWrite (12, HIGH);
            digitalWrite (13, HIGH);
            digitalWrite (14, HIGH);
            digitalWrite (15, LOW);
            digitalWrite (16, HIGH);
            digitalWrite (17, HIGH);
            digitalWrite (18, LOW);

            break;
          }
      }
    }


    void s1_press() {
      if (state == 0)
        state = 1;
      else if (state == 1)
        state = 0;
      delay (100);
    }

    void s2_press() {
      if (halt == 0)
        halt = 1;
      else
        halt = 0;
      delay(100);
    }
</code></pre>

<p>Here is my intended implementation of the processing code based on the serial write example;</p>

<p>`
    import processing.serial.*;</p>

<pre><code>Serial myPort;  // Create object from Serial class
int val;        // Data received from the serial port
color c1 = #75C58E;
color c2 = #75C5FF;
color c3 = #D07633;
void setup() 
{
  size(420, 200);
  String portName = Serial.list()[1];
  myPort = new Serial(this, portName, 9600);
}

//0 - count up and start
//1 - count down
//2 - stop
//3 - reset

void draw() {
  background(255);
  if (mouseOverRect() == true) {  // If mouse is over square,
    fill(c1);                    // change color and
    myPort.write('1');              // send a '1' to indicate mouse is over square
  } else                          //will be equivalent to the count up/count down trigger
  {
    fill(0);
    myPort.write('0');
  }
  rect(50, 50, 100, 100);         // Draw a square

  if (mouseOverRect2() == true) {  // If mouse is over square,
    fill(c2);                    // change color and
    myPort.write('2');              // send a 2 to indicate mouse is over square
  } else                        //stop trigger
  {
    fill(0);
    myPort.write('0');
  }
  rect(160, 50, 100, 100);

    if (mouseOverRect3() == true) {  // If mouse is over square,
    fill(c3);                    // change color and
    myPort.write('3');              // send a '3' to indicate mouse is over square
  } else                      //reset
  {
    fill(0);
    myPort.write('0');
  }
  rect(270, 50, 100, 100);
}


boolean mouseOverRect() { // Test if mouse is over square
  return ((mouseX &gt;= 50) &amp;&amp; (mouseX &lt;= 150) &amp;&amp; (mouseY &gt;= 50) &amp;&amp; (mouseY &lt;= 150));
}
boolean mouseOverRect2() { // Test if mouse is over square
  return ((mouseX &gt;= 160) &amp;&amp; (mouseX &lt;= 260) &amp;&amp; (mouseY &gt;= 50) &amp;&amp; (mouseY &lt;= 150));
}
boolean mouseOverRect3() { // Test if mouse is over square
  return ((mouseX &gt;= 270) &amp;&amp; (mouseX &lt;= 370) &amp;&amp; (mouseY &gt;= 50) &amp;&amp; (mouseY &lt;= 150));
}
</code></pre>

<p>`</p>

<p>Any tips on how this could be implemented? My implementation doesn't seem to affect the arduino program in any way.</p>
]]></description>
   </item>
   <item>
      <title>Processing to Arduino Serial</title>
      <link>https://forum.processing.org/two/discussion/17597/processing-to-arduino-serial</link>
      <pubDate>Wed, 20 Jul 2016 17:56:22 +0000</pubDate>
      <dc:creator>justincaselton</dc:creator>
      <guid isPermaLink="false">17597@/two/discussions</guid>
      <description><![CDATA[<p>Hello all!</p>

<p>I am new to Processing and want to be able to send and receive data between Processing 3 and my Arduino Mega 2560.</p>

<p>I have been following the examples provided in the Processing Serial library, SimpleRead and SimpleWrite.</p>

<p>I have managed to successfully  use the SimpleRead example and have sent data from my mega to Processing.</p>

<p>However when I try and use the SimpleWrite example, sending data from Processing to the mega, it does not work.  Basically what happens is once I have uploaded the code onto the mega and run the example in Processing the RX light of the Mega 2560 starts flashing indicating that it is receiving serial data from the program, all fine and good.  The on-board LED at pin 13 also remains on continuously, don't know why.</p>

<p>Most importantly the user defined ledPin (as defined in the Arduino programming) does not change value regardless of whether the conditions set in the Processing code have been met or not (i.e. whether or not the mouse is over the box).  I have assigned the ledPin to various different digital pins and it has not made a difference.</p>

<p>Any help would be most appreciated! The code I am using is below:</p>

<p>/**
 * Simple Write. 
 * 
 * Check if the mouse is over a rectangle and writes the status to the serial port. 
 * This example works with the Wiring / Arduino program that follows below.
 */</p>

<p>import processing.serial.*;</p>

<p>Serial myPort;  // Create object from Serial class
int val;        // Data received from the serial port</p>

<p>void setup() 
{
  size(200, 200);
  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}</p>

<p>void draw() {
  background(255);
  if (mouseOverRect() == true) {  // If mouse is over square,
    fill(204);                    // change color and
    myPort.write('H');              // send an H to indicate mouse is over square
  } 
  else {                        // If mouse is not over square,
    fill(0);                      // change color and
    myPort.write('L');              // send an L otherwise
  }
  rect(50, 50, 100, 100);         // Draw a square
}</p>

<p>boolean mouseOverRect() { // Test if mouse is over square
  return ((mouseX &gt;= 50) &amp;&amp; (mouseX &lt;= 150) &amp;&amp; (mouseY &gt;= 50) &amp;&amp; (mouseY &lt;= 150));
}</p>

<p>/*
  // Wiring/Arduino code:
 // Read data from the serial and turn ON or OFF a light depending on the value</p>

<p>char val; // Data received from the serial port
 int ledPin = 4; // Set the pin to digital I/O 4</p>

<p>void setup() {
 pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
 Serial.begin(9600); // Start serial communication at 9600 bps
 }</p>

<p>void loop() {
 while (Serial.available()) { // If data is available to read,
 val = Serial.read(); // read it and store it in val
 }
 if (val == 'H') { // If H was received
 digitalWrite(ledPin, HIGH); // turn the LED on
 } else {
 digitalWrite(ledPin, LOW); // Otherwise turn it OFF
 }
 delay(100); // Wait 100 milliseconds for next reading
 }</p>

<p>*/</p>
]]></description>
   </item>
   <item>
      <title>Android processing app crashes when using usb / processing serial library (Serial.list(this)) probs</title>
      <link>https://forum.processing.org/two/discussion/17375/android-processing-app-crashes-when-using-usb-processing-serial-library-serial-list-this-probs</link>
      <pubDate>Thu, 30 Jun 2016 19:56:51 +0000</pubDate>
      <dc:creator>gabriellalevine</dc:creator>
      <guid isPermaLink="false">17375@/two/discussions</guid>
      <description><![CDATA[<p>hi - I'm having trouble debugging why my android app is crashing when trying to use <a rel="nofollow" href="https://github.com/inventit/processing-android-serial">processing android serial</a> to talk via Processing android app to arduino. i can successfully install and launch the app on android, but the app keeps crashing. I'm using really simple code just to see if I can talk via an OTG cable via serial from Android to Arduino via processing app. But when I plug in the OTG USB cable that's plugged into arduino UNO, I can choose the android app to open up that I have installed from Processing to android, but right away it says "Unfortunately, this app has stopped".</p>

<p>I'm wondering how to go about debugging this. Is it the wrong port (Serial.list(this)[0]) that is doing this? or something else? I'm not sure how to debug why the app's crashing. I just recently started using Processing 0251 for Android. Even just the line "println(Serial.list(this));" triggers the app to shut down.</p>

<p>Thanks in advance!</p>

<p>I used this <a rel="nofollow" href="http://journeytounknownsoundscapes.blogspot.com/2013/12/how-to-arduino-with-android-really-good.html">link</a> to help getting set up:</p>

<p>Processing code in Android mode:</p>

<pre><code>import com.yourinventit.processing.android.serial.*;

Serial SerialPort;
boolean Toggle;

void setup()    
{fullScreen();
background(255,0,0);
  println(Serial.list(this)); //this line alone makes the app crash even if i dont have any other code
  SerialPort = new Serial(this, Serial.list(this)[0], 9600);
}

void draw()
{
}

void mousePressed() {    
  Toggle = !Toggle;
    // while (SerialPort.available() &gt; 0) {
  SerialPort.write( Toggle?"1":"0");
    // }
}
</code></pre>

<p>Arduino Code:</p>

<pre><code>    #define NUMBER_OF_CHANNELS 8
    #define PINLED1 13
    volatile char lastReceivedCharFromSerialIn = '\0';

    void setup() {
      pinMode(PINLED1, OUTPUT);
      Serial.begin(9600);    
    }

    void loop() {
      digitalWrite( PINLED1, lastReceivedCharFromSerialIn == '1');
    }

    void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        lastReceivedCharFromSerialIn = (char)Serial.read(); 
      }
    }
</code></pre>
]]></description>
   </item>
   <item>
      <title>How to send data from arduino after mousepressed()?</title>
      <link>https://forum.processing.org/two/discussion/17515/how-to-send-data-from-arduino-after-mousepressed</link>
      <pubDate>Wed, 13 Jul 2016 14:44:31 +0000</pubDate>
      <dc:creator>rojascan</dc:creator>
      <guid isPermaLink="false">17515@/two/discussions</guid>
      <description><![CDATA[<p>Basically what I want to do is to send values of a potentiometer to the processing and show them in the console after I press a button in the processing program. However, I'm not getting what I want.</p>

<p>My program does a few things that already worked. It has three different modes to move a servo and those are in the main screen of my program. And I've got another screen when I press the button and some of the values of the potentiometer are shown. However, those values don't keep showing unless I press the button again.</p>

<p>This is the relevant arduino code:</p>

<pre><code>void loop ()
{

  if (Serial.available()) {
    val = Serial.read();
  }
 //val is send from processing to the arduino to change modes 
  switch (val) {
    //-------------------------- Close Modes----------------------//
    case 0:
        digitalWrite(ledPot, LOW);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, LOW);
      break;
    //--------------------------CPM Mode----------------------//
    case 1:
        cpmMovement();
        digitalWrite(ledCPM, HIGH);
        digitalWrite(ledPot, LOW);
        digitalWrite(ledFSR, LOW);
      break;
    //--------------------------POT Mode----------------------//
    case 2:
        digitalWrite(ledPot, HIGH);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, LOW);
        potMovement();
      break;
    //--------------------------FSR Mode----------------------//
    case 3:
        digitalWrite(ledPot, LOW);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, HIGH);
        fsrMovement();
      break;
    //---------------------Calibration Mode-----------------------//
    case 4:
        digitalWrite(ledPot, HIGH);
        digitalWrite(ledCPM, HIGH);
        digitalWrite(ledFSR, HIGH);
      break;
    //----------------Sending Values--------------------//  This is the relevant block
    case 5:
        digitalWrite(ledPot, LOW);
        digitalWrite(ledCPM, LOW);
        digitalWrite(ledFSR, HIGH);
        stateCAL == true;
        while(stateCAL == true){
        sendMaxValue();
        }
     break; 

  }
}

void sendMaxValue(){ //Function which sends the values to the console
  unsigned long startTime = millis();
  long calibrationTime = 3000;

  while(millis() - startTime &lt;= calibrationTime) {
    maxforce = analogRead(Pot)/4;
    if (maxforce &gt; maxReading) maxReading = maxforce;
    Serial.print(maxReading);         
    Serial.print('\t');         
    Serial.print(maxforce);
    Serial.print('\t');         
    Serial.print(startTime);
    Serial.print('\t');         
    Serial.println(millis() - startTime);

  }

  if (millis() - startTime &gt; calibrationTime){
    stateCAL = false;
    Serial.println("Falso");
    Serial.print("After 5 seconds, the maximum reading was: ");
    Serial.println(maxReading);
    maxReading = 0;
  } 

}
</code></pre>

<p>And this is the relevant processing code:</p>

<pre><code>void mousePressed() {
  println("Coordinates: "  + mouseX + "," + mouseY);
  if (pressedCPMButton &amp;&amp; currentColorCPM==butColor) { //Changing color CPM to pressed button color
    currentColorCPM = butpreColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(1);   //Send 1 to port
    println(1);
  } else if (pressedCPMButton &amp;&amp; currentColorCPM==butpreColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }
  if (pressedPOTButton &amp;&amp; currentColorPOT==butColor) {
    currentColorCPM = butColor;
    currentColorPOT = butpreColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(2);   //Send 1 to port
    println(2);                                    //Send 2 to port
  } else if (pressedPOTButton &amp;&amp; currentColorPOT==butpreColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }
  if (pressedFSRButton &amp;&amp; currentColorFSR==butColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butpreColor;
    currentColorCAL = butColor;
    myPort.write(3);   //Send 1 to port
    println(3);                                  //Send 3 to port
  } else if (pressedFSRButton &amp;&amp; currentColorFSR==butpreColor) {
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }
  if (pressedCALButton &amp;&amp; currentColorCAL==butColor) {
    currentScreen = 1;
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butpreColor;
    myPort.write(4);   //Send 1 to port
    println(4);                                  //Send 4 to port
  } else if (pressedBACKButton) {
    currentScreen = 0;
    currentColorCPM = butColor;
    currentColorPOT = butColor;
    currentColorFSR = butColor;
    currentColorCAL = butColor;
    myPort.write(0);   //Send 1 to port
    println(0);
  }

  if (pressedSTARTCALButton) {     //This is the bit that isn't working well.
    if(myPort.available() &gt; 0){
    }
    myPort.write(5);     //Send 5 to port
    println(5);
    valforce = myPort.readString();
    println(valforce);
  }
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>Problem with Blink LED test using Shapes and Mouse</title>
      <link>https://forum.processing.org/two/discussion/17313/problem-with-blink-led-test-using-shapes-and-mouse</link>
      <pubDate>Sun, 26 Jun 2016 18:44:31 +0000</pubDate>
      <dc:creator>Ragooman</dc:creator>
      <guid isPermaLink="false">17313@/two/discussions</guid>
      <description><![CDATA[<p>Hello,
This is my first time using Processing on the Raspberry PI. So I made the traditional 'Blink the LED' test in Processing and it works fine. I connected a Red and Yellow LED on the breadboard to create a "ping-pong" type display.</p>

<p>But I noticed something when I started adding Shapes into the code. I added 2 shapes to represent the LED's, one is a red box and the other is a yellow box. And I have the code written to 'turn' on the shapes by changing the color whenever the LED on the breadboard is turned ON. Then when the LED is turned OFF, I change the color of the box to black.</p>

<p>But there seems to be some lag in the graphics. Basically the LED on the breadboard will turn on and the box in the window will change color about 1 second later. At first I thought maybe the "GPIO.digitalWrite" instruction is taking too long. But I swapped the code so the "fill" and "rect" instruction is done first and then after the "GPIO.digitalWrite" instruction is executed. But there was no difference or improvment.</p>

<p>Then I decided to add a mouse event so I can control when to start and end the blinking. There I noticed the lag in the graphics. If I clicked the mouse for a split second, where the LED's would change state just once. I would see the LED's change first, then about 1 sec later the graphics in the window would be updated. And this is a consistent anomaly.</p>

<p>I can't verify this on my desktop to see if I can reproduce the problem as I don't have any GPIO's available at the moment.</p>

<p>Has anyone noticed this before ?</p>

<p>Would I have something out of sequence in the code ?</p>

<p>below is my test code</p>

<pre>


//==================================================
// Import hardware IO library.
import processing.io.*;

// Pin #'s for LEDs and Button:
int redLEDPin   = 22;
int yelLEDPin = 27;
int count = 0;
int count2 = 0;
int i = 1;

// LED state, on or off (true or false).
boolean redLED = true;
boolean yelLED = false;
boolean mouseclk = false;

//----------------------------------------------------
void setup() 
{
  size(300, 200);
  textSize(10);
  //textFont(mono);

  // Initialize LEDs as outputs.
  GPIO.pinMode(redLEDPin, GPIO.OUTPUT);
  GPIO.pinMode(yelLEDPin, GPIO.OUTPUT);


  // Default to drawing black lines around buttons.
  stroke(0, 0, 0);
  
  // Turn the LEDs off.
  GPIO.digitalWrite(redLEDPin, false);
  GPIO.digitalWrite(yelLEDPin, false);

}

//-------------------------------------------------------
void draw()
{

  if (mouseclk)                      //check flag, only do this once
  {
    background(0, 0, 255);
    fill(255,255,255);
    text("BEGIN TEST:",5,10);
    text("WAIT FOR MOUSE CLICK",150, 10);
        
    text("TEST LOOP# " + i + " ",150,100);
    //blink
    redLEDiconON();
  
    redLEDiconOFF();
    
    yelLEDiconON();
  
    yelLEDiconOFF();
  
    redLED = !redLED;
    yelLED = !yelLED;
    
    i++;
    
    delay(1000);
      
    //count = 1;
    
  }
  
  if (!mouseclk)                      //check flag, only do this once
  {
    fill(255,255,255);
    text("END TEST:", 150,150);
  }

  //noLoop();
}

//------------------------------------------------------
void mousePressed() 
{
  count2 = 1;
  i = 1;
  redLED = true;
  yelLED = false;
  mouseclk = true;
}


//------------------------------------------------------
void mouseReleased() 
{
  mouseclk = false;
}
//----------------------------------------------------
void redLEDiconON()
{
  if (redLED)
  {
  fill(255, 0, 0);
  text("Red=ON",50, 80);
  rect(50, 20, 30, 30, 7);
  GPIO.digitalWrite(redLEDPin, true);
  //delay(200);
  }
}

//----------------------------------------------------
void redLEDiconOFF()
{
  if (!redLED)
  {
  fill(255, 0, 0);
  text("Red=OFF",50, 80);
  fill(0, 0, 0);
  rect(50, 20, 30, 30, 7);
  GPIO.digitalWrite(redLEDPin, false);
  //delay(200);
  }
}
//----------------------------------------------------
void yelLEDiconON()
{
  if (yelLED)
  {
  fill(255, 255, 0);
  text("Yel=ON",200, 80);
  rect(200, 20, 30, 30, 7);
  GPIO.digitalWrite(yelLEDPin, true);
  //delay(200);
  }
}

//----------------------------------------------------
void yelLEDiconOFF()
{
  if (!yelLED)
  {
  fill(255, 255, 0);
  text("Yel=OFF",200, 80);
  fill(0, 0, 0);
  rect(200, 20, 30, 30, 7);
  GPIO.digitalWrite(yelLEDPin, false);
  //delay(200);
  }
}
//=====================================================


</pre>
]]></description>
   </item>
   <item>
      <title>Very Slow Arduino Connection</title>
      <link>https://forum.processing.org/two/discussion/17268/very-slow-arduino-connection</link>
      <pubDate>Wed, 22 Jun 2016 15:55:28 +0000</pubDate>
      <dc:creator>CharlesDesign</dc:creator>
      <guid isPermaLink="false">17268@/two/discussions</guid>
      <description><![CDATA[<p>Hi there,</p>

<p>I'm trying to send a string of 16 sensor values from Arduino to Processing unfortunately, the connection is extremely slow. It  also reads fine from the Arduino serial monitor.</p>

<p>What I'm sending, the max for any of them is 255:</p>

<p><code>&lt;0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0&gt;</code></p>

<p>Can anyone see what I'm doing wrong?</p>

<p>Thanks in advance!
Charles</p>

<p>ps: There actually seems to be a 15 second delay on the connection</p>

<p>To Processing:</p>

<pre><code>import processing.serial.*;
Serial arduino;

boolean newData = false;

void setup() {
  size(700, 400);
  frameRate(60);
  arduino = new Serial(this, Serial.list()[5], 9600);
}

void draw() {
  background(255);
  char startMarker = '&lt;';
  char endMarker = '&gt;';
  char read;

  String out = " ";

  while (arduino.available() &gt; 0 &amp;&amp; newData == false) {
    read = char(arduino.read());
    if (read != ',' &amp;&amp; read != '&lt;' &amp; read != '&gt;') {
      out = out + read;
    } else if (read == '&gt;') {
      newData = true;
    } else if (read == ',') {
      out = out + " " ;
    }
  }

  if (newData) {
    fill(0);
    textSize(30);
    text(out, width*0.1, width*0.2);
    newData = false;
  }
}
</code></pre>

<p>From Arduino:</p>

<pre><code>/Mux control pins
const int s0 = 12;
const int s1 = 11;
const int s2 = 9;
const int s3 = 8;

//Mux in "SIG" pin
const int SIG_pin = 2;

const int sample_rate = 40;
unsigned long last = 0;



void setup() {
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);

  Serial.begin(9600);
}


void loop() {

  unsigned long current = millis();

  if ( current - last &gt; sample_rate) {
    Serial.print('&lt;');
    for (int i = 0; i &lt; 16; i++) {
      Serial.print(readMux(i) / 4);
      if (i &lt; 15) Serial.print(',');
    }
    Serial.println('&gt;');
  }

}


int readMux(int channel) {
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4] = {
    {0, 0, 0, 0}, //channel 0
    {1, 0, 0, 0}, //channel 1
    {0, 1, 0, 0}, //channel 2
    {1, 1, 0, 0}, //channel 3
    {0, 0, 1, 0}, //channel 4
    {1, 0, 1, 0}, //channel 5
    {0, 1, 1, 0}, //channel 6
    {1, 1, 1, 0}, //channel 7
    {0, 0, 0, 1}, //channel 8
    {1, 0, 0, 1}, //channel 9
    {0, 1, 0, 1}, //channel 10
    {1, 1, 0, 1}, //channel 11
    {0, 0, 1, 1}, //channel 12
    {1, 0, 1, 1}, //channel 13
    {0, 1, 1, 1}, //channel 14
    {1, 1, 1, 1} //channel 15
  };

  //loop through the 4 sig
  for (int i = 0; i &lt; 4; i ++) {
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //read the value at the SIG pin
  int val = analogRead(SIG_pin);

  //return the value
  return val;
}
</code></pre>
]]></description>
   </item>
   <item>
      <title>A problem ---"cannot convert from void to boolean"</title>
      <link>https://forum.processing.org/two/discussion/16224/a-problem-cannot-convert-from-void-to-boolean</link>
      <pubDate>Sun, 24 Apr 2016 11:29:17 +0000</pubDate>
      <dc:creator>zheng</dc:creator>
      <guid isPermaLink="false">16224@/two/discussions</guid>
      <description><![CDATA[<pre><code>                    `import org.firmata.*;
                    import cc.arduino.*;
                    import processing.serial.*;
                    Arduino arduino;

                    int s1 = 7;//(r) //sensor1
                    int s2 = 8;//(y) //sensor2
                    int s3 = 9;//(b) //sensor3
                    int s4 = 10;//(g)//sensor4
                    int s5 = 11;//(b)//sensor5


                    void setup() {
                     size(500, 500);
                     background(255);
                     println(Arduino.list());

                     arduino = new Arduino(this, Arduino.list()[4], 57600); 
                     arduino.pinMode(s1, Arduino.INPUT);
                     arduino.pinMode(s2, Arduino.INPUT);
                     arduino.pinMode(s3, Arduino.INPUT);
                     arduino.pinMode(s4, Arduino.INPUT);
                     arduino.pinMode(s5, Arduino.INPUT);
                    }
                    void draw() {
                     if (arduino.digitalWrite(s1, Arduino.LOW)) {
                       ellipse(50, 50, 50, 50);
                     }
                    }
                    `
</code></pre>

<p>When the sensor gets information, a circle will appear. But now it cannot work! WHY?</p>
]]></description>
   </item>
   <item>
      <title>Ramon64917021 (Arduino syntax errors)</title>
      <link>https://forum.processing.org/two/discussion/15162/ramon64917021-arduino-syntax-errors</link>
      <pubDate>Sat, 27 Feb 2016 21:03:23 +0000</pubDate>
      <dc:creator>Ramon64917021</dc:creator>
      <guid isPermaLink="false">15162@/two/discussions</guid>
      <description><![CDATA[<p>Estoy intentando cargar un programa y en el momento de verificarlo me salen un montón de errores
de los que no entiendo nada. Además no se nada de inglés.</p>

<p>¿Alguien me puede ayudar?</p>

<p>Gracias y perdón por las molestias</p>

<pre><code> const int inPin = A0;  // pin de entrada
 const int ledPin = 13; // pin del led
 int val = 0;

 void setup(); {
    pinMode(ledPin, OUTPUT);
    Serial.begin(9600);
 }

 void loop() {
    val = analogRead(inPin); // se lee el valor del pin de entrada
    digitalWrite(ledPin, HIGH); // enciende el led
    delay(val); // espera el valor leído en la entrada en milisegundos
    digitalWrite(ledPin, LOW); // apaga el led
    delay(val); // espera el valor leído en la entrada en milisegundos 
    int sensorValue = analogRead(inPin); // leemos el valor
    delay(1);   // pausa para estabilidad entre ciclos     
 }

 map() {
    int x = 11;
    int y = constrain(x,0,10,); // y tendra valor 10
    int z = constrain(x,0,100); // z tendrá valor 11 por estar entre los limites   
 }
}
</code></pre>

<p>Arduino:1.6.6 Hourly Build 2015/07/15 12:54 (Windows 8.1), Placa:"Arduino Uno"</p>

<p>sketch_feb27b:21: error: macro "constrain" passed 4 arguments, but takes just 3<br />
sketch_feb27b:4: error: expected unqualified-id before '{' token<br />
sketch_feb27b:19: error: ISO C++ forbids declaration of 'map' with no type [-fpermissive]<br />
sketch_feb27b.ino: In function 'int map()':<br />
sketch_feb27b:21: error: 'constrain' was not declared in this scope<br />
sketch_feb27b.ino: At global scope:<br />
sketch_feb27b:24: error: expected declaration before '}' token<br />
macro "constrain" passed 4 arguments, but takes just 3</p>

<p>This report would have more information with
  "Show verbose output during compilation"
  activala desde Archivo &gt; Preferencias</p>
]]></description>
   </item>
   <item>
      <title>Processing Signal in Arduino is not working</title>
      <link>https://forum.processing.org/two/discussion/15031/processing-signal-in-arduino-is-not-working</link>
      <pubDate>Sat, 20 Feb 2016 23:20:31 +0000</pubDate>
      <dc:creator>ranaabdullah</dc:creator>
      <guid isPermaLink="false">15031@/two/discussions</guid>
      <description><![CDATA[<p>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.</p>

<p>Arduino Programming</p>

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

<p>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:
}</p>

<p>Processing programming part</p>

<p>case UP:
     println("UP!");
     fill(255,0,0);
     triangle(100, 440, 160, 440, 130, 400);
     myPort.write('1');
     break;<img src="https://forum.processing.org/two/uploads/imageupload/851/83XAACO0PAZS.PNG" alt="Capture" title="Capture" /></p>
]]></description>
   </item>
   <item>
      <title>Unexpected behavior with basic excercise Processing and Arduino</title>
      <link>https://forum.processing.org/two/discussion/14729/unexpected-behavior-with-basic-excercise-processing-and-arduino</link>
      <pubDate>Tue, 02 Feb 2016 16:16:47 +0000</pubDate>
      <dc:creator>juanpal</dc:creator>
      <guid isPermaLink="false">14729@/two/discussions</guid>
      <description><![CDATA[<p>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.</p>

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

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

<p>I have the led in pin 13 to possitive and pin ground with negative.</p>

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

<p>Thanks</p>
]]></description>
   </item>
   <item>
      <title>Reaction time game. How to solve infinite loop.</title>
      <link>https://forum.processing.org/two/discussion/14581/reaction-time-game-how-to-solve-infinite-loop</link>
      <pubDate>Fri, 22 Jan 2016 18:30:12 +0000</pubDate>
      <dc:creator>luisandresgonzalez</dc:creator>
      <guid isPermaLink="false">14581@/two/discussions</guid>
      <description><![CDATA[<p>I'm programming my arduino to make a reaction time game as a sketch for a more serious scientific study. It works like this</p>

<ol>
<li>you press a button once, and a led blinks indicating the game begins</li>
<li>after a random lapse, the led lights up, and a clock starts to measure the time until you press the button again</li>
<li>if you do, it shows the reaction time in seconds</li>
<li>if you press before the led lights up, it blinks three times and the game ends</li>
<li>if you don't press the button after a tame, the led blinks twice and the game ends</li>
<li>once the game ends, it only begins again if you press the button again. </li>
</ol>

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

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

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



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

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

void loop() {
  // Check <a href="https://www.arduino.cc/en/Tutorial/StateChangeDetection" target="_blank" rel="nofollow">https://www.arduino.cc/en/Tutorial/StateChangeDetection</a> to understand the following code.
  if ((millis() - beginTime) &gt; (randomSeconds + maxTimer)) {
    Stop();
    
    //resets game:
    gameStarted = false;
    timerFlag = false;
    currentButton = LOW;
    lastButton = LOW;
    
    
    Blink(2);
    Serial.println("message");

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

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

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

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

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

    }
  }                             // end outer if

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




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

    Start();

  }
  
} // end void loop

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

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

void Start() {

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

}

void Stop() {
  if ( (millis() - beginTime) </pre>
]]></description>
   </item>
   <item>
      <title>How can i translate the arduino line to processing?  if(sum == 0b1101 || sum == 0b0100 || sum == 0b0</title>
      <link>https://forum.processing.org/two/discussion/14420/how-can-i-translate-the-arduino-line-to-processing-if-sum-0b1101-sum-0b0100-sum-0b0</link>
      <pubDate>Tue, 12 Jan 2016 23:48:51 +0000</pubDate>
      <dc:creator>Marc21758</dc:creator>
      <guid isPermaLink="false">14420@/two/discussions</guid>
      <description><![CDATA[<p>I based myself to build this circuit <a href="http://bildr.org/2012/08/rotary-encoder-arduino/" target="_blank" rel="nofollow">http://bildr.org/2012/08/rotary-encoder-arduino/</a> and started working it in processing 3.0 i'm "translating" the lines  but the most importan ones, the ones that give me the values for the rotary encoder, keeps sending me the same error "Syntax error, maybe a missing right parenthesis?"</p>

<p>if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++;
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;</p>

<p>These are the lines i have problems with</p>

<p>`import processing.serial.*;
import cc.arduino.*;
PImage img;</p>

<p>Arduino arduino;</p>

<p>int encoderPin1 = 2;
int encoderPin2 = 3;
int encoderSwitchPin = 4; //push button switch</p>

<p>int buttonPin = 7 ;
int ledPin = 13;</p>

<p>volatile int lastEncoded = 0;
volatile long encoderValue = 0;</p>

<p>long lastencoderValue = 0;</p>

<p>int lastMSB = 0;
int lastLSB = 0;</p>

<p>boolean buttonPushed = false;
int buttonState = 0;</p>

<p>void setup() {
  size(600, 600);</p>

<p>arduino = new Arduino(this, Arduino.list()[0], 57600);</p>

<p>arduino.pinMode(encoderPin1, Arduino.INPUT);
  arduino.pinMode(encoderPin2, Arduino.INPUT);</p>

<p>arduino.pinMode(ledPin, Arduino.OUTPUT);
  arduino.pinMode(buttonPin, Arduino.INPUT);</p>

<p>arduino.pinMode(encoderSwitchPin, Arduino.INPUT);</p>

<p>arduino.digitalWrite(encoderPin1, Arduino.HIGH);
  arduino.digitalWrite(encoderPin2, Arduino.HIGH);
  arduino.digitalWrite(encoderSwitchPin, Arduino.HIGH);</p>

<p>attachInterrupt(0, updateEncoder, Arduino.CHANGE); 
  attachInterrupt(1, updateEncoder, Arduino.CHANGE);</p>

<p>}</p>

<p>void draw(){
  buttonState = arduino.digitalRead(buttonPin);
  img = loadImage ("robotina.jpg");
  if(arduino.digitalRead(encoderSwitchPin) == Arduino.HIGH){
    buttonPushed= false;<br />
  }
  else{
   println("button pushed");</p>

<p>println (encoderValue);</p>

<p>}</p>

<p>if (buttonState == Arduino.HIGH) {
    println("back button");
    arduino.digitalWrite(ledPin, Arduino.HIGH);
    image (img,0,0);
  }
  else{
    arduino.digitalWrite(ledPin, Arduino.LOW);
  }</p>

<p>//println(encoderValue);<br />
  delay(100);
}</p>

<p>void updateEncoder(){
  int MSB = arduino.digitalRead(encoderPin1); //MSB = most significant bit
  int LSB = arduino.digitalRead(encoderPin2); //LSB = least significant bit</p>

<p>int encoded = (MSB &lt;&lt; 1) |LSB; //converting the 2 pin value to single number
  int sum  = (lastEncoded &lt;&lt; 2) | encoded; //adding it to the previous encoded value</p>

<p>//this is where i keep getting the error</p>

<p>if(sum == 0b1101 || sum == 0b0100 || sum == 0b0010 || sum == 0b1011) encoderValue ++; 
  if(sum == 0b1110 || sum == 0b0111 || sum == 0b0001 || sum == 0b1000) encoderValue --;</p>

<p>lastEncoded = encoded; //store this value for next time
}`</p>
]]></description>
   </item>
   <item>
      <title>How to use PC sounds to FFT for LEDs control with arduino?</title>
      <link>https://forum.processing.org/two/discussion/14070/how-to-use-pc-sounds-to-fft-for-leds-control-with-arduino</link>
      <pubDate>Fri, 18 Dec 2015 21:47:24 +0000</pubDate>
      <dc:creator>SrBla3000</dc:creator>
      <guid isPermaLink="false">14070@/two/discussions</guid>
      <description><![CDATA[<p>Hello, i'm new to Processing and all of this.</p>

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

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

<p>=== Minim Error ===
=== Minim.getLineIn: attempt failed, could not secure an AudioInput.
`</p>

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

<p>Can anyone help me with this?
Thank your very much.</p>

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

<p>`import ddf.minim.*;<br />
import ddf.minim.analysis.*;
import processing.serial.*;
import cc.arduino.*;</p>

<p>Arduino arduino;</p>

<p>Minim minim;
AudioInput sound;
FFT fft;</p>

<p>int redPin1 = 8;
int greenPin1 = 7;
int bluePin1 = 6;</p>

<p>int redPin2 = 2;
int greenPin2 = 3;
int bluePin2 = 4;</p>

<p>int redPin3 = 11;
int greenPin3 = 12;
int bluePin3 = 13;</p>

<p>int color_id = 0;</p>

<p>int common_cathode = 1;</p>

<p>void setup() {
    size(800, 600);</p>

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

minim = new Minim(this);
sound = minim.getLineIn();
fft = new FFT(sound.bufferSize(), sound.sampleRate());
</code></pre>

<p>}</p>

<p>void draw() {<br />
    background(#151515);</p>

<pre><code>fft.forward(sound.mix);

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

strokeWeight(1.3);
stroke(#FFF700);

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

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

stroke(#FF0000);

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

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

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

<p>}</p>

<p>void stop()
{
    for (int i = 0; i &lt;= 13; i++) arduino.digitalWrite(i,arduino.HIGH);
    sound.close();<br />
    minim.stop();
    super.stop();
}
void setColor1(int red, int green, int blue)
{
  if(common_cathode==1) {
    red = 255-red;
    green = 255-green;
    blue = 255-blue;
  }
  arduino.digitalWrite(redPin1, red);
  arduino.digitalWrite(greenPin1, green);
  arduino.digitalWrite(bluePin1, blue);<br />
}
void setColor2(int red, int green, int blue)
{
  if(common_cathode==1) {
    red = 255-red;
    green = 255-green;
    blue = 255-blue;
  }
  arduino.digitalWrite(redPin2, red);
  arduino.digitalWrite(greenPin2, green);
  arduino.digitalWrite(bluePin2, blue);<br />
}
void setColor3(int red, int green, int blue)
{
  if(common_cathode==1) {
    red = 255-red;
    green = 255-green;
    blue = 255-blue;
  }
  arduino.digitalWrite(redPin3, red);
  arduino.digitalWrite(greenPin3, green);
  arduino.digitalWrite(bluePin3, blue);<br />
}`</p>
]]></description>
   </item>
   <item>
      <title>Processing script (Minim example with serial stuff shoved in) displaying 'Null'  input from arduino</title>
      <link>https://forum.processing.org/two/discussion/13741/processing-script-minim-example-with-serial-stuff-shoved-in-displaying-null-input-from-arduino</link>
      <pubDate>Wed, 02 Dec 2015 06:12:26 +0000</pubDate>
      <dc:creator>snarejunkie</dc:creator>
      <guid isPermaLink="false">13741@/two/discussions</guid>
      <description><![CDATA[<p>I'm trying to control the gain value of a song that's playing by using inputs from an arduino (0 or 1) I tested the arduino code with the general processing serial comm example and it works fine. I also tested my processing script with an arduino code that generates just 0s and 1s and that also works okay</p>

<p>Here's the processing script I'm using:</p>

<p>`    /**
      * This sketch demonstrates how to play a file with Minim using an AudioPlayer. <br />
      * It's also a good example of how to draw the waveform of the audio. Full documentation 
      * for AudioPlayer can be found at <a href="http://code.compartmental.net/minim/audioplayer_class_audioplayer.html" target="_blank" rel="nofollow">http://code.compartmental.net/minim/audioplayer_class_audioplayer.html</a>
      * </p><p>
      * For more information about Minim and additional features, 
      * visit <a href="http://code.compartmental.net/minim/" target="_blank" rel="nofollow">http://code.compartmental.net/minim/</a>
      <em>/
    import processing.serial.</em>;
    import ddf.minim.*;</p>

<pre><code>Serial myPort;
String val;
int a;

Minim minim;
AudioPlayer player;

void setup()
{

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

  size(512, 200, P3D);

  // we pass this to Minim so that it can load files from the data directory
  minim = new Minim(this);

  // loadFile will look in all the same places as loadImage does.
  // this means you can find files that are in the data folder and the 
  // sketch folder. you can also pass an absolute path, or a URL.
  player = minim.loadFile("Highway to Hell.wav");
}

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


  background(0);
  stroke(255);

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

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

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


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

  }

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

<p>and the Arduino script I used to generate the 0s and1s:</p>

<pre><code>`Serial.begin(115200);

}

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

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


}
`
</code></pre>

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

<p>I then tried using the processing script with my actual arduino code:</p>

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

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


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

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


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




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

void setup() {

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

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


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

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


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

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

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

`
</code></pre>

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

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

<p>Any help would be greatly appreciated, Thank you!</p>
]]></description>
   </item>
   <item>
      <title>arduino.pulseIn(int,int) and Processing</title>
      <link>https://forum.processing.org/two/discussion/13476/arduino-pulsein-int-int-and-processing</link>
      <pubDate>Tue, 10 Nov 2015 23:03:45 +0000</pubDate>
      <dc:creator>Krysta</dc:creator>
      <guid isPermaLink="false">13476@/two/discussions</guid>
      <description><![CDATA[<pre><code>import processing.serial.*;
import cc.arduino.*;

Arduino arduino;

int l = 0;
int r=-180;
int t;
float z;

void setup() {
  frameRate(40);
  size(500, 500);
  println(Arduino.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(10, Arduino.SERVO);
  arduino.pinMode(8, Arduino.INPUT);
}

void draw() {
    translate(250, 250);
  background(250);
  screen();


  strokeWeight(3);
  stroke(0, 255, 0);
  strokeWeight(2);
  if (l&gt;=-181 ) {
    l--;
    t=1;
    z = radians(l);
  }
  if (l&lt;-180) {
    r++;
    t=r;
    z = radians(r);
  }
  if (r==0) {
    r=-180;
    l=0;
  }

  pushMatrix();
  rotate(z);
  line(0, 0, 100, 0);
  popMatrix();
}

void screen() {
stroke(0);
  fill(0);
  arc(0, 0, 200, 200, PI, TWO_PI);
}

void ar(){
arduino.servoWrite(10, t);  
arduino.digitalWrite(8, Arduino.HIGH);
arduino.pulseIn(8, Arduino.HIGH);
}
</code></pre>

<p>pulseIn(int,int); is not a function, Can I add this to the arduino library or would it not work for processing even if added? Or is there another way to use a ping sensor in processing?</p>
]]></description>
   </item>
   <item>
      <title>Send Data from Arduino to Processing over serial // help please</title>
      <link>https://forum.processing.org/two/discussion/11649/send-data-from-arduino-to-processing-over-serial-help-please</link>
      <pubDate>Sat, 11 Jul 2015 04:37:06 +0000</pubDate>
      <dc:creator>Casey_Scalf</dc:creator>
      <guid isPermaLink="false">11649@/two/discussions</guid>
      <description><![CDATA[<p>I am trying to send data from an Arduino Uno to Processing.</p>

<p>Video of situation: <span class="VideoWrap"><span class="Video YouTube" id="youtube-s68aYfD71WY"><span class="VideoPreview"><a href="http://youtube.com/watch?v=s68aYfD71WY"><img src="http://img.youtube.com/vi/s68aYfD71WY/0.jpg" width="640" height="385" border="0" /></a></span><span class="VideoPlayer"></span></span></span></p>

<p>I made a simple sketch which does this no problem. It is only when I try to have the Arduino send data to Procesing in an "if conditional" from an analog sensor reading that I run into trouble.</p>

<p>For instance, the simple send from Arduino looks like this:</p>

<pre><code>int ledPin = 13;

void setup()
{
  Serial.begin(9600);
   pinMode(ledPin, OUTPUT);
}
void loop()
{
  Serial.write(1);
   digitalWrite(ledPin, HIGH);
  delay(200);
  Serial.write(0);
   digitalWrite(ledPin, LOW);
  delay(200);
}
</code></pre>

<p>And the corresponding Processing code looks like this:</p>

<pre><code>import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;

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

  rectMode(CENTER);
}

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

  if (myPort.available()&gt;0)
  {
    val = myPort.read();
  }
  println(val);

  if (val == 1)  {
    rect(width/2, height/2, 30, 30);
  }
}
</code></pre>

<p>It makes a white square appears when the number "1" is sent to Processing. It works so simple. It works every time. I was so pleased.</p>

<p>However, when I try it with the next Arduino sketch, nothing ever happens. It always stays on "0" even though I can see on the Arduino the LED turns on showing that yes, this piece of code has run. The Processing portion can stay exactly the same.</p>

<p>Why am I not seeing it work right? I have tried so many things. This tells me it's either painfully obvious or I've done something horribly karmically wrong and this is my punishment.</p>

<p>Thank you for nay tips.</p>

<pre><code>    // Used to interface with electronic drum pads
    // Using a piezo sensor
    // Casey Scalf 2015


    int ledPin = 13;
    int padPin = 0; // Red
    // Black is Ground

    byte val;
    byte a = 0;

    int THRESHOLD = 20;

    void setup() {

      Serial.begin(9600);

      pinMode(ledPin, OUTPUT);
    }

    void loop() {

      val = analogRead(padPin);

      if (val &lt;= THRESHOLD) {
        digitalWrite(ledPin, LOW);
        a = 0;
        Serial.write(a);
      }

        if (val &gt;= THRESHOLD) {
        digitalWrite(ledPin, HIGH);
        a = 1;
        Serial.write(a);
      }

    }
</code></pre>
]]></description>
   </item>
   <item>
      <title>Reading data from txt file</title>
      <link>https://forum.processing.org/two/discussion/12876/reading-data-from-txt-file</link>
      <pubDate>Wed, 07 Oct 2015 13:41:28 +0000</pubDate>
      <dc:creator>cagdasakalin</dc:creator>
      <guid isPermaLink="false">12876@/two/discussions</guid>
      <description><![CDATA[<p>Hi all,</p>

<p>We are trying to read the data in the .txt file which include</p>

<pre><code>1   0   0   0   1549,01050
1   0   0   0   1549,08360
1   0   0   0   1549,07956
1   0   0   0   1549,07956
1   0   0   0   1549,07552
1   0   0   0   1549,03956
1   0   0   0   1549,07956
1   0   0   0   1549,08158
1   0   0   0   1549,08360
1   0   0   0   1549,07956
1   0   0   0   1549,04148
1   0   0   0   1549,07350
1   0   0   0   1549,02442
</code></pre>

<p>such values in it.</p>

<p>After doing that, what we would like to do is to compare the values just in the 5th column with 1549.05 one by one. If any decimal number in the 5th column is bigger than 1549.05, then in the processing, we may create a array or string or something(Since I am new in Processing and Arduino, I may not know true term ) like that which just includes 1s or 0s.</p>

<p>for example</p>

<p>arry=[]</p>

<p>for i=1</p>

<p>1549.05&gt;1549,01050 =&gt; make that; arry=[1]</p>

<p>for i=2</p>

<p>1549.05&lt;1549,08360 =&gt; make that; arry=[1 0]
.
.
.</p>

<p>The following code is what I found in the web and try to modify it for my purpose.</p>

<p>After obtaining such an array which I called above "arry", the Processing code will send that data to Arduino and it will turn on or off the pin13 depending on which number(0 or 1) is being sent from Processing to Arduino.</p>

<p>The Processing code that we try to modify</p>

<pre><code>import processing.serial.*; 
import java.io.*; 
int mySwitch=0; 
int counter=0;
int i=0;
String [] subtext;
Serial myPort; 

void setup() { 
  mySwitch=1; 
  myPort = new Serial(this, "COM12", 9600); 
  myPort.bufferUntil('\n');
} 

void draw() { 
  if (mySwitch&gt;0) { 
    readData("C:/Python32/BridgeStrain.txt"); 
    mySwitch=0;
  } 
  if (counter&lt;subtext.length) { 
    myPort.write(subtext[counter]); 
    delay(500); 
    myPort.write('0'); 
    delay(100); 
    counter++;
  } else { 
    delay(5000); 
    mySwitch=1;
  }
} 

void readData(String myFileName) { 

  File file=new File(myFileName); 
  BufferedReader br=null; 

  try { 
    br=new BufferedReader(new FileReader(file)); 
    String text=null;
        while ((text=br.readLine())!=null) { 
      subtext = splitTokens(text, ",");
    }
  }
  catch(FileNotFoundException e) { 
    e.printStackTrace();
  }
  catch(IOException e) { 
    e.printStackTrace();
  }
  finally { 
    try { 
      if (br != null) { 
        br.close();
      }
    } 
    catch (IOException e) { 
      e.printStackTrace();
    }
  }
} 
</code></pre>

<p>Arduino Code</p>

<pre><code>int outPin = 13;          //define outpin 
float signal; 
void setup() { 
  Serial.begin(9600); 
  pinMode(outPin,OUTPUT); //set output pin 
} 

void loop() { 
    while (Serial.available()&gt;0) { 
      signal = Serial.parseFloat(); 

      if(signal&gt;1){ 
        digitalWrite(outPin, LOW); 
      } 
      else{ 
        digitalWrite(outPin,HIGH); 
      } 
    } 
 } 
</code></pre>

<p>Your valuable comments for solving our problem are very appreciated.</p>

<p>Bests, Çağdaş</p>
]]></description>
   </item>
   <item>
      <title>photosensor triggers sound, how do I stop the sound from looping?</title>
      <link>https://forum.processing.org/two/discussion/11967/photosensor-triggers-sound-how-do-i-stop-the-sound-from-looping</link>
      <pubDate>Tue, 04 Aug 2015 20:10:56 +0000</pubDate>
      <dc:creator>charlie78</dc:creator>
      <guid isPermaLink="false">11967@/two/discussions</guid>
      <description><![CDATA[<p>Hello! I'm writing a code for a Lilypad and one of the inputs I'm hoping to use is a photosensor, which should trigger a sound when the sensor is covered. That bit is all working fine, but the sound is looped and I can't figure out how to stop that? I tried <code>noLoop()</code> but that just plays the sound when the Lilypad is first connected, and nothing happens when the sensor is covered.. This is my code:</p>

<pre><code>import processing.serial.*;
import cc.arduino.*;
import ddf.minim.*;

Minim minim;
Event event_example;
Arduino arduino;

int input_example, led; //the led just gives additional feedback if the the sensor was covered 

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

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

  input_example = 2; //this is the pin the photo resistor is connected to
  led = 6; //this is the pin that the led is connected to

  arduino.pinMode(input_example, Arduino.INPUT);

  minim = new Minim(this);
  event_example= new Event("audio/example.wav");
}

void draw() {

  if (arduino.analogRead(input_example) &lt; 500) {
    event_example.trigger();
    arduino.digitalWrite(led, Arduino.HIGH);
  } else {
    event_example.stop();
    arduino.digitalWrite(led, Arduino.LOW);
  }
}

//The following code is in another tab

public class Event {

  boolean flag;
  AudioSample sample;

  public Event (String file) {
    sample = minim.loadSample(file, 512);
    flag = false;
  }

  void trigger() {
    sample.trigger();
    flag = true;
  }

  void stop() {
    flag = false;
  }
}
</code></pre>

<p>Any help is much appreciated!!</p>
]]></description>
   </item>
   <item>
      <title>Arduino Uno and Processing</title>
      <link>https://forum.processing.org/two/discussion/10732/arduino-uno-and-processing</link>
      <pubDate>Sun, 10 May 2015 08:02:50 +0000</pubDate>
      <dc:creator>andoni</dc:creator>
      <guid isPermaLink="false">10732@/two/discussions</guid>
      <description><![CDATA[<p>I have a problem with analog Pin on Arduino Uno. I know this:</p>

<p>int ledPin1 = 1;    ---&gt;  LED connected to digital pin 1
 arduino.pinMode(ledPin1, Arduino.OUTPUT); 
 arduino.digitalWrite(ledPin1, Arduino.HIGH);
 arduino.digitalWrite(ledPin1, Arduino.LOW);</p>

<p>I suppose that the digital pin starts from 1 to 13,is it correct?</p>

<p>I want to use the analog pin(A1,A2,A3,A4,A5)for the command above, how can I do this?</p>

<p>thank you</p>
]]></description>
   </item>
   </channel>
</rss>