Home‎ > ‎Unit 08‎ > ‎

Etch-a-Sketch

Lets draw pictures with our slide potentiometers. For this lesson you'll nee dot attach two potentiometers. One to pin 2 and the other to pin 3. then try out this code:

import processing.serial.*; //Import the serial library into your sketch
import cc.arduino.*;        //Import the Arduino-Firmata library into your sketch

Arduino arduino;      //Create an instance of Arduino named arduino (can be any name) 
float xPos;
float yPos;

void setup()
{
  size(400,400);
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  smooth();
}

void draw()
{
  background(0);
  xPos = map(arduino.analogRead(2), 0, 1023, 5, width-5);
  yPos = map(arduino.analogRead(1), 0, 1023, 5, height-5);
  ellipse (xPos, yPos, 9, 9);
}

Pretty cool eh? But, we're not drawing a picture yet. Recall when you worked through Chapter 5 in  Getting Started with Processing? If not, go back and check it out starting on page 54. We're going to replace the mouse with your potentiometers! In Example 5-6 we used pmouseX and pmouseY. We'll have to create our own p-variables for this to work out.

Try this out:
import processing.serial.*; //Import the serial library into your sketch
import cc.arduino.*;        //Import the Arduino-Firmata library into your sketch

Arduino arduino;      //Create an instance of Arduino named arduino (can be any name) 
float xPos;
float yPos;
float pxPos=0;
float pyPos=0;

void setup()
{
  size(400, 400);
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  smooth();
  strokeWeight(4);
  stroke(240);
  background(0);
}

void draw()
{
  xPos = map(arduino.analogRead(2), 0, 1023, 5, width-5);
  yPos = map(arduino.analogRead(1), 0, 1023, 5, height-5);
  line (xPos, yPos, pxPos, pyPos);
  pxPos=xPos;  //update pxPos
  pyPos=yPos;  //update pyPos
}

There may be a problem, however. You may have noticed even in the first sketch that we always start in the corner and then jump to the position set by our potentiometers. If this doesn't happen for you then don't worry about this next bit. What's happening is the program is progressing prior to the Arduino sending data back. So you may need to add in a pause. Follow this link for a fix.

Assignment 8.2 - Create a slide pot version of Example 5-9 and draw a cool picture. As always post the code and picture to your blog. Bonus: Use keyPressed() to blank your canvas to start over.
Subpages (1): Delay Fix
Comments