Crit1 Development: Experiment with Button and p5js

I ran into challenges with the previous DHT22 sensor to p5js assignment. I performed another test run using input from a button. With this, I was able to connect the p5.js web editor to the arduino, and have an image on the screen of the web editor change when the button input changed.

Arduino sketch below:

const int buttonPin = 2;
int buttonValue = 0; 

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

}

void loop() {
  // put your main code here, to run repeatedly:
  buttonValue = digitalRead(buttonPin);
  Serial.println(buttonValue);
  delay(10);

}

p5js sketch:

let serial; 
let newData = "waiting for data";

function setup() {
  createCanvas(windowWidth, windowHeight);
  serial = new p5.SerialPort();
  serial.list();
  serial.open('COM5');
  serial.on('connected', serverConnected);
  serial.on('list',gotList);
  serial.on('data',gotData);
  serial.on('error',gotError);
  serial.on('open',gotOpen);
  
}

function serverConnected() {
  print("Connected to Server");
}

function gotList(thelist) {
  print("List of Serial Ports:");
  
  for (let i=0; i < thelist.length; i++) {
    print(i + " " + thelist[i]);
    
  }
}

function gotOpen() {
  print("Serial Port is Open");
}

function gotClose() {
  print("Serial Port is Closed");
  newData = "Serial Port is Closed";
}

function gotError(theerror) {
  print(theerror);
}

function gotData() {
  let currentString = serial.readLine();
  trim(currentString);
  if (!currentString) return;
  console.log(currentString);
  newData = currentString;
}

function draw() {
  background(245,245,245);
  fill(50,50,200);
  text(newData,10,10);
  
  
  if (newData == 0) {
    rectMode(CENTER);
    rect(width/2,height/2,100,100);
  } else {
    ellipse(width/2,height/2,200,200);
    
  }
  
}

Next, for the Crit1 project, I want to be able to record or represent the actions of the plant turntable with p5js.

Resources and Demos:

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.