Raspberry Pi中NodeJs与Arduino串口通信:字符串传输及灯光控制实现
Got it, let's walk through how to set up reliable serial communication between your Raspberry Pi (running Node.js) and Arduino for controlling those four lights. I’ve built similar setups before, so here’s a step-by-step solution that ensures your brightness commands get sent and received correctly:
1. Pre-Requisites (Get Everything Ready)
- Connect Hardware: Plug your Arduino into the Raspberry Pi using a USB cable. On the Pi, find the serial device path by running
ls /dev/tty*— it’s usually/dev/ttyACM0or/dev/ttyUSB0. - Fix Permissions: The Pi user needs access to the serial port. Run
sudo usermod -a -G dialout pi, then reboot your Pi to apply the change. - Install Node.js Library: Use the popular
serialportpackage for handling serial communication. Runnpm install serialport @serialport/parser-readlinein your Node.js project folder.
2. Node.js Code (Send Brightness Commands)
This code opens the serial port, sends formatted brightness strings, and even listens for responses from the Arduino (optional but helpful for debugging):
const { SerialPort } = require('serialport'); const { ReadlineParser } = require('@serialport/parser-readline'); // Configure serial port (match baud rate with Arduino!) const serialPort = new SerialPort({ path: '/dev/ttyACM0', // Replace with your Pi's serial device path baudRate: 9600, autoOpen: false }); // Use Readline parser to handle newline-separated messages const parser = serialPort.pipe(new ReadlineParser({ delimiter: '\n' })); // Open the serial connection serialPort.open((err) => { if (err) { console.error('Failed to open serial port:', err.message); return; } console.log('Serial port connected successfully!'); }); // Function to send brightness values to Arduino function sendLightControls(b1, b2, b3, b4) { // Format the command with a newline (critical for Arduino to detect end of message) const command = `${b1},${b2},${b3},${b4}\n`; serialPort.write(command, (err) => { if (err) { return console.error('Failed to send command:', err.message); } console.log(`Sent command: ${command.trim()}`); }); } // Test the function with your example values sendLightControls(255, 100, 100, 255); // Optional: Listen for responses from Arduino parser.on('data', (data) => { console.log('Arduino responded:', data.trim()); }); // Handle serial port errors serialPort.on('error', (err) => { console.error('Serial port error:', err.message); });
3. Arduino Code (Receive & Parse Commands)
This code listens for serial input, waits for a complete newline-terminated string, splits it into brightness values, and controls the lights with PWM:
// Define PWM pins for your 4 lights (use pins that support PWM — marked with ~ on Arduino) const int lightPins[] = {3, 5, 6, 9}; const int numLights = 4; String incomingString = ""; // Stores the received serial data bool isStringComplete = false; // Flag to mark when a full message is received void setup() { // Initialize serial communication (match baud rate with Node.js!) Serial.begin(9600); // Set all light pins as outputs for (int i = 0; i < numLights; i++) { pinMode(lightPins[i], OUTPUT); } // Pre-allocate memory for the incoming string to avoid dynamic allocation issues incomingString.reserve(200); } void loop() { // Read serial data until we get a newline while (Serial.available()) { char incomingChar = (char)Serial.read(); if (incomingChar == '\n') { isStringComplete = true; // Full message received } else { incomingString += incomingChar; } } // Process the complete command if it's ready if (isStringComplete) { // Optional: Send confirmation back to Node.js Serial.println("Received command: " + incomingString); // Split the string into individual brightness values int brightness[numLights]; int index = 0; // Use strtok to split the string by commas char* token = strtok((char*)incomingString.c_str(), ","); while (token != NULL && index < numLights) { // Convert string to integer, and clamp values to 0-255 (valid PWM range) brightness[index] = constrain(atoi(token), 0, 255); token = strtok(NULL, ","); index++; } // Set each light's brightness using PWM for (int i = 0; i < numLights; i++) { analogWrite(lightPins[i], brightness[i]); } // Reset for the next command incomingString = ""; isStringComplete = false; } }
4. Key Tips to Ensure Reliable Communication
- Use a Terminator Character: We added a newline
\nto every command from Node.js. This tells the Arduino exactly when a full message ends — no more partial string issues. - Match Baud Rates: Double-check that both the Node.js code and Arduino code use the same baud rate (we used 9600 here). Mismatched rates will cause garbled data.
- Clamp Brightness Values: The
constrain()function in Arduino ensures your brightness values stay between 0 and 255, which is the valid range for PWM output. - Debug with Responses: The optional serial responses from Arduino help you verify that commands are being received correctly.
内容的提问来源于stack exchange,提问作者Anh Tú Mai
相关产品推荐
相关产品推荐

