Category Archives: Stupid Pet Trick

Space game with physical controller

For my stupid pet trick assignment I recreated an asteroids style space game and began to work on a physical controller that would be used to maneuver the game. Unfortunately the controller is in its very early stages and the game itself is not working well since I added the laser.js file to it.

The code;

https://editor.p5js.org/cdh362@nyu.edu/sketches/r1oxeKKeN

Beginning of fabrication of the controllercab

Its not very far along but I will continue developing the idea.

No Pets, Just Music

For my project,  I stepped up my original “keyboard.” Instead of using a piezo buzzer as a sound output, I used serial communication to have the sound played by my laptop through p5.

Here is the finished product: https://vimeo.com/297586614

This my arduino code. Each button was assigned a number to print when it was pressed. The number would then be read by p5 through serial communication.

a a

In p5, each number that was serial printed by the arduino was assigned a corresponding sound. P5 would then check if the button was already pressed. If it was not already pressed down, and I  had just pressed it down, the corresponding sound would play.

https://editor.p5js.org/ach549@nyu.edu/sketches/SkdJGX0j7

a

Also, don’t forget to open the p5.serialcontrol app!

Online Cello

For my project, I wanted to create a cello online that could be controlled by the potentiometer. My idea was to have it so that when the potentiometer was cranked back and forth, the bow would move back and forth.

Here was my set up for the potentiometer:

second first

This is just the set up that was used in the lab.

I used the code for the lab also so that I could connect the Arduino and p5.

code

This gave me the window that it was supposed to:

?

 

I was not able to figure out how to connect these two together properly but I did create the cello and had the bow move along with the mouse instead.

Here’s the p5 code:

var x = 165;
var speed = 10;
function setup() {
createCanvas(400, 400);

}

function draw() {
background(181, 74, 13);
fill(0);
quad(275, 0, 125, 0, 100, 200, 300, 200);
fill(235, 178, 144);
noStroke();
rect(75, 300, 250, 10);

fill(84, 84, 84);
quad(132, 0, 136, 0, 121, 225, 117, 225) // c
quad(117, 225, 121, 225, 116, 300, 112, 300)
quad(116, 300, 112, 300, 112, 400, 116, 400)

quad(170, 0, 173, 0, x, 225, x – 3, 225); //g
quad(x, 225, x-3, 225, 158, 300, 162, 300);
quad(158, 300, 161, 300, 161, 400, 158, 400);
play();

quad(210, 0, 212, 0, 223, 225, 221, 225); //d
quad(223, 225, 221, 225, 226, 300, 228, 300);
quad(226, 300, 228, 300, 228, 400, 226, 400);

quad(250, 0, 251, 0, 275, 225, 274, 225); //a
quad(275, 225, 274, 225, 282, 300, 283, 300);
quad(282, 300, 283, 300, 283, 400, 282, 400);

fill(0);
rect(mouseX, 210, 450, 10); //instead of mouseX, connect to
//potentiometer
fill(240, 221, 194);
rect(mouseX, 225, 450, 3);
}

function play()
{
if(x < 175)
{
speed = – speed;
}
x = x + speed;
}

And here’s how it looks in p5: https://editor.p5js.org/aramakrishnan/full/H1PVJloom 

And here’s the link to the editor: https://editor.p5js.org/aramakrishnan/sketches/H1PVJloom 

 

Summary

For this project I created an interactive map of my travel in New York City since I’ve arrived here. It uses location data taken from my phone that can be scrubbed through using a potentiometer.

Screenshot of Webpage


Programming

For the code I set out to challenge myself and overcome the wall I hit during one of our first projects when I was not able to set up and use the NodeJS server in conjuction with Johnny-Five to receive Arduino serial communications.

Logistically, this program has a local server sync data from the potentiometer in nearly real time, which updates a variable within the looping app.js server file. Every 50 milliseconds the client-side script.js file sends an AJAX GET request back to the server at [server address]/data, to which it receives a 1-element array of the last seen potentiometer value. This format can easily be expanded to include any sort of sensor readings from the Arduino. It needs to be in either an array or object form, as integers, floats, and the like are not able to be sent by the server. Once script.js gets the data, it loops through all days since the beginning of the data adding a transparent SVG for each day with that day’s location tracking data. It also then calculates where the bottom bar should be indicated and what date that would correspond to.

Full hardware setup

//Library requests and declarations
  var express = require('express');
  var path = require('path');
  var app = express();

//Open public directory to client side access
  app.use(express.static(__dirname + '/public'));

//GET request for index
  app.get('/', function(req, res){
    //Sends 'index.html' file in response
      res.sendFile('views/index.html', {root: __dirname });
  });

//GET request for Arduino data
  app.get('/data', function(req, res){
    //Sends potentiometer data in array
    //Can't send int,float,etc. Only string, obj, and array
      res.send([potentiometer.value]);
  });

//Declare Johnny-Five board
  var five = require("johnny-five"), board, potentiometer;
//Set new board
  board = new five.Board();
//When board is ready
  board.on("ready", function() {
    // Create a new `potentiometer` hardware instance.
      potentiometer = new five.Sensor({pin: "A2",freq: 250});
  });

app.listen(3000);
var months = ["Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"];
var date;
var url;
var val;

$(document).ready(function(){
  window.setInterval(function(){
      //Send GET request to local server
        $.get('http://127.0.0.1:3000/data', {}, function(data){
          //Value received in 1-element array
          //Isolate data, map it from 0 to 686 range to 0 to 49 range
          //Round data down and convert it to integer for future calculations
            val =  Math.trunc(Math.floor(data[0]*(49/686)));
        }
      //Update background color on slider bar
        $("#dayRange").css('background-image',
                    '-webkit-gradient(linear, left top, right top, '
                    + 'color-stop(' + val/49 + ', #692DAA), '
                    + 'color-stop(' + val/49 + ', #C5C5C5)'
                    + ')'
                    );
    //Reset previous days
      $(".dayTravel").remove();
    //Loop through previous days
      for(i=0;i<=val+1;i++){
        //Reset base date to start of slider-1
          date = new Date(2018, 8, 13);
        //Set date to currently calculated date
          date.setDate(date.getDate() + parseInt(i));
        //Calculate new url for image
          url = (date.getFullYear()+"").substring(2)+"-"+(date.getMonth()+1)+"-"+date.getDate();
        //Append image to body
          $("body").append("<img src='days/" + url + ".png' class='dayTravel i"+i+"' id='" + url + "'>");
      }

    //Calculate and apply slider label movement
      let revisedVal = ((val/49)*(document.body.clientWidth/1.7))+(document.body.clientWidth*(18/100));
      $(".sliderAfter").css({"left":revisedVal});
    //Calculate and apply slider label text
      let revisedText = months[date.getMonth()]+" "+date.getDate();
      $(".sliderAfter").html(revisedText);

  }, 50);//End on input change
});//End on document ready
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>P5 Homework</title>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="http://nyu.ethanprintz.com/projects/script.js"></script>

  <link rel="stylesheet" href="http://nyu.ethanprintz.com/projects/style2.css">
</head>
<body>
  <div class="sliderSide sliderBefore">Sep 14</div>
  <div class="slideContainer">
    <input class="slider" id="dayRange" type="range" min="1" max="49" value="1">
  </div>
  <div class="sliderSide sliderAfter">Sep 14</div>
</body>
</html>

After hours of debugging and documentation checking, it finally all works! It’s a bit of a simple project outwardly, but inwardly the backbone created for this one can be very easily copied and ported to future projects, which opens up more possibilities for my final project.

GIF of project working

Cat and Fish

My work stopped because of a very strange problem. When I test the print of Arduino, everything went well.

https://drive.google.com/open?id=16v3lY0NDYYgPhZm5pRpYNDBpY-6c5Lzx

However, when I connected Arduino side with p5 side, the print went crazy and both sides cannot read accurately. So, the output (the color of the circle ) was not stable.

https://drive.google.com/open?id=1pVlV_xyDcIiO5Vxd8IfIGqjghUp-l1zL

I cannot deal with it and be able to move forward.

 

 

cat and fish:

https://drive.google.com/open?id=1oycetV20dXeXv8pLrA-DsKm-eDFOr5ko

Later, I still make a project, though the data is also weird. The fish changes in size with the potentiometer and the cat’s mouth open larger like it is laughing when the fish is bigger.

Fishie

Initially, I was going to go for something practical – guitar amp was the first idea to come to mind. After talking to some of my friends from the other section, though, whose assignment was literally to create a “pet”, I decided to make a tamagotchi-esque goldfish. It follows the cursor around (supposed to represent the user’s finger), which is controlled by a joystick, and you can feed it by pressing a button. It responds to signs of affection, like being fed, with a heart.

nnnknkl

sfdsfs

sdffdssfd sdfsdsfds

p5js code:

let fish;
let serial;
let xpos, ypos, button;

let deltaX = 0.0, deltaY = 0.0;
var accelX = 0.0, accelY = 0.0;
var springing = 0.0009, damping = 0.98;

function setup() {
  // Instantiate our SerialPort object
  serial = new p5.SerialPort();

  // Let's list the ports available
  var portlist = serial.list();

  // Assuming our Arduino is connected, let's open the connection to it
  // Change this to the name of your arduino's serial port
  serial.open("/dev/cu.usbmodem14301");

  // Register some callbacks

  // When we connect to the underlying server
  serial.on('connected', serverConnected);

  // When we get a list of serial ports that are available
  serial.on('list', gotList);

  // When we some data from the serial port
  serial.on('data', gotData);

  // When or if we get an error
  serial.on('error', gotError);

  // When our serial port is opened and ready for read/write
  serial.on('open', gotOpen);

  createCanvas(400, 400);
  frameRate(8);
  fish = new Fish();
  print(fish.x, fish.y);
}
    
function gotData() {
      
  var currentString = serial.readStringUntil("\r\n");
  if (currentString.length > 1){
  var values = split(currentString, ',');            // split the string on the commas
    if (values.length > 1) { 
  xpos = map(values[0],  0, 1024, 0, width);
  ypos = map(values[1], 0, 1024, height, 0);
  button = values[2];
  console.log(values);
    }
  }
}

function draw() {
  background(12, 169, 255)
  fish.show();
  followCursor();
  fish.follow();
  
  if (button > 0) {
    feed();
  }
  
}

function followCursor() {
  noFill();
  strokeWeight(5);
  stroke(255);
  ellipse(xpos, ypos, 20, 20);
}

function feed() {
    for(let x = 0; x < width; x += 50){
    let y = random (+200); 
     if(y<fish.y) {
    fish.heart();}
      fill(206, 114, 74);
    ellipse(x,y,5,5);}
  
}
  

function serverConnected() {
    print("We are connected!");
}

// Got the list of ports
function gotList(thelist) {
  // theList is an array of their names
  for (var i = 0; i < thelist.length; i++) {
    // Display in the console
    print(i + " " + thelist[i]);
  }
}

// Connected to our serial device
function gotOpen() {
  print("Serial Port is open!");
}

// Ut oh, here is an error, let's log it
function gotError(theerror) {
  print(theerror);
}

// Got the list of ports
function gotList(thelist) {
  // theList is an array of their names
  for (var i = 0; i < thelist.length; i++) {
    // Display in the console
    print(i + " " + thelist[i]);
  }
}

// Connected to our serial device
function gotOpen() {
  print("Serial Port is open!");
}

// Ut oh, here is an error, let's log it
function gotError(theerror) {
  print(theerror);
}

class Fish {
  constructor() {
    this.x = width/2;
    this.y = height/2;
    
  }
    
  follow() {
  deltaX = xpos - fish.x;
  deltaY = ypos - fish.y;
  deltaX *= springing;
  deltaY *= springing;
  accelX += deltaX;
  accelY += deltaY;

  // move predator's center
  fish.x += accelX;
  fish.y += accelY;

  // slow down springing
  accelX *= damping;
  accelY *= damping;
  }
    
  heart() {
  noStroke();
  fill(255,0,12);
  rect(fish.x+15,fish.y-10,3,3);
  rect(fish.x+12,fish.y-13,9,3);
  rect(fish.x+9,fish.y-16,15,3);
  rect(fish.x+9,fish.y-19,6,3);
  rect(fish.x+18,fish.y-19,6,3);
    
  }
  
  show() {
  noStroke();
  fill(255, 105, 12);
  rect(fish.x, fish.y, 30,30);
  rect(fish.x-15,fish.y+5,5,5);
  rect(fish.x-15,fish.y+25,5,5);
  rect(fish.x-5,fish.y+15,5,5);
  rect(fish.x-10,fish.y+15,5,5);
  rect(fish.x-10,fish.y+10,5,5);
  rect(fish.x-10,fish.y+20,5,5); 
  }
}

Arduino code:

void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
int Xpin = analogRead(A1);
int Ypin = analogRead(A0);
int button = digitalRead(2);

Serial.print (Xpin);
Serial.print (",");
Serial.print (Ypin);
Serial.print (",");
Serial.println (button);

}

 

 

 

Space Explorer

For my “Stupid Pet Trick”, I decided to use a potentiometer to trigger movement on p5.js in someway.

wiring wiring

^^This is the wiring of the two potentiometers I used to move my spaceship across the screen.

My original idea was to create a maze and use one potentiometer to move a ‘ball’ up and down and the other potentiometer to move side to side, to navigate the maze. But as I was learning how to use serial communication and code this, it became a project where I bit off more than I could chew. So in the end, I only got the potentiometers to move side to side. It was a happy accident that one potentiometer was much more sensitive that the other, and moved the object across the screen much faster and way off of my canvas on p5.js. But I decided to use that to my advantage and create this little space explorer world.

space explorer

^^I used pictures from online, and used a function to create the background, and replace what was originally a red circle into a spaceship.

arduino

^^This is the code on my arduino to to turn on my potentiometers.

var serial;
var latestData = "waiting for data"; 
var img1
var img2

function setup() {
createCanvas(700, 500);
img1 = loadImage("assets/Ship.png");
img2 = loadImage("assets/Space.png");
// Instantiate our SerialPort object
serial = new p5.SerialPort();
serial.open("/dev/cu.usbmodem14621");
serial.on('data', gotData);
}

function gotData() {
var currentString = serial.readLine(); 
trim(currentString); 
if (!currentString) return; 
latestData = int(currentString); 
console.log(latestData); 
var output = map(mouseX,0,255);
serial.write(output);
}

function draw() {
image(img2, 0,0, img2.width/2, img2.height/2);
fill(255,0,0);
var data1 = map(latestData, 0, 1023, 0,width);
image(img1,data1,200,150,150);
fill(255,255,255);
textSize(30);
text(data1, 10, 30);
textSize(20);
fill(255,0,0);
text('Left for Warp Speed!', 10, 480);
text('Right for Normal Speed!', 475, 480);

}

^^This is the code I used on p5.js. I did use Professor O’Sullivan’s code as a platform for my code, because he also used a potentiometer to move an object on the screen.

Troubleshooting: It was a little hard to write the code to make the spaceship move in the direction I wanted. At first, it had begun to move in a diagonal direction, but after a little debugging, I got the spaceship to move from left to right.

^^Success! There are two setting for the speed of the space ship, normal speed on the right and warp speed on the left!

Attribution!!

@Josh for helping me A LOT with my code!!

@Grace for giving me the spaceship idea!

@Professor O’ Sullivan for the basic code to help me with my project!

@the p5.js and arduino libraries!

Ou! He Lying!: A Serial Control Attempt

I wanted to make an interactive Pinocchio. When you toggle with the potentiometer, the nose would get longer, and when the potentiometer hits a certain value, the screen would display the text “OUUUUUUUU!”

This is my P5.js sketch not including the connection to serial control.

https://editor.p5js.org/yunglizard/sketches/r1d_lt9im

fullscreen:

https://editor.p5js.org/yunglizard/full/r1d_lt9im

Replacing the connection using serial control is where I struggled. I think I did not complete the correct setup, which prevented me from excelling in anything else. I had made the circuit, which included the potentiometer and tested it to see if it worked. These steps were a success as you can see below!

serial

serial

Unfortunately, I did not know how to connect my p5 sketch and my circuit in order to successfully complete the assignment. I tried many times to debug and reread the notes from class, but I ended up missing something.

 

I wanted to be a mean love guru, but being evil is hard

I decided to recreate an arcade game that I loved playing in middle school for this week’s assignment, but putting a small cynical twist on it in honor of this TRICK or treat season.

Here is a version of the arcade game I am referring to. arcade game

Essentially, a user would place their hands upon one of the two hands on the console and their partner would place their hand upon the other hand print. The game would then “calculate” how strong their love was for one another.

There were other versions of this game that were one player, in which the player would put their hand down on a similar hand print to determine if their crush liked them back or how hot you were.

Overrun by puberty, I loved games like this in middle school. I mean, for just 50 cents I could see if Jordan from 3rd period and I were really going to get married! (Of course, we did not haha).

I wanted to create a version of the one player game. In which, a user could determine how their current partner really feels about them. They would place their hand upon a box with a hand print and discover the answer onto the computer screen.

Here is the box:

box

In the middle of the “hand print” is a light sensor. Once a hand covered the light sensor, the computer screen would show how much that user’s lover actually cares about them on the screen through p5. The box was easily to make however, the following parts of the process is where things became complicated.

Before I begin discussing my process, I want to provide an overview of what my p5 code needed to have.

  1. To take in the light sensor data
  2. Recognize that the light sensor was covered
  3. Have an array of possible sentences (fortunes)
  4. display a random sentence when light sensor is covered

Getting the light sensor data was not a problem and recognizing when the sensor was covered was not difficult either. The problem emerged was having an array of sentences.

When I finally put together my initial code, I realized that when I covered the light sensor, p5 was receiving a range of numbers. It was considered covered at 30 all the way to 100. Yet, the issue was, that it would bounce between this range even though my hand was still and over the light sensor. The light sensor must have been detecting small amounts of light and then bouncing around. As a result, the code would continuously loop and display different sentences (fortunes). To better understand what I am referring to watch the video below.

In order to tackle this issue I decided that I need to take the range of numbers that are associated with the light sensor being covered.

My initial thought was to declare the range in p5 in my if statement, but that did not work. The I decided to try to divide up the range and that did not work. I realized I needed to covert “not covered” into one number and “covered” into another number before it even entered p5. Specifically, I needed to take an analog data and make it digital. I went onto my Arduino code and turned into a boolean. This allowed me to have the desired covered and not covered data input into my p5. Here is the Ardunio code:

arduino code

Now that the I was able to simplify how p5 was reading the light sensor I decided to go back to getting the random fortunes to display.

However, my own luck and fortune was not by my side. p5 crashed meaning that I had to redo my code (which was not that heartbreaking). However, for some reason when I redid the code my serial controller no longer wanted to stay on the serial port I was using and kept returning back to my bluetooth headphones. As a result, I kept getting an error that my serialEvent function was not working properly.

This resulted in a quick one hour long cry out of frustration. Luckily I was able to simply restart my computer, delete my serial controller app and redownload a new one and get it working again. Yet, I needed a break and since this was day two working on this project, I was very emotionally exhausted.

After the break, I was able to finally get it working!

Yet, as I kept playing around with it and testing with different graphics for the display, something terrible happened.

Basically, my light sensor started to think it was alway receiving light. When I checked on the serial monitor it always depicted “1”. Watch the video to see what I mean (also sorry for my gross room in the background):

I tried everything. I took the light sensor out of the box and tried to cover nothing worked. At this point, I am assuming that either this is karma for trying to make people sad about love or (more likely) I got my light sensor from a knock off ardunio kit, so it may simply not be the best quality. I could either add a new light sensor but it was past midnight and the shop was closed so I would be unable to solder it.

Update: I spent all night thinking about what went wrong and perhaps it was because my Arduino code made “no light” false. That meant if there was ANY source of light, it would depict true. However, maybe it should be flipped so that if there is any source of darkness it should be false. It is currently 6am but I’ll retry this after class. I really want to make this box work and I have faith that I can be an evil love guru!

current fullscreen: https://editor.p5js.org/andrikumar/full/r11wX9wjQ

current edit: https://editor.p5js.org/andrikumar/sketches/r11wX9wjQ

current arduino code (now that I am iterating upon it):

new code

Greyscale Potentiometer

This began as a mission to get my copycat Arduino working (finally). I had to download drivers and copy paste stuff into terminal and all that kind of stuff that I don’t understand. That worked – for a good two hours until my Arduino doesn’t know how to do what it’s supposed to do anymore.

My Code

Video

I really struggled with this one. As usual. My Serial Communication assignment consists of a potentiometer controlling the greyscale background hue of the p5 sketch. Linked above.

universe on canvas

https://vimeo.com/296276007

I tried two physical controllers to tell p5 to adjust the radius and the position of the circles on the canvas. I call this Universe on Canvas because I want to simulate planets’ movements in an abstract way.

First I used the potentiometer because it’s the easiest one. Using the potentiometer, I could get the maximum and the minimum value of the radius and the range of the circles’ positions.

Then I tried to use the photoresistor. Everything starts at its largest value and then decreases proportionally to the level of brightness perceived by the photoresistor. However, I couldn’t get to the smallest values no matter how hard I tried to cover the photoresistor.

Here’s the code I use.

// Declare a "SerialPort" object
var serial;
var latestData = "waiting for data";  // you'll use this to write incoming data to the canvas

function setup() {
  createCanvas(400, 400);

  // Instantiate our SerialPort object
  serial = new p5.SerialPort();
  serial.open("/dev/cu.usbmodem1411");
  serial.on('data', gotData);
}


// There is data available to work with from the serial port
function gotData() {
  var currentString = serial.readLine();  // read the incoming string
  //same as readStringUntil(‘\r\n’)
  trim(currentString);                    // remove any trailing whitespace
  if (!currentString) return;             // if the string is empty, do no more
  latestData = int(currentString);            // save it for the draw method
  console.log(latestData);             // println the string
  var output = map(mouseX,0,width,0,255);
  serial.write(output);
}

function draw() {
  background(255, 204, 0);
  //fill(0,0,0);
  var data = map(latestData, 0, 1023, 0, height);
  //ellipse(mouseX, mouseY, data);
  //text(data, 10, 20);
  
  noStroke();
  fill(200);
  ellipse(200+data, 210, 70);
  fill(255);
  ellipse(100+0.3*data, 210+0.4*data, 90);
  fill(145);
  ellipse(70+0.5*data, 160-0.2*data, 78+0.7*data);
  fill(70);
  ellipse(310, 300-data, 90);
  fill(240);
  ellipse(310-data, 20+data, 90+0.1*data);
  
  noFill();
  strokeWeight(3);
  stroke(40);
  ellipse(170, 65, 100+data);
  strokeWeight(10);
  stroke(220);
  ellipse(380, 210, 350+data);
  strokeWeight(20);
  stroke(80);
  ellipse(0, 390, 200+data);
}