Force Sensor
The LEGO Force Sensor (45606) is a button that also measures how hard it's pressed. Use it as a bumper, a trigger or a switch.
BuildHat comes from a library, not from the language, so this code won't build without it. In
IntelliJ, choose Tools | Nylon | Add Nylon Library… and pick build-hat. It brings the Raspberry
Pi library with it, and adds one line to your project's build.markup.code:
(+dependencies : RepositoryDependency coordinate={"com.grandtheorem:build-hat:0.3.0"} /)
Read a press
Plug the sensor into port C. Any port works, as long as the program names the same one.
Pi is the board, BuildHat is the HAT on top of it, and Port names the HAT's ports.
# Wait for a press, and say how hard it was.
namespace press
import grandtheorem.rpi.Pi
import grandtheorem.buildhat.BuildHat
import grandtheorem.buildhat.Port
import namespace nylon.time
BuildHat.connect starts the HAT, and forceSensor gives the sensor on a port.
# The Force Sensor in port C.
entrypoint.default main() {
let hat = BuildHat.connect(Pi)
let button = hat.forceSensor(Port.C)
waitUntilPressed waits for a press, for as long as you give it, and answers whether one came. force() is how hard
it's pressed, from 0 to 100.
# Wait up to 10 seconds for a press.
if (button.waitUntilPressed(10.seconds())) {
if (let force? = button.force()) {
println("pressed at ${force}")
}
button.waitUntilReleased(10.seconds())
println("released")
} else {
println("no press in 10 seconds")
}
peakForce() is the hardest it has been pressed since the HAT powered up, over every run since.
if (let peak? = button.peakForce()) {
println("the hardest press: ${peak}")
}
}
Press the button within 10 seconds and let go. It prints how hard the press was as it began, such as
pressed at 12, then released, then the hardest press since the HAT powered up.
Everything the sensor can do
| Call | What it does |
|---|---|
hat.forceSensor(port) | The Force Sensor on a port |
button.force() | How hard it's pressed, 0 to 100, as an i32? |
button.peakForce() | The hardest it has been pressed since the HAT powered up, 0 to 100, as an i32? |
button.isPressed() | Whether it's pressed, as the sensor itself judges it |
button.waitUntilPressed(timeout) | Waits for a press, and answers whether one came in time |
button.waitUntilReleased(timeout) | Waits for it to be let go, and answers whether it was in time |
Good to know
A reading is taken when you ask for it. Each call asks the sensor once. force() and peakForce() give nothing
when the sensor doesn't answer within half a second. isPressed() has to answer, so a sensor that doesn't ends the
run.
A wait checks every 50 milliseconds. A tap shorter than that can be missed.
The wrong part on the port ends the run. If port C has a motor instead, the run ends and says what's there.
Boards: every board on Boards.