Serial Communication

Schematic: It includes all 3 exercises using 1 Arduino.

Exercise 1

Arduino Code:

void setup() {
  Serial.begin(9600); // initialize serial communications
}
 
void loop() {
  // read the input pin:
  int potentiometer = analogRead(A0);                  
  // remap the pot value to fit in 1 byte:
  int mappedPot = map(potentiometer, 0, 1023, 0, 255);
  // print it out the serial port:
  Serial.write(mappedPot);
  //Serial.println(mappedPot);
  // slight delay to stabilize the ADC:
  delay(1);                                            
}

Exercise 2 (cred to Aisha)

Arduino Code:

int LED = 11;

void setup() {
  Serial.begin(9600);
  pinMode(LED, OUTPUT);
  // start the handshake
  while (Serial.available() <= 0) {
    Serial.println("Wait");  // send a starting message
    delay(300);               // wait 1/3 second
  }
}

void loop() {
  // wait for data from p5 before doing something
  while (Serial.available()) {
    int brightness = Serial.parseInt(); 
    if (Serial.read() == '\n') {
      analogWrite(LED, brightness); // turn on LED and adjusts brightness
      Serial.println("LIT"); 
    }
  }
}

Exercise 3 (cred to Joonha)

Arduino Code included in the p5.js sketch.

Working Video:

Leave a Reply