So the task was to make things happen in p5.js using arduino or physical actions of the user. We had a moisture sensor so we decided to make a simple weather application in p5. If the moisture sensor detects moisture it draws a raindrop animation, otherwise it shows sunny weather.
Here is a video of POC:
The way it works is this:
Step1: Make your simple circuit
Step2: Write your code in arduino and do Serial.println(sensorReading); Here is the code:
Step3: Now Arduino sends the sensor value to the port that it is connected to. All we need is for p5 to listen to the same port and accept the sensor values. Since we are using a web editor for p5, it cannot listen to the hardware on our computer directly, so we need a local server. Van Every has made one for us, download it from here:
Step4: Now we want p5 to listen to this local server. So here is the code you have to include:
and create a reference to it in your html file.
Step5: Declare a global variable called serial and include this code in your setup function:
in this the serial.open listens to the port you define in the parenthesis. This is the same port that your arduino is sending data to. The serial.on(‘data’, serialEvent) listens to data and whenever it receives data it triggers the function serialEvent. The serialEvent function looks like this:
Its accepts the values as a string and the number function converts it to integer. Once we have the sensorValue in p5 we can do whatever we want with it.
Here is the final p5 code: