Last active
April 24, 2021 11:39
-
-
Save pimpelsang/d4f2d91ada4dbeeb6ade03b5d7a2ac1c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <html> | |
| <head> | |
| <title>one motor wedo remote</title> | |
| <script src="https://cdn.jsdelivr.net/npm/node-poweredup@latest/dist/browser/poweredup.js"></script> | |
| <style type="text/css"> | |
| #forward { | |
| position: fixed; | |
| width: 100%; | |
| height: 50%; | |
| font-size: 50pt; | |
| } | |
| #backward { | |
| position: fixed; | |
| top:50%; | |
| width: 100%; | |
| height: 50%; | |
| font-size: 50pt; | |
| } | |
| #controls { | |
| display: none; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <button id="connect" onclick="connect()">connect</button> | |
| <div id="controls"> | |
| <button id="forward">⬆️</button> | |
| <button id="backward">⬇️</button> | |
| </div> | |
| <script> | |
| if (!PoweredUP.isWebBluetooth) { | |
| alert("Your browser does not support the Web Bluetooth."); | |
| } | |
| let SPEED = 80; | |
| const poweredUP = new PoweredUP.PoweredUP(); | |
| poweredUP.on("discover", onDiscover); | |
| let hub; | |
| function connect() { | |
| poweredUP.scan(); | |
| document.getElementById('connect').style.display='none'; | |
| document.getElementById('controls').style.display='block'; | |
| } | |
| let motorA; | |
| async function onDiscover(newHub) { | |
| hub = newHub; | |
| console.log(`Discovered ${hub.name}!`); | |
| await hub.connect(); | |
| motorA = await hub.waitForDeviceByType(PoweredUP.Consts.DeviceType.SIMPLE_MEDIUM_LINEAR_MOTOR); | |
| console.log('Motors ready') | |
| } | |
| // buttons and are they down | |
| let buttons = { | |
| forward: false, | |
| backward: false, | |
| }; | |
| for (const button in buttons) { | |
| let el = document.getElementById(button) | |
| el.addEventListener('touchstart', function(e) { | |
| e.preventDefault(); | |
| buttons[button] = true; | |
| // console.log(`${button} pressed`); | |
| update(); | |
| }) | |
| el.addEventListener('touchend', function(e) { | |
| e.preventDefault(); | |
| buttons[button] = false; | |
| // console.log(`${button} released`); | |
| update(); | |
| }); | |
| } | |
| async function update() { | |
| if (!motorA) return; | |
| let a = 0; | |
| // simple car mode | |
| if (buttons.forward) { | |
| console.log("driving forward"); | |
| a = 1; | |
| } else if (buttons.backward) { | |
| console.log("driving back"); | |
| a = -1; | |
| } else { | |
| console.log("stop driving"); | |
| } | |
| await motorA.setPower(a * SPEED); | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment