sam module, connect to your blocks by name, and call methods to set outputs or read sensor values. If you’ve used Python in class or in another project, the syntax will feel immediately familiar — and the sam module keeps hardware interactions simple and direct.
Python in SAM Script uses snake_case method names (for example,
set_color, get_value). This is different from the JavaScript API, which uses camelCase (for example, setColor, getValue). If you switch between languages, keep this naming difference in mind.Importing and connecting
Start every SAM Script Python program by importing thesam module. Then use sam.connect() to link up with a hardware block:
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 define functions to run each time it is pressed or released:on_press() and on_release(). Notice there are no parentheses after the function names in the last two lines.
You can also check the button’s state at any point in a loop:
DC motor
Control the speed and direction of a DC motor:Servo
Move 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 number of milliseconds:
Loops and conditions
Use standard Pythonwhile loops and if statements to keep your program running and respond to sensor readings:
Always include a
sam.wait() call inside a while True loop. Without it, 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 a good balance between responsiveness and reliability.Full example — light-reactive LED
This example reads a light sensor continuously and changes the LED colour depending on how bright or dark the room is:Common patterns
- Event-driven
- Polling loop
Register callback functions that fire automatically when something happens. Your program doesn’t need to check inputs in a loop.Best for: responding to button presses or other discrete events.