Show Posts
Pages: [1] 2
1  Using Arduino / Interfacing w/ Software on the Computer / Re: simplemessagesystem to connect arduino and Pure data - link not working on: February 04, 2011, 01:49:32 pm
I have and I have used it. Thanks.

But what I get is a flickering two digit number. It doesn't really change, it just flickers, as if arduino is sending signal, but something is blocking receiving in Pd. So it seems. Might be wrong of course.

My ping sensor is digital. The tutorial examplifies analog sensor. You think it works for digital sensors as well?

Here is my arduino code if anyone can see anything wrong (it worked nicely with Processing):

Code:
/* Ultrasonic Sensor
 *
 * Reads values (00014-01199) from an ultrasound sensor (3m sensor)
 * and writes the values to the serialport.
 */
 

int ultraSoundSignal = 7; // Ultrasound signal pin
int val = 0;
int ultrasoundValue = 0;
int timecount = 0; // Echo counter
int ledPin = 13; // LED connected to digital pin 13

void setup() {
  Serial.begin(9600);            // Sets the baud rate to 9600
  pinMode(ledPin, OUTPUT);       // Sets the digital pin as output
}

void loop() {
 timecount = 0;
 val = 0;
 pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output

// Send low-high-low pulse to activate the trigger pulse of the sensor

digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff

// Listening for echo pulse
 
pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
val = digitalRead(ultraSoundSignal); // Append signal value to val
while(val == LOW) { // Loop until pin reads a high value
  val = digitalRead(ultraSoundSignal);
}

while(val == HIGH) { // Loop until pin reads a high value
  val = digitalRead(ultraSoundSignal);
  timecount = timecount +1;            // Count echo pulse time
}

//Writing out values to the serial port

ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue

Serial.write('A'); // Example identifier for the sensor
Serial.print(ultrasoundValue);
Serial.write(10);
//Serial.Write(13);

// Light up LED if any value is passed by the echo pulse

if(timecount > 0){
  digitalWrite(ledPin, HIGH);
}

// Delay of the program

delay(100);
}
2  Using Arduino / Interfacing w/ Software on the Computer / simplemessagesystem to connect arduino and Pure data - link not working on: February 04, 2011, 01:39:41 am
On this website: http://www.arduino.cc/playground/Interfacing/PD

the link to download simplemessagesystem library is down.

Anyone knows why?

Any alternatives to get the library? (pduino with firmata not working well with ultrasonic sensor-arduino to PD)
3  Forum 2005-2010 (read only) / Interfacing / Re: Error inside Serial.ports() in Processing on: January 14, 2011, 07:05:55 pm
Any luck PaulS?

I'm still researching...
4  Forum 2005-2010 (read only) / Interfacing / Re: Error inside Serial.ports() in Processing on: January 13, 2011, 08:50:05 pm
OK, cool.
You probably had problems with the libraries because GSCapture is a linux version of Video Capture - which is for Win and Mac (works only with QuickTime player)

Here is the arduino code for the ultrasonic sensor:
Code:
/* Ultrasonic Sensor
 *
 * Reads values (00014-01199) from an ultrasound sensor (3m sensor)
 * and writes the values to the serialport.
 */
 

int ultraSoundSignal = 7; // Ultrasound signal pin
int val = 0;
int ultrasoundValue = 0;
int timecount = 0; // Echo counter
int ledPin = 13; // LED connected to digital pin 13

void setup() {
  Serial.begin(9600);            // Sets the baud rate to 9600
  pinMode(ledPin, OUTPUT);       // Sets the digital pin as output
}

void loop() {
 timecount = 0;
 val = 0;
 pinMode(ultraSoundSignal, OUTPUT); // Switch signalpin to output

// Send low-high-low pulse to activate the trigger pulse of the sensor

digitalWrite(ultraSoundSignal, LOW); // Send low pulse
delayMicroseconds(2); // Wait for 2 microseconds
digitalWrite(ultraSoundSignal, HIGH); // Send high pulse
delayMicroseconds(5); // Wait for 5 microseconds
digitalWrite(ultraSoundSignal, LOW); // Holdoff

// Listening for echo pulse
 
pinMode(ultraSoundSignal, INPUT); // Switch signalpin to input
val = digitalRead(ultraSoundSignal); // Append signal value to val
while(val == LOW) { // Loop until pin reads a high value
  val = digitalRead(ultraSoundSignal);
}

while(val == HIGH) { // Loop until pin reads a high value
  val = digitalRead(ultraSoundSignal);
  timecount = timecount +1;            // Count echo pulse time
}

//Writing out values to the serial port

ultrasoundValue = timecount; // Append echo pulse time to ultrasoundValue

Serial.write('A'); // Example identifier for the sensor
Serial.print(ultrasoundValue);
Serial.write(10);
//serialWrite(13);

// Light up LED if any value is passed by the echo pulse

if(timecount > 0){
  digitalWrite(ledPin, HIGH);
}

// Delay of the program

delay(100);
}

Here is the Processing sketch for the ultrasonic sensor graphics:

Code:
import processing.serial.*;

  float x1,y1,x2,y2,a,ai,b,bi,theta;  // cord parameters
  float H,S,B,Hi,Si,Bi;  // color parameters
  int fr;
  
  
  // variables for the serial port connection object
  Serial port;
  String portname = "/dev/ttyUSB0";  // find the name of your serial port in your system setup!
  int baudrate = 9600;  //  set baudrate
  int value;  // variables used to store value from serial port
  String buf=""; // String buffer to store serial values
  int value1;  // value1 is the read value
  int speedrate=100;
  float range=2.7;  //works well between 2.5 and 3.5
  int t=2;  //scales up the circle range


// the serial event function takes the value of the event and store it in the corresponding variable
void serialEvent(int serial)

{
    if(serial!=10) {        
          buf += char(serial);          
          } else {
          buf = buf.substring(1,buf.length());   //extract the value from the string 'buf'
          value1 = int(buf);    //cast the value to an integer
          buf="";
      }
     }
// initialize display and serial port objects
void setup(){
  
  size(500,500,P2D);
  fr=80;
  frameRate(fr);
  smooth();
  a=b=0.0;
  ai=bi=0.01;
  H=0; S=100; B=100; Hi=1; Si=0; Bi=0;

      port = new Serial(this, portname, baudrate);
      println(port);
     }

// draw listens to serial port, draw
void draw(){
  
  while(port.available() > 0){
        value = port.read();
        serialEvent(value);
    }
if(value1/t > width){
       value1 = width*2;  // range is set to 1200 mm (equivalent to 1200 pixels). Higher causes flickering
   }
    
  // center and scale
  translate(width/2,height/2);
  scale(width/2);
  
  // initialize color
  colorMode(RGB);
  background(0);
  colorMode(HSB,360,100,100);
  
  // draw 360 cords around a circle
    for(float i=value1/range;i<360;i++){
    theta=(float)i*PI/180;
    x1=sin(theta);
    y1=cos(theta);
    x2=sin(b*theta);
    y2=cos(a*theta);
    
    
    // each cord gets color in wheel
    H=i;
    stroke(H,S,B);
    line(x1,y1,x2,y2);
    
  }
    a+=ai*(value1/speedrate);  //uncommenting these two lines makes a nice radar screen graphics :)
    b+=bi*(value1/speedrate);
  }
5  Forum 2005-2010 (read only) / Interfacing / Re: Error inside Serial.ports() in Processing on: January 13, 2011, 08:18:49 pm
Ha! Interesting...

The above example I posted works in a direction from Processing to Arduino.

Now I have just tried uploading a different sketch on Arduino and plugged in the ultrasonic sensor. Serial monitor showed correct distance measurements dependent on my hand movement towards the sensor and back. SO Arduino works!!
Then I ran related Processing sketch that should turn the distance signal into graphics and there was the error. Processing couldn't read serial.

The problem is therefore with Processing...Hmm

Now what...?
6  Forum 2005-2010 (read only) / Interfacing / Re: Error inside Serial.ports() in Processing on: January 13, 2011, 08:01:43 pm
I'm using Duemilanove.

Error is generated with any Processing sketch that involves Serial function in a code, in my case:
println(Serial.list());
myPort=new Serial(this, Serial.list()[0],9600);

The whole code:
Code:
import ddf.minim.*;
import ddf.minim.signals.*;

Minim minim;
AudioOutput out;
SineWave sine;

// 1. Use the right port (replace 12000). modify pd sketch to receive the osc signal

//Camera capture of the fish in aquarium. Arduino dimms LED according to the fish position (X axis).

import codeanticode.gsvideo.*;     // library to work around QuickTime (which doesn't work with Linux)
import processing.serial.*;
//import oscP5.*;
//import netP5.*;

Serial myPort;

boolean new_video_image=false;
boolean fish;
int fast_parse=1;
int threshold_fish_detection=1500/fast_parse;
int average_column_difference;
int num_pixels;
int[] bgnd_lum;
int[] diff_lum;
int[] column_difference;
int[] ringbuffer_position;
float[] ringbuffer_target_position;
int left_cut;
int right_cut;
int middle;
int diff_sum;
int video_x=320;
int video_y=240;
int image_x=320;
int image_y=270;
int video_fps;
int draw_fps;
int video_fps_old;
int draw_fps_old;
int send_fish;

//OscP5 oscP5;
//NetAddress myRemoteLocation;

String index_number[]=new String[1];

GSCapture video;          //

PFont font;

void setup() {
  background(0);
  size(image_x, image_y);
  background(0);

   println(Serial.list());
   myPort=new Serial(this, Serial.list()[0],9600);
  //oscP5 = new OscP5(this,12000);
  //myRemoteLocation = new NetAddress("127.0.0.1",12000); // need to define the port (change 12000)

  video = new GSCapture(this, video_x,video_y);
  num_pixels = video_x*video_y;

  bgnd_lum = new int[num_pixels];
  diff_lum = new int[num_pixels];
  column_difference = new int[video_x];
  ringbuffer_position=new int [100];
  ringbuffer_target_position=new float [100];
  loadPixels();

  minim = new Minim(this);
  // get a line out from Minim, default bufferSize is 1024, default sample rate is 44100, bit depth is 16
  out = minim.getLineOut(Minim.STEREO);
  // create a sine wave Oscillator, set to 440 Hz, at 0.5 amplitude, sample rate from line out
  sine = new SineWave(440, 0.5, out.sampleRate());
  // set the portamento speed on the oscillator to 200 milliseconds
  sine.portamento(200);
  // add the oscillator to the line out
  out.addSignal(sine);
}

void draw() {                                                // LOOP BEGINS HERE

  new_video_image=false;                      
  draw_fps_old=draw_fps;                                    // draw refresh speed
  draw_fps=millis();                                        // """"""""""""""""""

  if (video.available()) {                                

    video.read();                                           // load new video image ...
    video.loadPixels();                                     // ... in pixel array

    //-------------------------------------------------------- parse video image for differences to previous image
    for (int i=0;i<video_x;i++) {  
      column_difference[i]=0;
    }

    diff_sum=0;                                               // reset difference of all video pixels
    for (int x=0;x<video_x;x++) {                             // draw video image & difference image
      for (int y=0;y<video_y;y+=fast_parse) {
        int i=(y*video_x)+x;                          // parse all video pixels for difference to previous video image
        int   curr_lum = ((video.pixels[i] >> 16) & 0xFF) + ((video.pixels[i] >> 8) & 0xFF) + (video.pixels[i] & 0xFF); // calculate luminance of pixel
        diff_lum[i] = abs(curr_lum - bgnd_lum[i]);            // calculate luminance difference to previous video pixel
        diff_sum+=diff_lum[i];                                // sum up difference of all video pixels
        column_difference[i%video_x]+= diff_lum[i];           // sum up difference for every column                                                          
        bgnd_lum[i]=curr_lum;                                 // store new background reference
      }
    }

    if (diff_sum>0) {                                        // if new video image is different from previous video image
      new_video_image=true;                                 // => new video image detected
      video_fps_old=video_fps;                              // video refresh speed
      video_fps=millis();                                   // """""""""""""""""""
    }                  

    if (new_video_image) {                                  // if there's a new video image [with, really, different content than the previous videoimage]
      for (int x=0;x<video_x;x++) {                         // draw video image & difference image
        for (int y=0;y<video_y;y+=fast_parse) {
          int image_pos=(y*image_x)+x;
          int video_pos=(y*video_x)+x;
          pixels[image_pos] = video.pixels[video_pos];      // draw video [left side]
          // pixels[image_pos+319] = 0xff000000 | (diff_lum[video_pos]<<8);// draw difference [right side; green]
        }
      }
      updatePixels();                                       // refresh pixel array
      for(int i = 2; i < video_x-2; i++) {                  // smooth all column differences (mix with neighbours)
        column_difference[i]=(column_difference[i-1]+column_difference[i-2]+column_difference[i]+column_difference[i+1]+column_difference[i+2])/5;
      }

      average_column_difference=diff_sum/video_x;           // calculate average column difference as reference


      //-------------------------------------------------------- calculate position of the fish

      fish=false;                                         // reset fish detection
      right_cut=0;            
      for(int i = 0; i < video_x; i++) {                    // parse [from left to right] for position, where difference exceeds threshold
        if (column_difference[i]-threshold_fish_detection>average_column_difference) {
          right_cut=i;
          fish=true;
        }
      }

      left_cut=320;        
      for(int i = video_x-1; i >= 0; i--) {                 // parse [from right to left] for position, where difference exceeds threshold
        if (column_difference[i]-threshold_fish_detection>diff_sum/video_x) {
          left_cut=i;
          fish=true;
        }
      }

      if (fish && right_cut-left_cut>15) {                // if difference in the picture is wider than 15 columns:
        middle=(left_cut+right_cut)/2;                      // => calculate middle
      }
      else {                                                // if difference is less ...
        fish=false;                                       // => fish is not accepted
      }

      stroke(0,255,0);
      line(middle,0,middle,240);                            // draw middle of the fish [green]
      strokeWeight(1);
      fill(0,255,0,230);
      text("FISH POSITION",2,255);              // """""""""""""""""""""""""""" [text]

      //-------------------------------------------------------- serial communication


      //  myPort.clear();                                        
      send_fish=int(map(middle, 10, 310, 0, 222));
      send_fish=constrain(send_fish,0,222);
      myPort.write(send_fish);
       //if(myPort.available()>0) {
       //char inByte = myPort.readChar();
       //real_position=int(inByte);
      
    }
  }

  // with portamento on the frequency will change smoothly
  float freq = map(send_fish, 0, 222, 1200, 40);
  sine.setFreq(freq);

 // OscMessage send_fish = new OscMessage("/test");
 // send_fish.add(123); /* add an int to the osc message */
 // oscP5.send(send_fish, myRemoteLocation);
}


/* incoming osc message are forwarded to the oscEvent method. */
//void oscEvent(OscMessage theOscMessage) {
  /* print the address pattern and the typetag of the received OscMessage
  print("### received an osc message.");
  print(" addrpattern: "+theOscMessage.addrPattern());
  println(" typetag: "+theOscMessage.typetag());
}
*/
void stop()
{
  out.close();
  minim.stop();

  super.stop();
}
7  Forum 2005-2010 (read only) / Interfacing / Error inside Serial.ports() in Processing on: January 13, 2011, 03:23:56 pm
HI,

I keep getting this error in Processing debuggung window when trying to communicate to arduino via serial. Is it a java rxtx library error? I am using 64 bit Ubuntu 10.10 and 64 bit Arduino. Everything works fine on my other 32 bit machine:

Error inside Serial.ports()

java.lang.UnsatisfiedLinkError: /home/matjaz/Clairvision/Project_Signal/Processing/Processing_software/processing-1.2.1/libraries/serial/library/librxtxSerial.so: /home/matjaz/Clairvision/Project_Signal/Processing/Processing_software/processing-1.2.1/libraries/serial/library/librxtxSerial.so: wrong ELF class: ELFCLASS32 (Possible cause: architecture word width mismatch) thrown while loading gnu.io.RXTXCommDriver
java.lang.UnsatisfiedLinkError: /home/matjaz/Clairvision/Project_Signal/Processing/Processing_software/processing-1.2.1/libraries/serial/library/librxtxSerial.so: /home/matjaz/Clairvision/Project_Signal/Processing/Processing_software/processing-1.2.1/libraries/serial/library/librxtxSerial.so: wrong ELF class: ELFCLASS32 (Possible cause: architecture word width mismatch)
    at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1803)
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1728)
    at java.lang.Runtime.loadLibrary0(Runtime.java:823)
    at java.lang.System.loadLibrary(System.java:1028)
    at gnu.io.CommPortIdentifier.<clinit>(CommPortIdentifier.java:83)
    at processing.serial.Serial.list(Unknown Source)
    at fish_matjaz_minimtest.setup(fish_matjaz_minimtest.java:82)
    at processing.core.PApplet.handleDraw(Unknown Source)
    at processing.core.PApplet.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:662)
processing.app.debug.RunnerException: RuntimeException: Error inside Serial.ports()
    at processing.app.Sketch.placeException(Sketch.java:1543)
    at processing.app.debug.Runner.findException(Runner.java:582)
    at processing.app.debug.Runner.reportException(Runner.java:558)
    at processing.app.debug.Runner.exception(Runner.java:498)
    at processing.app.debug.EventThread.exceptionEvent(EventThread.java:367)
    at processing.app.debug.EventThread.handleEvent(EventThread.java:255)
    at processing.app.debug.EventThread.run(EventThread.java:89)
Exception in thread "Animation Thread" java.lang.RuntimeException: Error inside Serial.ports()
    at processing.serial.Serial.errorMessage(Unknown Source)
    at processing.serial.Serial.list(Unknown Source)
    at fish_matjaz_minimtest.setup(fish_matjaz_minimtest.java:82)
    at processing.core.PApplet.handleDraw(Unknown Source)
    at processing.core.PApplet.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:662)


Confiuration::
Ubuntu 10.10., 64 bit
Sun java 6
64 bit arduino 0021, regular 32bit Processing 1.2.1 (no 64 available)

Other threads indicate problem in arduino's java rxtx libraries. I have replaced them but still keep getting this error.
Used this links:
http://chemicaloliver.net/arduino/fixing-arduino-on-ubuntu-9-10-karmic-x64/
http://myy.haaga-helia.fi/~karte/arduino_editor_on_64_bit_ubuntu_gutsy.html

Any clues? I'm in a need to make it work...

Thanks.

M
8  Forum 2005-2010 (read only) / Interfacing / Re: Controlling rgb LED via Arduino on: December 22, 2010, 12:44:35 pm
Quote
Brightness - what is your LED set up now?

I'm using red, green and blue leds from RadioSHack:
3.2V, 20mA ultra high brightness, with intensity 8000 mcd.
220 Ohm resistor for each led. Circuit: pwm pin 9--> 220ohm resistor --> led ground pin --> led anode into 5V pin. Same for green and blue.

But they don't shine brightly (they look they could shine brighter). Perhaps because I'm powering them without the external supply with only 5V (3.2V)?

Have never tried that. Do you simply plug in 9 or 12V adapter into the Arduino? I'd have to use different resistors wouldn't I (I use resistor calculator to get the proper values)?

The superbrightleds you're recommending include those for the boats or bed lamps - that kind of brightness would be exactly what I'd like.

Any recommendations?

Thank you!

Matjaz
9  Forum 2005-2010 (read only) / Interfacing / Re: Controlling rgb LED via Arduino on: December 22, 2010, 02:49:37 am
Thanks so much CrossRoads. That totally did it!

I might have already been there, but I haven't noticed the difference in the lights.
The byte value was visually not very noticeable, I had to optimize the code with some values ie for example multiplied by 3 for incomingbyte<70:
if (incomingByte < 70) {
    analogWrite(rpin, incomingByte*3);
    }

multiplied by 1.5 for the 70<incomingbyte<140
 and no change (multiply by 1) for >140.


@ James C45
Quote
Do you want the LED's color segments to have their brightness correlated to the values you are passing from your processing sketch?  If yes, then analogWrite() and PWM are your only options.

If you just want to turn on the color segments based on the value then you can use digitalWrite() and if statements.

Thanks James. That helped. When I move the mouseX, the red led lights up first gradually increasing in brightness, then after 1/3 of the screen the green one starts lighting up and then the blue. So yes, I'm using pwm.

But I think I might want to simply make them light up based on their value --> digitalWrite(). They shine brighter and might divide the area into 6 parts instead of three.

The setup I have is a live camera capture of a fish in a tank, using Processing. When the fish moves, different leds illuminate the tank. leds are very low brightness as you can imagine, finding a more powerful alternative will also be the next step.

Matjaz
10  Forum 2005-2010 (read only) / Interfacing / Re: Controlling rgb LED via Arduino on: December 20, 2010, 05:02:30 pm
Below is my attempt for red and green colors only. What happens is that led starts yellow (red + green) at x above 50, and the when I move x down towards 50, it changes to green.
 Then it stays green even if I move x above 50.
It's weird.
What's wrong with the code?
(Again, I'd like red light up until x=70, green 70<x<140, and blue x>140.)



Code:
int rpin = 9;
int gpin = 10;
//int bpin = 11;

void setup() {
  // initialize serial communication
  Serial.begin(9600);
  pinMode(rpin, OUTPUT);
  pinMode(gpin,OUTPUT);
  //pinMode(bpin, OUTPUT);
}

void loop() {  
  

  if (Serial.available() > 0) {
    
    if (Serial.read() < 50) {
    analogWrite(rpin, Serial.read());
    }
    else if (Serial.read() > 50) {
    analogWrite(gpin, Serial.read());
    }
  }
}
11  Forum 2005-2010 (read only) / Interfacing / Controlling rgb LED via Arduino on: December 20, 2010, 03:21:32 pm
Hello,

I'm trying to turn on different colors according to the input from Processing.

* Processing sends to arduino a byte value (x) from 0 to 222. This value is changing by my mouseX movement
* Arduino needs to light up red when x<70, green when 70<x<140 and blue when x>140

I have managed to make the "dimmer" example work. Here is my adjusted "dimmer":

Code:
int rpin = 9;
//int gpin = 10;
//int bpin = 11;

void setup() {
  // initialize serial communication
  Serial.begin(9600);
  pinMode(rpin, OUTPUT);
  //pinMode(gpin,OUTPUT);
  // pinMode(bpin, OUTPUT);
}

void loop() {  
  byte x;

  if (Serial.available()) {
    x = Serial.read();

    analogWrite(rpin, x);

  }
}

The red color lights up and dims when x increases.

But I'd like to divide 222 pixels into 3 zones (as described at the top) and light up colors according to the x value.

I have tried with digitalWrite method and if statements...didn't really work. Can post them if needed.

Seems like analogWrite() works because 9,10 and 11 are PWM pins? SHould I be looking into digitalWrite at all?

Thank you!

M
12  Forum 2005-2010 (read only) / Interfacing / Re: Digital input, Processing & Firmata on: November 19, 2010, 08:19:11 pm
Sorry, I don't understand the reasoning behind limiting the range to 7 feet.
I thought I need to convert inches to bytes...
13  Forum 2005-2010 (read only) / Interfacing / Re: Digital input, Processing & Firmata on: November 19, 2010, 04:42:49 pm
Quote
Limiting the value sent by the Arduino to a byte (and sending the value as such) would make it very easy to read in Processing, without the need to collect characters in a string and then convert the string to an integer.

PaulS, how would you change the Ping code, to limit the value to byte?
Would you convert time to bytes?

const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  delay(100);
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}
14  Forum 2005-2010 (read only) / Interfacing / Re: Digital input, Processing & Firmata on: November 19, 2010, 03:49:36 pm
This sounds good!

I think the "Ping" example gives data, converts time to distance (which one can see ain serial monitor in Arduino IDE).
If I could capture its signal and use it in Processing...hmm

A learning curve here (mostly work with Processing).

M

15  Forum 2005-2010 (read only) / Interfacing / Re: Digital input, Processing & Firmata on: November 19, 2010, 02:52:45 pm
Thanks PaulS!

I have tried commands from the "Ping" example, but processing doesn't recognize the pulseIn command (probably because it's an Arduino command?).

However, when I go to Arduino and Processing page (http://www.arduino.cc/playground/Interfacing/Processing)

and run the given LED example, I get the sensor to flash the LED (I just alter the delay a bit). Then I added a rectangle to "draw" with a mouseY function. Although the LED on the ping))) is flashing, the sensor isn't picking up my hand movement (--> no change in the drawing).

Here is my code (simplified the previous one):
Code:
import processing.serial.*;
import cc.arduino.*;
Arduino arduino;

void setup()
{
  size(200, 200);
  noStroke();
  rectMode(CENTER);
  
  println(Serial.list());
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(7, Arduino.OUTPUT);
}

 void draw()
 {
   arduino.digitalWrite(7, Arduino.HIGH);
   delay(50);
   arduino.digitalWrite(7, Arduino.LOW);
   delay(20);
  
   background(51);
   fill(255, 204);
   rectMode(CENTER);
   rect(width/2,height/2, arduino.digitalRead(7), arduino.digitalRead(7));
   fill(255, 204);
  
 }

What does it mean when the LED on the sensor is flashing, but the sensor isn't emitting any signal (at least I don't know that)??

(PS: Maybe you were on the right track PaulS with the pulseIn...I just don't know how to combine Arduino commands with Processing)

Thanks!
Pages: [1] 2