Mam taki kod Arduino:
const int ledPin = 8;
String ledStatus = "off";
String inputString = "";
void setup()
{
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
}
void loop()
{
updateLedStatus();
}
void updateLedStatus() {
if (stringComplete) {
if (inputString == "on\r") {
ledStatus = "on";
}
if (inputString == "off\r") {
ledStatus = "off";
}
Serial.println("Updated led state: " + ledStatus);
inputString = "";
stringComplete = false;
}
digitalWrite(ledPin, ledStatus == "on" ? HIGH : LOW);
}
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
Serial.println("Method from arduino");
inputString += inChar;
if (inChar == '\r') {
stringComplete = true;
}
}
}
I taki kod serwera w Nodejs:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const server = require('http').createServer(app);
const io = require('socket.io').listen(server);
const SerialPort = require('serialport');
var cors = require('cors');
const PORT = 8000;
lightStatus = 'off';
sp = new SerialPort('COM4', {
baudRate: 115200
});
// websocket
io.sockets.on('connection', function (socket) {
socket.emit('lightStatus', lightStatus);
socket.on('lightStatus', function () {
lightStatus = lightStatus === 'off' ? 'on' : 'off';
sp.write(lightStatus + '\r', function () {
console.log('the light should be: ' + lightStatus);
io.emit('lightStatus', lightStatus);
});
});
});
sp.on('close', function (err) {
console.log('Port closed!');
});
sp.on('error', function (err) {
console.error('error', err);
});
sp.on('open', function () {
console.log('Socket port opened!');
});
app.use(cors({credentials: true, origin: '*'}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/users', UsersRouter);
server.listen(PORT, function () {
console.log('Server is running on Port: ' + PORT);
});
Jak powinienem to przerobić by działało z Ethernet Shieldem? Za pomocą tego kodu i portu USB wszystko mi działa.
Problem jest tutaj:
sp = new SerialPort('COM4', {
baudRate: 115200
});
Tylko nie wiem jak do tego podejść. Chcę mieć tak zrobione: Po zalogowaniu do Web Portalu widzę aktualny stan czujników (łączę się z serwerem na websocketach). Serwer komunikuje się z Arduino. Jak tu powinno to wyglądać? Jakoś nie potrafię sobie tego wyobrazić. Powinienem ustawić komunikację po stronie serwera by widziało Arduino z serwerem czy odwrotnie? No i jest założenie, że całe sterowanie ma się odbywać po stronie nodejs nie arduino- czyli np zmiana stanu diody led. Będę wdzieczny za wszelkie wskazówki.