Week 12 In-class Exercise

1. Make something that uses only one sensor  on Arduino and makes the ellipse in p5 move on the horizontal axis, in the middle of the screen, and nothing on Arduino is controlled by p5. 

For this task, I have used a photoresistor as the sensor. The sensor reading is being sent to the P5.js sketch to move the ellipse on the horizontal axis and change the background color.

Arduino Code

const int analogIn = A1;
void setup() {
  Serial.begin(9600);
}
void loop() {
    int analogValue = analogRead(analogIn); 
    Serial.println(analogValue);
}

 

P5.js Sketch

 

2.  Make something that controls the LED brightness from p5

For this task, I have made a p5.js sketch that makes the canvas a switch. If you click on the left of the canvas, the LED brightness decreases and the color of the canvas gets darker.  Conversely, if you click on the right of the canvas, the brightness increases and the canvas becomes lighter.

Arduino Code

int LED = 11;

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
  while (Serial.available() <= 0) {
    Serial.println("Initializing Connection");
    delay(200);
  }
}

void loop() {
  while (Serial.available()) {

    int brightness = Serial.parseInt();
    if (Serial.read() == '\n') {
      analogWrite(LED, brightness);
      Serial.println("ON");
    }
  }
}

 

P5.js Sketch

 

3. Take the gravity wind example and make it so every time the ball bounces one LED lights up and then turns off, and you can control the wind from one analog sensor

In this exercise, I established bi-directional data exchange. Firstly, when the ball hits the ground in the p5.js sketch, a signal is sent to the Arduino. This signal is triggered by checking if the bottom portion of the ellipse touches the lower boundary of the canvas. Upon receiving this signal, the Arduino program toggles the LED accordingly. Conversely, the Arduino sends the photoresistor value to p5.js. This value is mapped to the range of wind strength (wind.x).

Arduino Code

const int analogIn = A0;
const int LED = 12;
void setup() {
  Serial.begin(9600);
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(analogIn, INPUT);
  while (Serial.available() <= 0) {
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println("0,0");
    delay(200);
    digitalWrite(LED_BUILTIN, LOW);
    delay(50);
  }
}
void loop() {
  while (Serial.available()) {
    digitalWrite(LED_BUILTIN, HIGH);
    digitalWrite(LED, LOW);
    int position = Serial.parseInt();

    if (Serial.read() == '\n') {
      int sensorValue = analogRead(analogIn);
      Serial.println(sensorValue);
    }
    if (position == 0) {
      digitalWrite(LED, HIGH);
    } else {
      digitalWrite(LED, LOW);
    }
  }
  digitalWrite(LED_BUILTIN, LOW);
}

 

P5.js Sketch

 

 

 

 

Leave a Reply