Week 11 Project Exercises

 

 

 

Exercise 1.1

let port;
let connectBtn;
let baudrate = 9600;
let lastMessage = "";

function setup() {
  createCanvas(400, 400);
  background(220);

  port = createSerial();

  // in setup, we can open ports we have used previously
  // without user interaction

  let usedPorts = usedSerialPorts();
  if (usedPorts.length > 0) {
    port.open(usedPorts[0], baudrate);
  }

  // any other ports can be opened via a dialog after
  // user interaction (see connectBtnClick below)

  connectBtn = createButton("Connect to Arduino");
  connectBtn.position(80, 200);
  connectBtn.mousePressed(connectBtnClick);

}

function draw() {
  background("255");
  

  
  // Read from the serial port. This non-blocking function
  // returns the complete line until the character or ""
  let str = port.readUntil("\n");
  if (str.length > 0) {
    // Complete line received
    // console.log(str);
    lastMessage = str;
    
  
  }
  
      
  
  // Display the most recent message
  text("Last message: " + lastMessage, 10, height - 20);

  // change button label based on connection status
  if (!port.opened()) {
    connectBtn.html("Connect to Arduino");
  } else {
    connectBtn.html("Disconnect");
  }
  
  
  ellipse(lastMessage,10,20,20)
}

function connectBtnClick() {
  if (!port.opened()) {
    port.open("Arduino", baudrate);
  } else {
    port.close();
  }
}

 

Exercise 1.2

let port;
let connectBtn;
let baudrate = 9600;
function setup() {
  createCanvas(255, 285);
  port = createSerial();
  let usedPorts = usedSerialPorts();
  if (usedPorts.length > 0) {
  port.open(usedPorts[0], baudrate);
 } else {
  connectBtn = createButton("Connect to Serial");
  connectBtn.mousePressed(() => port.open(baudrate));
 }
}
function draw() {
  background(225);
  circle(140,mouseY,25,25):
  let sendtoArduino = String(mouseY) + "\n"
  port.write(sendtoArduino);
}

Exercise 1.3

 

 

int led = 5;
void setup() {
  Serial.begin(9600);
}
 
void loop() {
  if (Serial.available()) {
    int ballState = Serial.parseInt(); 
    if (ballState == 1) {
      digitalWrite(led, HIGH); // ball on ground
    } else {
      digitalWrite(led, LOW); // ball in air or default
     }
  }
  // read the input pin:
  int potentiometer = analogRead(A1);                  
  int mappedPotValue = map(potentiometer, 0, 1023, 0, 900); 
  // print the value to the serial port.
  Serial.println(mappedPotValue);                                            
  
  delay(100);
}

 

 

 

 

Leave a Reply