Stap 6: Weergavegrootte van 3D-objecten op het scherm ten opzichte van de afstand met verwerking
Het doel was hier om te zien de afstand meer figuurlijk dan slechts een nummer op het scherm. De grootte varieert objecten op basis van de afstand MaxSonic leest van een object.
Verwerking van code:
import processing.serial.*; Serial myPort; // The serial port, wont be able to connect if the seril monitor in arduino is open so make sure to close it String inBuffer = null; // stores one line of data from serial port int x, y, z; int lf = 10; // Linefeed in ASCII void setup() { size(640, 360, P3D); noStroke(); println(Serial.list()); myPort = new Serial(this, Serial.list()[5], 9600); // serial.list[1] for usb [0] for direct serial } void draw() { if(x<60){ x=40; } lights(); background(204); float cameraY = height/2.0; float fov =( x/float(width))+0.2 * PI/2; float cameraZ = cameraY / tan(fov / 2.0); float aspect = float(width)/float(height); if (mousePressed) { aspect = aspect / 2.0; } perspective(fov, aspect, cameraZ/10.0, cameraZ*10.0); fill(150,0,0); translate(width/2+30, height/2, 0); rotateX(-PI/6); rotateY(PI/3 + 7/8* PI); box(45); translate(0, 0, -50); box(30); } void serialEvent(Serial myPort) { inBuffer = myPort.readStringUntil(lf); // store serial port buffer in global var inBuffer (read string until linefeed (int lf = 10; // Linefeed in ASCII) etc if (inBuffer != null) { println("SERIAL:" + inBuffer); // print the linefrom then serial input try { float[] dat = float(split(inBuffer, ',')); // parse comma-separated number string into numbers array x= int (dat[0]); y= int (dat[1]); z= int (dat[2]); } catch (Exception e) { // if there is a non parsible string its declared null inBuffer=null; } println( x ); } }
We kregen deze code van Nicholas Stevens.
Arduino code:
//Please be respectful by acknowledging the author in the code if you use or modify it.<br>//Author: Bruce Allen //Date: 23/07/09 //Digital pin 7 for reading in the pulse width from the MaxSonar device. //This variable is a constant because the pin will not change throughout execution of this code. const int pwPin = 7; //variables needed to store values long pulse, inches, cm; int output; void setup() { //This opens up a serial connection to shoot the results back to the PC console Serial.begin(9600); } void loop() {<br> pinMode(pwPin, INPUT);<br> //Used to read in the pulse that is being sent by the MaxSonar device. //Pulse Width representation with a scale factor of 147 uS per Inch.<br> pulse = pulseIn(pwPin, HIGH); //147uS per inch inches = pulse/147; //change inches to centimetres cm = inches * 2.54;<br>// Serial.print(inches); // Serial.print("in, "); // Serial.print(cm); // Serial.print("cm"); // Serial.println(); output= map(cm,0,645,0,1023);<br> Serial.println(output);<br> delay(1);<br>}
We vonden de code hier, onder de PW: http://playground.arduino.cc/Main/MaxSonar (Allen, 09.10.14)
Wij veranderde de code, de uitvoer is slechts cm (niet de cm en inch).