### HTML/JavaScript Full-Stack Example for Raspberry Pi
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
A complete example demonstrating how to control hardware directly from a web browser on a Raspberry Pi. It includes HTML for the user interface and JavaScript to initialize GPIO for an LED and an I2C sensor for temperature monitoring. The script toggles an LED via a button and displays real-time temperature readings. Requires the CHIRIMEN polyfill.
```html
// Raspberry Pi でのフルスタック例
CHIRIMEN Example
温度モニター
--
```
--------------------------------
### Control GPIO with JavaScript (CHIRIMEN)
Source: https://tutorial.chirimen.org/index
This code snippet demonstrates how to control GPIO pins using the CHIRIMEN environment. It requires the 'requestGPIOAccess' function to get access to GPIO ports, which are then exported for output. The example shows a simple LED blink pattern by alternating the output value.
```javascript
const gpioAccess = await requestGPIOAccess(); // GPIO を操作する
const port = gpioAccess.ports.get(26); // 26 番ポートを操作する
await port.export("out"); // ポートを出力モードに設定
while (true) { // 無限に繰り返す
// ポートの出力値を 0/1 交互に変更
await port.write(1); // LED を点灯
await sleep(1000); // 1000ms 待機
await port.write(0); // LED を点灯
await sleep(1000); // 1000ms 待機
}
```
--------------------------------
### JavaScript Combined Control: Sensor to Actuator
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
Combines sensor readings with actuator control. This example reads temperature data from an I2C sensor and uses it to control an LED connected to a GPIO pin. The LED turns on if the temperature exceeds a threshold, demonstrating a basic feedback loop. Requires CHIRIMEN environment.
```javascript
// 温度に応じたLED制御の例
const gpioAccess = await requestGPIOAccess();
const i2cAccess = await requestI2CAccess();
// LED設定
const ledPort = gpioAccess.ports.get(26);
await ledPort.export("out");
// 温度センサー設定
const i2cPort = i2cAccess.ports.get(1);
const sensor = await i2cPort.open(0x48);
// 監視ループ
while (true) {
try {
// 温度読み取り
const data = await sensor.read8(0x00, 2);
const temperature = (data[0] << 8 | data[1]) / 16;
console.log(`温度: ${temperature.toFixed(1)}℃`);
// 閾値判定
if (temperature > 28) {
await ledPort.write(1); // 暑い → LED点灯
console.log("警告: 高温です");
} else {
await ledPort.write(0); // 正常 → LED消灯
}
await sleep(1000);
} catch (error) {
console.error("エラー:", error);
}
}
```
--------------------------------
### Production-ready IoT Controller in JavaScript
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
This JavaScript class, IoTController, is designed for production environments. It handles initialization of GPIO and I2C access, setup of LEDs and sensors, reading sensor data with retry logic, and includes essential cleanup methods. It utilizes async/await for non-blocking operations and incorporates error handling for robust device interaction.
```javascript
// プロダクション対応のCHIRIMENコード
class IoTController {
constructor() {
this.gpioAccess = null;
this.i2cAccess = null;
this.isInitialized = false;
}
async initialize() {
try {
// 初期化処理
this.gpioAccess = await requestGPIOAccess();
this.i2cAccess = await requestI2CAccess();
this.isInitialized = true;
console.log("初期化成功");
return true;
} catch (error) {
console.error("初期化エラー:", error);
return false;
}
}
async setupLED(pinNumber) {
if (!this.isInitialized) {
throw new Error("初期化されていません");
}
try {
const port = this.gpioAccess.ports.get(pinNumber);
await port.export("out");
return port;
} catch (error) {
console.error(`LED設定エラー (ピン${pinNumber}):`, error);
throw error;
}
}
async setupSensor(i2cAddress) {
if (!this.isInitialized) {
throw new Error("初期化されていません");
}
try {
const port = this.i2cAccess.ports.get(1);
const device = await port.open(i2cAddress);
// センサー疎通確認
await device.read8(0x00, 1);
console.log(`センサー接続成功 (0x${i2cAddress.toString(16)})`);
return device;
} catch (error) {
console.error(`センサー設定エラー (0x${i2cAddress.toString(16)}):`, error);
throw error;
}
}
async readTemperature(sensor) {
const maxRetries = 3;
for (let i = 0; i < maxRetries; i++) {
try {
const data = await sensor.read8(0x00, 2);
const temperature = (data[0] << 8 | data[1]) / 16;
// 妥当性チェック
if (temperature < -40 || temperature > 125) {
throw new Error(`異常な温度値: ${temperature}`);
}
return temperature;
} catch (error) {
console.warn(`読み取り失敗 (試行 ${i + 1}/${maxRetries}):`, error);
if (i === maxRetries - 1) throw error;
await this.sleep(100);
}
}
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async cleanup() {
console.log("クリーンアップ中...");
// リソース解放処理
this.isInitialized = false;
}
}
// 使用例
const controller = new IoTController();
async function main() {
try {
// 初期化
const success = await controller.initialize();
if (!success) {
console.error("初期化失敗");
return;
}
// デバイス設定
const led = await controller.setupLED(26);
const sensor = await controller.setupSensor(0x48);
// メインループ
while (true) {
try {
const temperature = await controller.readTemperature(sensor);
console.log(`温度: ${temperature.toFixed(2)}℃`);
// 温度に応じた制御
await led.write(temperature > 28 ? 1 : 0);
} catch (error) {
console.error("ループエラー:", error);
}
await controller.sleep(1000);
}
} catch (error) {
console.error("致命的エラー:", error);
} finally {
await controller.cleanup();
}
}
// シグナルハンドリング
process.on("SIGINT", async () => {
console.log("\n終了します...");
await controller.cleanup();
process.exit(0);
});
main();
```
--------------------------------
### JavaScript I2C Communication: Temperature Sensor Control
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
Communicates with I2C devices such as sensors. This example demonstrates reading temperature data from an ADT7410 sensor by opening an I2C port, accessing the device at a specific address, and reading data from its registers. It requires the CHIRIMEN polyfill or compatible environment.
```javascript
// 温度センサー (ADT7410) の読み取り例
const i2cAccess = await requestI2CAccess(); // I2C初期化
const port = i2cAccess.ports.get(1); // I2Cポート1を取得
const address = 0x48; // ADT7410のI2Cアドレス
const sensor = await port.open(address); // デバイスを開く
// 温度レジスタ (0x00) から2バイト読み取り
const data = await sensor.read8(0x00, 2);
// 温度値の計算 (13ビット解像度)
let temperature;
if (data[0] & 0x80) {
// 負の温度
temperature = ((data[0] << 8 | data[1]) - 8192) / 16;
} else {
// 正の温度
temperature = (data[0] << 8 | data[1]) / 16;
}
console.log(`温度: ${temperature.toFixed(2)}℃`);
// 連続読み取り
setInterval(async () => {
const data = await sensor.read8(0x00, 2);
const temp = (data[0] << 8 | data[1]) / 16;
console.log(`現在温度: ${temp.toFixed(2)}℃`);
}, 1000);
```
--------------------------------
### JavaScript GPIO Digital Output: LED Blinking
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
Controls a digital device like an LED using GPIO pins. This example demonstrates basic LED blinking functionality by exporting a GPIO port in output mode and alternating between writing HIGH and LOW states with a delay. It requires the CHIRIMEN polyfill or environment.
```javascript
// LED点滅 (Lチカ) の基本例
const gpioAccess = await requestGPIOAccess(); // GPIO操作の初期化
const port = gpioAccess.ports.get(26); // 26番ポートを取得
await port.export("out"); // ポートを出力モードに設定
// LEDを1秒間隔で点滅
while (true) {
await port.write(1); // LED点灯 (HIGH)
await sleep(1000); // 1000ms待機
await port.write(0); // LED消灯 (LOW)
await sleep(1000); // 1000ms待機
}
// sleep関数のヘルパー
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
```
--------------------------------
### JavaScript GPIO Digital Input: Button Reading
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
Reads the state of digital input devices such as buttons or switches using GPIO pins. This example shows how to export a GPIO port in input mode and either monitor for changes using an event handler or periodically poll the port's value. It relies on the CHIRIMEN environment.
```javascript
// ボタン入力の読み取り例
const gpioAccess = await requestGPIOAccess();
const port = gpioAccess.ports.get(5); // 5番ポートを取得
await port.export("in"); // ポートを入力モードに設定
// 状態変化の監視
port.onchange = (value) => {
console.log(`ボタン状態: ${value}`); // 0 or 1
if (value === 1) {
console.log("ボタンが押されました");
} else {
console.log("ボタンが離されました");
}
};
// または定期的にポーリング
setInterval(async () => {
const value = await port.read();
console.log(`現在の値: ${value}`);
}, 100);
```
--------------------------------
### Control micro:bit LED and read sensors via Bluetooth
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
This JavaScript code snippet demonstrates how to connect to a micro:bit via Bluetooth, initialize GPIO ports, control an LED with a blinking pattern, monitor button presses, and read accelerometer data. It relies on the micro:bit Bluetooth API and assumes a micro:bit environment.
```javascript
// micro:bit Bluetooth接続とLED制御
const microBitBle = await requestMicroBitBle();
await microBitBle.connect();
// GPIO初期化
const gpioAccess = await microBitBle.requestGPIOAccess();
const ledPort = gpioAccess.ports.get(0); // P0ピン
await ledPort.export("out");
// パターン点滅
const pattern = [1, 0, 1, 0, 1, 1, 0, 0];
for (const state of pattern) {
await ledPort.write(state);
await sleep(200);
}
// ボタン監視 (micro:bit内蔵ボタンA)
microBitBle.onButtonAPressed = () => {
console.log("ボタンAが押されました");
};
// 加速度センサー読み取り
microBitBle.onAccelerometerDataChanged = (x, y, z) => {
console.log(`加速度: X=${x}, Y=${y}, Z=${z}`);
// 傾き検出
if (Math.abs(x) > 200) {
console.log("左右に傾いています");
}
};
```
--------------------------------
### Node.js GPIO, I2C, and Express.js on Raspberry Pi Zero
Source: https://context7.com/context7/tutorial_chirimen/llms.txt
This Node.js code snippet shows how to control GPIO pins, interact with I2C sensors, and create a web API using Express.js on a Raspberry Pi Zero with CHIRIMEN. It requires the 'node-web-gpio', 'node-web-i2c', and '@chirimen/raspi3' libraries. The API provides endpoints for reading temperature and controlling an LED.
```javascript
// Node.js での GPIO/I2C 制御
import { requestGPIOAccess } from "node-web-gpio";
import { requestI2CAccess } from "node-web-i2c";
import { RaspberryPi3 } from "@chirimen/raspi3";
// ハードウェアバインディング
const gpioAccess = await requestGPIOAccess(RaspberryPi3);
const i2cAccess = await requestI2CAccess(RaspberryPi3);
// GPIO制御
const ledPort = gpioAccess.ports.get(26);
await ledPort.export("out");
// I2Cセンサー
const i2cPort = i2cAccess.ports.get(1);
const sensor = await i2cPort.open(0x48);
// Express.jsでWeb APIを提供
import express from "express";
const app = express();
app.get("/temperature", async (req, res) => {
try {
const data = await sensor.read8(0x00, 2);
const temperature = (data[0] << 8 | data[1]) / 16;
res.json({ temperature, unit: "celsius" });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post("/led/:state", async (req, res) => {
const state = req.params.state === "on" ? 1 : 0;
await ledPort.write(state);
res.json({ led: state ? "on" : "off" });
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.