Using millis instead of delay

The function delay pauses the program for the amount of time (in milliseconds) specified as parameter.  This can make your project a bit confusing sometimes, especially when you use it in Processing. As an advice, never use delay function in Processing.

Below a sample code you can use in Arduino:

int period = 5000;
long time_now = 0;
 
void setup() {
    Serial.begin(9600);
}
 
void loop() {
    if(millis() >= time_now + period){
        time_now += period;
        Serial.println("Hello");
    }
   
    //Run other code
}

If you are using Processing the code will be this:

int period = 5000;
long time_now = 0;
 
void setup() {
}
 
void draw() {
    if(millis() >= time_now + period){
        time_now += period;
        println("Hello");
    }
   
    //Run other code
}

this tutorial is based on this website:

Arduino Tutorial: Using millis() Instead of delay()

 

How to fix cursor location in Windows

This is the post on how to fix the cursor located in the wrong place in Processing 4 for Windows. 

  1.  Open the file location where processing.exe is, right click on the processing.exe, open Properties.
  2. Go to the Compatibility tab.
  3. Click Change settings for all users > Change High DPI settings.
  4. In the High DPI scaling override, select System(Enhanced) and apply it.

Serial Communication

In this tutorial:

  1. Arduino To Processing
  2. Processing to Arduino
  3.  Read and Write – Full Duplex (Arduino and Processing are both sending and receiving data) 

Download all the code here or review it on Github.


1. Arduino To Processing

1.1. Arduino To Processing: Arduino Example Code:

Start the communication using Serial.begin

void setup() {
  Serial.begin(9600);
}

First, we will create variables for storing the values from each sensor. In the next example we are using three sensors connected to three different analog pins, so we use analogRead, but if we were reading values from a button, we should use digitalRead instead. It will depend on what type of sensor you are using, so change the code accordingly.

void loop() {
  // to send values to Processing assign the values you want to send
  //this is an example
  int sensor1 = analogRead(A0);
  int sensor2 = analogRead(A1);
  int sensor3 = analogRead(A2);

Next, we need to find a way to send multiple values and get Processing know each one of them and when to replace them for updated values. The way we are going to do it is to send them as a String of values separated by a comma. When we finish sending all the sensor values we will finish with a linefeed, so Processing will know that now it’s time to replace the values for the new ones coming. 

  // send the values keeping this format
  Serial.print(sensor1);
  Serial.print(",");  // put comma between sensor values
  Serial.print(sensor2);
  Serial.print(",");  // put comma between sensor values
  Serial.print(sensor3);
  Serial.println(); // add linefeed after sending the last sensor value

Finally, we might need to add a delay, but it will depend on the sensors you are using in your project.

  // too fast communication might cause some latency in Processing
  // this delay resolves the issue.
  delay(100);
}

1.2. Arduino To Processing:  Processing Example Code:

Start the code by adding the Processing Serial Library

import processing.serial.*;

Define the number of sensor values you will be receiving from Arduino and create an array to store these values. In this example we are receiving three values, so NUM_OF_VALUES = 3.

int NUM_OF_VALUES_FROM_ARDUINO = 3;   /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/
int sensorValues[];      /** this array stores values from Arduino **/

We will create a new String to receive the values from Arduino, this String is the one written like:
sensorValueOne, sensorValueTwo, sensorValueThree
At the end of this line there will be a line feed we will identify and replace the previous String with the new one. We will also split the values when we see a comma.

String myString = null;

Create the serial port

Serial myPort;

Start your setup code as you wish. You must include in the setup a function called setupSerial() that will contain the code to start the communication with Arduino. You will need to set the function up by defining the port number your computer gives to your USB port. 

void setup() {
  setupSerial();
}

So go down to the setupSerial() function:

void setupSerial() {
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[ PORT_INDEX ], 9600);
  // WARNING!
  // You will definitely get an error here.
  // Change the PORT_INDEX to 0 and try running it again.
  // And then, check the list of the ports,
  // find the port "/dev/cu.usbmodem----" or "/dev/tty.usbmodem----" 
  // and replace PORT_INDEX above with the index number of the port.

  myPort.clear();
  // Throw out the first reading,
  // in case we started reading in the middle of a string from the sender.
  myString = myPort.readStringUntil( 10 );  // 10 = '\n'  Linefeed in ASCII
  myString = null;

  sensorValues = new int[NUM_OF_VALUES_FROM_ARDUINO];
}

Now replace “PORT_INDEX” by a number 0, like this:

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

Next, run the code and find in the console the list of ports your computer has. Choose the USB port, for example 1 or 3 in this case:

Change the PORT_INDEX accordingly. In this example your line would be:

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

But again, this depends on everyone’s computer, so find your own number.
Now your Processing sketch is connected with Arduino.

In the draw loop we will use a function called getSerialData() to update the sensor values as they change.

void draw() {
  getSerialData();
}

Remember that the values from the sensors are stored in an array of variables and these variables will be filled with data according to the information we get from Arduino. In this function, we will split the String containing all the sensor values every time there is a comma and we will stop reading the String when we get a line feed (value 10 in ASCII code).  We will also print to the console the values we are receiving from Arduino.
Note: If you want to know why we are using trim, check this out.

void getSerialData() {
  while (myPort.available() > 0) {
    myString = myPort.readStringUntil( 10 ); // 10 = '\n'  Linefeed in ASCII
    if (myString != null) {
      String[] serialInArray = split(trim(myString), ",");
      if (serialInArray.length == NUM_OF_VALUES_FROM_ARDUINO) {
        for (int i=0; i<serialInArray.length; i++) {
          sensorValues[i] = int(serialInArray[i]);
        }
      }
    }
  }
}

Finally, write your code and use the values from the sensors knowing that sensorValues[0] is the value from the first sensor, sensorValues[1] is the value from the second sensor, and sensorValues[2] is the value from the third one.

void draw() {
  getSerialData();
  printArray(sensorValues);

  // use the values like this!
  // sensorValues[0] 

  // add your code

  //
}

For example, if you want to draw a circle and change the size of that circle according to the values of the first sensor you are sending from Arduino, your code should look like this:

void draw() {
  getSerialData();
  printArray(sensorValues);
  
  circle(width/2, height/2, sensorValues[0]);
}

You will probably need to map the values according to what you are doing, for example, if the values you are receiving from the sensor correspond to values from a potentiometer, these values are in a range between 0 and 1023, then the size of the circle will grow outside the canvas. So you might want to map the potentiometer values to the minimum size for the circle to the maximum size you want the circle takes. Then, your code could be something like this:

  float size = map(sensorValues[0], 0, 1023, 0, width);
  circle(width/2, height/2, size);

You can now be creative and write the code for your project as you need.


2. Processing To Arduino

2.1 Processing To Arduino: Processing Code:

After opening a new sketch in Processing, the library is needed to be imported. 

import processing.serial.*;

Then we need to define the global variables needed for serial communication. Define the number of values you will be sending to Arduino and create an array to store these values. In this example we are sending three values, so NUM_OF_VALUES_FROM_PROCESSING = 3. 

int NUM_OF_VALUES_FROM_PROCESSING = 3;  /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/
int processing_values[] = new int[NUM_OF_VALUES_FROM_PROCESSING]; /** this array stores values you might want to send to Arduino **/

You will have to create a serial port, under which you will create a new String, just like in the previous example, but in this case to send the values to Arduino. This String is the one written like:
ValueOne, ValueTwo, ValueThree

Serial myPort;
String myString;

Start your setup code as you wish. Change the size accordingly. You must include in the setup a function called setupSerial() that will contain the code to start the communication with Arduino. Do not forget to change the port number in setupSerial function down below. 

void setup() {
  size(500, 500);
  background(0);
  setupSerial();
}

You will find the setupSerial() function below and this is setting up the port of communication, so you have to go down, find it and set up your PORT_INDEX.

void setupSerial() {
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[PORT_INDEX], 9600);
  // WARNING!
  // You will definitely get an error here.
  // Change the PORT_INDEX to 0 and try running it again.
  // And then, check the list of the ports,
  // find the port "/dev/cu.usbmodem----" or "/dev/tty.usbmodem----" 
  // and replace PORT_INDEX above with the index number of the port.

  myPort.clear();
  // Throw out the first reading,
  // in case we started reading in the middle of a string from the sender.
  myString = myPort.readStringUntil( 10 );  // 10 = '\n'  Linefeed in ASCII
  myString = null;

}

To set up the port, first replace “PORT_INDEX” by a number 0, like this:

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

Next, run the code and find in the console the list of ports your computer has. Choose the USB port, for example 1 or 3 in this case:

Change the PORT_INDEX accordingly. In this example your line would be:

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

But again, this depends on everyone’s computer, so find your own number.
Now your Processing sketch is connected with Arduino. 

Finally, write your own code to send values to Arduino.

void draw() {
  background(0);

  // give values to the variables you want to send here
  //change the code according to your project

You will assign values to the array of values, knowing that processing_values[0] is the first value, processing_values[1] is the second value, and processing_values[2] is the third value. The values in this array will be the NUM_OF_VALUES_FORM_PROCESSING you set up at the beginning. In this example NUM_OF_VALUES_FORM_PROCESSING = 3, so the index number of the array goes from 0 to 2.

Let’s see an example. If you would like to control an output like an LED connected to Arduino by checking whether the mouse is pressed you can send 1 or 0 and then turn the LED on when Arduino receives 1 and off when Arduino receives 0. 

    if (mousePressed) {
      processing_values[0] = 1;
    } else {
      processing_values[0] = 0;
    }

Another example, if you would like to control the pitch and duration of a buzzer you can send the values of where the mouse is on the screen. You could use mouseX for controlling the pitch and mouseY to control the duration of the sound. Remember that you will need to map the values either in Processing before you send them, or in Arduino when you get them.

    processing_values[1] = mouseX;
    processing_values[2] = mouseY;

Finally, you need to send the values to Arduino with the function sendSerialData(). Do not delete this line of code from the draw loop!

  sendSerialData();

You will find this function below in your code, make sure you use it. This function will send every value of your array to Arduino and will also print to the console the values you are sending.

void sendSerialData() {
  String data = "";
  for (int i=0; i<processing_values.length; i++) {
    data += processing_values[i];
    //if i is less than the index number of the last element in the values array
    if (i < processing_values.length-1) {
      data += ","; // add splitter character "," between each values element
    } 
    //if it is the last element in the values array
    else {
      data += "\n"; // add the end of data character linefeed "\n"
    }
    
  }
  //write to Arduino
  myPort.write(data);
  print(data); // this prints to the console the values going to arduino 
  
}

2.2 Processing To Arduino: Arduino Code:

First you will define the number of values you are receiving from Processing. In the previous example we are sending 3 values, so NUM_OF_VALUES_FROM_PROCESSING is 3. Change the number 3 according to the number of values you are receiving.

#define NUM_OF_VALUES_FROM_PROCESSING 3    /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/

/** DO NOT REMOVE THESE **/
int tempValue = 0;
int valueIndex = 0;

We will create an array to store the data from Processing. 

int processing_values[NUM_OF_VALUES_FROM_PROCESSING];

Start the communication using Serial.begin.
Add any line of code as your project needs.

void setup() {
  Serial.begin(9600); 
}

For example, if you want to control a LED when you press the mouse, you should add the line pinMode in the setup. For example:

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

In void loop you must include getSerialData. This function will get the values coming from Processing and will place them into the array “values” that we created at the beginning.

void loop() {
  getSerialData();
}

You will find the function getSerialData below in the code. Do not change anything here and make sure you have it in your code!

//receive serial data from Processing
void getSerialData() {
  while (Serial.available()) {
    char c = Serial.read();
    //switch - case checks the value of the variable in the switch function
    //in this case, the char c, then runs one of the cases that fit the value of the variable
    //for more information, visit the reference page: https://www.arduino.cc/en/Reference/SwitchCase
    switch (c) {
      //if the char c from Processing is a number between 0 and 9
      case '0'...'9':
        //save the value of char c to tempValue
        //but simultaneously rearrange the existing values saved in tempValue
        //for the digits received through char c to remain coherent
        //if this does not make sense and would like to know more, send an email to me!
        tempValue = tempValue * 10 + c - '0';
        break;
      //if the char c from Processing is a comma
      //indicating that the following values of char c is for the next element in the values array
      case ',':
        processing_values[valueIndex] = tempValue;
        //reset tempValue value
        tempValue = 0;
        //increment valuesIndex by 1
        valueIndex++;
        break;
      //if the char c from Processing is character 'n'
      //which signals that it is the end of data
      case '\n':
        //save the tempValue
        //this will b the last element in the values array
        processing_values[valueIndex] = tempValue;
        //reset tempValue and valueIndex values
        //to clear out the values array for the next round of readings from Processing
        tempValue = 0;
        valueIndex = 0;
        break;
    }
  }
}

Get creative and write your own code using the elements in the values array. Consider the following example if you would like that when the mouse is clicked, a LED will turn on and a buzzer will play sound. You can control pitch sounds and duration of a buzzer through mouse position.  Notice that we are mapping the values here.

if (processing_values[0] == 1) {
  //turn on an LED when the mouse is pressed
  digitalWrite(13, HIGH);
  // map values from mouseX to frequency from (0 - 500 pixels)
  //to the output pitch range (120 - 1500Hz)
  int f = map(processing_values[1], 0, 500, 120, 1500);
  // map values from mouseY to frequency from (0 - 500 pixels)
  //to the output duration range (10 - 2000 milliseconds)
  int d = map(processing_values[2], 0, 500, 10, 2000);
  // play the pitch:
  tone(8, processing_values[1], processing_values[2]);
  delay(1);        // delay in between reads for stability
  } else {
     digitalWrite(13, LOW);
  }  
  //end of example
}

 


3. Read and Write – Full Duplex
(Arduino and Processing are both sending and receiving data)

3.1 Full Duplex Arduino Code:

Start out by specifying the number of values coming from Processing. 

#define NUM_OF_VALUES_FROM_PROCESSING 2    /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/

/** DO NOT REMOVE THESE **/
int tempValue = 0;
int valueIndex = 0;

We will create an array of values for storing data from Processing. 

int values[NUM_OF_VALUES_FROM_PROCESSING];

In setup, start serial communication with Serial.begin. After that you can write whatever you need in your code according to your project.

void setup() {
  Serial.begin(9600); 
}

For example, if you had an LED and  a DC motor, these would be OUTPUTS and you would use pinMode(pin number, OUTPUT) for each of them. If you would like to have a button, so you can send this information to processing, you should set it up as an INPUT when using pinMode.

void setup() {
  Serial.begin(9600);
  // this block of code is an example of an LED, a DC motor, and a button
    pinMode(13, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(2, INPUT);
  //end example
}

To receive a value from Processing, you must have the function getSerialData(); in void loop. This function will get the values coming from Processing and will place them into the array “values” that we created at the beginning.

void loop() {
  getSerialData();
}

You will find the function getSerialData below in the code. Do not change anything here and make sure you have it in your code!

//receive serial data from Processing
void getSerialData() {
  while (Serial.available()) {
    char c = Serial.read();
    //switch - case checks the value of the variable in the switch function
    //in this case, the char c, then runs one of the cases that fit the value of the variable
    //for more information, visit the reference page: https://www.arduino.cc/en/Reference/SwitchCase
    switch (c) {
      //if the char c from Processing is a number between 0 and 9
      case '0'...'9':
        //save the value of char c to tempValue
        //but simultaneously rearrange the existing values saved in tempValue
        //for the digits received through char c to remain coherent
        //if this does not make sense and would like to know more, send an email to me!
        tempValue = tempValue * 10 + c - '0';
        break;
      //if the char c from Processing is a comma
      //indicating that the following values of char c is for the next element in the values array
      case ',':
        processing_values[valueIndex] = tempValue;
        //reset tempValue value
        tempValue = 0;
        //increment valuesIndex by 1
        valueIndex++;
        break;
      //if the char c from Processing is character 'n'
      //which signals that it is the end of data
      case '\n':
        //save the tempValue
        //this will b the last element in the values array
        processing_values[valueIndex] = tempValue;
        //reset tempValue and valueIndex values
        //to clear out the values array for the next round of readings from Processing
        tempValue = 0;
        valueIndex = 0;
        break;
    }
  }
}

After that in the next example we will first demonstrate how to use received values from Processing. Doing so by allowing the first element (values[0]) from the values array coming from Processing turn the LED on or off. Values[1] will control the speed of the DC motor. You can find more information on how to use the received values from Processing in section 2.2 Processing to Arduino.

//example of using received values
if (processing_values[0] == 1) {
  digitalWrite(13, HIGH);
} else {
  digitalWrite(13, LOW);
}
analogWrite(9, processing_values[1]);
// too fast communication might cause some latency in Processing
// this delay resolves the issue.
delay(10);
//end of example of using received values

At the same time we will send data back to Processing from two sources: a potentiometer and a button. You can find more information on how to send values from Arduino in section 1.1 Arduino to Processing

//example of sending the values to Processing
int sensor1 = analogRead(A0); // a potentiometer
int sensor2 = digitalRead(2); // the button

// send the values keeping this format
Serial.print(sensor1);
Serial.print(",");  // put comma between sensor values
Serial.print(sensor2);
Serial.println(); // add linefeed after sending the last sensor value
// end of example sending values
 
// end of example

3.2 Full Duplex Processing Code:

When you open your new Processing sketch, first you need to import the library used for serial communication.

import processing.serial.*;

Then there will be two variables for storing the number of values: first one to store values from Processing that will be sent to Arduino, the second to receive values from Arduino. In this example, we are telling Processing to expect to send two values to Arduino and to wait for receiving two different set of values from Arduino.

int NUM_OF_VALUES_FROM_PROCESSING = 2;  /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/
int NUM_OF_VALUES_FROM_ARDUINO = 2;  /** YOU MUST CHANGE THIS ACCORDING TO YOUR PROJECT **/

We will create a serial port, under which we will create a new String where we will store the string of values coming from Arduino.

Serial myPort;
String myString;

In the next part, we will create two arrays, one to store the values we will send from Processing (values) and another one to store the values we will receive from Arduino (sensorValues).

int processing_values[]; /** this array stores values you might want to send to Arduino **/
int sensorValues[];      /** this array stores values from Arduino **/

Start the serial communication by using the function setupSerial.

void setup() {
  setupSerial();
}

You will find the setupSerial() function below and this is setting up the port of communication, so you have to go down, find it and set up your PORT_INDEX.

void setupSerial() {
  printArray(Serial.list());
  myPort = new Serial(this, Serial.list()[PORT_INDEX], 9600);
  // WARNING!
  // You will definitely get an error here.
  // Change the PORT_INDEX to 0 and try running it again.
  // And then, check the list of the ports,
  // find the port "/dev/cu.usbmodem----" or "/dev/tty.usbmodem----" 
  // and replace PORT_INDEX above with the index number of the port.

  myPort.clear();
  // Throw out the first reading,
  // in case we started reading in the middle of a string from the sender.
  myString = myPort.readStringUntil( 10 );  // 10 = '\n'  Linefeed in ASCII
  myString = null;

}

To set up the port, first replace “PORT_INDEX” by a number 0, like this:

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

Next, run the code and find in the console the list of ports your computer has. Choose the USB port, for example 1 or 3 in this case:

Change the PORT_INDEX accordingly. In this example your line would be:

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

But again, this depends on everyone’s computer, so find your own number.
Now your Processing sketch is connected with Arduino. 

In the draw loop we will use a function called getSerialData() to update the sensor values as they change.

void draw() {
  getSerialData();
}

Remember that the values from the sensors are stored in an array of variables and these variables will be filled with data according to the information we get from Arduino. In this function, we will split the String containing all the sensor values every time there is a comma and we will stop reading the String when we get a line feed (value 10 in ASCII code). We will also print to the console the values we are receiving from Arduino.
Note: If you want to know why we are using trim, check this out.

void getSerialData() {
  while (myPort.available() > 0) {
    myString = myPort.readStringUntil( 10 ); // 10 = '\n'  Linefeed in ASCII
    if (myString != null) {
      String[] serialInArray = split(trim(myString), ",");
      if (serialInArray.length == NUM_OF_VALUES) {
        for (int i=0; i<serialInArray.length; i++) {
          sensorValues[i] = int(serialInArray[i]);
        }
      }
    }
  }
}

Finally, you must include by the end of the draw loop the function sendSerialData().

void draw() {
  getSerialData();
 //your code here
  sendSerialData();
}

You will find this function below in your code, make sure you use it!
This function will send every value of your array “values” to Arduino and will also print to the console the values you are sending.

void sendSerialData() {
  String data = "";
  for (int i=0; i<processing_values.length; i++) {
    data += processing_valuess[i];
    //if i is less than the index number of the last element in the values array
    if (i < processing_values.length-1) {
      data += ","; // add splitter character "," between each values element
    } 
    //if it is the last element in the values array
    else {
      data += "\n"; // add the end of data character "n"
    }
  }
  //write to Arduino
  myPort.write(data); 
  print("to arduino: "+ data); // this prints to the console the values going to arduino
}

In the example below, we will first use the values coming from Arduino to change the color and size of a circle. Then the code will change the value of values[1] that will control the LED on the Arduino. Notice that we are mapping the values collected from the mouse’s X position and convert it to be compatible with the DC motor range of speed values (0-255).

void draw() {
  background(0);
  //receive the values from Arduino
  getSerialData();

  //use the values from arduino
  //this is an example
    
      //sensorValues[1] are the values from the button
       if (sensorValues[1] == 1) { 
       fill(random(255), random(255), random(255));
       }
       //sensorValues[0] are the values from the potentiometer
       float r = map(sensorValues[0], 0, 1023, 0, width); 
       circle(width/2, height/2, r);
       
       // give values to the variables you want to send here
       //change the code according to your project
       
       if (mousePressed) {
       processing_values[0] = 1;
       } else {
       processing_values[0] = 0;
       }
       processing_values[1] = int(map(mouseX, 0, width, 0, 255));
       
  //end of example
  
  // send the values to Arduino.
  sendSerialData();
}

 

Button: State v.s. Moment

In this tutorial, we will learn two ways of using a button (digital input) to control an LED (digital output). You have learned in class how to turn an LED on by pressing down a button, and off by releasing the button. But sometimes you might not want to hold a button to keep an LED on (if you want it to be on for hours!). How do we press a button to turn a light on, and again to turn it off?

How to detect a moment of a trigger (a key/mouse/button gets pressed) is actually a common issue you might encounter not only in Arduino, but also in other programming circumstances like Processing, Unity, and MaxMSP. Once you understand the logic of the examples below, you will be able to achieve the same goal in other software.

For the two examples below, we will be using the same circuit. Here is a diagram of the circuit that I made with Tinkercad: 

diagram of button controlling LED

You can find the circuit and code of the two examples here in Tinkercad.

Example1 – Push for on, release for off: 
built-in LED at pin 13
built-in LED at pin 13

You have probably learned this example in class — the “Button” example(Arduino>File>Example>Digital>Button) in Arduino shows how to use a button to control the built-in LED on Arduino (digital 13) by synchronising the state of the input and the output. (You can also connect an external LED to digital pin 13, as I did in the diagram above. The external LED will basically behave the same as the built-in one, controlled by the same code that’s controlling the built-in LED.)

/*
  Button

  Turns on and off a light emitting diode(LED) connected to digital pin 13,
  when pressing a pushbutton attached to pin 2.

  The circuit:
  - LED attached from pin 13 to ground
  - pushbutton attached to pin 2 from +5V
  - 10K resistor attached to pin 2 from ground

  - Note: on most Arduinos there is already an LED on the board
    attached to pin 13.

  created 2005
  by DojoDave <http://www.0j0.org>
  modified 30 Aug 2011
  by Tom Igoe

  This example code is in the public domain.

  http://www.arduino.cc/en/Tutorial/Button
*/

// constants won't change. They're used here to set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

 

EXAMPLE2 – Press once to turn on, press again to turn off: 

Sometimes we don’t want to hold a button in order to keep an LED on. Things like light switches in our daily life work in the way that we push a button once to turn it on, and again to turn it off. How do we realize this?

In order to do so, we need to detect the moment of a button getting pressed down, instead of counting on the state of it. In other words, we need to detect the moment when the value of the digital input changes from 0 to 1. The key to realizing this is to create a pair of booleans: prevButtonStateand currentButtonState in which keep records of the previous state of the button, as well as the current state. We also need a third boolean LEDstatus to store the state of the LED.

The full code would write as below:

int ledPin = 13; //connect pin 13 to led
int buttonPin = 2; //connect pin 2 to button

// creating variables to store the current and previous button states
//false for not pressed, true for pressed
bool prevButtonState = false;
bool currentButtonState = false;

//creating a variable to store whether the LED is on or not
bool LEDstatus = false;

void setup() {
   //initialize the LED pin as output and the button pin as input
   pinMode(ledPin, OUTPUT);
   pinMode(buttonPin, INPUT);
}

void loop() {
  //read currentButtonState
   currentButtonState = digitalRead(buttonPin);

  //if my current button state is NOT the same as previously, AND the button is being pressed at this moment,
  //then this is the MOMENT the button just got pressed down
  if ( currentButtonState != prevButtonState && currentButtonState == true )  {
    //if the LED is off, then turn it on.
    if ( LEDstatus == false ) {
      digitalWrite(ledPin, HIGH);
      LEDstatus = true;
    }
    //else, turn the LED off.
    else {
      digitalWrite(ledPin, LOW);
      LEDstatus = false;
    }
  }        
    //at the end of the loop, store the currentButtonState in variable prevButtonState to update it for the next loop
    prevButtonState = currentButtonState;  
}
Variations and simplifications of the code in example2

While the code above can realize the effect we want, it is not the most optimized version. There are variations and simplifications that could be done for certain parts of the code. Some are simply another way to write the code without optimizing it, for example —

//false for not pressed, true for pressed 
bool prevButtonState = false;
bool currentButtonState = false;

//can also be written as --

//0 for not pressed, 1 for pressed 
bool prevButtonState = 0; 
bool currentButtonState = 0;

Some can make the code a bit shorter —

  if ( currentButtonState != prevButtonState && currentButtonState == true )

//works in the same way as --

  if ( prevButtonState == false && currentButtonState == true )

Some help shorten the code massively. The farthest thing you could do to the code is probably to rewrite the section below —

  if ( currentButtonState != prevButtonState && currentButtonState == false )  {
    //if the LED is off, then turn it on.
    if ( LEDstatus == false ) {
      digitalWrite(ledPin, HIGH);
      LEDstatus = true;
    }
    //else, turn the LED off.
    else {
      digitalWrite(ledPin, LOW);
      LEDstatus = false;
    }
  }        

into —

 if ( currentButtonState != prevButtonState && currentButtonState == false )  {
    //when button pressed, reverse the LEDstatus
    LEDstatus = !LEDstatus;
    digitalWrite(ledPin, LEDstatus);
  }

The full code after optimization will look like:

// Defining variables
int ledPin = 13; //connect pin 13 to led
int buttonPin = 2; //connect pin 2 to button

// creating variables to store the cuurent and previous button states
//false for not pressed, true for pressed
bool prevButtonState = false;
bool currentButtonState = false;

//creating a variable to store whether the LED is on or not
boolean LEDstatus = false;

void setup() {
   //initialize the LED pin as output and the button pin as input
   pinMode(ledPin, OUTPUT);
   pinMode(buttonPin, INPUT);
}

void loop() {
  //update currentButtonState
   currentButtonState = digitalRead(buttonPin);

  //if my current button state is NOT the same as previously, AND the button is being pressed at this moment,
  //then this is the MOMENT the button just got pressed down
  if ( prevButtonState == false && currentButtonState == true )  {
    //if the LED is off, then turn it on.
    LEDstatus = !LEDstatus;
    digitalWrite(ledPin, LEDstatus);    
  }

  //at the end of the loop, store the currentButtonState in variable prevButtonState to update it for the next loop
  prevButtonState = currentButtonState;  
}

 

How To Open The Mic In Catalina

I followed similar instructions from the Video library.
My mac version is Catalina 10.15.5 and my Processing version is 3.5.4

  • Install “processing-java” so you can run a sketch from terminal. (I guess if you did this for the video library you don’t need to do it again)
    From the processing tools menu select – install processing-java. Select For all users when prompted.
  • Open terminal and run the AudioInput sketch or any sketch that tries to use the microphone. Copy and paste the next line in the terminal (make sure you change “mg3273” for the name of your computer user):

processing-java --sketch=/Users/mg3273/Documents/Processing/libraries/sound/examples/IO/AudioInput --run

running the “AudioInput” sketch from terminal Catalina prompts you to allow permission!
You will get something like this: 

mic

Click OK and that will make your microphone work from now on.

How To Camera Capture

Windows 10

Method #1:

cam = new Capture(this, “pipeline:kvvideosrc”);

Method #2:

The following instructions are a workaround to let Processing use the webcam on Windows . This was tested on PC computers with the os version Windows 10 and using the Processing version 4.0b2.

In the code you run, instead of using the default method of
cam = new Capture(this, width, height);

You can initialize the camera using the following line: 

Capture = new  Capture(this, “pipeline:autovideosrc”);

Note that if you want to set the input to an external camera, you should use:

Capture = new  Capture(this, “pipeline:avfvideosrc device-index=1”);

Catalina macOS

Method #1:

cam = new Capture(this, “pipeline:avfvideosrc”);

Method #2:

The following instructions are a workaround to let Processing use the webcam on macOS. This was tested on MacBook Pro 2019 with the os version Catalina 10.15.5 and using the Processing version 3.5.4.

We used the Video Library v2 installed from the menu Sketch/Import Library/Add Library. Optionally, you can also download the library from this link and expanding it inside of the Processing/libraries folder as described in these instructions.

  • Open the Processing App and install “processing-java” so you can run a sketch from the terminal. You will find the option from the Tools menu. Select – install processing-java. Select For all users when prompted.
  • Open the terminal and run the gettingStartedCapture sketch or any other sketch that tries to use the camera. You will need the full path to the sketch. Copy and paste the next line in the terminal (make sure you change “mg3273” to the name of your computer user):

processing-java --sketch=/Users/mg3273/Documents/Processing/libraries/video/examples/Capture/GettingStartedCapture --run

Running the “GettingStartedCapture” sketch from terminal Catalina prompts you to allow permission! You will get something like this: 

Click OK and that will make your camera work from now on.

* this solution was compiled from this website: https://github.com/processing/processing-video/issues/134


Note that some examples wont work unless you specify the name of the camera. To open the camera in Processing, you should use:

 
import processing.video.*;
String[] cameras = Capture.list();
Capture cam;
void setup() {
  size(640, 480);
  cam = new Capture(this, cameras[0]);
  cam.start();
}
void draw() {
  if (cam.available()) {
   cam.read(); 
  } 
  image(cam, 0, 0);
}