Your browser does not support the canvas tag.

Week 12
P5.JS week! Lauren McCarthy is an interesting artist and the creator of P5.js.
direct link to comment on the FCC
link to FCC folks
Dungeon crawl collision detection

There was some interest last week in alternate ideas of collision detection. The trick is to use a simple graphic as a guide. Then calculate where the front of your ship will be after the next step and grap the color of the pixel in the image at that location. If it's white, go ahead and add the step to the current location, but if it's black, don't move.
In the example we're putting the image on the screen, but you could put a different artwork as the image if you wanted.
Don't use a png with transparency, it can throw off some quirky data when you grab the color.

float  locX = 100; 
float locY = 100; 
float speed = 0; 
int shipWidth = 20; 
boolean up, left, right; 
PImage d1; 
float rot = 0; // rotation of character
void setup() {
  size(400, 400);
  d1 = loadImage("d1.jpg");
  noStroke();
}
void draw() {
  background(200); 
  image(d1, 0, 0); 
  d1.loadPixels();
  float newX = locX + cos(rot)*(shipWidth/2 + speed); // current location + the next "step"
  float newY = locY + sin(rot)*(shipWidth/2 + speed);
  color joe = d1.get(int(newX), int(newY)); // get color of the pixel at the next step
  if (brightness(joe) != 0) { // if the 
    locX +=  cos(rot)*(speed); 
    locY +=  sin(rot)*(speed);
  }
  if (up) { // up down changes speed
    speed = +2;
  } else {
    speed = 0;
  }
  if (left) { // left right changes rotation
    rot -= .05;
  } else if (right) {
    rot += .05;
  } 
  fill(100, 100, 200); 
  ellipse(locX, locY, shipWidth, shipWidth);
  fill(255, 0, 0); 
  ellipse(newX, newY, 4, 4); // draw dot to see the rotation
}

void keyPressed() {
  if (keyCode == RIGHT) {
    right = true;
  }
  if (keyCode == LEFT) {
    left = true;
  }
  if (keyCode == UP) {
    up = true;
  }

}

void keyReleased() {
  if (keyCode == RIGHT) {
    right = false;
  }
  if (keyCode == LEFT) {
    left = false;
  }
  if (keyCode == UP) {
    up = false;
  }

}
Try it with this loveyl garden image
p5js

How to put your sketch on the inter-webs.
The old-old way. In the days of yore (2009-ish), you could export your sketch as a "Java applet". This applet could then be embedded into a webpage and the browser would use Java to put it on screen. This was already on the way out when the Java exploits started to get really popular, and suddenly nobody was making applets any more. Then Processing created a mode called "javascript mode". You would switch from regular processing to Javascript mode and Processing would convert your sketch into something that could run in a browser. Not well, but it would run. You can still use this mode in processing 2. With Processing 3, there is a new method called P5.js. This program uses Processing keywords and syntax, but you don't actually write the code IN Processing, you write it in a text editor (or eventually in their own stand alone application which is in beta).
Technically P5.js is a Javascript Library, and because of this you need to learn a little bit about how Javascript works and how to embed your code into the HTML of a web page. The big down side of using p5js is your libraries are very limited. The upside is of course your sketch can live on a website. The good news is that p5js has a lot of people working on it, so features you may want are not here now may soon be in the future.

The creators of p5.js have the new programmer in mind, and they are making a conscious effort to have the code be as straight forward and easy to understand as possible. They have even created a handy page for those who already understand some processing and want to apply it to p5.js.

p5js.org

Sidebar - If you're new to SublimeText prepare to have your mind blown. Open a page with some writing and option-drag through the text. Yes, multiple cursors. Now select a word and press command - control -g.
Do not try and bend the spoon. That's impossible. Instead, only try to realize the truth ... there is no spoon.
Sublime Text

Yeah, okay, the real truth is there's a P5 mode now in Processing. We should give that a try too I suppose (but Sublime is cool and the white on black makes you look l33t!) There's a browser based P5 comming too (It's awesome).
Check the transition page to see the major differences between p5js and Processing. The major points are:

Check out the other tutorials, examples and the reference page to get a feel for the program.

The structure of a website
The DOM - Javascript CSS and HTML5 all have to happen on a page in a certain sequence - this sequence is called the DOM (Document Object Model). In p5.js we can also tap into the DOM and communicate directly with the CSS and HTML. This is cool. It means your sketches run in a canvas which is sort of like a sketch window, but they can also communicate with the rest of the page in interesting ways. If you wan to experiment with this you need to enable the dom library in the head section of the html page.

Add to this, there are specific keywords in p5.js that account for mobile devices and all the sensors and capabilities that they have.

HOW DOES MY MOM SEE IT?!
Right now your page works, but only on the machine you're looking at. Your website is only "local". To put it online you need web-space. If you've take web at Purchase you probably already have web-space through the school, or perhaps you have your own space already. You will need to upload the html file, the sketch,js file AND the library folder to your website, and maintain the relationship between these files. Typically you use and FTP client like Cyberduck or FileZilla to transfer the files. Here's a link to the CTS page where you can establish a website.

This image shows the ftp settings in CyberDuck for conecting to the student server. Filezilla will work too and looks similar. When you're connected place the files into the WEB folder (or create a sub-directory within the WEB folder if you want). Now your sketch is online!

Controlling where the sketch goes on the page

Graphic elements in HTML5 go into something called the "Canvas" and P5.js takes advantage of this. In the example index provided by p5.js the canvas is drawn by default, but it is possible to designate that the sketch load into a particular div that you control.
This section is the p5.js sketch. Notice that instead of "create Canvas", we set the canvas to a variable, then we give the variable a "parent", which is the div we want it to reside in.

function setup() {
	var cnv = createCanvas(200, 200);
	cnv.parent("myContainer");
}
function draw() {
  fill(0, 255, 0);
  rect(20, 20, 100, 100);
}
This section is the html
<head>
	<script language="javascript" src="../p5.js"></script>
	<script language="javascript" src="sketch.js"></script>
	<style type="text/css">
		#myContainer{
         box-shadow: 10px 5px 5px black;
         width: 200px;
         height: 200px;
		} 
	</style>
</head>

<body>
	Text above the sketch 
	<div id="myContainer"></div>
	text below the sketch
</body>

Here's a page to help convert Processing sketches to p5.js

If you're itching for more P5 there's lots to learn. I have a page on my web class website that discusses incorporating p5 into the "DOM" of the website.


Arduino

The Arduino is a wonderful little cheap microcontoller. You can upload programs to it and then have it run independently of the computer, or you can use it as an input/output breakout box and leave it attached to the computer.

The arduino syntax is much like Processing in fact the early version was BASED on Processing. Arduino, however compile to C not to Java, but you don't need to worry about that too much, especially at first. The biggest difference between the two is that Arduino has no screen, so there is no point to have any of the drawing fuctions like rect ellipse fill. In fact draw itself is now called loop to avoid confusion.
The other big difference is reading the pins (the porst on the arduino). You do that with code like this.
 
 digitalWrite(13, HIGH);
This would turn the digital pin 13 on, allowing current to flow from pin 13 to ground.

The best way to destroy an arduino is to plug the 5v or 3.3V pins directly into ground. Don't do this. If you're using a breadboard for the first time, get familiar with how they work first with some simple cheap circuits.

Arduino with Processing
Using Arduino with Processing requires running Firmata on the arduino, and The Arduino library in Processing. Firmata acts as a conduit between the arduino and Processing and it allows us to easily address the ports on the arduino. The advantage is that once we have the arduino running with Firmata loaded on it we do not need to work in the arduino programming environment. The disadvantage is that setup can be a bit confusing. Hopefully this page makes things a little easier.

The steps described are for a mac, but the process on a PC should be largely the same.

Step one
Download and install the latest versions of Processing and Arduino. If you have the programs already, make sure you have a recent version.

Step two

PC users can follow this link for driver instalation instructions - mostly it involves allowing the wizard to do its tricks.

If you are using an Uno or later the driver is not an issue but if you have a Duemilanove or Diecimila this page also has the latest drivers - link
There is an Arduno library for processing that is neceesary also. Fortunately it is included in recent versions of processing, but if it's missing here's instructions for downloading and installing.

Step Three
  1. Open the Arduino software
  • Plug the arduino into the computer with a USB cable. A little LED light should turn on the arduino showing that it has power.
  • Go file – Examples – Firmata - StandardFirmata
  • Go Tools – Board and make sure the right board is selected.
  • Go Tools – Serial Port and select the correct Serial port. It should be /dev/tty.usbserial on the mac or COM3 (or higher) on the PC. If it's not there ask yourself if you did step two?
  • Go File – Upload to IO Board. Two LED's on the arduino should blink on and off, telling you that it's uploading. It should only take a few seconds.
  • if it doesn't work - check out the arduino help page.
  • Quit the Arduino programing environment. (not absolutely necessary but I find the processing screen to look so similar that I start writing in the wrong place by accident)
  • Step Four
    Look to see if the arduino library for processing is installed already. In the finder, go Documents - Processing. Inside the Processing folder should be a folder called "libraries" (with a lower case l). If there isn't one, go ahead and create it. If you do have a Libraries folder look inside and see if you have a folder in there called "arduino". If so you can skip ahead to the next step - if not you will need to download the arduino library. Once downloaded drag the whole Arduino folder (not just the contents of the folder) into the new libraries folder you just created (inside the Processing folder inside the Documents folder). Are you having fun yet?

    Step Five.
    "Hello World". There is a small LED on the Arduino that is "tethered" to pin 13. Set pin 13 to HIGH and the led turns on, set it LOW and it turns off. You can insert the long leg of an LED into digital pin 13 on the Arduino, and the short leg into GND, (the hole right next to it). The power on most pins are too great for an LED, but 13 is an exception, it has a resistor built in.

    Open Processing and Copy/Paste the code below into a new sketch.


    import processing.serial.*; // accesses the serial library
    import cc.arduino.*; // accesses the arduino library
    Arduino arduino; // creates a variable called arduino
    int ledPin = 13; // a variable for the pin on the arduino
    int counter = 0; // a variable for timing; 
    boolean onoff = true; // a variable that is either true or false   
    
    void setup() {
      for (int i = 0; i < Arduino.list ().length; i ++) {
        println(i + "  " + Arduino.list()[i]); // prints your USB bus
      }
      arduino = new Arduino(this, Arduino.list()[13], 57600); // sets our variable "arduino" to the actual arduino
      arduino.pinMode(ledPin, Arduino.OUTPUT);// sets port 13 to output
    }
    void draw() {
      counter ++; // adds 1 to the varaible counter with each loop
      if (counter > 20) { // checks the condition of counter 
        onoff = !onoff; // the !changes the state from true to false or false to true. 
        counter = 0; // reset our counter to zero
      } 
      if (onoff == true) { // check the state of our boolean
        arduino.digitalWrite(ledPin, Arduino.HIGH); // light goes on
      } else { // if the boolean is false 
        arduino.digitalWrite(ledPin, Arduino.LOW);// light goes off
      }
    }
    

    Press Run (command-R)
    Hooray, a blinking light, what joy.
    For further reference, here's a reference with info about the firmata library, it includes all the methods used to talk to the arduino from processing.

    Troubleshooting