範例2-4

範例程式
程式結果
1為未按按鈕、0為按按鈕
套用結合processing程式檔
結合按鈕前進後退
程式碼:
import processing.serial.*;
Serial myPort;
int val;
void setup() {
size(640, 480, P3D);
rectMode(CENTER);
myPort=new Serial(this,"COM3",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){
val=myPort.read();
}
println(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;
}
background(100);
drawCar();
rect(0+187/2, 0+89/2, 187, 89);
rect(450+187/2, 0+89/2, 187, 89);
}
設置兩按鈕
程式:
/*
Input Pullup Serial
This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a
digital input on pin 2 and prints the results to the serial monitor.
The circuit:
* Momentary switch attached from pin 2 to ground
* Built-in LED on pin 13
Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
20K-ohm resistor is pulled to 5V. This configuration causes the input to
read HIGH when the switch is open, and LOW when it is closed.
created 14 March 2012
by Scott Fitzgerald
http://www.arduino.cc/en/Tutorial/InputPullupSerial
This example code is in the public domain
*/
void setup(){
//start serial connection
Serial.begin(9600);
//configure pin2 as an input and enable the internal pull-up resistor
pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
pinMode(13, OUTPUT);
}
void loop(){
//read the pushbutton value into a variable
int sensorVal = digitalRead(2);
int sensorVal2 = digitalRead(3);
//print out the value of the pushbutton
if(sensorVal==LOW) Serial.println('0');
if(sensorVal2==LOW) Serial.println('1');
// Keep in mind the pullup means the pushbutton's
// logic is inverted. It goes HIGH when it's open,
// and LOW when it's pressed. Turn on pin 13 when the
// button's pressed, and off when it's not:
if (sensorVal == HIGH) {
digitalWrite(13, LOW);
}
else {
digitalWrite(13, HIGH);
}
}



沒有留言:
張貼留言