Quantcast
Channel: Processing Forum
Viewing all 1768 articles
Browse latest View live

Re : How do I make the white square stay over the webcam?

$
0
0
ops late...
:)

I could not run your code... the order you draw stuff is the order they appear so if you draw your rect after the img(cam,0,0) it will be drawn over the cam image. As for a trail you might need to set a transparency for the cam, but this will blur the cam image also... So you might need to store yours rect positions in an array and draw a them with decreasing transparency, like this example...

hth

Re : Serial Library and Arduino

$
0
0
 Bracket the myPort.writes with println commands. Then give it shot.

For example:
println("SA " + millis());
myPort.write(arr.);
println("EA " + millis());
println("SB " + millis());
myPort.write((byte)1);
println("EB " + millis());
 

Re : serial problem in reading a string

$
0
0
For what it is worth, here is some information that hopefully will help. Keep in mind I'm just a hack. I do remember how frustrating this was at first, especially before the Ardunio IDE had a serial monitor. Maybe it always had one. It certainly is a huge help. Exit Processing and run your Ardunio IDE with the serial monitor open and set to the correct baud rate. Have the Ardunio hooked up and running. The serial monitor will show you exactly what your Ardunio code is sending. It is essential that you do this to make sure what is being sent by the Ardunio is what you expect to receive in Processing and to make sure the data comes when it is supposed to.

I've never seen the error "disabling serialEvent() ..." but it seems to me this could be resulting from outside of your code. Make sure you have the Ardunio IDE shut down before running your Processing code. I don't think they can coexist while both are looking at the serial port. Shutting down the Ardunio IDE eliminates that possibility.

What follows are three working Ardunio/Processing serial communication schemes. Each is different.

1) Ardunio sends integer values as new line string followed by the character A. Processing receives the string using the readStringUntil method on the letter A, strips the A off and uses the remainder as the data. Having the Ardunio "code" the data with the marker letter and having the Processing side only process incoming serial data coded this way ensures that the processed data is legit. 

Ardunio code: Many years old!

String arduinoUSB = "/dev/tty.usbserial-A7006Tac";
int myArd;

void setupSerial(){
  println("Available serial ports:");
  println(Serial.list());
  // Use the port corresponding to your Arduino board.  The last
  // parameter (e.g. 9600) is the speed of the communication.  It
  // has to correspond to the value passed to Serial.begin() in your
  // Arduino sketch.
  println("Looking for " +arduinoUSB);
  myArd = check4SerialDevice(arduinoUSB);
  //println(myArd + " check4");
  if (myArd != -1){
    println("Found " +arduinoUSB + " at " +myArd);
    port = new Serial(this, Serial.list()[myArd], 14400);
    port.bufferUntil(MARKER);
  }
  else{
    println("Did not find Arduino USB driver " + arduinoUSB);
  }
}


void loop(){
  // read the analog input on pin 0:
  analogValue = analogRead(0);
  if (abs(analogValue-lastValue) > analogDelta) {
    //Serial.println(analogValue);
    Serial.print(analogValue);
    Serial.print("A");
    lastValue = analogValue;
    digitalWrite(ledPin, HIGH);
  }
  if (  analogValue == 0 & lastValue != 0) {
    Serial.print(analogValue);
    Serial.print("A");
    lastValue = analogValue;
    digitalWrite(ledPin, HIGH);
  }
  if (analogValue == 1023 & lastValue != 1023){
    Serial.print(analogValue);
    Serial.print("A");
    lastValue = analogValue;
    digitalWrite(ledPin, HIGH);
  }  
  delay(10);
  digitalWrite(ledPin, LOW);

Processing code

// MARKER = 65; // the letter A used to decode the serial input sent by the Arduino

void serialEvent(Serial port) { 
  dataStr = (port.readStringUntil(MARKER));
  if (dataStr.length() >=2){
    dataStr = dataStr.substring(0, dataStr.length()-1); // strip off the last  char
    //println(dataStr);
    if (myCal != -1){  // normal condition
      potV = calibrationTable.getCalValue(float(dataStr));
    } 
    else { // abnormal, calibration table not found
      potV = map(float(dataStr),spiroMinData,spiroMaxData,0,1023)*litersPerDataVal;  
    }
    if ((dataStr != null) & (curTest < qtyTests)) { // ie stop after last test
      arypotV[curTest] = potV;
      if(arypotV[curTest] > arypotMax[curTest]){
        arypotMax[curTest] = arypotV[curTest];
      }
    }
  }
}

2) Ardunio sends coded number data groups, each followed by an "\n". The data is coded into two group types designated by a specific letter. Within each group the information pieces are separated by a | character. This data is a list of temperature sensor IDs and a list of the corresponding temperature values.  Processing receives the string using the bufferUntil method looking for the the integer 10, which is a line feed. Processing then splits the string into an array using the | character and then processes the array, being either sensor ID or sensor temperature, based upon the array's first element "code" letter.

Ardunio code:

//// temp sampler/output function
void tempSample()
{
  sensors.requestTemperatures();
  // output sensor addresses
  Serial.print("A|");
  Serial.print(int(goldTop));
  Serial.print("|");
  Serial.print(int(silverTop));
  Serial.print("|");
  Serial.print(int(silvrGndGoldVdd));
  Serial.print("|");
  Serial.print(int(redVdd));
  Serial.print("|");
  Serial.print(int(blueVdd));
  Serial.print("\n");
  // output temperatures
  Serial.print("T|");
  printTempF(goldTop);
  Serial.print("|");
  printTempF(silverTop);
  Serial.print("|");
  printTempF(silvrGndGoldVdd);
  Serial.print("|");
  printTempF(redVdd);
  Serial.print("|");
  printTempF(blueVdd);
  Serial.print("\n");
}

void printTempF(DeviceAddress deviceAddress)
{
  float tempF = sensors.getTempF(deviceAddress);
  if (tempF == NULL) { 
    Serial.print("Error getting temperature");
  } else {
    Serial.print(tempF);
  }
}

Processing code:

// This runs whenever a serial event occurs as defined in setup
//
// Prev defined: int lf = 10; // linefeed
// p = new Serial(this, serialPortName, 9600);
// p.bufferUntil(lf);

void serialEvent(Serial p){ 
  inString = p.readString();
  // the adrunino temp reader program is set to code data in groups
  // all divded by the | character and followed by lf. Since we have
  // Serial to buffer until lf the data shows up in code groups startng
  // with a signature letter and then the data separated by |. So we
  // first split according to | and then examine the first item to detect
  // the data code.

  String[] dataStr = split(inString,"|");  // split into an array
  //println("head: " + dataStr[0]);
  // Now check the code group.

  if (dataStr[0].equals("A") == true){
    //println("found A: " + dataStr[0]);
    addrString = dataStr;
  }

  if (dataStr[0].equals("T") == true){
    //println("found T: " + dataStr[0]);
    tempString = dataStr;
    for (int i = 0; i < qtySensr; i = i+1){  
      Sensors[i].storeCurrent(i+1);
    }
  }
}

3) Ardunio sends status messages as strings as if printing to a console. Processing uses readStringUntil('\n') to read the string. It then fills an array with the string lines. Each array element is a string line. These are continuously drawn to the display and scrolled as new message come in.

Ardunio code: There are many different message types . These are some. This code was initially made to write to the Adrunio IDE serial monitor and not changed in any way to accomodate how the Processing side needed.  

// reportStatus - prints out status line
void reportStatus(){
  byte _nextIndx;
  _nextIndx = nextSchdIndx(currentSchdIndx);
  reportTime();
  Serial.print("\nSchd ");
  Serial.print(currentSchdIndx);
  Serial.print(" start ");
  Serial.print(schdPeriod_arr[currentSchdIndx].hrs_S);
  Serial.print(":");
  Serial.print(schdPeriod_arr[currentSchdIndx].min_S);
  Serial.print(", end ");
  Serial.print(schdPeriod_arr[_nextIndx].hrs_S);
  Serial.print(":");
  Serial.print(schdPeriod_arr[_nextIndx].min_S);
  Serial.print(", mode ");  
  if (schedModeOverRide == 0) {
    Serial.print(cycleMode);
  } else {
    Serial.print("overriden to ");
    Serial.print(cycleMode);
  }
  Serial.print(", inhibited ");
  Serial.print(noPumping);
  if (feeding == 1) {
    Serial.print(" by feeding");
  } else {
    if (noPumping == 1) {
      Serial.print(" by POFF");
    }
  }
  Serial.print(", main cycle period ");
  Serial.print(millisToSec(cycleMode_arr[cycleObj].cyclePeriod));
  Serial.print(" sec, active timers ");
  Serial.print(tpumps.getNumTimers());
  Serial.println();
}

// reportTime - prints out current RTC data and time
void reportTime(){
  DateTime now = RTC.now();
  Serial.print("\nTime is: ");
  Serial.print(now.year());
  Serial.print("/");
  Serial.print(now.month());
  Serial.print("/");
  Serial.print(now.day());
  Serial.print(" ");
  Serial.print(now.hour());
  Serial.print(":");
  Serial.print(now.minute());
  Serial.print(":"); 
  Serial.print(now.second());
  
}

// reportSchedule - prints out the current daily schedule
void reportSchedule(){
  Serial.print("\nDaily Schedule");
  for (byte indx = 0; indx <= maxSchdIndx; indx++){
      Serial.print("\nSchd ");
      padding (indx,2);
      Serial.print(" starts ");
      padding (schdPeriod_arr[indx].hrs_S,2);
      Serial.print(":");
      padding (schdPeriod_arr[indx].min_S,2);
      Serial.print(", cycle mode ");
      Serial.print(schdPeriod_arr[indx].pmode);
  }  
  Serial.println();
}

void padding( int number, byte width ) {
  int currentMax = 10;
  for (byte i=1; i<width; i++){
    if (number < currentMax) {
      Serial.print("0");
    }
    currentMax *= 10;
  } 
  Serial.print(number);
}

Processing code: The event code is very basic. The nextLine() function is included here to avoid confusion. It has nothing to do with the serial event. It is just the mechanism being used to place the new incoming string into the correct location in the lines[] array. Its action happens to also create the text scrolling effect.


The serial setup was using: myPort.bufferUntil('\n');

void serialEvent(Serial myPort)
{
 newmsg = (myPort.readStringUntil('\n')); 
 lines[nextLine()] = newmsg;
}

int nextLine() {
  for (int i = 0; i < maxLines; i++){
   if (lines[i] == "") {
      return i;
   }
  }
  for (int i = 0; i < maxLines-1; i++){
   lines[i] = lines[i+1];
  }
  return maxLines-1;
}

Maybe these examples can help.



Re : Cant get my processing sketch to wait for a response from the arduino

$
0
0
I don't think you need to wait for the Ardunio in your code. In just glancing at the code (Forgive me but you did not explain what you really are trying to do, so I am lazy.) it looks like you are calculating a value that is sent to the Ardunio. You have yet to figure out how to get something back from the Ardunio.  You have decided it will be values in the 300 range. It looks like you have not shown what happens with those 300 range values.

Why does the main loop (the draw) need to wait? Why can it not just continue to do what it has been doing just like any other Processing draw loop?  That is what you want it to do so that it can continue to do something else, if it needs to. That is the key, "if it needs to". You need to devise the switching functions and its supports. There are bunch of examples posted to one of the other posted serial/ardunio questions that might help. You also might be looking at bufferUntil() the wrong way.  

Re : Help with Serial read

$
0
0
There are some examples posted to one of the other serial/ardunio questions that might help.

Re : High resolution frames from an animation

$
0
0
Hey PhiLho,
Thanks a lot for your help!
Everything's working fine now.

Re : Cant get my processing sketch to wait for a response from the arduino

$
0
0
Ok so to clarify.
The data produced by the sketch is used to move a plotter. they way i am building it, the processing sketch needs to send ONE number (ascii between 0 and 9) , wait for the arduino to finish physically moving, before sending the next single number.
I am intending to use ASCII commands, therefore between each movement i was thinking of using "ACK" and for the carrige returns, "CR"

here is an example image:, the darker blocks will be represented by a 9, the white ones, by a 0.


The code works, the serial connection works, however the processing sketch and the arduino do not acknowledge each other. I would like them to take it in turns to do what they need to do.

I have tried many various examples and tutorials, however none of them have worked in this scenario.
maybe i am not using the ASCII bytes correctly It doesnt help that ALL the tutorialsi have found work the other way around, with the arduino waiting for processing. Therefore, in frustration i have stripped out all the references to "bufferUntil"

here is the code, without any attempt at the serial response. Any suggestions would be greatly appreciated.

http://pastebin.com/f6x7QuQj

  1. /* sends shades in single waves, using an int, to keep track of total steps made per row (x axis).
  2.  */
  3. import processing.serial.* ;
  4. Serial myPort;
  5. PImage img1;
  6. int Ysize = 10; // height of the rows
  7. int squareSize = 300; // size of the working frame
  8. float greyscalein; // inward greyscale reading of 0- 255
  9. byte greyscaleround; // converted and rounded down to whole bytes for transmission (0 - 9)
  10. int xprogress = 0; // integer for keeping track of progress across image
  11. int stepsize = 0; // integer for transmitting how far to move the motors per step
  12. void setup() {
  13.   size(squareSize * 2, squareSize); // frame is twice image width. Original image on the left, processed image on the right.
  14.   println(Serial.list());
  15.   myPort = new Serial(this, Serial.list()[0], 9600);
  16. }
  17. void draw() {
  18.   background(0); // background - 0 is black
  19.   img1 = loadImage("STRS.jpg"); // image, 300 x 300 (STRS or grad)
  20.   imageMode(CENTER);
  21.   image(img1, (squareSize/2), (squareSize/2)); // draws the image, centred
  22.   for (int y = 0; y < squareSize; y = y + Ysize ) {
  23.     // "carrige return" instruction from processing to the arduino will go in here (probably)
  24.     for (int x = 0; x < squareSize; x = x + stepsize) {
  25.       color c = get(xprogress, y + Ysize/2);
  26.       float greyscalein = brightness(c);  // Sets 'greyscale' to 255-0
  27.       greyscalein = map(greyscalein, 0, 255, 48, 57); // maps the resolution of the trsnamisted data from 0-255, to 0- ???
  28.       int greyscaleround = round(greyscalein); // rounds the floating value of the greyscalein(read from c) to a whole number (greyscaleround)
  29.       print("Greyscale:");
  30.       print(greyscaleround-48); //show the greyscale, adjusted from ascii so that 0 is black
  31.       myPort.write(greyscaleround);    // send it to the arduino
  32.       delay (0);        // delay for easy reading of monitor
  33.       // *** this section is for printing of the preview in the processing window.It is not required by the arduino.***
  34.       stepsize = ((greyscaleround - 46)*1);
  35.       fill(c);
  36.       stroke(100); // bounded by a box, dark grey
  37.       rect(squareSize + xprogress, y, squareSize + xprogress + stepsize, y + Ysize);
  38.       xprogress =  xprogress + stepsize;
  39.       print(" ; stepsize:");
  40.       println(stepsize); //show the size of the step taken on the monitor
  41.       delay (00);
  42.     }
  43.     xprogress = 0; // reset x-progress before going to next line (y axis)
  44.   }
  45. }

Re : frameRate() can crash 2.0b7

$
0
0
Thanks, also note the inconsistency with what is reported for framerate vs visual.  It reports 60fps for me, but 60fps should be very smooth.  So why is it jerky if it is running at 60fps?  It seems the processing of each frame is fast, but maybe what is displayed / rendered is not properly "in-sync" or something.  I'm not seeing any tearing, but perhaps there is a delay or out-of-sync between the frame rate and when flush is ready / loaded.  ??

Re : Serial Library and Arduino

$
0
0
Sketch:
  1. import processing.serial.*;
  2. Serial myPort;
  3. byte arr[] = {0,1,2,3,4,5,6,7,8,9};

  4. void setup() 
  5. {
  6.   size(400, 600);
  7.   myPort = new Serial(this, "/dev/tty.HC-05-DevB", 57600);
  8.   while (true)
  9.   {
  10.       println("SA " + millis());
  11.       myPort.write(arr);
  12.       println("EA " + millis());
  13.       println("SB " + millis());
  14.       myPort.write((byte)1);
  15.       println("EB " + millis());
  16.   }
  17. }

  18. void draw()
  19. {
  20. }
Result:
  1. SA 3314
  2. EA 3314
  3. SB 3315
  4. EB 3324
  5. SA 3324
  6. EA 3453
  7. SB 3453
  8. EB 3703
  9. SA 3703
  10. EA 3953
  11. SB 3953
  12. EB 4203
  13. SA 4203
  14. EA 4453
  15. SB 4453
  16. EB 4703
  17. SA 4703
  18. EA 4953
  19. SB 4953
  20. EB 5203
  21. SA 5203
  22. EA 5453
  23. SB 5453
How the hell can be sending 10bytes faster than sending a single one?

Creating Complex Shapes

$
0
0
I've been playing around with Minim, and used it to create a visualiser however I'd like it to look a lot more interesting.

I found this: https://vimeo.com/24133373
Although I've found tutorials on creating small 3D objects, but how would I go about creating something like this that would still be reactive to the FFT from minim.

Cheers

Re : Cant get my processing sketch to wait for a response from the arduino

$
0
0
I personally like using the SerialCommand ( Stefan Rado / Steven Cogswell) on the Arduino side to handle the incoming Processing commands which you structure to look like <command> <data> <data>. So lets say the command is PL for plot and 1234 is the data. The string sent by Processing would be "PL 12324". On the Ardunio side you associate a callback function for PL. That function will be called when serial sees data with a first word PL. In that PL callback function you extract the 1234 and do what needs to be done. With this scheme you can add commands as you need them with a simple callback definition line. You are wide open to add features to your program. You might add "SP 10" to mean spit out 10 copies. There can be more than one argument companying the command. So you could have command string "WH 12 34 This" where WH is the command type and 12 34 This is the data. You can use a similar scheme on the Processing side where your Processing serial event code is checking all incoming serial messages for codes that represent the Arduino states. Your Processing code would not be "waiting", i.e. stopped, for the the Ardunio is ready message. It would just react appropriately when the ready message arrives. Structure the message scheme so that you can easily add message types. The Processing side might be looking for two or one characters to represent Ardunio states.  

Re : serial problem in reading a string

$
0
0
Hi...
thanks for your reply.
it is very useful for me
thanx once again...........

Refresh displayed text based on condition?

$
0
0
Hi everyone, I've only just started using Processing today so i'm a bit stumped on this..

I'm trying to display whether a user is online or offline by using text(). I have two different methods, either one printing based on a condition, but when that condition changes, the text does not. I'm getting a readout in the console so I know that the condition statement is switching, but the displayed text isn't..

Here's the code - you can find the text methods towards the end of draw()

  1. import processing.serial.*;
  2. Serial port;
  3. PFont f;

  4. void setup() {
  5.   size(640, 360);
  6.   port = new Serial(this, "COM3", 9600);
  7.   port.bufferUntil('\n');
  8.   f = createFont("Arial",16,true);
  9. }

  10. void draw() {
  11.   background(0);
  12.   
  13.   int i=0;
  14.   int temp=-1;
  15.   int lastLogin = 0, lastLogout = 0;

  16.   String[] lines = loadStrings("C:/McMyAdmin/Minecraft/plugins/BeardStat/stats.yml");
  17.   
  18.   println("there are " + lines.length + " lines");
  19.   
  20.   String searchLogin = "stats-lastlogin";
  21.   while(i < lines.length){
  22.     int index = lines[i].indexOf(searchLogin);
  23.     if(index >= 0){
  24.       String sub1 = lines[i].substring(index+17);
  25.       //println(sub1);
  26.       lastLogin = int(sub1);
  27.     }
  28.     i++;
  29.   }
  30.   
  31.   i=0;
  32.   
  33.   String searchLogout = "stats-lastlogout";
  34.   while(i < lines.length){
  35.     int index = lines[i].indexOf(searchLogout);
  36.     if(index >= 0){
  37.       String sub2 = lines[i].substring(index+18);
  38.       //println(sub2);
  39.       lastLogout = int(sub2);
  40.     }
  41.     i++;
  42.   }
  43.   
  44.   textFont(f,16);
  45.   fill(255);
  46.   
  47.   if(lastLogin < lastLogout){
  48.     println("User is logged out.");
  49.     port.write(0);
  50.     text("User is logged out.", 10, height/2);
  51.   } else {
  52.     println("User is logged in.");
  53.     port.write(1);
  54.     text("User is logged in.", 10, height/2);
  55.   }
  56.   
  57.   myDelay(5000);
  58. }

  59. void myDelay(int ms){
  60.   try{    
  61.     Thread.sleep(ms);
  62.   }
  63.   catch(Exception e){}
  64. }


EDIT - I have not noticed that if I leave it run for a while, the text does eventually update, but not instantly. The console messages do change instantly though, so it it something to do with loading the text?

Re : Creating Complex Shapes

Re : Creating Complex Shapes

$
0
0
Thanks, just found it. :)

I think from the looks of her earlier work, each band is given a point circle and these join with the points nearby to them.

I need to work out how to make these point shapes which I'll research now.

Could anybody suggest some good books on creating visual art/motion art with Processing. Thankyou!

Re : Creating Complex Shapes

Re : Creating Complex Shapes

$
0
0
Cheers, I'll check them out.
Just withdrew Processing: A Programming Handbook for Visual Designers and Artists.

Re : Refresh displayed text based on condition?

$
0
0


I think println is done instantly by processing while the screen (so text() as well) is only updated once
at the end of draw()

since your delay that's only after 5 seconds

draw() itself runs 60 times per sec unless stopped as in your case.

So consider throw out delay

and consider to put loadString into setup() because it's very time consuming

           

Re : Different shaders for geometry, lines and text?

$
0
0
I have give it a try in Processing's new version, 2.0b8, using the #define in each shader code and changing the names:

Color shader:
  1. #define PROCESSING_COLOR_SHADER

    varying vec4 vertColor;

    uniform float fogNear;
    uniform float fogFar;

    void main(){
        gl_FragColor = vertColor;
       
        vec3 fogColor = vec3(1.0,1.0,1.0);
        float depth = gl_FragCoord.z / gl_FragCoord.w;
        float fogFactor = smoothstep(fogNear, fogFar, depth);
        gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor);
    }


Line shader:
  1. #define PROCESSING_LINE_SHADER

    varying vec4 vertColor;

    uniform float fogNear;
    uniform float fogFar;

    void main(){
        gl_FragColor = vertColor;
       
        vec3 fogColor = vec3(1.0,1.0,1.0);
        float depth = gl_FragCoord.z / gl_FragCoord.w;
        float fogFactor = smoothstep(fogNear, fogFar, depth);
        gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor);
    }


Texture shader
  1. #define PROCESSING_TEXTURE_SHADER

    uniform sampler2D texture;
    varying vec4 vertColor;
    varying vec4 vertTexCoord;

    uniform float fogNear;
    uniform float fogFar;

    void main() {
      gl_FragColor = texture2D(texture, vertTexCoord.st) * vertColor;
     
      vec3 fogColor = vec3(1.0,1.0,1.0);
      float depth = gl_FragCoord.z / gl_FragCoord.w;
      float fogFactor = smoothstep(fogNear, fogFar, depth);
      gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor);
    }

The color and texture shaders work, and there's no error in the console, but lines are not affected but the shader. There is no Line shader example to check for name changes



Adding PShape vertex dynamically

$
0
0
Is there any way to add and remove vertices from a PShape dynamically?
Viewing all 1768 articles
Browse latest View live