Ok, der Ultraschallsensor ist eingebaut und ich kann die Distanz in cm auf meinem Processing-GUI anzeigen.
Aber nach 1-2s stürzt mir das Teil ab.
java.lang.NullPointerException
at processing.mode.java.runner.Runner.findException(Runner.java:947)
at processing.mode.java.runner.Runner.reportException(Runner.java:892)
at processing.mode.java.runner.Runner.exceptionEvent(Runner.java:818)
at processing.mode.java.runner.Runner$2.run(Runner.java:707)
Ich weiss jetzt echt nicht wo suchen...
Arduino-Code:
int TableDown = 7; // Arduino Pin to move the table down, Relais 1
int TableUp = 6; // Arduino Pin to move the table up, Relais 2
int trigPin = 12; // Arduino Pin to trigger ultrasonic sensor
int echoPin = 11; // Arduino Pin to receive ultrasonic values
void setup()
{
pinMode(TableDown, OUTPUT);
pinMode(TableUp, OUTPUT);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
// initialize the serial communication:
Serial.begin(9600);
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;
//delayMicroseconds(100);
Serial.println(distance);
//delayMicroseconds(100);
byte buttonPressed;
// check if data has been sent from the computer:
if (Serial.available()) {
// read the most recent byte (which will be from 0 to 255):
buttonPressed = Serial.read();
// 1 = Button Down
if(buttonPressed == 1){
digitalWrite(TableDown,HIGH);// NO1 and COM1 Connected;
}
// 2 = Button Up
if(buttonPressed == 2){
digitalWrite(TableUp,HIGH);// NO2 and COM2 Connected;
}
// Stop all Buttons
if(buttonPressed == 0){
digitalWrite(TableDown,LOW);// NO1 and COM1 Disconnected;
digitalWrite(TableUp,LOW);// NO2 and COM2 Disconnected;
}
}
}
Processing Code (ohne GUI):
// Need G4P library
import g4p_controls.*;
import processing.serial.*;
Serial port;
public void setup(){
size(480, 320, JAVA2D);
createGUI();
customGUI();
// Place your setup code here
}
public void draw(){
background(230);
}
// Use this method to add additional statements
// to customise the GUI controls
public void customGUI(){
port = new Serial(this, "COM4", 9600);
buttonDown.fireAllEvents(true);
buttonUp.fireAllEvents(true);
}
void serialEvent(Serial port) // Is called everytime there is new data to read
{
if (port.available() > 0)
{
String completeString = port.readStringUntil(10); // Read the Serial port until there is a linefeed/carriage return
if (completeString != null) // If there is valid data insode the String
{
trim(completeString); // Remove whitespace characters at the beginning and end of the string
distanceVal.setText(completeString);
}
}
}
Kann mir höchstens vorstellen, dass das dauernde write und read auf dem serialport Probleme macht, habe schon Diverses versucht, ohne Erfolg. Delays, Exceptions, irgendwas mit threadsave iterations...
Hat jemand ne Idee?
Gruss
Mario