SAM object. You can set outputs, read sensor values, respond to button presses, and build looping programs — all in standard JavaScript with a small set of extra tools built in.
SAM Script runs all JavaScript inside an async context, which means you must use
await before any call that talks to hardware. Forgetting await is the most common mistake — your code will run but the hardware won’t respond as expected.Connecting to a block
Before you can control a SAM hardware block, you need to connect to it by name. UseSAM.connect() and give it the block type as a string:
const (or let) variable. All subsequent calls to that block go through this variable.
Controlling hardware blocks
LED
Control the LED’s colour and brightness. Pass red, green, and blue values, each between 0 and 255:Button
Connect to a button and register callback functions that fire when the button is pressed or released:DC motor
Control the speed and direction of a DC motor:Servo
Set a servo to a specific angle between 0 and 180 degrees:Light sensor
Read the current light level or register a callback that fires whenever the value changes:Buzzer
Play musical notes or raw frequencies on a buzzer block:Pausing your program
UseSAM.wait() to pause execution for a set number of milliseconds:
await this call — without it your program won’t actually pause.
Loops and conditions
You can use any standard JavaScript control flow in SAM Script. Here’s a complete example that reads a button and changes an LED colour in a continuous loop:Adding a short
SAM.wait() inside a while (true) loop is important. Without a pause, your program sends commands to the hardware as fast as possible, which can overwhelm the Bluetooth connection. A wait of 50–200 ms is usually enough.Common patterns
There are two main ways to structure a SAM Script JavaScript program: event-driven and polling loops. Each suits different situations.- Event-driven
- Polling loop
In an event-driven program, you register callback functions that run automatically when something happens — for example, when a button is pressed. Your main program doesn’t need to check anything repeatedly.Best for: reacting to button presses, timers, or other discrete events.
When you use
await inside a callback, mark the callback as async, as shown above.