Skip to content

Commit 4578da4

Browse files
committed
Fixes error when writing new address to the ultrasonic object forcing an unnecessary reload
* Updates example four to continue with reading distance at the changed address.
1 parent 8668f36 commit 4578da4

File tree

2 files changed

+22
-11
lines changed

2 files changed

+22
-11
lines changed

examples/Example4_ChangeAddress/Example4_ChangeAddress.ino

+19-6
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ void setup()
6666
// Call change address.....
6767
sfeTkError_t err = myUltrasonic.changeAddress(newAddr);
6868

69+
6970
if(err)
7071
{
7172
while(1)
@@ -75,16 +76,28 @@ void setup()
7576
delay(1000);
7677
}
7778
}
78-
delay(1000);
7979

80-
Serial.print("Load up example 1 with the new address at: ");
81-
Serial.println(newAddr, HEX);
82-
Serial.println("Freezing....");
83-
while(1)
84-
;
80+
Serial.println("Address changed successfully!");
81+
Serial.println("Reading Distance at new address......");
82+
delay(3000);
8583

8684
}
8785

8886
void loop()
8987
{
88+
uint16_t distance = 0;
89+
myUltrasonic.triggerAndRead(distance);
90+
91+
// Print measurement
92+
Serial.print("Distance (mm): ");
93+
Serial.println(distance);
94+
95+
//Serial.println("Distance (cm): ");
96+
//Serial.print((distance / 10.0), 2);
97+
98+
//Serial.println("Distace (in): ");
99+
//Serial.print((distance / 25.4), 2);
100+
101+
// Wait a bit
102+
delay(100);
90103
}

src/sfeQwiicUltrasonic.cpp

+3-5
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,8 @@ sfeTkError_t sfeQwiicUltrasonic::changeAddress(uint8_t &address)
8686
return kSTkErrFail;
8787

8888
// We want to shift the address left before we send it.
89-
address <<= 1;
90-
const uint8_t toWrite[2] = {kUltrasonicAddressChangeCommand, address};
89+
uint8_t tempAddress = address << 1;
90+
const uint8_t toWrite[2] = {kUltrasonicAddressChangeCommand, tempAddress};
9191

9292
// Write the new address to the device
9393
err = _theBus->writeRegion(toWrite, numBytes);
@@ -99,13 +99,11 @@ sfeTkError_t sfeQwiicUltrasonic::changeAddress(uint8_t &address)
9999
return kSTkErrFail;
100100
}
101101

102+
_theBus->setAddress(address);
102103
// Check whether the write was successful
103104
if (err != kSTkErrOk)
104105
return err;
105106

106-
// Update the address in the bus
107-
_theBus->setAddress(address);
108-
109107
// Done!
110108
return kSTkErrOk;
111109
}

0 commit comments

Comments
 (0)