For Pcomp this week I used an analog raindrop sensor board to simulate rainfall in p5. The sensor “senses rain” when water shorts the connections running throughout the board.

I adapted some code Daniel Shiffman wrote for a purple rain sketch to create the rain effect when p5 reads the sensor value in via serial. This was my first time using p5 and I found it super easy to use, if not a little basic (seems a lot easier to get started with than something like d3).

 

The circuit itself was super straightforward, nano + sensor:

Fritzing diagrams:

 

Arduino code:

#define RAIN_SENSOR_PIN A7

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

void loop() {
  int rainValue = analogRead(RAIN_SENSOR_PIN);
  rainValue = map(rainValue, 0, 1023, 50, -16); //map sensor on 0-50 scale
  Serial.println(rainValue);
  delay(1);
}

Sketch.js code:


// Code adapted from Daniel Shiffman's purple rain coding challenge
// https://youtu.be/KkyIDI6rQJI

// define global vars
var drops = [];
var serial;
var portName = '/dev/cu.wchusbserial1410';
var sensorData = 0;
var rainData = 0;
var rainSound;

function preload(){
  rainSound = loadSound("rain.mp3");
}

function setup() {
  createCanvas(640, 360);
  for (var i = 0; i < 1000; i++) {
    drops[i] = new Drop();
  }

  rainSound.play();
  
  serial = new p5.SerialPort();
	serial.on('connected', serverConnected);
	serial.on('open', portOpen);
	serial.on('data', serialEvent);
	
	serial.list();
	serial.open(portName);
}

function serverConnected() {
  //println('connected to server.');
}
 
function portOpen() {
  //println('the serial port opened.')
}

function serialEvent() {
	sensorData = serial.readLine();
}


function draw() {
  background(220,220,220);
  
  rainData = lerp(rainData, sensorData, 0.04);
  text("rain percentage: " + round((rainData /50)*100) + "%", 30, 30);

  var rainAmount = rainData * 15; 
  for (var i = 0; i < rainAmount; i++) {
    drops[i].fall();
    drops[i].show();
  }
  
  var rainVol = rainData * 2
  var volume = map(rainVol, 0, 50, 0, 1);
  rainSound.setVolume(volume);
}

October 17, 2017

Leave a Reply