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

How do I get controlP5 generated knob in Processing to change values in Arduino code?

$
0
0

Background: I am working on a electric brewing project using an Arduino Uno R3, two DS18b20 digital temp sensors and Processing IDE. I am using the sensors to monitor and control two separate heating elements on SSRs for various steps in beer brewing. I have successfully used the following Arduino and Processing code to send serial data to Processing to generate a dumb temp output GUI showing two separate temps (ACTUAL1,2), relay set points (SETPOINT1,2) and relay states (HEATPIN1,2).

Problem: The control knob generated with the controlP5 library is in the Processing sketch as you will see below but I am asking for help getting it to communicate back to Arduino. I may be going about this all wrong dataflow wise: Arduino to serial to Processing...back to serial? back to Arduino? I tried to scrap most of the Arduino code and use Firmata but I still need to code in the Dallas sensors into Arduino. Any suggestions would be greatly appreciated, very new to coding, I have the brewing process, hardware and wiring down but lack experience with code. Thank you in advance.

Arduino Code:

//#include <Boards.h>
//#include <Firmata.h>

#include <OneWire.h>
#include <DallasTemperature.h>
int ACTUAL1;
int ACTUAL2;
int SETPOINT1 = 145;
int SETPOINT2 = 150;
int HEATPIN1 = 13;
int HEATPIN2 = 12;
#define ONE_WIRE_BUS 3
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
DeviceAddress Probe1 = { 0x28, 0xFF, 0x14, 0x23, 0x16, 0x15, 0x03, 0xB9 };
DeviceAddress Probe2 = { 0x28, 0xFF, 0xBA, 0x0D, 0x16, 0x15, 0x03, 0x4D };

void setup(void)
{
  pinMode(HEATPIN1, OUTPUT);
  pinMode(HEATPIN2, OUTPUT);
  Serial.begin(9600);
  sensors.begin();
  sensors.setResolution(Probe1, 10);
  sensors.setResolution(Probe2, 10);
}

void printTemperature(DeviceAddress deviceAddress)
{
  float TempC = sensors.getTempC(deviceAddress);
  if (TempC == -127.00) {
    Serial.print("Error getting temperature");
  } else {
    ACTUAL1 = (DallasTemperature::toFahrenheit(TempC));
    ACTUAL2 = (DallasTemperature::toFahrenheit(TempC));
    Serial.print(ACTUAL1);
    //Serial.print(ACTUAL2);
  }
}

void loop(void)
{
  delay(2000);
  sensors.requestTemperatures();

  //Serial.read();
  //SETPOINT1 = Serial.parseInt();

  printTemperature(Probe1);
  if (ACTUAL1 < 100) {
    Serial.print(" ");
  }
  Serial.print(",");
  Serial.print(SETPOINT1);
  if (SETPOINT1 < 100) {
    Serial.print(" ");
  }
  if (ACTUAL1 >= SETPOINT1)
  {
    Serial.print ("OFF");
    digitalWrite(HEATPIN1, LOW);
  }
  else
  {
    Serial.print ("ON ");
    digitalWrite(HEATPIN1, HIGH);
  }

  printTemperature(Probe2);
  if (ACTUAL2 < 100) {
    Serial.print(" ");
  }
  Serial.print(SETPOINT2);
  if (SETPOINT2 < 100) {
    Serial.print(" ");
  }
  if (ACTUAL2 >= SETPOINT2)
  {
    Serial.print ("OFF.");
    digitalWrite(HEATPIN2, LOW);
  }
  else
  {
    Serial.print ("ON .");
    digitalWrite(HEATPIN2, HIGH);
  }
}

Processing Code:

import controlP5.*;
ControlP5 cp5;
Knob myKnobA;
Knob myKnobB;

import processing.serial.*;
Serial port;
String ACTUAL1 = "";
String ACTUAL2 = "";
String SETPOINT1 = "";
String SETPOINT2 = "";
String HEATPIN1 = "";
String HEATPIN2 = "";
String data = "";
int index = 0;
PFont font;


void setup()
{

  smooth();
  noStroke();
  cp5 = new ControlP5(this);
  myKnobA = cp5.addKnob("SETPOINT 1")
    .setRange(50, 215)
      .setValue(50)
        .setPosition(50, 350)
          .setRadius(50)
            .setNumberOfTickMarks(33)
              .setTickMarkLength(10)
                .snapToTickMarks(true)
                  .setColorForeground(color(255))
                    .setColorBackground(color(0, 160, 100))
                      .setColorActive(color(255, 255, 0))
                        .setDragDirection(Knob.VERTICAL)
                          ;
  myKnobB = cp5.addKnob("SETPOINT 2")
    .setRange(50, 215)
      .setValue(50)
        .setPosition(200, 350)
          .setRadius(50)
            .setNumberOfTickMarks(33)
              .setTickMarkLength(10)
                .snapToTickMarks(true)
                  .setColorForeground(color(255))
                    .setColorBackground(color(0, 160, 100))
                      .setColorActive(color(255, 255, 0))
                        .setDragDirection(Knob.VERTICAL)
                          ;

  size(360, 500);
  port = new Serial(this, "COM4", 9600);
  port.bufferUntil('.'); 
  font = loadFont("AgencyFB-Bold-200.vlw");
  textFont(font, 100);
}

void draw()
{


  background(0, 0, 0);
  fill(46, 209, 2);
  text(ACTUAL1, 50, 100);
  fill(0, 102, 153);
  text(SETPOINT1, 50, 200);
  fill(50, 2, 100);
  text(HEATPIN1, 50, 300);

  fill(46, 209, 2);
  text(ACTUAL2, 200, 100);
  fill(0, 102, 153);
  text(SETPOINT2, 200, 200);
  fill(50, 2, 100);
  text(HEATPIN2, 200, 300);

  float S1;
  S1 = (myKnobA.getValue());
  println(S1);
}

void keyPressed() {
  switch(key) {
    case('1'):
    myKnobA.setValue(50);
    break;
    case('2'):
    myKnobA.setValue(215);
    break;
    case('3'):
    myKnobB.setValue(50);
    break;
    case('4'):
    myKnobB.setValue(215);
    break;
  }
}

void serialEvent (Serial port)
{
  data = port.readStringUntil('.');
  data = data.substring(0, data.length() - 1);
  index = data.indexOf(",");

  ACTUAL1 = data.substring(0, data.length() - 16);
  SETPOINT1 = data.substring(index+1, data.length() - 12);
  HEATPIN1 = data.substring(index+4, data.length() - 9);

  ACTUAL2 = data.substring(index+7, data.length() - 6);
  SETPOINT2 = data.substring(index+10, data.length() - 3);
  HEATPIN2 = data.substring(index+13, data.length());
}

mapping error - arduino, very basic

$
0
0

Hey yall - firstly thanks for any help.

I am trying to run the very basic "graph" tutorial off of an arduino. (https://www.arduino.cc/en/Tutorial/Graph). I have a simple circuit with a potentiometer.

When I run this processing code, I get the following error:

map(NaN, 0, 1023, 0, 300) called, which returns NaN (not a number)

Weird. But if I type "println(inByte)" after my map line, the console shows me changing potentiometer values just fine. No error. Also, I should say the pop-out window which is supposed to graph my moving values is black, and never shows any sort of graph. Thanks again for all your help -

Arduino com port

$
0
0

Hello everybody...i'm totally new at this so forgive me for asking stupid questions...i build a cnc router and i want to use processing to run it. i uploaded the arduino firmware and that worked fine but when i try to run the processing ide it always want's to connect to com port 3 but my arduino is running on com port 4...now how can i change that. thanks....marc7974

Arduino ambilight: detect black bars

$
0
0

Hello,

Some days ago I bought myself some LEDs, an arduino micro and a power supply. I wanted to create an ambilight setup for my 41" television.

Now I have created this and it works fine for normal videos (that play over the whole screen). I was wondering if there is any way to detect black bars in videos in top and bottom, to ignore this and take the first line of colored pixels, to show off in the LEDs ?

The code I am using for my arduino micro is:

// Slightly modified Adalight protocol implementation that uses FastLED
// library (http://fastled.io) for driving WS2811/WS2812 led stripe
// Was tested only with Prismatik software from Lightpack project

#include "FastLED.h"

#define NUM_LEDS 166 // Max LED count
#define LED_PIN 6 // arduino output pin
#define GROUND_PIN 10
#define BRIGHTNESS 255 // maximum brightness
#define SPEED 115200 // virtual serial port speed, must be the same in boblight_config 

CRGB leds[NUM_LEDS];
uint8_t * ledsRaw = (uint8_t *)leds;

// A 'magic word' (along with LED count & checksum) precedes each block
// of LED data; this assists the microcontroller in syncing up with the
// host-side software and properly issuing the latch (host I/O is
// likely buffered, making usleep() unreliable for latch).  You may see
// an initial glitchy frame or two until the two come into alignment.
// The magic word can be whatever sequence you like, but each character
// should be unique, and frequent pixel values like 0 and 255 are
// avoided -- fewer false positives.  The host software will need to
// generate a compatible header: immediately following the magic word
// are three bytes: a 16-bit count of the number of LEDs (high byte
// first) followed by a simple checksum value (high byte XOR low byte
// XOR 0x55).  LED data follows, 3 bytes per LED, in order R, G, B,
// where 0 = off and 255 = max brightness.

static const uint8_t magic[] = {
  'A','d','a'};
#define MAGICSIZE  sizeof(magic)
#define HEADERSIZE (MAGICSIZE + 3)

#define MODE_HEADER 0
#define MODE_DATA   2

// If no serial data is received for a while, the LEDs are shut off
// automatically.  This avoids the annoying "stuck pixel" look when
// quitting LED display programs on the host computer.
static const unsigned long serialTimeout = 150000; // 150 seconds

void setup()
{
  pinMode(GROUND_PIN, OUTPUT); 
  digitalWrite(GROUND_PIN, LOW);
  FastLED.addLeds(leds, NUM_LEDS);

  // Dirty trick: the circular buffer for serial data is 256 bytes,
  // and the "in" and "out" indices are unsigned 8-bit types -- this
  // much simplifies the cases where in/out need to "wrap around" the
  // beginning/end of the buffer.  Otherwise there'd be a ton of bit-
  // masking and/or conditional code every time one of these indices
  // needs to change, slowing things down tremendously.
  uint8_t
    buffer[256],
  indexIn       = 0,
  indexOut      = 0,
  mode          = MODE_HEADER,
  hi, lo, chk, i, spiFlag;
  int16_t
    bytesBuffered = 0,
  hold          = 0,
  c;
  int32_t
    bytesRemaining;
  unsigned long
    startTime,
  lastByteTime,
  lastAckTime,
  t;
  int32_t outPos = 0;

  Serial.begin(SPEED); // Teensy/32u4 disregards baud rate; is OK!

  Serial.print("Ada\n"); // Send ACK string to host

    startTime    = micros();
  lastByteTime = lastAckTime = millis();

  // loop() is avoided as even that small bit of function overhead
  // has a measurable impact on this code's overall throughput.

  for(;;) {

    // Implementation is a simple finite-state machine.
    // Regardless of mode, check for serial input each time:
    t = millis();
    if((bytesBuffered < 256) && ((c = Serial.read()) >= 0)) {
      buffer[indexIn++] = c;
      bytesBuffered++;
      lastByteTime = lastAckTime = t; // Reset timeout counters
    } 
    else {
      // No data received.  If this persists, send an ACK packet
      // to host once every second to alert it to our presence.
      if((t - lastAckTime) > 1000) {
        Serial.print("Ada\n"); // Send ACK string to host
        lastAckTime = t; // Reset counter
      }
      // If no data received for an extended time, turn off all LEDs.
      if((t - lastByteTime) > serialTimeout) {
        memset(leds, 0,  NUM_LEDS * sizeof(struct CRGB)); //filling Led array by zeroes
        FastLED.show();
        lastByteTime = t; // Reset counter
      }
    }

    switch(mode) {

    case MODE_HEADER:

      // In header-seeking mode.  Is there enough data to check?
      if(bytesBuffered >= HEADERSIZE) {
        // Indeed.  Check for a 'magic word' match.
        for(i=0; (i 0) and multiply by 3 for R,G,B.
            bytesRemaining = 3L * (256L * (long)hi + (long)lo + 1L);
            bytesBuffered -= 3;
            outPos = 0;
            memset(leds, 0,  NUM_LEDS * sizeof(struct CRGB));
            mode           = MODE_DATA; // Proceed to latch wait mode
          } 
          else {
            // Checksum didn't match; search resumes after magic word.
            indexOut  -= 3; // Rewind
          }
        } // else no header match.  Resume at first mismatched byte.
        bytesBuffered -= i;
      }
      break;

    case MODE_DATA:

      if(bytesRemaining > 0) {
        if(bytesBuffered > 0) {
          if (outPos < sizeof(leds))
            ledsRaw[outPos++] = buffer[indexOut++];   // Issue next byte
          bytesBuffered--;
          bytesRemaining--;
        }
        // If serial buffer is threatening to underrun, start
        // introducing progressively longer pauses to allow more
        // data to arrive (up to a point).
      } 
      else {
        // End of data -- issue latch:
        startTime  = micros();
        mode       = MODE_HEADER; // Begin next header search
        FastLED.show();
      }
    } // end switch
  } // end for(;;)
}

void loop()
{
  // Not used.  See note in setup() function.
}

In processing I am using the Adalight project code. https://learn.adafruit.com/adalight-diy-ambient-tv-lighting/download-and-install

Greetings Svenq

Specific frequency audio input data

$
0
0

Hello, I would like to be able to play a musical note into the Adruino and it give the frequency value. ( i.e. play a G on a guitar and it returns a value of 196hz) I would then give that result a value that could be called in the coding to perform a function when that sound is heard again. Honestly my biggest problem is I don't know the correct names of things to even know what to search for, so is there a sensor to get these results or a software that can read the sound input to show specific frequency? I have no problem looking and learning I'm just not sure what to even look for! If anyone could point me in a direction I would be grateful. Thank you.

I downloaded 3.0 and now my Arduino PID Tuning FrontEnd sketch by Brett Beauregard does not work

$
0
0

/******************************************************** * Arduino PID Tuning Front-End, Version 0.3 * by Brett Beauregard * License: Creative-Commons Attribution Share-Alike * April 2011 * * This application is designed to interface with an * arduino running the PID Library. From this Control * Panel you can observe & adjust PID performance in * real time * * The ControlP5 library is required to run this sketch. * files and install instructions can be found at * http://www.sojamo.de/libraries/controlP5/ * ********************************************************/ /********************** * user\Documents\Processing\libraries\PID_FrontEnd_v03\PID_FrontEnd_v03\PID_FrontEnd_v03USER20 ********/

import java.nio.ByteBuffer; import processing.serial.*; import controlP5.*;

/*********************************************** * User specification section **********************************************/ int windowWidth = 900; // set the size of the int windowHeight = 600; // form

float InScaleMin = 0; // set the Y-Axis Min float InScaleMax = 1024; // and Max for both float OutScaleMin = 0; // the top and float OutScaleMax = 255; // bottom trends

int windowSpan = 300000; // number of mS into the past you want to display int refreshRate = 100; // how often you want the graph to be reDrawn;

//float displayFactor = 1; //display Time as Milliseconds //float displayFactor = 1000; //display Time as Seconds float displayFactor = 60000; //display Time as Minutes

String outputFileName = "C:/A1Trash holder/ProcessorOutputFileFolder/USERProcOut.txt"; // if you'd like to output data to // a file, specify the path here

/*********************************************** * end user spec **********************************************/

int nextRefresh; int arrayLength = windowSpan / refreshRate+1; int[] InputData = new int[arrayLength]; //we might not need them this big, but int[] SetpointData = new int[arrayLength]; // this is worst case int[] OutputData = new int[arrayLength];

float inputTop = 25; float inputHeight = (windowHeight-70)2/3; float outputTop = inputHeight+50; float outputHeight = (windowHeight-70)1/3;

float ioLeft = 150, ioWidth = windowWidth-ioLeft-50; float ioRight = ioLeft+ioWidth; float pointWidth= (ioWidth)/float(arrayLength-1);

int vertCount = 10;

int nPoints = 0;

float Input, Setpoint, Output;

boolean madeContact =false; boolean justSent = true;

Serial myPort;

// USER adds a test to print the String String inString; // Input string from serial port USER added

ControlP5 controlP5; controlP5.Button AMButton, DRButton; controlP5.Textlabel AMLabel, AMCurrent, InLabel, OutLabel, SPLabel, PLabel, ILabel, DLabel,DRLabel, DRCurrent; controlP5.Textfield SPField, InField, OutField, PField, IField, DField;

PrintWriter output; PFont AxisFont, TitleFont;

void setup() { frameRate(30); size(900, 600);

println(Serial.list()); // * Initialize Serial myPort = new Serial(this, Serial.list()[0], 9600); //USER changed 1 to 0for comport 3 //USER Communication with arduino via comport this is because it is the first listed of the serial list and 1st one is number 0 // myPort.bufferUntil(10); // the Arduino

controlP5 = new ControlP5(this); // * Initialize the various SPField= controlP5.addTextfield("Setpoint",10,100,60,20); // Buttons, Labels, and InField = controlP5.addTextfield("Input",10,150,60,20); // Text Fields we'll be OutField = controlP5.addTextfield("Output",10,200,60,20); // using PField = controlP5.addTextfield("Kp (Proportional)",10,275,60,20); // IField = controlP5.addTextfield("Ki (Integral)",10,325,60,20); // DField = controlP5.addTextfield("Kd (Derivative)",10,375,60,20); // AMButton = controlP5.addButton("Toggle_AM",0.0,10,50,60,20); // AMLabel = controlP5.addTextlabel("AM","Manual",12,72); // AMCurrent = controlP5.addTextlabel("AMCurrent","Manual",80,65); // controlP5.addButton("Send_To_Arduino",0.0,10,475,120,20); // SPLabel=controlP5.addTextlabel("SP","3",80,103); // InLabel=controlP5.addTextlabel("In","1",80,153); // OutLabel=controlP5.addTextlabel("Out","2",80,203); // PLabel=controlP5.addTextlabel("P","4",80,278); // ILabel=controlP5.addTextlabel("I","5",80,328); // DLabel=controlP5.addTextlabel("D","6",80,378); // DRButton = controlP5.addButton("Toggle_DR",0.0,10,425,60,20); // DRLabel = controlP5.addTextlabel("DR","Direct",12,447); // DRCurrent = controlP5.addTextlabel("DRCurrent","Direct",80,440); //

AxisFont = loadFont("axis.vlw"); TitleFont = loadFont("Titles.vlw");

nextRefresh=millis(); if (outputFileName!="") output = createWriter(outputFileName); }

void draw() { background(200); drawGraph(); drawButtonArea();

}

void drawGraph() { //draw Base, gridlines stroke(0); fill(230); rect(ioLeft, inputTop,ioWidth-1 , inputHeight); rect(ioLeft, outputTop, ioWidth-1, outputHeight); stroke(210);

//Section Titles textFont(TitleFont); fill(255); text("PID Input / Setpoint",(int)ioLeft+10,(int)inputTop-5); text("PID Output",(int)ioLeft+10,(int)outputTop-5);

//GridLines and Titles textFont(AxisFont);

//horizontal grid lines int interval = (int)inputHeight/5; for(int i=0;i<6;i++) { if(i>0&&i<5) line(ioLeft+1,inputTop+iinterval,ioRight-2,inputTop+iinterval); text(str((InScaleMax-InScaleMin)/5(float)(5-i)+InScaleMin),ioRight+5,inputTop+iinterval+4);

} interval = (int)outputHeight/5; for(int i=0;i<6;i++) { if(i>0&&i<5) line(ioLeft+1,outputTop+iinterval,ioRight-2,outputTop+iinterval); text(str((OutScaleMax-OutScaleMin)/5(float)(5-i)+OutScaleMin),ioRight+5,outputTop+iinterval+4); }

//vertical grid lines and TimeStamps int elapsedTime = millis(); interval = (int)ioWidth/vertCount; int shift = elapsedTime*(int)ioWidth / windowSpan; shift %=interval;

int iTimeInterval = windowSpan/vertCount; float firstDisplay = (float)(iTimeInterval(elapsedTime/iTimeInterval))/displayFactor; float timeInterval = (float)(iTimeInterval)/displayFactor; for(int i=0;i<vertCount;i++) { int x = (int)ioRight-shift-2-iinterval;

line(x,inputTop+1,x,inputTop+inputHeight-1);
line(x,outputTop+1,x,outputTop+outputHeight-1);    

float t = firstDisplay-(float)i*timeInterval;
if(t>=0)  text(str(t),x,outputTop+outputHeight+10);

}

// add the latest data to the data Arrays. the values need // to be massaged to get them to graph correctly. they // need to be scaled to fit where they're going, and // because 0, 0 is the top left, we need to flip the values. // this is easier than having the user stand on their head // to read the graph. if(millis() > nextRefresh && madeContact) { nextRefresh += refreshRate;

for(int i=nPoints-1;i>0;i--)
{
  InputData[i]=InputData[i-1];
  SetpointData[i]=SetpointData[i-1];
  OutputData[i]=OutputData[i-1];
}
if (nPoints < arrayLength) nPoints++;

InputData[0] = int(inputHeight)-int(inputHeight*(Input-InScaleMin)/(InScaleMax-InScaleMin));
SetpointData[0] =int( inputHeight)-int(inputHeight*(Setpoint-InScaleMin)/(InScaleMax-InScaleMin));
OutputData[0] = int(outputHeight)-int(outputHeight*(Output-OutScaleMin)/(OutScaleMax-OutScaleMin));

} //draw lines for the input, setpoint, and output strokeWeight(2); for(int i=0; i<nPoints-2; i++) { int X1 = int(ioRight-2-float(i)pointWidth); int X2 = int(ioRight-2-float(i+1)pointWidth); boolean y1Above, y1Below, y2Above, y2Below;

//DRAW THE INPUT
boolean drawLine=true;
stroke(255,0,0);
int Y1 = InputData[i];
int Y2 = InputData[i+1];

y1Above = (Y1>inputHeight);                     // if both points are outside 
y1Below = (Y1<0);                               // the min or max, don't draw the 
y2Above = (Y2>inputHeight);                     // line.  if only one point is 
y2Below = (Y2<0);                               // outside constrain it to the limit, 
if(y1Above)                                     // and leave the other one untouched.
{                                               //
  if(y2Above) drawLine=false;                   //
  else if(y2Below) {                            //
    Y1 = (int)inputHeight;                      //
    Y2 = 0;                                     //
  }                                             //
  else Y1 = (int)inputHeight;                   //
}                                               //
else if(y1Below)                                //
{                                               //
  if(y2Below) drawLine=false;                   //
  else if(y2Above) {                            //
    Y1 = 0;                                     //
    Y2 = (int)inputHeight;                      //
  }                                             //
  else Y1 = 0;                                  //
}                                               //
else                                            //
{                                               //
  if(y2Below) Y2 = 0;                           //
  else if(y2Above) Y2 = (int)inputHeight;       //
}                                               //

if(drawLine)
{
  line(X1,Y1+inputTop, X2, Y2+inputTop);
}

//DRAW THE SETPOINT
drawLine=true;
stroke(0,255,0);
Y1 = SetpointData[i];
Y2 = SetpointData[i+1];

y1Above = (Y1>(int)inputHeight);                // if both points are outside 
y1Below = (Y1<0);                               // the min or max, don't draw the 
y2Above = (Y2>(int)inputHeight);                // line.  if only one point is 
y2Below = (Y2<0);                               // outside constrain it to the limit, 
if(y1Above)                                     // and leave the other one untouched.
{                                               //
  if(y2Above) drawLine=false;                   //
  else if(y2Below) {                            //
    Y1 = (int)(inputHeight);                    //
    Y2 = 0;                                     //
  }                                             //
  else Y1 = (int)(inputHeight);                 //
}                                               //
else if(y1Below)                                //
{                                               //
  if(y2Below) drawLine=false;                   //
  else if(y2Above) {                            //
    Y1 = 0;                                     //
    Y2 = (int)(inputHeight);                    //
  }                                             //
  else Y1 = 0;                                  //
}                                               //
else                                            //
{                                               //
  if(y2Below) Y2 = 0;                           //
  else if(y2Above) Y2 = (int)(inputHeight);     //
}                                               //

if(drawLine)
{
  line(X1, Y1+inputTop, X2, Y2+inputTop);
}

//DRAW THE OUTPUT
drawLine=true;
stroke(0,0,255);
Y1 = OutputData[i];
Y2 = OutputData[i+1];

y1Above = (Y1>outputHeight);                   // if both points are outside 
y1Below = (Y1<0);                              // the min or max, don't draw the 
y2Above = (Y2>outputHeight);                   // line.  if only one point is 
y2Below = (Y2<0);                              // outside constrain it to the limit, 
if(y1Above)                                    // and leave the other one untouched.
{                                              //
  if(y2Above) drawLine=false;                  //
  else if(y2Below) {                           //
    Y1 = (int)outputHeight;                    //
    Y2 = 0;                                    //
  }                                            //
  else Y1 = (int)outputHeight;                 //
}                                              //
else if(y1Below)                               //
{                                              //
  if(y2Below) drawLine=false;                  //
  else if(y2Above) {                           //
    Y1 = 0;                                    //
    Y2 = (int)outputHeight;                    //
  }                                            //  
  else Y1 = 0;                                 //
}                                              //
else                                           //
{                                              //
  if(y2Below) Y2 = 0;                          //
  else if(y2Above) Y2 = (int)outputHeight;     //
}                                              //

if(drawLine)
{
  line(X1, outputTop + Y1, X2, outputTop + Y2);
}

} strokeWeight(1); }

void drawButtonArea() { stroke(0); fill(100); rect(0, 0, ioLeft, windowHeight); }

void Toggle_AM() { if(AMLabel.valueLabel().getText()=="Manual") { AMLabel.setValue("Automatic"); } else { AMLabel.setValue("Manual");
} }

void Toggle_DR() { if(DRLabel.valueLabel().getText()=="Direct") { DRLabel.setValue("Reverse"); } else { DRLabel.setValue("Direct");
} }

// Sending Floating point values to the arduino // is a huge pain. if anyone knows an easier // way please let know. the way I'm doing it: // - Take the 6 floats we need to send and // put them in a 6 member float array. // - using the java ByteBuffer class, convert // that array to a 24 member byte array // - send those bytes to the arduino void Send_To_Arduino() { float[] toSend = new float[6];

toSend[0] = float(SPField.getText()); toSend[1] = float(InField.getText()); toSend[2] = float(OutField.getText()); toSend[3] = float(PField.getText()); toSend[4] = float(IField.getText()); toSend[5] = float(DField.getText()); Byte a = (AMLabel.valueLabel().getText()=="Manual")?(byte)0:(byte)1; Byte d = (DRLabel.valueLabel().getText()=="Direct")?(byte)0:(byte)1; myPort.write(a); myPort.write(d); myPort.write(floatArrayToByteArray(toSend)); justSent=true; }

byte[] floatArrayToByteArray(float[] input) { int len = 4input.length; int index=0; byte[] b = new byte[4]; byte[] out = new byte[len]; ByteBuffer buf = ByteBuffer.wrap(b); for(int i=0;i<input.length;i++) { buf.position(0); buf.putFloat(input[i]); for(int j=0;j<4;j++) out[j+i4]=b[3-j]; } return out; }

//take the string the arduino sends us and parse it void serialEvent(Serial myPort) { // String read = myPort.readStringUntil(10); String read = myPort.readStringUntil(10); //USER changed from 10 to // inString = myPort.readString(); //USER added this //try the next one String inString = myPort.readStringUntil(10); //USER added this if(outputFileName!="") output.print(str(millis())+ " "+read); String[] s = split(read, " ");

if (s.length ==9) { Setpoint = float(s[1]); // * pull the information println("setpoint:",Setpoint); //TBGFE Input = float(s[2]); // we need out of the println("Inpute:", Input); //TGBFE Output = float(s[3]); // string and put it println("Output: ",Output); //TGBFE

//USER adds test print text(" text received: " + inString, 10,50); //USER added this println ("println read received: " ,read); //USER added to see what is in string
println ("println inString received: " ,inString); //USER added to see what is in string SPLabel.setValue(s[1]); // where it's needed InLabel.setValue(s[2]); // OutLabel.setValue(trim(s[3])); // PLabel.setValue(trim(s[4])); // ILabel.setValue(trim(s[5])); // DLabel.setValue(trim(s[6])); // AMCurrent.setValue(trim(s[7])); // DRCurrent.setValue(trim(s[8])); if(justSent) // * if this is the first read { // since we sent values to SPField.setText(trim(s[1])); // the arduino, take the InField.setText(trim(s[2])); // current values and put OutField.setText(trim(s[3])); // them into the input fields PField.setText(trim(s[4])); // IField.setText(trim(s[5])); // DField.setText(trim(s[6])); // // mode = trim(s[7]); // AMLabel.setValue(trim(s[7])); // //dr = trim(s[8]); // DRCurrent.setValue(trim(s[8])); // justSent=false; // } //

if(!madeContact) madeContact=true;

} }

Processing doesn't display lines in window

$
0
0

Hello- I'm trying to graph some arduino analog output to processing with the attached standard code.

I can see that everything works well in the processing console: 1 120 2 115 3 126 ...

But the lines are never drawn in my Processing window... It keeps a black background. Even weirder: when I draw the random line(0, height,0,height/2); inside the draw() function, then I can see that line displayed and about one out of 10 lines from the serialEvent() function are displayed...

Any idea how to fix this? Thanks, Clement

Here is the code:

import processing.serial.*;

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

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

 myPort = new Serial(this, Serial.list()[5], 9600);
 // don't generate a serialEvent() unless you get a newline character:
 // set inital background:
 background(0);
 }
 void draw () {
 // everything happens in the serialEvent()
 }

 void serialEvent (Serial myPort) {
 int inByte = myPort.read();  
 // draw the line:
 stroke(127,34,255);
 line(xPos, height, xPos, height - inByte);
 println(xPos);
 println(inByte);


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

Arduino to Processing importing variables.

$
0
0

Hey all, I am quite new at that world, but I would like to know why does it happen to me. The thing is that I created a variable on Arduino which receives a random number between 0 and 100; however, I wanted to print in on Processing but it is not recognized because instead of that it writes COM3, the port where Arduino is connected. By the way, here is the Arduino code:

void setup() { //initialize serial communications at a 9600 baud rate

Serial.begin(9600); }

void loop() {

int num = random(0, 100);

Serial.println(num);

delay(100);

}

And here the Processing one:

import vsync.*;

import processing.serial.*;

Serial myPort;

void setup() {

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

}

void draw() {

println(Serial.list());

delay(1000); }

I don't know if I am missing some libraries but I am kinda stocked for hours.

Thank you.


Serial Port connection too slow?

$
0
0

Suddenly my Serial port connection got very slow, but only when dealing with processing. No problems on arduino console. The delay is huge and sometimes no communication happens even though it is established. This happened after two things that I think are not related: 1. Installed PlatformIO (PlatformIO.org); 2. Installed Processing3 (already tried the same example scripts over and over on different versions);

I'm running it on MacOsX.

Can you help me?

Thanks in Advance,

André

Arduino Serialread makes my processing animation stop

$
0
0

Hey guys, I want to control a ball's acceleration in a proccesing animation, accordingly to a analogue input on my Arduino. The balls acceleration and behaviour is written with PVectors (see code below) but when I activate my arduino sketch, the ball just disappears from the window. I have made several simple tests were I for an example changed the size of an ellipse by mapping the serialRead with success, so the communication between Arduino and Processing is not the problem.

//the code:

import processing.serial.*;
Serial myPort; 

Mover mover;

float inByte;

void setup(){
  size(800,600);
  background(240);
  smooth();
  mover = new Mover();

  myPort = new Serial(this,Serial.list()[2], 9600);
  myPort.bufferUntil('\n');
}


void draw(){
  background(240);
  mover.update();
  mover.checkEdges();
  mover.display();

  fill(10);

}

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

  if(inString != null){
    inString = trim(inString);
    inByte = float(inString);
    inByte = map(inByte,0,1023,0,5);
  }
}


//newtab 
class Mover{
  PVector location;
  PVector velocity;
  PVector acceleration;
  float topspeed;

  Mover(){
    location = new PVector(width/2,height/2);
    velocity = new PVector(0,0);
    topspeed = 10;
  }

  void update(){
    acceleration = PVector.random2D();
    acceleration.mult(inByte);

    velocity.add(acceleration);
    velocity.limit(topspeed);
    location.add(velocity);
  }

  void display(){
    noStroke();
    fill(10);
    ellipse(location.x, location.y, 50, 50);

  }


void checkEdges(){
  if(location.x > width){
    location.x = 0;
  }
  else if (location.x < 0 ){
    location.x = width;
  }

  if(location.y > height){
    location.y = 0;
  }
  else if(location.x < 0){
    location.y = height;
  }
}
}

processing to arduino not working reliably

$
0
0

hi all,

i am trying to help a friend with a demo interface for some hardware that was made by someone else. basically i have 4 inputs to send a signal to, and this info is processed and makes a light turn a different color. i am using processing -> arduino mini over ftdi to talk to the 4 inputs i have from the hardware. whenever i test it, it seems to be working, but my friend reports that it is not working reliably. it's like when i leave the room it breaks, so it has been frustrating to troubleshoot as i have not seen the error happen. but i am not super confident in the code as i am super rusty.

i was wondering if there is anything i am doing in the code that might be causing a lag or error. i do have a lot of resets... or if you have any idea if the error is from the arduino side, or processing side, or hardware.

here is the processing code, there are some button and scrollbar classes i didn't include, sorry it's so long (tried to summarize) basically there are 2 screens in the interface that are being loaded.


    Serial myPort;  
    PImage jewel1, jewel3;
    Button jewel2;
    PImage background, purple, giaboard, ledred, scrollbg, scrolltop;
    Button ledblue, homecon;
    PImage ledgreen, scrollcon;
    PImage wind, tower, home;
    PImage blueicon, greenicon, redicon, unlock, jewel, vibration, gear;
    boolean toggle, upload, panel;
    float angle;
    int trigger = 0;
    int jtrigger = 0;
int start = 900;
int stop;
float mil;
float theta=0;
int state = 1, modenum = 0;

HScrollbar red, blue, green, rainbow, solid; 

void setup()   //initalize all locations, shapes, and sizes
{
  size(600, 576);
  String portName = Serial.list()[2]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
  resetAll();

}

void draw()
{
    modenum = jtrigger +trigger;
    showIcon();

  if  (state == 1) { //initial control panel mode
    background(background);
    image(giaboard, width/2-giaboard.width/2, height/2-50);
    image(gear, width/2 - 78, 333);
    showControls();

    showIcon();
    panel = false;
  } else if  (state == 2) {  //led control mode
    background(purple);
    image(giaboard, width/2-giaboard.width/2, height/2-50);
    image(gear, width/2 - 78, 333);
    LEDmode();
    showIcon();
    toggle = false;
  }

  if (upload == true) {  //spin gears and send data
   myPort.write(modenum);
    jewel2.display();

    println("mode" + modenum);

    background(background);
    image(giaboard, width/2-giaboard.width/2, height/2-50);
    showControls();
    showIcon();

    if (millis()-mil <4000) {  //spin for 4 seconds
      spin();
    } else if (millis()-mil > 4000) {  //then reset
    resetAll();
}
  }
  homecon.display();

  println("upload:" + upload);
} 

void resetAll(){
  background=loadImage("background1.jpg");
  purple= loadImage("bgpurple.png");
  giaboard= loadImage("giaboard.png");
  jewel1= loadImage("jewel_solid.png");
 ....

  red = new HScrollbar(90, 70, 150, 20, 16, #ff0000 );
  blue = new HScrollbar(90, 135, 150, 20, 16, #0000ff );
  green = new HScrollbar(90, 205, 150, 20, 16, #00ff00 );
  rainbow = new HScrollbar(370, 70, 150, 20, 16, #000000 );
  solid = new HScrollbar(370, 160, 150, 20, 16, #ffffff );
  myPort.write('0');
}

void mousePressed() {
  ledblue.click(mouseX, mouseY);
  jewel2.click(mouseX, mouseY);
  homecon.click(mouseX, mouseY);
  upload = jewel2.getState();
  toggle = ledblue.getState();
  panel = homecon.getState();
  if (toggle == true) {
    state = 2;
  } 
  if (upload == true) {
    myPort.write(modenum);
    mil = millis();

  }
  if (panel ==true) {
    state = 1;
resetAll();
}
}

void showIcon() {  //draw icon on giaboard

  if (red.getPos() > 290) {
    image(redicon, width/2 - 35, height/2-50);
    trigger = 1;
  }
....

  if (rainbow.getPos() > 630) {
   image(jewel1,width/2-40, height/2+80);
    jewel= jewel1;
    jtrigger = 0;
  }
}

void spin() {  //spin gear and jewel for upload sequence
  ......
}

void showControls() {  //draw control panel buttons and icons

    image(wind, width/2 + 150, height/2-120);
  image(tower, width/2+40, height/2-150);
  ledblue.display();
  image(vibration, width/2 - 80, height/2-160);
}

void LEDmode() {  //load 2nd screen for LED mode selection
  image(scrolltop, 75, 0);
  image(scrollbg, 75, 30);
  green.display();
  green.update();
 ....
}

and the arduino code:

char val;


int clock = 10;
int LED1= 11;
int LED2= 12;
int LED3= 13;

void setup() {
  // initialize digital pin 13 as an output.
  pinMode(clock, OUTPUT);
  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  digitalWrite(clock, LOW);

  if (Serial.available()){
    val = Serial.read();
  }

  if (val ==1){
  //turn light 1 on
  digitalWrite(clock, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED1, HIGH);
   digitalWrite(LED2, HIGH);
   digitalWrite(LED3, HIGH);
    delay(25);   
  digitalWrite(clock, LOW);    // turn the LED off by making the voltage LOW
  delay(100);              // wait for a second
  digitalWrite(clock, HIGH);
  delay(1000);
  }

if (val ==5){
//  //turn light 2 on
  digitalWrite(clock, HIGH);   // turn the LED on (HIGH is the voltage level)
  digitalWrite(LED1, HIGH);
  digitalWrite(LED2, HIGH);
 digitalWrite(LED3, LOW);
  delay(25);   
  digitalWrite(clock, LOW);    // turn the LED off by making the voltage LOW
  delay(100);              // wait for a second
  digitalWrite(clock, HIGH);
  delay(1000);
}

}

How to change the value of graph?

$
0
0

Hi there, Im using processing to control the birghtness of led with arduino. I already can control the brightness of led using mouse. But the problem is i want to change the value of graph so that the intersection of graph x and graph y is located in the middle. Below is the code that i used.

Processing Code

//Processing Code
 import processing.serial.*;
Serial myPort;
void setup()
{
size(255, 255);
String portName = Serial.list()[0]; // This gets the first port on your computer.
myPort = new Serial(this, portName, 9600);
}

void draw() {
// Create a gradient for visualisation
for (int i = 0; i<width; i++) {
for (int j = 0; j<height; j++) {
color myCol = color(i,j,0);
set(i, j, myCol);

}
}
// Send an event trigger character to indicate the beginning of the communication
myPort.write('S');
// Send the value of the mouse's x-position
myPort.write(mouseX);
// Send the value of the mouse's y-position
myPort.write(mouseY);
}

Arduino code

Arduino Code
int val, xVal, yVal;
void setup() {
Serial.begin(9600);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
}
void loop(){
// check if enough data has been sent from the computer:
if (Serial.available()>2) {
// Read the first value. This indicates the beginning of the communication.
val = Serial.read();
// If the value is the event trigger character 'S'
if(val == 'S'){
// read the most recent byte, which is the x-value
xVal = Serial.read();
// Then read the y-value
yVal = Serial.read();
}
}
// And send those to the LEDS!
analogWrite(10, xVal);
analogWrite(11, yVal);
}

Arduino sensor update in processing

$
0
0

**Hey all, I am using Arduino and Processing. On my Arduino I am simply using the Standard Firmata. My goal is for the sensor data of Arduino to be written out in Processing in a readable way. my first code was: This sort of "cheats" with the white rectangle over the text every-time to update to the new information. **

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

Arduino arduino; int sensorpin = 0; // analog pin used to connect the sharp sensor int val = 0; // variable to store the values from sensor(initially zero)

void setup() { //println(Arduino.list()); arduino = new Arduino(this, Arduino.list()[0], 57600); background(255); size(1000, 1000); }

void draw() { val=arduino.analogRead(sensorpin); // reads the value of the sharp sensor stroke (255); fill(255); rect(0, 0, 400, 400);

if (val >= 0) { textSize(32); fill(0, 102, 153, 204); text("sensor pin value is ", 10, 30);
text(val, 10, 60); println (val); } delay(300);

}

**** My second goals is for when there is a mouseclicked, I want the data to change color but to still update. This is where I am having trouble. The Sensor data changes to the current value in the new color when clicked but not in between (when not clicked) ... any ideas?**** import processing.serial.*; import cc.arduino.*;

Arduino arduino; int sensorpin = 0; // analog pin used to connect the sharp sensor int val = 0; // variable to store the values from sensor(initially zero) int DayNight = 0; void setup() { //println(Arduino.list()); arduino = new Arduino(this, Arduino.list()[0], 57600); background(255); size(1800, 800); }

void draw() {
val=arduino.analogRead(sensorpin); // reads the value of the sharp sensor

}

void mouseClicked() { if (DayNight == 0) { val=arduino.analogRead(sensorpin);
stroke (255); fill(255); rect(0, 0, 400, 400);

fill(0, 102, 153, 204);
textSize(32);
text("sensor pin value is ", 10, 30);  
text(val, 10, 60);
println (val);

DayNight = 1;

} else { val=arduino.analogRead(sensorpin);
stroke (255); fill(255); rect(0, 0, 400, 400);

fill(0, 102, 13, 104); 
textSize(32);
text("sensor pin value is ", 10, 30);  
text(val, 10, 60);
println (val);
DayNight = 0;

} }

IndexOutOfBounds error on my Arduino+Processing code

$
0
0

When I try to run this code in processing it gives me an "ArrayIndexOutOfBoundsException: 3" error, I think it has something to do with line 8 of the code, but I don't know how to fix it.screenshot01

Arduino Processing serial slow

$
0
0

Hi there,

I've put this same question on the Arduino forum and not getting anywhere really (http://forum.arduino.cc/index.php?topic=350736.0)

I've got a LED matrix that I'm sending a stream of real-ish time data to from a processing sketch. This is working fine and what I want displayed is appearing on the screen, albeit with a undesirable frame rate. I've narrowed the problem down to where the processing sketch actually sends out the data:

sPort = new Serial(this, "COM11", 115200);

`

int t1 = millis(); for(int y = 0; y < 11; y++) { for(int x = 0; x < 11; x++) { sPort.write(buffer[y][x][0]); //red sPort.write(buffer[y][x][1]); //green sPort.write(buffer[y][x][2]); //blue } } int t2 = millis(); println("SENDING DATA: " + (t2 - t1) / 1000.0F);`

From that I'm getting that it takes ~360ms to send the data out meaning I get a frame rate of about 2-3 frames a second. I'm using 115200 bps Serial which should give me 11520 bytes/sec, and as I'm sending 121*3 = 363 bytes, this should give a max frame rate of ~30 fps minus any other overheads. It appears that processing is sending at nowhere near the correct speed.

Anyone have any ideas for what I can change on either the processing or arduino side?

I am using Windows 7, 64bit. I have tried using an empty sketch on the arduino and that has the same results so I know it's not a delay introduced there.

Thanks in advance, Andy


Transmission of a float through a serial link

$
0
0

Hi everybody,

I am trying to send a float through a USB link between an Arduino and a Processing (ver 3) application.

On the Arduino, I am breaking the float with a union before sending the 4 chars:

`union _UVAL { float f; char c[4]; } uval;

`

That's the easy part!

Now I am trying to reconstruct the float under Processing knowing that Processing doesn't handle the union, the pointer, the bitwise shift (<<, >>), etc.

As an example, 1.0 is encoded as '63 128 0 0' (or in hexa: 3F 80 00 00). You can check on the IEEE754 web site:

http://www.h-schmidt.net/FloatConverter/IEEE754.html

With the 4 bytes received and coded as chars, can you please provide a way to retrieve the float.

Thank you very much in advance.

JM

How can I send a variable to Arduino from Processing?

$
0
0

Hey, I'm a little new in Processing and I'd want to know what is the code for sending a variable (an integer) to Arduino. I've already know the Arduino code, but I have lots of troubles with the Processing.

Could anyone help me? Thank you!

Networked Cat - image upload and mailer not being triggered by serial events

$
0
0

I have a php server running 127.0.0.1:8080 on the root of this structure:

**NetworkedCat>

                   |data|>script-cat.php

                   index.html

                   NetworkedCat.pde

                   img.jpg

                   save2web.php

                   |swiftmailer|**

this Arduino-based app should:

1) receive an input from a pressure sensor; 2) verify whether threshold is surpassed 3) take picture from build-in camera 4) upload pic to website 5) mail me about the upload

testing on browser, save2web.php and cat-script.php are working, that is, scripts are uploading and emailing.

pressure sensor is also reading and printing, and threshold have been calibrated.

but NetworkedCat.pde is NOT triggering the events.

please note:

Processing opens localhost at another port (80), because php server works on 8080.

are they compatible?

why is the Processing code below not woking?

if I shorten the Processing code, and test the image capture and upload only, it works. so, the bug must be related to the serial events.

please help!

/*Serial String reader
Context: Arduino

Reads in a string of characters until it gets a linefeed (ASCII 10).
then converts the string into a number
*/

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

Serial myPort;              //the serial port
float sensorValue = 0;      //the value form the sensor
float prevSensorValue = 0;  //previous value from the sensor
int threshold = 200;        //above this number, the cat is on the mat

int currentTime = 0;       //the current time as a single number
int lastMailTime = 0;      //last minute you sent a mail
int mailInterval = 60;     //minimum seconds betweeen mails
String mailUrl = "cat-script.php";
int lastPicture = 0;       //last minute you sent a picture
int lastPictureTime = 0;   //last minute you sent a picture
int pictureInterval = 10;  //minimum seconds between pictures

Capture myCam;            //camera capture library instance
String fileName = "img.jpg"; //file name for the picture

//location on your server for the picture script:
String pictureScriptUrl = "save2web.php";
String boundary = "----H4rkNrF"; //string boundary for the post request

Client thisClient;        //instance for the net library


//float xPos = 0;             //horizontal position of the graph
//float lastXPos = 0;         //previous horizontal position  



void setup(){
  size(400, 300);
  //list all the available serial ports
  println(Serial.list());

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

  //reads bytes into a buffer until you get a newline (ASCII 10);
  myPort.bufferUntil('\n');

  //set initial background and smooth drawing:
  background(#543174);
  smooth();
  //for a list of cameras on your computer, use this line:
  println(Capture.list());

  //use the default camera for capture at 30 fps
  myCam = new Capture(this, width, height, 30);
  myCam.start();
}

void draw(){
  //make a single number fmor the current hour, minute, and second
  currentTime = hour() * 3600 + minute() * 60 + second();

  if (myCam.available() == true) {
    //draw the camera image to the screen;
    myCam.read();
    set(0, 0, myCam);

    //get the time as a string
    String timeStamp = nf(hour(), 2) + ":" + nf(minute(), 2)
    + ":" + nf(second(), 2) + "   " + nf(day(), 2) + "-"
    + nf(month(), 2) + "-" + nf(year(), 4);

    //draw a dropshadow for the time text:
    fill(15);
    text(timeStamp, 11, height - 19);
    //draw the main time next
    fill(255);
    text(timeStamp, 10, height - 20);
  }
}

void serialEvent (Serial myPort){
  //get the ASCII string
  String inString = myPort.readStringUntil('\n');

  if (inString != null){
    //trim off any whitespace:
    inString = trim(inString);
    //convert to an int and map to the screen height
    sensorValue = float(inString);
    //println(sensorValue);
    sensorValue = map(sensorValue, 0, 1023, 0, height);
    println(sensorValue);

    if (sensorValue > threshold){
      if(currentTime - lastPictureTime > pictureInterval){
        PImage thisFrame = get();
        thisFrame.save(fileName);
        postPicture();
        lastPictureTime = currentTime;
      }
      //if the last reading was less than the threshold
      //then the cat just got on the mat
      if(prevSensorValue <= threshold){
        println("Peti na casinha");
        sendMail();
      }
    }
    else{
      //if the sensor value is less than the threshold,
      //and the previous value was greater, then the cat
      //just left the mat
      if (prevSensorValue > threshold){
        println("Peti não está na casinha");
      }
    }
    //save the current value for the next time
    prevSensorValue = sensorValue;
  }
}


void sendMail(){
  //how long has passed since the last mail
  int timeDifference = currentTime - lastMailTime;

  if( timeDifference > mailInterval){
    String[] mailScript = loadStrings(mailUrl);
    println("results from mail script:");
    println(mailScript);

    //save the current minute for next time
    lastMailTime = currentTime;
  }
}

void postPicture(){
  //load the saved image into an array of bytes
  byte[] thisFile=loadBytes(fileName);

  //open a new connection to the server
  thisClient = new Client(this, "localhost", 80);
  //make an HTTP POST request:
  thisClient.write("POST" + pictureScriptUrl + " HTTP/1.1\n");
  thisClient.write("Host: localhost\n");
  //tell the server you're sending the POST in multiple parts
  //and send a unique string that will delineate the parts
  thisClient.write("Content-Type: multipart/form-data; boundary=");
  thisClient.write(boundary + "\n");

  //form the beginning of the request
  String requestHead ="\n--" + boundary + "\n";
  requestHead +="Content-Disposition: form-data; name=\"file\"; ";
  requestHead += "filename=\"" + fileName + "\"\n";
  requestHead +="Content-Type: image/jpeg\n\n";

  //form the end of the request
  String tail="\n\n--" + boundary + "--\n\n";

  //calculate and send the length of the total request
  //including the head of the request, the file, and the tail
  int contentLength = requestHead.length() + thisFile.length + tail.length();
  thisClient.write("Content-Length: " + contentLength + "\n\n");

  //send the header of the request, the file and the tail
  thisClient.write(requestHead);
  thisClient.write(thisFile);
  thisClient.write(tail);
}

real-time plot

$
0
0

I know this question has been asked many many times, but I am just not getting anything to work so far. I am using processing to communicate with arduino. And my arduino is receiving data from two units, one accelerometer and the other one is a gyroscope. All the x,y,z axis data points are read and sent using serial.print to processing, stored in a string inString, and split(inString,",") into an array.

how can I take use of the data I received and make a real time plot? I can't effectively store the previous data points, so I am not able to use line(x1,y1,x2,y2) to make the plot.

Please help and my great thanks in advance.

Need a simple accelerometer visualization example!

$
0
0

Hello!

I'm doing a project using the ADXL335 accelerometer from SparkFun. The actual project I'm using P5 and it's working great. I'm running workshops in parallel and want to demo the chip in real-time but am currently out of time to build something from scratch. I'm desperate for a simple processing (or something else) sketch that takes my x, y, z values being printed to the serial port from Arduino and visualizes them in some way. Can anyone point me to anything that won't need a lot of coding time and effort just now?

Thank you! Claudia

Viewing all 747 articles
Browse latest View live