Skip to main content
SAM Script’s JavaScript mode gives you direct, text-based control over your SAM Labs hardware using a clean, purpose-built API. Every hardware block you connect to SAM Studio is accessible through the global 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. Use SAM.connect() and give it the block type as a string:
Store the result in a const (or let) variable. All subsequent calls to that block go through this variable.
If you have more than one block of the same type, SAM Studio will prompt you to select which physical block you mean when SAM.connect() runs.

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:
You can also check the button’s current state at any point in your program:

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

Use SAM.wait() to pause execution for a set number of milliseconds:
Always 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.
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.

Quick reference

Use console.log() to print values to the SAM Script console panel at the bottom of the editor. This is the quickest way to check what a sensor is reading or to trace through your program’s logic.