Serial Communication Exercises

Exercise 1:

P5.Js

Arduino

void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(5, OUTPUT);
  //handshake method ALWAYS - LEAVE THIS ALWAYS
  while (Serial.available() <= 0) {
    Serial.println("0,0"); // send a starting message
    delay(300);              // wait 1/3 second
  }
}

void loop() {
  while (Serial.available() > 0) {
    // read the incoming byte - always read whether you need that info or not
   int inByte = Serial.read();
    switch (inByte) {
      case 0:
        digitalWrite(2, LOW);
        digitalWrite(5, LOW);
        break;
      case 1:
        digitalWrite(2, HIGH);
        break;
      case 2:
        digitalWrite(5, HIGH);
        break;
    }

    int sensorValue = analogRead(A0);
    Serial.print(sensorValue);
    Serial.print(",");
    sensorValue = analogRead(A1);
    Serial.print(sensorValue);
    Serial.println();
  }
}

Exercise 2:

P5.Js

Arduino

void setup() {
  Serial.begin(9600);
  pinMode(3, OUTPUT);
  pinMode(5, OUTPUT);
  while (Serial.available() <= 0) {
    Serial.println("0,0"); // send a starting message
    delay(300);              // wait 1/3 second
  }
}
void loop() {
 
  while (Serial.available() > 0) {
    // read the incoming byte:
   int inByte = Serial.read();
       analogWrite(3, inByte);
    int sensorValue = analogRead(A0);
    Serial.print(sensorValue);
    Serial.println();
  }
}

 

Exercise 3:

P5.Js

Arduino

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

void loop() {
  while (Serial.available() > 0) {
    // read the incoming byte:
   int inByte = Serial.read();
    switch (inByte) {
      case 0:
        digitalWrite(2, HIGH);
        break;
      case 1:
        digitalWrite(2, LOW);
        break;
    }

    int sensorValue = analogRead(A0);
    Serial.print(sensorValue);
    Serial.println();
  }
}void setup() {
  Serial.begin(9600);
  pinMode(2, OUTPUT);
  pinMode(5, OUTPUT);
  while (Serial.available() <= 0) {
    Serial.println("0,0"); // send a starting message
    delay(300);              // wait 1/3 second
  }
}

void loop() {
  while (Serial.available() > 0) {
    // read the incoming byte:
   int inByte = Serial.read();
    switch (inByte) {
      case 0:
        digitalWrite(2, HIGH);
        break;
      case 1:
        digitalWrite(2, LOW);
        break;
    }

    int sensorValue = analogRead(A0);
    Serial.print(sensorValue);
    Serial.println();
  }
}

Video

https://youtube.com/shorts/ZJeZDM73hmI?feature=share

Leave a Reply