Important: This guide requires a Script block version 1.3.3 or later. Don't know what version you have? Find out |
All hardware blocks have settings you can configure to alter the behaviour of the device. Through the UI you normally do it by opening the properties panel, changing the settings you wish and then pressing save. But the Script block has a native way to do the same without even adding other blocks into the canvas.
In this tutorial, we will learn how to read and change the settings of a MotorDriver block as well as how to call native API Methods to make a motor rotate.
- Snap together a WiFi + Power Station and Motor Driver block.
- Connect a brushed motor to port 1 of the Motor Driver. Make sure your PowerStation is connected to a power source.
- Make sure that the MotorDriver appears online and then add a Script block into the canvas. If you don't have a Script block installed yet, you can install it from the Market Place.
- Go into editing mode by double-clicking on the canvas icon or by clicking on the ‘Logic Maker’ icon:
- Inside the editor paste the following code and hit ‘Apply’:
async function main(){
var motorBlock = await Kitsi.waitForBlock(BlockTypes.MotorDriver); // Wait for motor driver to be online
// -----------------------------------------------------------------------------------------------------------------------
// This is only required if the block's settings haven't been pre-configured
var settings = await Kitsi.readSettings(motorBlock); // Read current settings
settings.Custom.DeviceMode[1] = 2; // Make sure output 1 is configured as brushed
settings.Custom.PowerTimeout[1] = 1000 ; // Keep rotating for 1000ms (1 second);
await Kitsi.saveSettings(motorBlock, settings); // Save new settings
// -----------------------------------------------------------------------------------------------------------------------
await Kitsi.APICall('SetSpeed', {1: 25}, motorBlock); // Rotate the motor at 25% power
console.info("OK");
}
main();
If the MotorDriver is online, the motor should rotate for about a second and then stop. Feel free to tweak the code to see what happens. Try increasing the amount of time the motor will remain rotating.
Note how the section in the middle is there to read the block settings and change the device mode and timeouts. This only needs to be done once to configure the block and can be removed after the first time the scripts runs, leaving you with a simpler version of the code:
async function main(){
var motorBlock = await Kitsi.waitForBlock(BlockTypes.MotorDriver); // Wait for motor driver to be online
await Kitsi.APICall('SetSpeed', {1: 25}, motorBlock); // Rotate at 25% power
console.info("OK");
}
main();