2017年1月13日 星期五

Week13 林育廷

一、使用arduino範例的Digital中的DigitalInputPullup



參考範例



實作->按下會發亮



沒按時為1



按下時為0



二、套用到車子程式碼



測試回傳值是否正確



程式碼:

import processing.serial.*;
Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

void setup() {
size(640, 480, P3D);
rectMode(CENTER);
myPort = new Serial(this, "COM4", 9600);
}
  float carX=640/2, carY=320/2;
  float carDir=PI, carWheel=0;
  void drawCar() {
    pushMatrix();
    translate(carX, carY);
    rotateZ(carDir);
    rect(0, 0, 187, 89);
    drawWheel(127/2, 89/2, 1);
    drawWheel(127/2, -89/2, 1);
    drawWheel(-127/2, 89/2, 0);
    drawWheel(-127/2, -89/2, 0);
  if (keyPressed && keyCode==UP) {
    carX+= cos(carDir+carWheel); 
    carY+=sin(carDir+carWheel);
    carDir+=carWheel/50;
  } else if (keyPressed && keyCode==DOWN) {
    carX-= cos(carDir+carWheel); 
    carY-=sin(carDir+carWheel);
    carDir-=carWheel/50;
  } else if (keyPressed && keyCode==RIGHT) {
    carWheel+=0.01;
  if (carWheel > 0.3) carWheel=0.3;
  } else if (keyPressed && keyCode==LEFT) {
  carWheel-=0.01;
  if (carWheel < -0.3) carWheel=-0.3;
  }
  popMatrix();
}
void drawWheel(float x, float y, int front) {
pushMatrix();
translate(x, y);
if (front==1) rotateZ(carWheel);
rect(0, 0, 40, 20);
popMatrix();
}
void draw() {
  while ( myPort.available() > 0) {  // If data is available,
    val = myPort.read();     // read it and store it in val
  if(val==48)  //前進 
  {
    carX+=cos(carDir+carWheel);
    carY+=sin(carDir+carWheel);
    carDir+=carWheel/50;
  }
  else if(val==49) //後退
  {
    carX-=cos(carDir+carWheel);
    carY-=sin(carDir+carWheel);
    carDir-=carWheel/50;
  }
}
  println(val);
  background(100);
  drawCar();
  rect(0+187/2, 0+89/2, 187, 89);
  rect(450+187/2, 0+89/2, 187, 89);
}




沒有留言:

張貼留言