Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagec#
titleA computer can connect wirelessly to the Arduino and get the measured distance via bluetooth terminal
linenumberstrue
collapsetrue
#define trigPin 31
#define echoPin 33
char blueToothVal;
 
void setup() {
 Serial.begin(9600); 
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
}
 
long getDistance() {
  long duration, distance;
  digitalWrite(13,HIGH);
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;
  
  if (distance >= 400 || distance <= 0){
      distance = getDistance();
  }
  
  return distance;
}
 
 
void loop() {
  
  if(Serial.available()>0) {
    blueToothVal=Serial.read();
  }
  if (blueToothVal=='x') {
    Serial.print(getDistance());
    Serial.println(" cm");
  }
 
  // Reset blueToothVal to any letter but 'x'
  blueToothVal = 'c';
  delay(100);
}

The Bluetooth bluetooth module is found on the MacBook Pro as HC-06 in the list of available Bluetooth bluetooth devices. A connection can be established with Code '1234'.

...

Unfortunately the MacBook does not reconnect automatically after reset of the Arduino. The Bluetooth bluetooth module has to be unpaired and paired again to be usable again. Hopefully this will can be fixed somehow...

...

A much easier way of connecting via Bluetooth bluetooth is to use the Arduino Serial Monitor (Tools -> Serial Monitor).

It is now clear, how the module is handled by the MacBook Pro. Once paired, the HC-06 is always shown in the list of Bluetooth devices bluetooth devices as 'Not connected', unless an explicit connection is established. Establish a connection with a screen or the Serial Monitor. Once the connection is closed, HC-06 will be shown as 'Not connected' again. It is important to notice that the previous screen method has to be killed explicitly, not only closed, since there can only be one serial connection at once.

...