Howdy, Stranger!

We are about to switch to a new forum software. Until then we have removed the registration on this forum.

  • How to tell servo to follow a pendulum movement

    in the processing script:

    this

    port.write(sangle);

    should be

    port.write(angle_degrees); or something like this.

    Remark

    You can use map() to transfer the values of angle_degrees to the value that the servo needs, e.g.

    valueForServo = map(angle_degrees,0,360,-22,22);
    port.write( valueForServo ); 
    

    Chrisir

  • How to tell servo to follow a pendulum movement

    I have a pendulum and arduino reading script. I was able to track simple movements, but I cannot make it follow pendulum curve and convert it into degrees.

    #include <Servo.h> 
    
    //load servo to control it
        Servo myservo;  
    #define servoPin 9
    
    int sangle=0;
    //information comming into servo = numbers read from processing
    int inByte=0;
    
    void setup() { 
    //attach a pin 9 to servo
      myservo.attach(servoPin); 
     Serial.begin(9600);
    } 
    
    void loop() { 
    
     if(0<Serial.available()){
      inByte=Serial.read();
     }
     sangle=inByte;
     myservo.write(sangle);
    }
    

    and processing script:

    import processing.serial.*;
    Serial port;
    
    float x= (PI/2);
    float pos=0; 
    float pos1=PI/4;
    byte sangle=0;
    float angle_degrees=0;
    float rotangle=0;
    
    void setup() {
      size(800, 800);
     port=new Serial(this,"COM3",9600);
    }
    
    void draw() {
      background(255);
    
    // float rotangle = atan2(height/4, width/2);
    //my servo is 90 degrees to each side =180
      rotangle=constrain(rotangle,0,PI);
      angle_degrees=degrees(rotangle);
      println(angle_degrees);
    //send information into arduino
      port.write(sangle);
    
      translate(width/2, height/4);
      rotate(pos1*cos(millis()/900.0));
      stroke(0);
      strokeWeight(3);
      line(0, 0, 0, 300);
      fill(#0074FF);
      noStroke();
      ellipse(0, 300, 40, 40);
      println(pos1);
      println(angle_degrees);
      }
    
  • How to get a Sparkfun Servo Motor to Turn both Backwards and Forwards

    I am working on a maze robot project and I am at the stage where I am testing out my servo motors to make sure they work properly. I am using a Sparkfun ArduMoto Motor Driver Shield kit, which includes two servo motors that I will use for my wheels. The program is not complete yet. I do not have commands to turn left and right, my if statements, and more coding for my 3 ultrasonic sensors, but with the coding I have, I cannot get the motors to turn backwards, only forwards. I tried switching the HIGH and LOW commands for the digitalWrite partsin my Void statements, but that did not work. However, the speed difference from a variable of 100 to 255 in my void loop statement worked. So, it is reading and looping through the code properly, but the direction will not change. If anyone can see a problem or a solution to my coding I would appreciate it.

    Attached is my code so far. (without turn left and right, my if statements, and more coding for my 3 ultrasonic sensors which are not quite needed yet at this point.)

    const int sens_1_echoPin = 4; const int sens_1_trigPin = 5; const int sens_2_echoPin = 6; const int sens_2_trigPin = 7; const int sens_3_echoPin = 8; const int sens_3_trigPin = 9;

    int m1direction = 12; int m2direction = 13; int motor1Speed = 3; int motor2Speed = 11;

    float distance_sens_1; float distance_sens_2; float distance_sens_3; long duration1; long duration2; long duration3;

    void setup() {

    pinMode(sens_1_echoPin, INPUT); pinMode(sens_1_trigPin, OUTPUT); pinMode(sens_2_echoPin, INPUT); pinMode(sens_2_trigPin, OUTPUT); pinMode(sens_3_echoPin, INPUT); pinMode(sens_3_trigPin, OUTPUT);

    pinMode(m1direction, OUTPUT); pinMode(m2direction, OUTPUT); pinMode(motor1Speed, OUTPUT); pinMode(motor2Speed, OUTPUT);

    Serial.begin (9600); }

    void goForward (int duration, int pwm) { digitalWrite (m1direction, HIGH); digitalWrite (m2direction, HIGH); analogWrite (motor1Speed, pwm); analogWrite (motor2Speed, pwm); delay(duration); analogWrite (motor1Speed, 0); analogWrite (motor2Speed, 0); }

    void goBackward (int duration, int pwm) { digitalWrite (m1direction, LOW); digitalWrite (m2direction, LOW); analogWrite (motor1Speed, pwm); analogWrite (motor2Speed, pwm); delay (duration); analogWrite (motor1Speed, 0); analogWrite (motor2Speed, 0); }

    void loop() { digitalWrite; goForward (5000, 100); delay (1000); digitalWrite; goBackward (5000, 255); delay (1000);

  • GUI for arduino code

    Hey, I'm new to this whole processing thing, been learning some basic stuff for this particular assignment. How ever I'm not sure if I should make some changes to my Arduino code to make this assignment easier.

    This is the task I've got: Using Processing, build a GUI for the system that you built for Tasks 1, 2 and 3. Your Arduino program might need to be adapted.

    -You should built a user interface to implement all the functions of the previous tasks. -The physical push-buttons should still work, but their functions should be also present in the GUI. -Depending on where the user clicks on the screen, your program should send the appropriate character to Arduino. -The values returned by the Arduino should be printed in the Processing console and also indicated using a graphical scale of your choice (bar graph, scope like plot, etc.).

    Here is the code for Arduino:

        #include <Servo.h> // include Servo library
    
        Servo myServo; 
    
        int sensorValueTemp;
        int sensorValueHum;    
        int heartBeat = 0;
        int blinkingMIN = 0;
        int blinkingMAX = 0;
        int angle1;                   // angle to be rotated by servo when sensing temperature
        int angle2;                   // angle to be ratated by servo when sensing humidity
        int selectedSensor = 2;
        int leds = 2;
        int reading1;
        int reading2;
    
        boolean continuousRead = false;
    
        const int humiditySensor = A1;    // humidity sensor in A1 pin
        const int tempSensor = A0;        // temperature sensor in AO pin
        const int button1 = 11;           // push-button for changing which sensor is active
        const int button2 = 10;           // push-botton for switching the digital ledscale ON/OFF
        const int led = 12;               // which sensor is reading; ON=temperature, OFF=humidity
    
        float temperature;
        float voltage;
        float sensorRH;
        float trueRH;
    
        const float roomTemp = 23;
    
        unsigned long timer1;
        unsigned long timer2;
        unsigned long timer3;
        unsigned long timer4;
        unsigned long timer5;
    
        void setup() {
    
          myServo.attach(9,480,2240);                   // (servo attached to pin 9, minimum pulse, servo maximum pulse)
          Serial.begin(9600);                           // open a serial connection to display values
          Serial.setTimeout(10);
    
          // set the LED button and sensors as inputs
          pinMode(button1, INPUT);
          pinMode(button2, INPUT);
          pinMode(tempSensor, INPUT);
          pinMode(humiditySensor, INPUT);
    
    
          // set the LED pins as outputs
          pinMode(13, OUTPUT);
          pinMode(led, OUTPUT);
          for (int pinNumber = 2; pinNumber < 8; pinNumber++) {
            pinMode(pinNumber, OUTPUT);
            digitalWrite(pinNumber, LOW);
          }
    
          //LED test at startup
          digitalWrite(2,HIGH);
          delay(100);
          digitalWrite(3,HIGH);
          delay(100);
          digitalWrite(4,HIGH);
          delay(100);
          digitalWrite(5,HIGH);
          delay(100);
          digitalWrite(6,HIGH);
          delay(100);
          digitalWrite(7,HIGH);
          delay(500);
          for (int pinNumber = 2; pinNumber < 8; pinNumber++) {
            digitalWrite(pinNumber, LOW);
          }
          delay(500);
        }
    
        void ledScale() {
          // if the current temperature is lower than the roomTemp: turn off all LEDs and blink the LED in pin 2 -> temperature under minimum value
          if (temperature < roomTemp +2) {
            for (int pinNumber = 3; pinNumber < 8; pinNumber++) {
            digitalWrite(pinNumber, LOW);
    
          // Make the LED blink
          if (millis() - timer1 > 500){
           blinkingMIN = !blinkingMIN;
           digitalWrite (2, blinkingMIN);
           timer1 = millis();  
          }
            }
          }
    
          // if the temperature rises 2-3 degrees: turn an LED on
          else if (temperature >= roomTemp + 2 && temperature < roomTemp + 3) {
            digitalWrite(2, HIGH);
            for (int pinNumber = 3; pinNumber < 8; pinNumber++) {
            digitalWrite(pinNumber, LOW);
            }
          }
    
          // if the temperature rises 3-4 degrees: turn a second LED on
          else if (temperature >= roomTemp + 3 && temperature < roomTemp + 4) {
            digitalWrite(2, HIGH);
            digitalWrite(3, HIGH);
            for (int pinNumber = 4; pinNumber < 8; pinNumber++) {
            digitalWrite(pinNumber, LOW);
            }
          }
    
          // if the temperature rises 4-5 degrees: turn a third LED on
          else if (temperature >= roomTemp + 4 && temperature < roomTemp + 5) {
            for (int pinNumber = 2; pinNumber < 5; pinNumber++) {
            digitalWrite(pinNumber, HIGH);
            for (int pinNumber = 5; pinNumber < 8; pinNumber++) {
            digitalWrite(pinNumber, LOW);
            }
            }
          }
    
          // if the temperature rises 5-6 degrees: turn a fourth LED on
          else if (temperature >= roomTemp + 5 && temperature < roomTemp + 6) {
            for (int pinNumber = 2; pinNumber < 6; pinNumber++) {
            digitalWrite(pinNumber, HIGH);
            digitalWrite(6, LOW);
            digitalWrite(7, LOW);
            }
          }
    
          // if the temperature rises 6-7 degrees, turn a fifth LED on
          else if (temperature >= roomTemp + 6 && temperature < roomTemp + 7) {
            for (int pinNumber = 2; pinNumber < 7; pinNumber++) {
            digitalWrite(pinNumber, HIGH);
            digitalWrite(7, LOW);
            }
          }
    
          // if the temperature goes 7 degrees over the roomTemp: turn on all LEDs and blink the led in pin 7 -> maximum value has been crossed
          else if (temperature >= roomTemp + 7) {
            for (int pinNumber = 2; pinNumber < 7; pinNumber++) {
            digitalWrite(pinNumber, HIGH);
    
          // Make the LED blink
          if (millis() - timer2 > 500) {
           blinkingMAX = !blinkingMAX;
           digitalWrite (7, blinkingMAX);
           timer2 = millis();  
          }
            }
          }
        }
    
        void sendMeasurements() {
          Serial.print("Temperature: ");
          Serial.print(temperature);
          Serial.println("°C");
    
          Serial.print("Humidity: ");
          Serial.print(trueRH);
          Serial.println("%");
        }
    
        void toggleSensor() {
            selectedSensor++;
              if(selectedSensor > 2)
                selectedSensor = 1;
        }
    
        void toggleLeds() {
            leds++;
              if(leds > 2)
                leds = 1;
        }
    
        void parseCommands(char input) {
          switch (input) {
    
            case 'L':
            case 'l': 
            if (leds == 2){
              leds = 1;
            }
            else{
              leds = 2;  
            }
            break;
    
            case 'M':
            case 'm':
            sendMeasurements();
            break;
    
            case 'C':
            case 'c':
            continuousRead = !continuousRead;
            break;
    
            case 'S':
            case 's': 
            toggleSensor();
            break;
    
            case 'K':
            case 'k': 
            Serial.print("Selected sensor: ");
            switch (selectedSensor){
            case 1: 
            Serial.println("Temperature");
            break;
            case 2:
            Serial.println("Humidity");
            break;
            }
    
            Serial.print("Leds ON/OFF: ");
            switch (leds){
            case 1: 
            Serial.println("OFF");
            break;
            case 2:
            Serial.println("ON");
            break;
            }
            break;
          }
        }
    
        void loop() {  
    
          // Make the LED blink in pin 13 for "heart beat"
          if (millis() - timer3 > 500){
            heartBeat = !heartBeat;
            digitalWrite (13, heartBeat);
            timer3 = millis();
          }
    
          // Button 1 to toggle sensor
          reading1 = digitalRead(button1);
            if(digitalRead(button1)) {
              toggleSensor();
          }
    
          // Read the temperature sensor values
          analogRead(tempSensor); 
    
          // Timer for updating the sensor values at 1Hz
          if(millis() - timer4 > 1000){
          sensorValueTemp = analogRead(tempSensor);
          temperature = (5.0 * sensorValueTemp * 100.0) / 1024;
    
          // Mapping the servo for temperature sensor
          angle1 = map(temperature, 10, 50, 0, 180);
    
          // Read the humidity sensor values
          sensorValueHum = analogRead(humiditySensor);
          voltage = (5.0 * sensorValueHum) / 1024.0;
          sensorRH = (voltage - 0.958) / 0.03068;
          trueRH = (sensorRH) / (1.0546 - 0.00216 * 23);
    
          // Mapping the servo for humidity sensor
          angle2 = map(trueRH, 40, 80, 0, 180);
    
          // Switchcase for button 1 to select which sensor is active
          switch(selectedSensor) {
    
          case 1:
          digitalWrite(led, HIGH);
          myServo.write(angle1);
          break;
    
          case 2:
          digitalWrite(led, LOW);
          myServo.write(angle2);
          break;  
          }
          timer4 = millis();
          }
    
          // Reading the parse commands
          char command = Serial.read();
          while(command != -1) {
            parseCommands(command);
            command = Serial.read();
          }
    
          // Timer for seding the sensor values to serial monitor once a second
          if(millis() - timer5 > 1000 && continuousRead) {
            sendMeasurements();
            timer5 = millis();
          }
    
          // Button 2 to toggle leds
          reading2 = digitalRead(button2);
            if(digitalRead(button2)) {
              toggleLeds();
          }
    
          // Switchcase for button 2 to switch ON/OFF the digital ledScale
          switch(leds) {
    
            case 1:
            for (int pinNumber = 2; pinNumber < 8; pinNumber++) {
            digitalWrite(pinNumber, LOW);
            }
            break;
    
            case 2:
            ledScale();
            break;
          }
        }
    

    Any help will be appreciated,

    Jonathan.

  • How to visualise sensor data from arduino in processing?

    Hi there.

    I'm currently working on a thermal imaging camera for my project in university. The system is as follows: there is an mlx90614 temperature sensor mounted on two servo motors and connected to an arduino leonardo. One to control y-axis rotation and one to control x-axis rotation. The arduino currently collects data by rotating the x-axis servo motor (right to left) to take 90 measurements( one measurement per degree of rotation). Once this is done the y-axis motor rotates one degree up and repeats the previous step). This continues until the x-axis motor has completed 90 increments. The data is being sent to the serial monitor as it is measurement.

    I'm new to using processing and I'm not sure how to create a processing script to visually represent the data. My idea was to assign a coloured square to each temperature measurement (For example between 10 and 40 degrees, the colour would change from blue at 10 degrees to red at 40 degrees as you go from 10 to 40) and position them one by one in the position they were measured from.

    I would appreciate any ideas people can give me. Sorry this question is so long winded and maybe confusing. If there is any more information needed i will provide it.

  • Need Help With Pan/Tilt Facetracking with servos and Arduino

    I have made some changes to the code, now the video stream works but no response from servos.

    Processing:

    /**********************************************************************************************
    * Pan/Tilt Face Tracking Sketch
    * Written by Ryan Owens for SparkFun Electronics
    * Uses the OpenCV real-time computer vision  framework from Intel
    * Based on the OpenCV Processing Examples from ubaa.net
    * This example is released under the Beerware License.
    * (Use the code however you'd like, but mention us and by me a beer if we ever meet!)
    *
    * The Pan/Tilt Face Tracking Sketch interfaces with an Arduino Main board to control
    * two servos, pan and tilt, which are connected to a webcam. The OpenCV library
    * looks for a face in the image from the webcam. If a face is detected the sketch
    * uses the coordinates of the face to manipulate the pan and tilt servos to move the webcam
    * in order to keep the face in the center of the frame.
    *
    * Setup-
    * A webcam must be connected to the computer.
    * An Arduino must be connected to the computer. Note the port which the Arduino is connected on.
    * The Arduino must be loaded with the ServoFirmata Sketch.
    * Two servos mounted on a pan/tilt backet must be connected to the Arduino pins 4 and 7.
    * The Arduino must be powered by a 9V external power supply.
    * 
    * Read this tutorial for more information:
    **********************************************************************************************/
    import gab.opencv.*;
    import processing.video.*;
    import java.awt.*;
    import processing.serial.*;
    
    Capture video;
    OpenCV opencv;  //Create an instance of the OpenCV library.
    
    Serial serial; // The serial port
    
    //Variables for keeping track of the current servo positions.
    char servoTiltPosition;
    char servoPanPosition;
    //The pan/tilt servo ids for the Arduino serial command interface.
    char tiltChannel = 0;
    char panChannel = 1;
    
    //These variables hold the x and y location for the middle of the detected face.
    int midFaceY=0;
    int midFaceX=0;
    
    //The variables correspond to the middle of the screen, and will be compared to the midFace values
    int midScreenY = (height/2);
    int midScreenX = (width/2);
    int midScreenWindow = 10;  //This is the acceptable 'error' for the center of the screen. 
    
    //The degree of change that will be applied to the servo each time we update the position.
    int stepSize=1;
    
    void setup() {
      size(640, 480);
      video = new Capture(this, 640/2, 480/2);
      opencv = new OpenCV(this, 640/2, 480/2);
      opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE);  
    
      video.start();
    
      printArray(Serial.list());
    
    
      serial = new Serial(this, "COM3", 57600);
    
    }
    
    
    
    void draw() {
      scale(2);
      opencv.loadImage(video);
    
      image(video, 0, 0 );
    
      noFill();
      stroke(53, 204, 255);
      strokeWeight(3);
      Rectangle[] faces = opencv.detect();
      println(faces.length);
    
      for (int i = 0; i < faces.length; i++) {
        println(faces[i].x + "," + faces[i].y);
        rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height);
      }
    
    
      if(faces.length > 0){
        //If a face was found, find the midpoint of the first face in the frame.
        //NOTE: The .x and .y of the face rectangle corresponds to the upper left corner of the rectangle,
        //      so we manipulate these values to find the midpoint of the rectangle.
        midFaceY = faces[0].y + (faces[0].height/2);
        midFaceX = faces[0].x + (faces[0].width/2);
    
        //Find out if the Y component of the face is below the middle of the screen.
        if(midFaceY < (midScreenY - midScreenWindow)){
          if(servoTiltPosition >= 5)servoTiltPosition -= stepSize; //If it is below the middle of the screen, update the tilt position variable to lower the tilt servo.
        }
        //Find out if the Y component of the face is above the middle of the screen.
        else if(midFaceY > (midScreenY + midScreenWindow)){
          if(servoTiltPosition <= 175)servoTiltPosition +=stepSize; //Update the tilt position variable to raise the tilt servo.
        }
        //Find out if the X component of the face is to the left of the middle of the screen.
        if(midFaceX < (midScreenX - midScreenWindow)){
          if(servoPanPosition >= 5)servoPanPosition -= stepSize; //Update the pan position variable to move the servo to the left.
        }
        //Find out if the X component of the face is to the right of the middle of the screen.
        else if(midFaceX > (midScreenX + midScreenWindow)){
          if(servoPanPosition <= 175)servoPanPosition +=stepSize; //Update the pan position variable to move the servo to the right.
        }
    
      }
      //Update the servo positions by sending the serial command to the Arduino.
      serial.write(tiltChannel);      //Send the tilt servo ID
      serial.write(servoTiltPosition); //Send the updated tilt position.
      serial.write(panChannel);        //Send the Pan servo ID
      serial.write(servoPanPosition);  //Send the updated pan position.
      delay(50);
    }
    
    
    
    void captureEvent(Capture c) {
    
      c.read();
    }
    

    Arduino:

    /*******************************************************
    * SerialServoControl Sketch
    * Written by Ryan Owens for SparkFun Electronics
    * 7/15/11
    *
    * This sketch listens to serial commands and uses the data
    * to set the position of two servos.
    *
    * Serial Command Structure: 2 bytes - [ID Byte][Servo Position byte]
    * ID byte should be 0 or 1.
    * Servo position should be a value between 0 and 180.
    * Invalid commands are ignored
    * The servo position is not error checked.
    * 
    * Hardware Setup
    * Servos should be connected to pins 2 and 3 of the Arduino.
    * 9V DC Power supply is recommended as USB can't always handle powering two servos
    */
    #include <Servo.h>  //Used to control the Pan/Tilt Servos
    
    //These are variables that hold the servo IDs.
    char tiltChannel=0, panChannel=1;
    
    //These are the objects for each servo.
    Servo servoTilt, servoPan;
    
    //This is a character that will hold data from the Serial port.
    char serialChar=0;
    
    void setup(){
      servoTilt.attach(2);  //The Tilt servo is attached to pin 2.
      servoPan.attach(3);   //The Pan servo is attached to pin 3.
      Serial.begin(57600);  //Set up a serial connection for 57600 bps.
    }
    
    void loop(){
      if(Serial.available() > 0);  //Wait for a character on the serial port.
      serialChar = Serial.read();     //Copy the character from the serial port to the variable
      if(serialChar == tiltChannel){  //Check to see if the character is the servo ID for the tilt servo
        while(Serial.available() <=0);  //Wait for the second command byte from the serial port.
        servoTilt.write(Serial.read());  //Set the tilt servo position to the value of the second command byte received on the serial port
      }
      else if(serialChar == panChannel){ //Check to see if the initial serial character was the servo ID for the pan servo.
        if(Serial.available() <= 0);  //Wait for the second command byte from the serial port.
        servoPan.write(Serial.read());   //Set the pan servo position to the value of the second command byte received from the serial port.
      }
      //If the character is not the pan or tilt servo ID, it is ignored.
    }
    

    Thank you in advance

  • Program freezing when using Serial out

    Hi guys,

    This program I've made is designed to read data from a csv file and output it to an arduino (which will in turn eventually output it to a motor). Strangely, it runs just fine without the Arduino plugged in, but with the Arduino plugged in it starts freezing every one or two seconds after the first eight seconds or so. I presume some buffer somewhere is being filled up and is not clearing itself fast enough, but I have no idea where. Any thoughts?

    /*  CSV_READER
        Version 3.4
    
        Improvements from last version:
        - 
    
        Improvements to be made:
        - Begins to freeze when Arduino plugged in
    
    */
    
    import processing.serial.*;
    
    int xpos=90; // set x servo's value to mid point (0-180);
    int ypos=90; // and the same here
    Serial port; // The serial port we will be using
    Table table;
    final int motorPulley = 17; //number of teeth on the pulley
    final int enginePulley = 51;
    final int calibrationFactor = (2880 * (enginePulley/motorPulley))/360; //2880 = max rpm of motor
    int rowCount = 1;
    int timeResolution; //the time interval in ms of the chosen data file
    boolean fileSelected = false;
    boolean run = false;
    boolean pause = false;
    boolean stop = false;
    int time, rpm;
    boolean debounce = true; //ensures button is released before it can be pressed again
    int stopCount = 0; //how long before program closes
    int timeRunning = 0; //time the program has spent running
    int timePaused = 0;
    String fileName;
    
    void setup() 
    {
      size(360, 360, P2D);
      background(50);
    
      selectInput("Select a file to process:", "fileSelected");
      //table = loadTable(file, "header");
    
      frameRate(1000); //sets framerate
    
      //println(Serial.list()); // List COM-ports
      port = new Serial(this, Serial.list()[5], 9600);
    
    
    }
    
    void fileSelected(File selection) //selects the file
    {
      if (selection == null) 
      {
        println("Window was closed or the user hit cancel.");
      } 
      else 
      {
        println("User selected " + selection.getAbsolutePath());
        fileName = selection.getName();
        table = loadTable(selection.getAbsolutePath(), "header");
        fileSelected = true;
        TableRow row1 = table.getRow(1);
        TableRow row2 = table.getRow(2);
        int time1 = row1.getInt("time");
        int time2 = row2.getInt("time");
        timeResolution = time2 - time1;
      }
    }
    
    void draw() 
    {
      while (fileSelected == false) //Does not run unti a file has actually been selected
      {
        delay(1);
      }
    
      clear();
      //println(frameRate); //use for testing a specific variable
    
      if (stop == false) //normal running section of program
      {
          if (run == true) //loads row data
          {
            timeRunning = millis() - timePaused;
            nextRow();
          }
    
          else
          {
            timePaused = millis() - timeRunning;
          }
    
          //println(rpm);
          update(0, rpm/calibrationFactor); //update serial signal being sent to arduino
    
          strokeWeight(10);
          stroke(0, 191, 255);
          fill(0, 0, 0);
          //ellipse(180, 180, rpm/24,rpm/24);
          arc(180,180,180,180, 0, radians(rpm/24)); //draws an arc whic represents the rpm value
          fill(255);
          text(rpm, 163, 185);
          text("rpm",166,195);
          text((float) time/1000, 30, 230);
          text("time (s)", 30, 240); //displays the time and rpm values
          text(fileName,30,30);
          text("timeR: " + (float) timeRunning/1000, 30, 260);
    
          if (run == false) //displays start button
          {
           strokeWeight(0);
            fill(51,255,51);
           rect(160,320,50,20);
           fill(0);
           text("START",165,332);
    
    
          }
    
          if (run == true) //displays pause button
          {
            strokeWeight(0);
            fill(255,153,51);
           rect(160,320,50,20);
           fill(0);
           text("PAUSE",165,332);
    
          }
    
          strokeWeight(0);
            fill(255,0,0);
           rect(230,320,50,20);
           fill(0);
           text("STOP",235,332);  
    
          if (mousePressed && overRect(160,320,50,20) && debounce) //detects if start/pause button has been pressed
           {
             debounce = false;
             if (run == false)
               run = true;
             else if (run == true)
               run = false;
            }
    
          if (mousePressed && overRect(230,320,50,20) && debounce)
          {
            stop = true;
          }
    
          if (rowCount >= table.getRowCount()) //end program when end of file is reached
          {
            stop = true;
          }
      }
    
      else if (stop == true)
      {
    
        fill(255);
        text("Run finished",150,160);
        stopCount++;
        if (stopCount >= 500)
          exit();
      }
    }
    
    boolean overRect(int x, int y, int width, int height) //checks to see if the mouse is over the defined rectangle
    {
      if (mouseX >= x && mouseX <= x+width && 
          mouseY >= y && mouseY <= y+height) {
        return true;
      } 
      else 
      {
        return false;
      }
    }
    
    void nextRow() //loads data from the next row in the table
    {
      TableRow row = table.getRow(rowCount);
      time = row.getInt("time");
      if (time <= timeRunning) //loads new rpm if we have reached that time
      {
        rpm = row.getInt("rpm"); 
        rowCount++;
      }
      if(time + timeResolution < timeRunning) //catches up if it falls behind
      {
         rowCount++; 
         println(rowCount);
      }
    
    }
    
    void mouseReleased() //ensures mouse is released before it can be pressed again
    {
       debounce = true; 
    }
    
    void update(int x) //updates output to arduino
    {
      //Calculate servo postion from mouseX
      xpos= x/2;
      ypos = y/2;
      //Output the servo position ( from 0 to 180)
      port.write(xpos+"x");
      port.write(ypos+"y");
    }
    
  • Move a servo motor (Ax-12) with arduino, processing and kinect

    I will suggest to drop the frameRate of processing to maybe 1 or 2 to start, as you have a delay of 1000 in your arduino code.

    Now, you said that your arduino works well by itself.

    When I tried only with the Arduino moving randomly the servo it worked perfectly

    This was done arduino+processing or you introduced the random numbers in the ino code? I suggest you run a simple sketch of processing +arduino.

    Notice that Arduino will read a byte (check here), a value from 0 to 255. However, you are sending a value of 0 to 360. This is not the main problem in your code right now but you will need to tackle it sooner or later.

    Kf

  • Move a servo motor (Ax-12) with arduino, processing and kinect

    Hey guys,

    I'm having a problem with my code. I wanna move a Dynamixel servo according to the movement of a person, using kinect and processing. When I tried only with the Arduino moving randomly the servo it worked perfectly, but when I try with processing+kinect it doesnt move at all. I'm gonna appreciate any help :) Oh and I'm new at this... so correct me please if y'all find dumb mistakes :P

    Arduino code:

    #include <DynamixelSerial.h>
    int angulo=0;
    
    void setup() {
      Dynamixel.begin(1000000, 2); // Inicialize the servo at 1Mbps and Pin Control 2
      Serial.begin(9600);
    }
    
    void loop() {
    
      if (Serial.available() > 0) {
      // get incoming byte:
      angulo=Serial.read();
      }
    
      Dynamixel.ledStatus(1, ON);
      Dynamixel.move(1,angulo);
    
      delay(1000);
    
    
    }
    

    Processing code:

    import SimpleOpenNI.*;
    import processing.serial.*;
    import cc.arduino.*;
    Arduino arduino;
    int pos=0;
    Serial myPort;
    
    SimpleOpenNI context;
    color[] userClr = new color[] { 
      color(255, 0, 0), 
      color(0, 255, 0), 
      color(0, 0, 255), 
      color(255, 255, 0), 
      color(255, 0, 255), 
      color(0, 255, 255)
    };
    PVector com = new PVector(); 
    PVector com2d = new PVector();
    
    void setup() {
      size(640, 480);
      println(Serial.list());
      String portName = Serial.list()[1];
      myPort = new Serial(this, portName, 9600);
      //arduino = new Arduino(this, Arduino.list()[1], 9600); //your offset may vary
      //arduino.pinMode(2);
      context = new SimpleOpenNI(this);
      if (context.isInit() == false) {
        println("Can't init SimpleOpenNI, maybe the camera is not connected!"); 
        exit();
        return;
      }
      // enable depthMap generation 
      context.enableDepth();
      // enable skeleton generation for all joints
      context.enableUser();
      context.enableRGB();
      background(200, 0, 0);
      stroke(0, 0, 255);
      strokeWeight(3);
      smooth();
    }
    
    void draw() {
      // update the cam
      context.update();
      // draw depthImageMap
      //image(context.depthImage(),0,0);
      image(context.userImage(), 0, 0);
      // draw the skeleton if it's available
      int[] userList = context.getUsers();
      for (int i=0; i<userList.length; i++) {
        if (context.isTrackingSkeleton(userList)) {
          stroke(userClr[ (userList - 1) % userClr.length ] );
          drawSkeleton(userList);
        }
      }
    }
    
    
    
    // draw the skeleton with the selected joints
    void drawSkeleton(int userId) {
    
    
      // aqui é definido qual parte do corpo vai rastrear
      PVector jointPos = new PVector();
      context.getJointPositionSkeleton(userId, SimpleOpenNI.SKEL_HEAD, jointPos);
      PVector convertedHead = new PVector();
      context.convertRealWorldToProjective(jointPos, convertedHead);
      //desenhar uma elipse sobre a parte do corpo rastreada
      fill(255, 0, 0);
      ellipse(convertedHead.x, convertedHead.y, 20, 20);
    
      //draw YOUR Right Shoulder
      PVector jointPosLS = new PVector();
      context.getJointPositionSkeleton(userId, SimpleOpenNI.SKEL_LEFT_SHOULDER, jointPosLS);
      PVector convertedLS = new PVector();
      context.convertRealWorldToProjective(jointPosLS, convertedLS);
      //int LS = convertedLS.x, convertedLS.y
    
      //draw YOUR Right Elbow
      PVector jointPosLE = new PVector();
      context.getJointPositionSkeleton(userId, SimpleOpenNI.SKEL_LEFT_ELBOW, jointPosLE);
      PVector convertedLE = new PVector();
      context.convertRealWorldToProjective(jointPosLE, convertedLE);
      fill(200, 200, 200);
      ellipse(convertedLE.x, convertedLE.y, 20, 20);
    
    
      //angulooo
      int anguloLSE =int(degrees(atan2(convertedLS.x - convertedLE.x, convertedLS.y - convertedLE.y)));
      println(anguloLSE); 
      myPort.write(anguloLSE);
    
    
    
      //se quiser desenhar o esqueleto inteiro, descomentar as linhas abaixo
      context.drawLimb(userId, SimpleOpenNI.SKEL_HEAD, SimpleOpenNI.SKEL_NECK);
    
      context.drawLimb(userId, SimpleOpenNI.SKEL_NECK, SimpleOpenNI.SKEL_LEFT_SHOULDER);
      context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_SHOULDER, SimpleOpenNI.SKEL_LEFT_ELBOW);
      context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_ELBOW, SimpleOpenNI.SKEL_LEFT_HAND);
    
      context.drawLimb(userId, SimpleOpenNI.SKEL_NECK, SimpleOpenNI.SKEL_RIGHT_SHOULDER);
      context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_SHOULDER, SimpleOpenNI.SKEL_RIGHT_ELBOW);
      context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_ELBOW, SimpleOpenNI.SKEL_RIGHT_HAND);
    
      context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_SHOULDER, SimpleOpenNI.SKEL_TORSO);
      context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_SHOULDER, SimpleOpenNI.SKEL_TORSO);
    
      context.drawLimb(userId, SimpleOpenNI.SKEL_TORSO, SimpleOpenNI.SKEL_LEFT_HIP);
      context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_HIP, SimpleOpenNI.SKEL_LEFT_KNEE);
      context.drawLimb(userId, SimpleOpenNI.SKEL_LEFT_KNEE, SimpleOpenNI.SKEL_LEFT_FOOT);
    
      context.drawLimb(userId, SimpleOpenNI.SKEL_TORSO, SimpleOpenNI.SKEL_RIGHT_HIP);
      context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_HIP, SimpleOpenNI.SKEL_RIGHT_KNEE);
      context.drawLimb(userId, SimpleOpenNI.SKEL_RIGHT_KNEE, SimpleOpenNI.SKEL_RIGHT_FOOT);
    }
    
    // -----------------------------------------------------------------
    // SimpleOpenNI events
    
    
    void onNewUser(SimpleOpenNI curContext, int userId)
    {
      println("onNewUser - userId: " + userId);
      println("\tstart tracking skeleton");
    
      curContext.startTrackingSkeleton(userId);
    }
    
    void onLostUser(SimpleOpenNI curContext, int userId)
    {
      println("onLostUser - userId: " + userId);
    }
    
    void onVisibleUser(SimpleOpenNI curContext, int userId)
    {
      //println("onVisibleUser - userId: " + userId);
    }
    void keyPressed()
    {
      switch(key)
      {
      case ' ':
        context.setMirror(!context.mirror());
        break;
      }
    }
    
  • correct value is not sent to arduino from processing for servo -where is the error in my code?

    I am trying to control servo by sending values from processing to arduino but whatever value i send within 0 to 180 degree it rotates only 90 degree,after first time 90 degree rotation it stood still...even if i run the code again then also......

    Arduino Code:

    String data;
    #include <Servo.h>`> `
    Servo myservo;        
            int i = 0;
    
    void setup() {
      Serial.begin(9600);
      myservo.attach(9); 
    }
    
    void loop() {
      if(Serial.available())
      {
       char c = Serial.read();
        if(c == '\n')
        {
        parseCommand(data);
        data = "";
        }
         else
          {
            data += c;
    
          }
    }
    }
    void parseCommand(String data1)
    {
      String X;
      X = data1;
      int pos = X.toInt();
    
      for(i = 0; i<=pos; i += 1)
      {
        myservo.write(i);
      }
      Serial.println("X:"+X); 
    }
    

    if i send values from the serial monitor of arduino then it works perfectly.

    Processing code:

    import processing.serial.*;
    Serial myPort;
    
    void setup(){
    size(300, 300);
    myPort = new Serial(this, "COM4", 9600);
    
    }
    
    void draw(){
    int c = 45;
    myPort.write(c);
    delay(3000);
    
    }**
    

    this is the processing code..i'm changing the c value every time i run the code but it rotates 90.for one time only if its positon is 0 deg or less than 90 deg.

    please help me to figure the problem out....

  • Reading multiple values in processing > Help needed!
    • First image is TRUE

    • When the photoresistor value is between 2 value s: First image is FALSE
      Then a ball is displayed and moves

    • When the ball is on top of the screen:
      A second image is TRUE

    • When you click a push button:
      A servo turns and the second image is FALSE.

    • Servo done?:
      After that the first image becomes TRUE again

    Base on the layout of your code, you should consider using states in your program. Think of every state as a page. When you are done the state, you flip the page. This next post provides an example code using pages: https://forum.processing.org/two/discussion/558/creating-a-next-page-button

    This means you will need to drop the boolean values in processing and change to using a single int field to keep track of the current page.

    final int PAGE0=0;
    final int PAGE1=1;
    final int PAGE2=2;
    final int NPAGES=PAGE2+1;
    
    int currentPage;
    
    void setup(){
        currentPage=PAGE0;
    }
    
    void draw(){
    
        if(currentPage==PAGE0){
    
        } else if(currentPage==PAGE1){
    
        }else if(currentPage==PAGE2){
    
        }    
    }
    
    void mycustomEvent(){  //Serial,keyEvent, mouseEvent, etc...
        currentPage++;
        currentPage=(currentPage+1)%NPAGES;  //Ensures values stays in range 0 to n.
    }
    

    Kf

  • Reading multiple values in processing > Help needed!

    Hello,

    For a school project i’m making an interactive installation where you can make a digital ball go higher with a sensor. I’m trying to make this work with processing and Arduino. Several things are working, but for some reason i can’t combine everything to one smooth proces. I think this is because i try to read two different sensor values.

    The steps that i want: - First image is TRUE - When the photoresistor value is between 2 values, First image is FALSE - Then a ball is displayed - When the ball is on top of the screen, a second image is TRUE - When you click a push button a servo turns and the second image is FALSE. After that the first image becomes TRUE again

    All of this is working, except for the photoresistor and push button part. For now it works when you press DOWN or ENTER.

    I really hope someone can help me with this. I can provide additional information if needed.

    The scripts i’m using now:

    PROCESSING: import processing.serial.*; // import the Processing serial library

            Serial FirstArduino;
            float yTrim, gFill;
            Ball ball1;
    
            PImage a;
            PImage b;
            PImage c;
            boolean welcome = true;
            boolean corner = false;
    
            void setup() {
              fullScreen();
              smooth();
              noStroke();
              background(0);
              a = loadImage("ball.png");
              b = loadImage("1scannen.png");
              c = loadImage("2balweg.png");
    
              ball1 = new Ball (600, 0);
              ball1.initialiseBall();
              FirstArduino = new Serial(this, "/dev/tty.usbmodem1421",9600);
              // read incoming bytes to a buffer
              // until you get a linefeed (ASCII 10):
              FirstArduino.bufferUntil('\n');
            }
    
            void draw() {
              fill(0, 0, 0, height);
              rect(0, 0, width, height);
              ball1.run();
              if (welcome) image(b, 0, 0, width, height);
              if (corner) image(c, 0, 0, width, height);
    
            }
    
            void serialEvent(Serial myPort) {
              // read the serial buffer:
              String myString = FirstArduino.readStringUntil('\n');
              if (myString != null) {
                myString = trim(myString);
    
                // split the string at the commas
                // and convert the sections into integers:
                int sensors[] = int(split(myString, ','));
                //Next, print out those three integers using a for() loop, like so:
    
                for (int sensorNum = 1; sensorNum < sensors.length; sensorNum++) {
                  // print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t");
                }
    
                // add a linefeed at the end:
                //println();
                // make sure you've got all three values:
                if (sensors.length > 1) {
                  gFill= sensors[1];
                  yTrim = 750-sensors[1]*8.5;
                  yTrim += (0);
                }
    
                  if (keyCode == DOWN) {
                  welcome = false;
    
                }
    
                if (v1.y < 0) {
                  corner = true;
                }
    
                    if (keyCode == ENTER) {
                  corner = false;
                  welcome = true;
                }
              }
    
            }
    

    ARDUINO:

        #include <Servo.h>
                    Servo myservo;  // create servo object to control a servo
                    // twelve servo objects can be created on most boards
    
                    int pos = 0;    // variable to store the servo position
                    int sensorPin = A0;
                    int servoPin = 9; 
                    int pushPin = 2;   // choose the input pin (for a pushbutton)
                    int lowThreshold = 450;
                    int highThreshold = 150;
                    int sensorValue = 0;
                    int val;    // variable to read the value from the analog pin
                    int ldrValue;
                    int ldrPin = 3;      // photoresistor pin
    
                    void setup() {
                       Serial.begin(9600);            // Start serial communication at 9600 bps
                       pinMode(sensorPin, INPUT);
                       pinMode(servoPin, OUTPUT);
                       pinMode(pushPin, INPUT);    // declare pushbutton as input
                       digitalWrite(sensorPin, LOW);
                       digitalWrite(servoPin, LOW);
                       myservo.attach(9);  // attaches the servo on pin 9 to the servo object
                    }
    
                    void loop() {
                      for (int thisSensor = 0; thisSensor < 2; thisSensor++) {
                        int sensorValue = analogRead(thisSensor) / 3;
                        Serial.print(sensorValue);
                        // if you're on the last sensor value, end with a println()
                        // otherwise, print a comma
                        if (thisSensor == 1) {
                        Serial.println();
                      } else {
                        Serial.print(",");
                          }
                        }
    
                        myservo.write(0);
                        val = digitalRead(pushPin);  // read input value
                        if (val == HIGH) {         // check if the input is HIGH (button released)
                          delay(500);
                          for (pos = 0; pos < 180; pos += 1) // goes from 0 degrees to 180 degrees
                          { // in steps of 1 degree
                            myservo.write(180);              // tell servo to go to position in variable 'pos'
                            delay(1);                       // waits 15ms for the servo to reach the position
                          }
                          delay(300);
                          for (pos = 180; pos >= 1; pos -= 1) // goes from 180 degrees to 0 degrees
                          {
                            delay(1);                       // waits 15ms for the servo to reach the position
                            myservo.write(0);              // tell servo to go to position in variable 'pos'
                          }
                        } else {
                        }
    
                      ldrValue = analogRead(A3)/4; 
                      Serial.println(ldrValue);  // Send the value
                      delay(100);  // Wait 100ms for next reading
                    }
    

    Thanks in advance!

  • how to control 20 RC servo motors using Arduino mega

    pwm expander??

    You can explain it better. Why not use your serial word?

  • Remove objects with many CP5 controllers

    Here's an example code using the ArrayList for flexibility.

            import controlP5.*;
                ControlP5 gui;
    
            ArrayList<SvoPkg> layout;
            int pkgTot = 3;
    
            void setup() {
              size (550, 200);
              gui = new ControlP5(this);
              layout = new ArrayList<SvoPkg>();
            gui.addBang ("Set")
                .setPosition(width*.8, height*.7)
                .setSize(40, 30)
                ;
            gui.addBang ("Kill")
                .setPosition(width*.9, height*.7)
                .setSize(40, 30)
                ;
            for (int j=0; j<pkgTot; j++) {
                String namJ = "Tog"+(j+1);
                makeTog(namJ, j, .8);
              }
            }
            void draw() {
              background(190, 130, 30);
            }
            Toggle makeTog(String togNam, int togNum, float vertPos) {
              return gui.addToggle(togNam)
                .setValue(1)
                .setPosition((width*.05+(60*togNum)), height*(vertPos))
                .setSize(20, 20)
                ;
            }
            void Set() {
              for (int i=0; i<pkgTot; i++) {
                String namI = "Tog"+(i+1);
                float state = gui.get(Toggle.class, namI).getValue();
                if (state == 1) {        
                  layout.add(new SvoPkg(this, 20+(175*i), 30));
                }
              }
            }
            void Kill() {
               for (int i=0;i<layout.size();i++){
                   layout.get(i).gui.hide();
              } 
             layout.clear();
            }
    class SvoPkg {
      PApplet app;
      ControlP5 gui;
    
    SvoPkg(PApplet papp, float tempX, float tempY){
     app = papp;
     gui = new ControlP5(papp);
    
    gui.addSlider("Angle")
       .setPosition(tempX+15, tempY+ 15)
       .setSize(100, 10)
       .setRange(600,2400)
    .plugTo(this,"setValue")
       ;
    gui.addSlider("Speed")
      .setPosition(tempX+15, tempY + 30)
      .setSize(100, 10)
      .setRange(50,1000)
      ;
     }
    }
    

    I plan on a toggle (Tog) for each servo, and this method seems to work pretty well for me so far. My next step is to integrate the two bangs into one, so I when the "set" bang is hit, any checked toggles will produce a corresponding slider package, and if not, the sliders will be removed.

  • Remove objects with many CP5 controllers

    Hello, I'm rather new to Processing, so please bear with me. I am writing code to allow me to control multiple servos with two CP5 sliders. I hope to make it variable, allowing for a pair for each servo attached. I have made a class for the slider pairs (SvoPkg), and have no issues using a bang to call them up. However, I'm stuck on how to make them disappear. I'm using an ArrayList to call the object, but remove() will only clear the List, not the objects on screen. Similarly, since the sliders are nested in an object, I can't seem to remove them piecemeal using .getController().remove() either (I get a Static/non-static error). I've tried using the draw() function to add the object to better update the screen when the List is cleared, but that won't work because the sliders aren't usable anymore -the draw loop make them essentially a picture and immobile. I'd like to basically have a remove() function for the object (like CP5 has for its individual controllers), but don't quite know how to implement one.

    Here is a dumbed-down version of the code; for clarity's sake I'm just using one Package and have altered the position data. Right now, I'm trying to just use one bang to make the object, and the other to remove it.

        import controlP5.*;
        ControlP5 gui;
    
        ArrayList<SvoPkg> layout;
        int PkgTot = 1;
    
        void setup(){
          size (300, 150);
        gui = new ControlP5(this);
          layout = new ArrayList<SvoPkg>();
          fill(230,170,90);
    
        gui.addBang ("Make")
          .setPosition(200,95)
          .setSize(40,30)
          ;
        gui.addBang ("Kill")
          .setPosition(250,95)
          .setSize(40,30)
          ;
        }
        void draw(){
         background(190,130,30);
            }
    
        void Make(){
          for(int i=0; i<PkgTot;i++){
              layout.add(new SvoPkg(this, 20, 30));
             }     
         }
         void kill(){ //I've left this blank for now, but is where I'd like to remove the object
         }
    
         class SvoPkg {
          PApplet app;
          ControlP5 Objgui;
    
        SvoPkg(PApplet papp, float Xpos, float Ypos){
         app = papp;
         Objgui = new ControlP5(papp);
    
        Objgui.addSlider("Angle")
           .setPosition(Xpos+15, Ypos+ 15)
           .setSize(120, 10)
           .setRange(600,2400)
           ;
        Objgui.addSlider("Speed")
          .setPosition(Xpos+15, Ypos + 30)
          .setSize(120, 10)
          .setRange(50,1000)
          ;
        }
        }
    

    Thanks for your input

  • Lighting up an LED from Processing to Arduino

    This is my Arduino Code:

     #include <Servo.h>  //Used to control the Pan/Tilt Servos
        int GreenLED = 13;
        int RedLED = 12;
        //These are variables that hold the servo IDs.
        char tiltChannel=0, panChannel=1;
    
        //These are the objects for each servo.
        Servo servoTilt, servoPan;
    
        //This is a character that will hold data from the Serial port.
        char serialChar=0;
    
    
        void setup(){
          servoTilt.attach(5);  //The Tilt servo is attached to pin 2.
          servoPan.attach(3);   //The Pan servo is attached to pin 3.
          servoTilt.write(15);  
          servoPan.write(45);    
    
    
          Serial.begin(57600);  //Set up a serial connection for 57600 bps.
        }
    
        void loop(){
          while(Serial.available() <=0);  //Wait for a character on the serial port.
          serialChar = Serial.read();     //Copy the character from the serial port to the variable
          if(serialChar == tiltChannel){  //Check to see if the character is the servo ID for the tilt servo
            while(Serial.available() <=0);  //Wait for the second command byte from the serial port.
            servoTilt.write(Serial.read());  //Set the tilt servo position to the value of the second command byte received on the serial port
          }
          else if(serialChar == panChannel){ //Check to see if the initial serial character was the servo ID for the pan servo.
            while(Serial.available() <= 0);  //Wait for the second command byte from the serial port.
            servoPan.write(Serial.read());   //Set the pan servo position to the value of the second command byte received from the serial port.
          }
        }
    
  • Lighting up an LED from Processing to Arduino

    My project is a face tracking webcam and I want it to turn on an LED whenever it recognizes a face but can not figure out the if statement to accomplish this. My Processing code is as follows. Any help would be greatly appreciated.

    import hypermedia.video.*;  //Include the video library to capture images from the webcam
    import java.awt.Rectangle;  //A rectangle class which keeps track of the face coordinates.
    import processing.serial.*; //The serial library is needed to communicate with the Arduino.
    
    OpenCV opencv;  //Create an instance of the OpenCV library.
    
    //Screen Size Parameters
    int width = 320;
    int height = 240;
    
    // contrast/brightness values
    int contrast_value    = 0;
    int brightness_value  = 0;
    
    Serial port; // The serial port
    
    //Variables for keeping track of the current servo positions.
    char servoTiltPosition = 90;
    char servoPanPosition = 90;
    //The pan/tilt servo ids for the Arduino serial command interface.
    char tiltChannel = 0;
    char panChannel = 1;
    
    //These variables hold the x and y location for the middle of the detected face.
    int midFaceY=0;
    int midFaceX=0;
    
    //The variables correspond to the middle of the screen, and will be compared to the midFace values
    int midScreenY = (height/2);
    int midScreenX = (width/2);
    int midScreenWindow = 10;  //This is the acceptable 'error' for the center of the screen. 
    
    //The degree of change that will be applied to the servo each time we update the position.
    int stepSize=1;
    
    void setup() {
      //Create a window for the sketch.
      size( width, height );
    
      opencv = new OpenCV( this );
      opencv.capture( width, height );                   // open video stream
      opencv.cascade( OpenCV.CASCADE_FRONTALFACE_ALT );  // load detection description, here-> front face detection : "haarcascade_frontalface_alt.xml"
    
      println(Serial.list()); // List COM-ports (Use this to figure out which port the Arduino is connected to)
    
      //select first com-port from the list (change the number in the [] if your sketch fails to connect to the Arduino)
      port = new Serial(this, Serial.list()[0], 57600);   //Baud rate is set to 57600 to match the Arduino baud rate.
    
      // print usage
      println( "Drag mouse on X-axis inside this sketch window to change contrast" );
      println( "Drag mouse on Y-axis inside this sketch window to change brightness" );
    
      //Send the initial pan/tilt angles to the Arduino to set the device up to look straight forward.
      port.write(tiltChannel);    //Send the Tilt Servo ID
      port.write(servoTiltPosition);  //Send the Tilt Position (currently 90 degrees)
      port.write(panChannel);         //Send the Pan Servo ID
      port.write(servoPanPosition);   //Send the Pan Position (currently 90 degrees)
    }
    
    
    public void stop() {
      opencv.stop();
      super.stop();
    }
    
    
    
    void draw() {
      // grab a new frame
      // and convert to gray
      opencv.read();
      opencv.convert( GRAY );
      opencv.contrast( contrast_value );
      opencv.brightness( brightness_value );
    
      // proceed detection
      Rectangle[] faces = opencv.detect( 1.2, 2, OpenCV.HAAR_DO_CANNY_PRUNING, 40, 40 );
    
      // display the image
      image( opencv.image(), 0, 0 );
    
      // draw face area(s)
      noFill();
      stroke(255,0,0);
      for( int i=0; i<faces.length; i++ ) {
        rect( faces[i].x, faces[i].y, faces[i].width, faces[i].height );
      }
    
      //Find out if any faces were detected.
      if(faces.length > 0){
        //If a face was found, find the midpoint of the first face in the frame.
        //NOTE: The .x and .y of the face rectangle corresponds to the upper left corner of the rectangle,
        //      so we manipulate these values to find the midpoint of the rectangle.
        midFaceY = faces[0].y + (faces[0].height/2);
        midFaceX = faces[0].x + (faces[0].width/2);
    
        //Find out if the Y component of the face is below the middle of the screen.
        if(midFaceY < (midScreenY - midScreenWindow)){
          if(servoTiltPosition >= 5)servoTiltPosition += stepSize; //If it is below the middle of the screen, update the tilt position variable to lower the tilt servo.
        }
        //Find out if the Y component of the face is above the middle of the screen.
        else if(midFaceY > (midScreenY + midScreenWindow)){
          if(servoTiltPosition <= 175)servoTiltPosition -=stepSize; //Update the tilt position variable to raise the tilt servo.
        }
        //Find out if the X component of the face is to the left of the middle of the screen.
        if(midFaceX < (midScreenX - midScreenWindow)){
          if(servoPanPosition >= 5)servoPanPosition -= stepSize; //Update the pan position variable to move the servo to the left.
        }
        //Find out if the X component of the face is to the right of the middle of the screen.
        else if(midFaceX > (midScreenX + midScreenWindow)){
          if(servoPanPosition <= 175)servoPanPosition +=stepSize; //Update the pan position variable to move the servo to the right.
        }
    
      }
      //Update the servo positions by sending the serial command to the Arduino.
      port.write(tiltChannel);      //Send the tilt servo ID
      port.write(servoTiltPosition); //Send the updated tilt position.
      port.write(panChannel);        //Send the Pan servo ID
      port.write(servoPanPosition);  //Send the updated pan position.
      delay(1);
    }
    
    
    
    /**
     * Changes contrast/brigthness values
     */
    void mouseDragged() {
      contrast_value   = (int) map( mouseX, 0, width, -128, 128 );
      brightness_value = (int) map( mouseY, 0, width, -128, 128 );
    }
    
  • Sending Serial Data From Processing to arduino to test reliability?

    @kloud

    Unfortunately I don't have any more ideas without checking the documentation. I suggest you explore the links they provide in the response on this question: http://stackoverflow.com/questions/16874096/firmata-servo-control

    Also I found this following link useful : https://www.arduino.cc/en/reference/firmata

    However, I am not sure if it applies to the Servo case because i don't know if you are allowed to read from it. Because you are using firmata, I don't think you can get an event response as discussed in this post. Maybe maybe if you areable to set an event callback as described in the previous link....

    Also explore this example: https://github.com/firmata/arduino/tree/master/examples/ServoFirmata

    Kf

  • Checking Whether Button Was Pressed or not?

    For this part of the code I am shooting in the dark. The reason are:

    • I don't know how your servo operates
    • I don't have experience with firmatta
    • I am not able to test your code

    Btw, what is Servo4.getValue()? Is that a controlP5 object?

    Notice you are writing to your servo in draw. When you do that in testing mode (what you are doing now), you have not control of these events as they are happening 30 or even 60fps. I suggest this instead:

    void draw(){}
    
    void keyReleased(){
      background(color(51,102,153));                    
      text("Sending Servo Data: "+ServoValue,360,680);   
      arduino.servoWrite(4, int(Servo4.getValue())); 
    }
    

    Which means the servo makes a movement then goes back to its original position. But the text("Servo data", +ServoValue, 360, 480) function on the processing window for the ServoValue only displays the default, it does not show +15 then -15

    If Servo4 is a controlP5, then you need to update the value of the value field:

    ServoValue = int(Servo4.getValue()+15);
    Servo4.setvalue(ServoValue);
    

    Please notice that it is customary to write the first letters of variables and instantiated objects in lower case: servoValue, servo4 instead of ServoValue, Servo4. For classes, the first letter is always capital: class MyCustomObkect {}.

    If I were you, I will be more interested to know if my servo does what it suppose to do. For example, if you write to it, does it turn consistently? Does it go back and forth? For example, check the code below. Use the left/right arrow keys to issue turn commands to your servo.

    Kf

    import processing.serial.*;          //imports serail library
    import cc.arduino.*;                 //imports arduino library so I don't have to use arduino IDE
    
    final int kStep=45;  //Increment step
    
    Arduino arduino;
    int svalue;
    
    void setup() 
    {
      size(950, 900);
      textAlign(CENTER,CENTER);
      fill(255);
                                   //sends data to serial port for arduino
      arduino = new Arduino(this, Arduino.list()[0], 57600);    //sets COMM Port Baud Rate 
      arduino.pinMode(3, Arduino.SERVO);
      svalue=0;
    
    }
    
    void draw() {
      background(0);
      text("Current value "+svalue,width/2,height/2);  
    }
    
    void keyReleased() {
    
      if(key == CODED){
        if(keyCode==RIGHT){
          svalue+=kStep;
        }
        if(keyCode == LEFT){
          svalue-=kStep;
        }
      }
    
      arduino.servoWrite(3, svalue);
    
    }
    
  • Checking Whether Button Was Pressed or not?

    Ah ok. And kfajer, I edited your function, to this:

                int ServoValue=0;
                   public void controlEvent(ControlEvent theEvent) {`  
                      if (setupDone==false)
                        return;
    
                      println(theEvent.getController().getName());        
    
                      if (theEvent.getController().getName().equals("Push Button")){
    
                           ServoValue = int(Servo4.getValue()+15); 
    
                           arduino.servoWrite(4,ServoValue); 
    
    
    
                           delay(3000);
    
                           ServoValue = ServoValue-15; 
                           arduino.servoWrite(4,ServoValue); 
    
                      }
                }
    

    and my issue is in my void draw, I have

    void draw()
            {
    
    
             background(color(51,102,153));                    
    
    
               text("Sending Servo Data: "+ServoValue,360,680);  
    
              arduino.servoWrite(4, int(Servo4.getValue())); 
            }
    

    which based on the control event function, it outputs the value of ServoValue. Now ServoValue changes from +15 of whatever position my Servo4 is at, then -15. Which means the servo makes a movement then goes back to its original position. But the text("Servo data", +ServoValue, 360, 480) function on the processing window for the ServoValue only displays the default, it does not show +15 then -15 of whatever value my ServoValue is at?

    I even used println(), and on the console ServoValue changes, but not on the processing window that shows up.