Hi, I'm trying to use a HC-sr04 ultrasonic sensor and use the data in MaxMsP. I have a working sketch for the HC-sr04 and another one for communication with MaxMsp, tried to put them together into one working patch, but without result. Is there an easier way to send the data from the serial monitor into Max? Or can someone help me with merging the two sketches?
/*
* Ultrasonic Sensor HC-SR04 and Arduino Tutorial
*
* by Dejan Nedelkovski,
* www.HowToMechatronics.com
*
*/
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
int x = 0; // a place to hold pin values
// defines variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
digitalWrite(13,HIGH); ///startup blink
delay(600);
digitalWrite(13,LOW);
pinMode(13,INPUT);
}
void loop() {
if (Serial.available() > 0){ // Check serial buffer for characters
if (Serial.read() == 'r') { // If an 'r' is received then read the pins
for (int pin= 2; pin<=13; pin++){ // Read and send digital pins 2-13
x = digitalRead(pin);
sendValue (x);
}
Serial.println(); // Send a carriage returnt to mark end of pin data.
delay (5); // add a delay to prevent crashing/overloading of the serial port
}
}
}
void sendValue (int x){ // function to send the pin value followed by a "space".
Serial.print(x);
Serial.write(32);
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
Here's the attempt to merge them:
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}
if (Serial.read() == 'r') { // If an 'r' is received then read the pins
for (int pin= 2; pin<=13; pin++){ // Read and send digital pins 2-13
x = digitalRead(pin);
sendValue (x);
}
What's with the piss-poor indenting? That often stems from piss-poor thinking.
For example, why are you reading the state of the ping sensor pins? That will be useless information to Max/MSP.
Why does sendValue() read the ping sensor? There is NOTHING in the name of the function that says that it will do something stupid like that.
The poorly written code you posted does something. You forgot to tell us what it does.
You expect that mess to do something. You forgot to tell us what you expect.
P.S. It takes VERY little effort to use Tools + Auto Format, but makes a huge improvement in the look of your code.