Serial Communication Exercises Collaboration with Ahmed

In collaboration with Ahmed 

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

p5.js

 

Arduino

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(200);                                            
}

 

Exercise 2

Make something that controls the LED brightness from p5:

p5.js

Arduino

void setup() {
 Serial.begin(9600); // initialize serial communications
}
void loop() {
 if(Serial.available()) {
   digitalWrite(LED_BUILTIN, HIGH); // led on while receiving data
 
   int light = Serial.read();
   Serial.println(light);

   // the led is connected to digital pin 3 with pwm
   analogWrite(3, light);
 }                                         
}

 

Exercise 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.

p5.js

Arduino

int potentiometer = A0;
int serialRead = 0;

void setup()
{
  Serial.begin(9600);
  pinMode(3, OUTPUT); //the led is connected to 3 pwm digital
}
 
void loop() 
{
  while (Serial.available() > 0) 
  {
    serialRead = Serial.read();
    analogWrite(3, serialRead); //the led is connected to 3 pwm digital
  }

  int mappedPotentiometer = map(analogRead(potentiometer), 0, 1023, 0, 255); 
  Serial.write(mappedPotentiometer);                                            
  delay(200);
}

Video

Leave a Reply