Finally, it run on Raspberry to communicate with/control Arduino Uno board to:
Showing posts with label example code.Arduino. Show all posts
Showing posts with label example code.Arduino. Show all posts
Friday, September 18, 2015
Raspberry Pi (Java/JavaFX) control Arduino with USB connection
It's a series in my another blogspot Arduino-er about how to control USB connected Arduino Uno board, using Java/JavaFX/jSSC, develop on Windows 10 with NetBeans IDE, run on Remote Java SE Platform (target Raspberry Pi 2/Raspbian).
Wednesday, January 7, 2015
Raspberry Pi + Arduino i2c communication, Wire.write() multi-byte from Arduino requestEvent
Last exercise show Raspberry Pi master + Arduino slave i2c communication, write block of data from Pi to Arduino Uno, and read a single byte from Arduino Uno. In this post show how to echo multi-byte from Arduino in requestEvent, by calling Wire.write().
In Raspberry Pi, i2c master, it send block of data to Arduino Uno, i2c slave, by calling bus.write_i2c_block_data(), to trigger receiveEvent in Arduino.
then call number of bus.read_byte() to trigger requestEvent in Arduino. The first byte echo from Arduino is the number of byte to sent, then echo the data in reversed sequency.
i2c_uno.py run on Raspberry Pi
i2c_slave_12x6LCD.ino, run on Arduino Uno
In Raspberry Pi, i2c master, it send block of data to Arduino Uno, i2c slave, by calling bus.write_i2c_block_data(), to trigger receiveEvent in Arduino.
then call number of bus.read_byte() to trigger requestEvent in Arduino. The first byte echo from Arduino is the number of byte to sent, then echo the data in reversed sequency.
i2c_uno.py run on Raspberry Pi
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os
# display system info
print os.uname()
bus = smbus.SMBus(1)
# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd_write = 0x01
i2c_cmd_read = 0x02
def ConvertStringToBytes(src):
converted = []
for b in src:
converted.append(ord(b))
return converted
# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd_write, bytesToSend)
# loop to send message
exit = False
while not exit:
r = raw_input('Enter something, "q" to quit"')
print(r)
bytesToSend = ConvertStringToBytes(r)
bus.write_i2c_block_data(i2c_address, i2c_cmd_write, bytesToSend)
# delay 0.1 second
# with delay will cause error of:
# IOError: [Error 5] Input/output error
time.sleep(0.1)
data = ""
numOfByte = bus.read_byte(i2c_address)
print numOfByte
for i in range(0, numOfByte):
data += chr(bus.read_byte(i2c_address));
print data
if r=='q':
exit=True
i2c_slave_12x6LCD.ino, run on Arduino Uno
/*
LCD part reference to:
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
#include <LiquidCrystal.h>
#include <Wire.h>
#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte slave_address = 7;
int echonum = 0;
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print startup message to the LCD.
lcd.print("Arduino Uno");
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Wire.begin(slave_address);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void loop() {
}
char echo[32];
int index = 0;
void requestEvent(){
toggleLED();
if(index==0){
Wire.write(echonum);
}else{
Wire.write(echo[echonum-1-(index-1)]);
}
index++;
}
void receiveEvent(int howMany) {
lcd.clear();
int numOfBytes = Wire.available();
//display number of bytes and cmd received, as bytes
lcd.setCursor(0, 0);
lcd.print("len:");
lcd.print(numOfBytes);
lcd.print(" ");
byte b = Wire.read(); //cmd
lcd.print("cmd:");
lcd.print(b);
lcd.print(" ");
index = 0;
//display message received, as char
lcd.setCursor(0, 1);
for(int i=0; i<numOfBytes-1; i++){
char data = Wire.read();
lcd.print(data);
echo[i] = data;
}
echonum = numOfBytes-1;
}
void toggleLED(){
ledon = !ledon;
if(ledon){
digitalWrite(LED_PIN, HIGH);
}else{
digitalWrite(LED_PIN, LOW);
}
}
Thursday, December 25, 2014
Raspberry Pi + Arduino i2c communication, write block and read byte
This example extends work on last example "Raspberry Pi send block of data to Arduino using I2C"; the Raspberry Pi read byte from Arduino Uno after block sent, and the Arduino always send back length of data received.
i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
i2c_uno.py, python program run on Raspberry Pi.
Next:
- Wire.write() multi-byte from Arduino requestEvent
WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.
i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
/*
LCD part reference to:
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
#include <LiquidCrystal.h>
#include <Wire.h>
#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte slave_address = 7;
int echonum = 0;
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print startup message to the LCD.
lcd.print("Arduino Uno");
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Wire.begin(slave_address);
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
}
void loop() {
}
void requestEvent(){
Wire.write(echonum);
toggleLED();
}
void receiveEvent(int howMany) {
lcd.clear();
int numOfBytes = Wire.available();
//display number of bytes and cmd received, as bytes
lcd.setCursor(0, 0);
lcd.print("len:");
lcd.print(numOfBytes);
lcd.print(" ");
byte b = Wire.read(); //cmd
lcd.print("cmd:");
lcd.print(b);
lcd.print(" ");
//display message received, as char
lcd.setCursor(0, 1);
for(int i=0; i<numOfBytes-1; i++){
char data = Wire.read();
lcd.print(data);
}
echonum = numOfBytes-1;
}
void toggleLED(){
ledon = !ledon;
if(ledon){
digitalWrite(LED_PIN, HIGH);
}else{
digitalWrite(LED_PIN, LOW);
}
}
i2c_uno.py, python program run on Raspberry Pi.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os
# display system info
print os.uname()
bus = smbus.SMBus(1)
# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd = 0x01
def ConvertStringToBytes(src):
converted = []
for b in src:
converted.append(ord(b))
return converted
# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
# loop to send message
exit = False
while not exit:
r = raw_input('Enter something, "q" to quit"')
print(r)
bytesToSend = ConvertStringToBytes(r)
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
# delay 0.1 second
# with delay will cause error of:
# IOError: [Error 5] Input/output error
time.sleep(0.1)
number = bus.read_byte(i2c_address)
print('echo: ' + str(number))
if r=='q':
exit=True
Next:
- Wire.write() multi-byte from Arduino requestEvent
WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.
Sunday, December 14, 2014
Raspberry Pi send block of data to Arduino using I2C
In this example, Raspberry Pi programmed using Python with smbus library, act as I2C master, ask user enter something as string, then send to Arduino Uno in blocks of data. In Arduino side, act as I2C slave, interpret received data in number of bytes, command, and body of data, to display on 16x2 LCD display.
Prepare on Raspberry Pi for I2C communication, refer to previous post "Communication between Raspberry Pi and Arduino via I2C, using Python".
Connection between Raspberry Pi, Arduino Uno and 16x2 LCD:
i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
i2c_uno.py, python program run on Raspberry Pi.
next:
- Raspberry Pi + Arduino i2c communication, write block and read byte
WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.
Prepare on Raspberry Pi for I2C communication, refer to previous post "Communication between Raspberry Pi and Arduino via I2C, using Python".
Connection between Raspberry Pi, Arduino Uno and 16x2 LCD:
i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
/*
LCD part reference to:
http://www.arduino.cc/en/Tutorial/LiquidCrystal
*/
#include <LiquidCrystal.h>
#include <Wire.h>
#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
byte slave_address = 7;
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// Print startup message to the LCD.
lcd.print("Arduino Uno");
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, HIGH);
Wire.begin(slave_address);
Wire.onReceive(receiveEvent);
}
void loop() {
}
void receiveEvent(int howMany) {
lcd.clear();
int numOfBytes = Wire.available();
//display number of bytes and cmd received, as bytes
lcd.setCursor(0, 0);
lcd.print("len:");
lcd.print(numOfBytes);
lcd.print(" ");
byte b = Wire.read(); //cmd
lcd.print("cmd:");
lcd.print(b);
lcd.print(" ");
//display message received, as char
lcd.setCursor(0, 1);
for(int i=0; i<numOfBytes-1; i++){
char data = Wire.read();
lcd.print(data);
}
toggleLED();
}
void toggleLED(){
ledon = !ledon;
if(ledon){
digitalWrite(LED_PIN, HIGH);
}else{
digitalWrite(LED_PIN, LOW);
}
}
i2c_uno.py, python program run on Raspberry Pi.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os
# display system info
print os.uname()
bus = smbus.SMBus(1)
# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd = 0x01
def ConvertStringToBytes(src):
converted = []
for b in src:
converted.append(ord(b))
return converted
# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
# loop to send message
exit = False
while not exit:
r = raw_input('Enter something, "q" to quit"')
print(r)
bytesToSend = ConvertStringToBytes(r)
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
if r=='q':
exit=True
next:
- Raspberry Pi + Arduino i2c communication, write block and read byte
WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.
Saturday, December 13, 2014
Communication between Raspberry Pi and Arduino via I2C, using Python.
This exercise implement communiation between Raspberry Pi and Arduino using I2C. Here Raspberry Pi, programmed with Python, act as I2C host and Arduino Uno act as slave.
Download the sketch (I2CSlave.ino) to Arduino Uno. It receive I2C data, turn ON LED if 0x00 received, turn OFF LED if 0x01 received.
Prepare on Raspberry Pi, refer to last post "Enable I2C and install tools on Raspberry Pi".
Connection between Raspberry Pi and Arduino.
Then you can varify the I2C connection using i2cdetect command. Refer to below video, the I2C device with address 07 match with slave_address = 7 defined in Arduino sketch.
On Raspberry Pi, run the command to install smbus for Python, in order to use I2C bus.
$ sudo apt-get install python-smbus
Now create a Python program (i2c_uno.py), act as I2C master to write series of data to Arduino Uno, to turn ON/OFF the LED on Arduino Uno. Where address = 0x07 have to match with the slave_address in Arduino side.
Finally, run with command:
$ sudo python i2c_uno.py
Next:
- Raspberry Pi send block of data to Arduino using I2C
- Write block and read byte
- Wire.write() multi-byte from Arduino requestEvent
WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.
Download the sketch (I2CSlave.ino) to Arduino Uno. It receive I2C data, turn ON LED if 0x00 received, turn OFF LED if 0x01 received.
#include <Wire.h>
#define LED_PIN 13
byte slave_address = 7;
byte CMD_ON = 0x00;
byte CMD_OFF = 0x01;
void setup() {
// Start I2C Bus as Slave
Wire.begin(slave_address);
Wire.onReceive(receiveEvent);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
}
void loop() {
}
void receiveEvent(int howMany) {
byte cmd = Wire.read();
if (cmd == CMD_ON){
digitalWrite(LED_PIN, HIGH);
}else if(cmd == CMD_OFF){
digitalWrite(LED_PIN, LOW);
}
}
Prepare on Raspberry Pi, refer to last post "Enable I2C and install tools on Raspberry Pi".
Connection between Raspberry Pi and Arduino.
Then you can varify the I2C connection using i2cdetect command. Refer to below video, the I2C device with address 07 match with slave_address = 7 defined in Arduino sketch.
On Raspberry Pi, run the command to install smbus for Python, in order to use I2C bus.
$ sudo apt-get install python-smbus
Now create a Python program (i2c_uno.py), act as I2C master to write series of data to Arduino Uno, to turn ON/OFF the LED on Arduino Uno. Where address = 0x07 have to match with the slave_address in Arduino side.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
bus = smbus.SMBus(1)
# I2C address of Arduino Slave
address = 0x07
LEDst = [0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01]
for s in LEDst:
bus.write_byte(address, s)
time.sleep(1)
Finally, run with command:
$ sudo python i2c_uno.py
Next:
- Raspberry Pi send block of data to Arduino using I2C
- Write block and read byte
- Wire.write() multi-byte from Arduino requestEvent
WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.
Wednesday, September 3, 2014
Node.js Chat Server on RPi, send msg to Arduino Uno, display on LCD Module
This example combine the last post of "Node.js Chat application using socket.io, run on Raspberry Pi", and "Node.js send string to Arduino Uno" in my another blog for Arduino. To create a Chat server, and send the received messages to USB connected Arduino Uno board, then display on the equipped 2x16 LCD Module on Arduino.
In order to use serialport in Node.js to send message to serial port, enter the command on Raspberry Pi command line to install serialport.
$ npm install serialport
Modify index.js in last post to add handles for serialport.
For the sketch on Arduino Uno, refer to the post "Read from Arduino Serial port, and write to 2x16 LCD".
In order to use serialport in Node.js to send message to serial port, enter the command on Raspberry Pi command line to install serialport.
$ npm install serialport
Modify index.js in last post to add handles for serialport.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyACM0',
{ baudrate: 9600
});
serialPort.on("open", function () {
console.log('open');
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
serialPort.write(msg, function(err, results) {
console.log('err ' + err);
console.log('results ' + results);
});
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
For the sketch on Arduino Uno, refer to the post "Read from Arduino Serial port, and write to 2x16 LCD".
Monday, March 24, 2014
Bi-directional control between Raspberry Pi + Node.js + Arduino
This example show how to pass data between Node.js client, Node.js server running on Raspberry Pi, and Arduino, bi-directionally. A Arduino Esplora is connected to Raspberry Pi, with Node.js running up a simple web app. Client can load the web app with Pi's IP and port 8080.
the tablet in the video for demo only.
From Node.js clients to server to Arduino:
- User can toggle the button to set Arduino LED ON/OFF.
- User can select color from of Arduino LCD color.
From Arduino to Node.js server to clients.
- When the Slider on Esplora changed, the setting will be sent to Node.js server to clients' progress bar on page.
Node.js code, app.js
index.html
Arduino code:
Cross post with Arduino-er, same code run on PC running Ubuntu Linux.
From Node.js clients to server to Arduino:
- User can toggle the button to set Arduino LED ON/OFF.
- User can select color from of Arduino LCD color.
From Arduino to Node.js server to clients.
- When the Slider on Esplora changed, the setting will be sent to Node.js server to clients' progress bar on page.
Node.js code, app.js
var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
fs = require('fs'),
os = require('os'),
sp = require("serialport");
//All clients have a common status
var commonStatus = 'ON';
var commonColor = 0xffffff;
var commonSldValue = 0;
//init for SerialPort connected to Arduino
var SerialPort = sp.SerialPort
var serialPort = new SerialPort('/dev/ttyACM0',
{ baudrate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
var receivedData = "";
serialPort.on("open", function () {
console.log('serialPort open');
serialPort.write("LEDOFF\n");
//handle data receive from Arduino
serialPort.on('data', function(data) {
receivedData += data.toString();
if (receivedData.indexOf("SLD#") >= 0
&& receivedData.indexOf("\n") >= 0) {
sldValue = receivedData.substring(
receivedData.indexOf("SLD#")+4,
receivedData.indexOf("\n"));
receivedData = "";
if ((sldValue.length == 1)
|| (sldValue.length == 2)){
commonSldValue = parseInt("0x"+sldValue);
io.sockets.emit('update slider',
{ value: commonSldValue});
console.log('update slider: ' + commonSldValue);
}
}
});
});
//Display my IP
var networkInterfaces=os.networkInterfaces();
for (var interface in networkInterfaces) {
networkInterfaces[interface].forEach(
function(details){
if (details.family=='IPv4'
&& details.internal==false) {
console.log(interface, details.address);
}
});
}
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
//Send client with his socket id
socket.emit('your id',
{ id: socket.id});
//Info all clients a new client caaonnected
io.sockets.emit('on connection',
{ client: socket.id,
clientCount: io.sockets.clients().length,
});
//Set the current common status to the new client
socket.emit('ack button status', { status: commonStatus });
socket.emit('ack color', { color: commonColor });
socket.emit('update slider', { value: commonSldValue});
socket.on('button update event', function (data) {
console.log(data.status);
//acknowledge with inverted status,
//to toggle button text in client
if(data.status == 'ON'){
console.log("ON->OFF");
commonStatus = 'OFF';
serialPort.write("LEDON\n");
}else{
console.log("OFF->ON");
commonStatus = 'ON';
serialPort.write("LEDOFF\n");
}
io.sockets.emit('ack button status',
{ status: commonStatus,
by: socket.id
});
});
socket.on('update color', function (data) {
commonColor = data.color;
console.log("set color: " + commonColor);
var stringColorHex = "COL" + commonColor.toString(16);
console.log("stringColorHex: " + stringColorHex);
serialPort.write(stringColorHex + "\n");
io.sockets.emit('ack color',
{ color: data.color,
by: socket.id
});
});
//Info all clients if this client disconnect
socket.on('disconnect', function () {
io.sockets.emit('on disconnect',
{ client: socket.id,
clientCount: io.sockets.clients().length-1,
});
});
});
index.html
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, user-scalable=no">
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
onclick="toggle(this);">
</form>
<br/>
Select color: <br/>
<input id="colorpick" type="color" name="favcolor"
onchange="JavaScript:colorchanged()"><br>
<br/>
<progress id="progressbar" max="255"><span>0</span>%</progress>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);
var myId;
socket.on('update slider', function (data) {
console.log("update slider: " + data.value);
document.getElementById("progressbar").value = data.value;
});
socket.on('on connection', function (data) {
console.log("on connection: " + data.client);
console.log("Number of client connected: " + data.clientCount);
});
socket.on('on disconnect',function(data) {
console.log("on disconnect: " + data.client);
console.log("Number of client connected: " + data.clientCount);
});
socket.on('your id',function(data) {
console.log("your id: " + data.id);
myId = data.id;
});
socket.on('ack button status', function (data) {
console.log("status: " + data.status);
if(myId==data.by){
console.log("by YOU");
}else{
console.log("by: " + data.by);
}
if(data.status =='ON'){
document.getElementById("buttonToggle").value="ON";
}else{
document.getElementById("buttonToggle").value="OFF";
}
});
socket.on('ack color', function (data) {
console.log("ack color: " + data.color);
document.body.style.background = data.color;
if(myId==data.by){
console.log("by YOU");
}else{
console.log("by: " + data.by);
}
});
function toggle(button)
{
if(document.getElementById("buttonToggle").value=="OFF"){
socket.emit('button update event', { status: 'OFF' });
}
else if(document.getElementById("buttonToggle").value=="ON"){
socket.emit('button update event', { status: 'ON' });
}
}
function colorchanged()
{
//console.log("colorchanged()");
var colorval = document.getElementById("colorpick").value;
console.log("colorchanged(): " + colorval);
//document.body.style.background = colorval;
socket.emit('update color', { color: colorval });
}
</script>
</body>
</html>
Arduino code:
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>
int MAX_CMD_LENGTH = 10;
char cmd[10];
int cmdIndex;
char incomingByte;
int prevSlider = 0;
void setup() {
EsploraTFT.begin();
EsploraTFT.background(0,0,0);
EsploraTFT.stroke(255,255,255); //preset stroke color
//Setup Serial Port with baud rate of 9600
Serial.begin(9600);
//indicate start
Esplora.writeRGB(255, 255, 255);
delay(250);
Esplora.writeRGB(0, 0, 0);
cmdIndex = 0;
}
void loop() {
if (incomingByte=Serial.available()>0) {
char byteIn = Serial.read();
cmd[cmdIndex] = byteIn;
if(byteIn=='\n'){
//command finished
cmd[cmdIndex] = '\0';
//Serial.println(cmd);
cmdIndex = 0;
String stringCmd = String(cmd);
if(strcmp(cmd, "LEDON") == 0){
//Serial.println("Command received: LEDON");
Esplora.writeRGB(255, 255, 255);
}else if (strcmp(cmd, "LEDOFF") == 0) {
//Serial.println("Command received: LEDOFF");
Esplora.writeRGB(0, 0, 0);
}else if(stringCmd.substring(0,4)="COL#"){
//Serial.println("Command received: COL#");
if(stringCmd.length()==10){
char * pEnd;
long int rgb = strtol(&cmd[4], &pEnd, 16);
int r = (rgb & 0xff0000) >> 16;
int g = (rgb & 0xff00) >> 8;
int b = rgb & 0xff;
//Serial.println(r);
//Serial.println(g);
//Serial.println(b);
EsploraTFT.background(b,g,r);
}
}else{
//Serial.println("Command received: unknown!");
}
}else{
if(cmdIndex++ >= MAX_CMD_LENGTH){
cmdIndex = 0;
}
}
}
//Read Slider
int slider = Esplora.readSlider();
//convert slider value from [0-1023] to [0x00-0xFF]
slider = slider>>2 & 0xff;
if(slider!=prevSlider){
prevSlider = slider;
String stringSlider = String(slider, HEX);
Serial.println("SLD#" + stringSlider +"\n");
}
}
Cross post with Arduino-er, same code run on PC running Ubuntu Linux.
Monday, March 10, 2014
Communication between Raspberry Pi and Arduino, using Node.js
The 'serialport' module for Node.js provide basic building block to make Node.js communication with serial port. Here is a simple example to send data between Raspberry Pi and Arduino Esplora board via USB, using Node.js.
Cross-post with Arduino-er: Arduino + Raspberry Pi + Node.js
node_arduino.js, Node.js script run on Raspberry Pi side.
The code in Arduino Esplora board.
Cross-post with Arduino-er: Arduino + Raspberry Pi + Node.js
node_arduino.js, Node.js script run on Raspberry Pi side.
//To install 'serialport' locally, enter the command:
//$ npm install serialport
//Otherwise, Error: Cannot find module 'serialport' will reported
var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyACM0',
{ baudrate: 9600,
dataBits: 8,
parity: 'none',
stopBits: 1,
flowControl: false
});
serialPort.on("open", function () {
console.log('open');
serialPort.on('data', function(data) {
console.log('data received: ' + data);
});
serialPort.write("Hello from Raspberry Pi\n", function(err, results) {
console.log('err ' + err);
console.log('results ' + results);
});
});
The code in Arduino Esplora board.
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>
int prevSw1 = HIGH;
int incomingByte = 0;
String charsIn = "";
char printout[20]; //max char to print: 20
void setup() {
EsploraTFT.begin();
EsploraTFT.background(0,0,0);
EsploraTFT.stroke(255,255,255); //preset stroke color
//Setup Serial Port with baud rate of 9600
Serial.begin(9600);
//indicate start
Esplora.writeRGB(255, 255, 255);
delay(250);
Esplora.writeRGB(0, 0, 0);
}
void loop() {
int sw1 = Esplora.readButton(SWITCH_1);
if(sw1 != prevSw1){
if(sw1 == LOW){
Serial.println("Hello from Arduino Esplora");
}
prevSw1 = sw1;
}
while (Serial.available()) {
char charRead = Serial.read();
charsIn.concat(charRead);
}
if(charsIn != ""){
Serial.println("How are you, " + charsIn);
charsIn.toCharArray(printout, 21);
EsploraTFT.background(0,0,0);
EsploraTFT.text(printout, 0, 10);
charsIn = "";
}
}
Friday, November 15, 2013
Send and receive from Raspberry Pi to and from Arduino, with Python
This example show how to write a simple Python program on Raspberry Pi to get keyboard input and send to Arduino via USB. In Arduino, send back the received chars to Raspberry Pi, then print on screen in Pi side.
In this example, Raspberry Pi act as host and Arduino Due act as device, and connect with USB on Programming USB Port.
Python code in Raspberry Pi:
Code in Arduino side:
Cross post with my another blog: Arduino-er
In this example, Raspberry Pi act as host and Arduino Due act as device, and connect with USB on Programming USB Port.
Python code in Raspberry Pi:
import serial
ser = serial.Serial('/dev/ttyACM1', 9600)
name_out = raw_input("Who are you?\n")
ser.write(name_out + "\n")
name_return = ser.readline()
print(name_return)
Code in Arduino side:
int pinLED = 13;
boolean ledon;
void setup() {
Serial.begin(9600);
pinMode(pinLED, OUTPUT);
ledon = true;
digitalWrite(pinLED, ledon = !ledon);
}
void loop() {
if(Serial.available() > 0){
Serial.print("Hello ");
while(Serial.available()>0){
char charIn = (char)Serial.read();
Serial.print(charIn);
if (charIn == '\n')
break;
}
digitalWrite(pinLED, ledon = !ledon);
}
}
Cross post with my another blog: Arduino-er
Tuesday, November 12, 2013
Prepare Arduino to send data to Raspberry Pi via USB
It's a example to send data from Arduino to Raspberry Pi via USB. In this post, I will show a simple program in Arduino side (tested on Arduino Due), to send something out to USB, and also toggle the on-board LED. In the next post, I will show how to receive in Raspberry Pi Board, from USB, using Python.
The code simple send "Hello Pi" to Serial port (USB) repeatly. After download to your Arduino board, you can use the build-in Tools > Serial Monitor to varify it.
The code in Arduino Due to send "Hello Pi" to USB and toggle LED repeatly every second.
int pinLED = 13;
boolean ledon;
void setup() {
Serial.begin(9600);
pinMode(pinLED, OUTPUT);
ledon = true;
}
void loop() {
Serial.print("Hello Pi\n");
digitalWrite(pinLED, ledon = !ledon);
delay(1000);
}
The code simple send "Hello Pi" to Serial port (USB) repeatly. After download to your Arduino board, you can use the build-in Tools > Serial Monitor to varify it.
Subscribe to:
Posts (Atom)