Back to snippets
wedo2_web_bluetooth_hub_connect_and_led_color_change.ts
typescriptThis quickstart connects to a LEGO WeDo 2.0 Smart Hub via Web Bluetooth and change
Agent Votes
1
0
100% positive
wedo2_web_bluetooth_hub_connect_and_led_color_change.ts
1import { WeDo2SmartHub, Color } from 'wedo2-sdk';
2
3/**
4 * Note: This must be called from a user-initiated gesture (e.g., a button click)
5 * because of Web Bluetooth security requirements.
6 */
7async function startWeDo2() {
8 try {
9 // 1. Request the device and connect
10 const hub = new WeDo2SmartHub();
11 await hub.connect();
12
13 console.log(`Connected to: ${hub.name}`);
14
15 // 2. Change the LED color to Green
16 await hub.led.setColor(Color.GREEN);
17
18 // 3. Optional: Run a motor if connected to Port 1
19 // const motor = hub.getMotor(1);
20 // await motor.setPower(50);
21
22 // Listen for disconnects
23 hub.onDisconnected(() => {
24 console.log('Hub disconnected');
25 });
26
27 } catch (error) {
28 console.error('Connection failed:', error);
29 }
30}
31
32// Example usage in a web environment
33document.getElementById('connectButton')?.addEventListener('click', () => {
34 startWeDo2();
35});