Skip to content

Instantly share code, notes, and snippets.

@billykwok
Created September 15, 2021 22:02
Show Gist options
  • Save billykwok/62d36694504c101a9c6f15e85579e252 to your computer and use it in GitHub Desktop.
Save billykwok/62d36694504c101a9c6f15e85579e252 to your computer and use it in GitHub Desktop.
import SerialPort from 'serialport';
import readline from 'readline';
(async () => {
const entries = await SerialPort.list();
const entry = entries.find(
(it) => it.manufacturer && it.manufacturer.includes('Arduino')
);
if (!entry) {
console.warn('No Arduino found');
return;
}
console.info(`Connecting to ${entry.path}...`);
const port = new SerialPort(entry.path, { baudRate: 9600 });
const parser = port.pipe(
new SerialPort.parsers.Readline({ delimiter: '\r\n', encoding: 'ascii' })
);
await new Promise((resolve, _) => {
const listener = () => {
resolve(undefined);
parser.removeListener('data', listener);
};
parser.addListener('data', listener);
});
console.info('Device is now ready for serial communication');
const rgb = [0, 0, 0];
readline.emitKeypressEvents(process.stdin);
process.stdin.setRawMode(true);
process.stdin.on('keypress', (c, key) => {
if (key.sequence === '\u0003') {
process.exit();
}
switch (c) {
case 'r':
rgb[0] = (rgb[0] + 20) % 256;
break;
case 'g':
rgb[1] = (rgb[1] + 20) % 256;
break;
case 'b':
rgb[2] = (rgb[2] + 20) % 256;
break;
}
port.write(Buffer.from(Uint8ClampedArray.of(...rgb, 0x0a)));
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment