Running a local server

When we work from the p5 Editor and and press play to view your program, a window will open to preview our project. In the background, the p5 editor is starting a server for us, and testing our project on this local server.

When you are NOT working from the p5 editor, and you are developing from Sublime Text or another code editor of your choice, you may need to start a local server to test a p5 project. 

Certain p5 functionality relies on a server to host the project (loading external files and using the sound library, for example). Everything will work as expected when the files are placed online via FTP or SSH, but during development, you will get cross-origin errors in the console when you try to view the project locally.

The solution to this is to view them using what’s called a local web server. This tutorial includes instructions for setting this up a local server using Python or Node.js.

Python SimpleHTTPServer

Python comes with a simple builtin HTTP server. With the help of this little HTTP server you can turn any directory in your system into your web server directory. The only thing you need to have installed is Python (Python is already installed if you are using Mac OS X).

Open the Command Line (Terminal on a Mac, Command Prompt on Windows)

Change directories to your p5 folder. Use the cd command (with a space after) then drag your p5 folder into the Terminal window. 

change directories

Press ENTER. Verify that you are now located inside that p5 folder.

screen-shot-2016-11-14-at-5-48-51-pm

To start a simple python server, type the following command, then press ENTER.

python -m SimpleHTTPServer

screen-shot-2016-11-14-at-5-52-43-pm

You’ll receive feedback in the command line that a server has been started. To view your page in the browser, go to: localhost:port, in this case, localhost:8000. You can click on the project directory to preview that page in the browser.

local server

Node HTTP Server

An alternative is node.js http-server. It is much faster than a python simple server, but requires a little bit of setup.

1. Download and Install node.js

2. Open a terminal or command prompt

3. On OSX/Linux type

  1. sudo npm install -g http-server
    

    On Windows type (you might need to open the command prompt as admin)

    npm install -g http-server
    

Done!

From then on just cd to the folder that has the files you want to serve and type

http-server

The full set of commands looks like this:screen-shot-2016-11-14-at-6-00-28-pm

To test your page, copy one of the addresses in green and paste that in your browser.

Apache Server

Python SimpleHTTPServer is great to get started, but at some point you might want to set up an Apache server. The Apache server supports a greater range of HTTP functionality and scales well for bigger projects. See below for OS specific setup.

Mac OS X

Mac OS X since 10.5 Leopard ships with Apache web server installed, all you have to do is enable it and place the files in the right place.

Mac OS X 10.7 and above

Open Terminal and type:

sudo apachectl start

Verify it is working by going to http://localhost on your browser. You should see “It works!” on the browser.

Enable permissions for the files on the server by typing the following two commands into Terminal:

sudo chown root:<your username> -R /Library/WebServer/Documents

sudo chmod -R 755 /Library/WebServer/Documents

Place your project somewhere inside /Library/WebServer/Documents/.

View it at http://localhost/(the project folder in /Library/WebServer/Documents).

http://localhost/my-p5-sketch

Mac OS X 10.5 and 10.6

Turn on the web server. Go into Sys­tem Pref­er­ences > Shar­ing, and check the “Web Shar­ing” box.

Verify it is working by going to http://localhost/~<your username> on your browser. You should see a default webpage with a title of “Your Website”.

Place your project somewhere inside <your username folder>/Sites.

View it at http://localhost/~(your username)/(the project folder in <your username folder>/Sites).

http://localhost/~macusername/my-p5-sketch

Windows

Download WampServer from http://www.wampserver.com/en/.

Install WampServer and follow instructions.

The “www” directory will be automatically created (usually c:\wamp\www).

Create a subdirectory in “www” and put your HTML/JS files inside.

Open your internet browser and go to the URL : http://localhost/yourfile.html.

Linux

Install apache2 via apt-get.

Place your project somewhere inside /var/www/.

View it at http://localhost.

p5 + html / css

There are a few ways to embed p5 sketches in an html page.

First, you can connect your p5 sketch to a particular div in your HTML. To to this, you need to set your canvas to a variable, and then set the parent of your canvas to be a div in your html.

In the setup() of your sketch.js, you would include the following code:

var myCanvas = createCanvas(600, 300);
myCanvas.parent("p5-sketch");

Then, in your index.html page, you need to create a div inside of the <body> with a div that will exist as the parent of the sketch – give this div an id of ‘p5-sketch’.

<div id="p5-sketch"></div>

The second way to embed a p5 sketch is using an HTML iFrame. This is essentially the same as linking to the p5 sketch, and displaying it in a little window. You connect to the sketch via an absolute link. Add this to your html:

<iframe src="http://creative.colorado.edu/~heinae/p5/simple-array/" width="600px" height="300px"></iframe>

This live example demonstrates both of these ways.

P5 + Serial

In this demo, we will have a simple Arduino circuit communicate with a sketch in the P5 editor.

Build the Circuit

Connect a potentiometer to power, ground and Analog pin 0 on your Arduino. You can actually skip the breadboard and connect the potentiometer directly to your board (assuming you have wires soldered to your pot).

potentiometer_schem1potentiometer_bb

Program the Arduino

void setup() {
   Serial.begin(9600); // initialize serial communications
}
 
void loop() {
   // read the input pin
   int potentiometer = analogRead(A0); 

   // remap the pot value to fit in 1 byte
   int mappedPot = map(potentiometer, 0, 1023, 0, 255); 

   // write that mapped value to the serial port
   Serial.write(mappedPot); 
   
   // slight delay to stabilize the ADC
   delay(1); 
}

Install the P5.serialcontrol App

Download the latest version of the P5.serialcontrol application and save it in your Applications folder. When you run it, it will check serial ports on your machine. Click “list ports” to refresh the list, and you should see the serial port of your Arduino board show up.

This App needs to be open anytime you’re using the p5 editor to read serial data.

Move to the P5 Editor

Download this serial-boilerplate. Open this project in the p5 Editor. This project contains the usual setup of any p5 project (index.html, sketch.js, and the base p5 libraries), plus it includes a p5.serialport.js library that allows us to connect the p5 editor to the serial port. That library is doing a lot of the work here for us, yay 🎉

SerialPort setup in the sketch.js file

Open the sketch.js file and create a new instance of the serial port library (this allows us to utilize the code in the p5.serialport.js library).

At the very top of your sketch.js file, create the following variables that will work with the serialport library:

var serial;  // var for instance of the serialport library
var portName = 'your-port';   // fill in your serial port name here

You should replace ‘your-port’ with the port listed on the p5serialControl app that we downloaded before. For example, mine is: /dev/cu.usbmodem1411

Then, inside the setup() function on your sketch.js file, add the following code:

serial = new p5.SerialPort(); // make a new instance of the serialport library
serial.on('connected', serverConnected); // callback for connecting to the server
serial.on('open', portOpen); // callback for the port opening
serial.on('data', serialEvent); // callback for when new data arrives
serial.on('error', serialError); // callback for errors
serial.on('close', portClose); // callback for the port closing
serial.open(portName); // open a serial port

Add Callback functions for Serial

At the bottom of the sketch.js file, add the following code:

function serverConnected() {
   println('connected to server.');
}
 
function portOpen() {
   println('the serial port opened.')
}
 
function serialEvent() {
   
}
 
function serialError(err) {
   println('Something went wrong with the serial port. ' + err);
}
 
function portClose() {
   println('The serial port closed.');
}

Read data from the Serial Port

Add the following variable at the top to store data from the serial monitor to:

var inData;     // variable for incoming serial data

Next, find the serialEvent() function, and inside that we need to read the input from the serial port.

inData = Number(serial.read());

Then, inside of draw() let’s print this variable to the console:

console.log(inData);

Now, use inData to do fun stuff – can you make the inData value change the size of an Ellipse? Or move an ellipse across the screen?

 

Going Further