Monday, March 31, 2014

Send string command from Android to Arduino in USB Host Mode

This is a example in my another blog show how Android send command to Arduino in USB Host mode. When user toggle the LED by clicking on the button, or change the screen color by slideing the bars, the commands will be add in a command queue, and then send to Arduino in background.

The code in Arduino Esplora is same as the previous example of Node.js + Arduino, running on PC.


Saturday, March 29, 2014

Arduino Day with Massimo Banzi - ASK AN ENGINEER LIVE SHOW at 7pm ET

Celebrate Arduino Day 2014 with Massimo Banzi, the co-founder and CEO of Arduino and Adafruit on a special Saturday night 7pm ET March 29th, 2014 LIVE show!

http://day.arduino.cc/

Arduino Day is a worldwide celebration of Arduino's first 10 years. It's 24 hours full of events -- both official and independent, anywhere around the world -- where people interested in Arduino can meet, share their experiences, and learn more.


#ArduinoD14

Monday, March 24, 2014

Node.js + Arduino, running on PC

This example show how to pass data between Node.js and Arduino bi-directionally. A Arduino Esplora is connected to a PC running Ubuntu, with Node.js running up a simple web app. Client can load the web app with Node.js Server's IP and port 8080.


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.

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");
    }
    
}

app.js, on Node.ja server.
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>

Cross post with Hello Raspberry Pi, the same code run on Raspberry Pi.

Saturday, March 22, 2014

Convert int to String

This example show how to convert int to String in various number base, BIN, HEX, DEC.
void setup() {
  
}

void loop() {
  int i = 1023;
  Serial.println("http://arduino-er.blogspot.com/");
  Serial.println("Test String: convert int to String");
  Serial.println();
  
  Serial.println("String(i) = " + String(i));
  Serial.println();
  
  Serial.println("String(i, BIN) = " 
      + String(i, BIN));
  Serial.println("String(i, HEX) = " 
      + String(i, HEX));
  Serial.println("String(i, DEC) = " 
      + String(i, DEC));
  Serial.println();
  
  Serial.println("String(i+i, BIN) = " 
      + String(i+i, BIN));
  Serial.println("String(i+i, HEX) = " 
      + String(i+i, HEX));
  Serial.println("String(i+i, DEC) = " 
      + String(i+i, DEC));
  Serial.println();
  
  Serial.println("String(i, BIN)+String(i, BIN) = " 
      + String(i, BIN)+String(i, BIN));
  Serial.println("String(i, HEX)+String(i, HEX) = " 
      + String(i, HEX)+String(i, HEX));
  Serial.println("String(i, DEC)+String(i, DEC) = " 
      + String(i, DEC)+String(i, DEC));
  Serial.println();
  
  delay(1000);
}

Convert int to String
Convert int to String

Thursday, March 20, 2014

Webcast recorded online now: Beyond the Arduino: Programming AVR Microcontrollers in C

The webcast "Beyond the Arduino: Programming AVR Microcontrollers in C" hold on March 18 2014, recorded and online now. This presentation will be available to audience members until June 16, 2014 at 12:30 PM Pacific Daylight Time. Visit http://oreillynet.com/pub/e/3018 to view it online, free register and log-in required.



In this webcast, dive straight into the deep end. Show you what you need to get started programming the AVR ATMega (and ATTiny) series microcontrollers, give you an overview of their built-in peripherals, and demonstrate most of the important functionality. And while the focus of this webcast is on Atmel's AVR series, nearly everything you'll learn here is transferable to other microcontrollers.

About Elliot Williams

Elliot Williams is a Ph.D. in Economics, a former government statistician, and a lifelong electronics hacker. He taught himself to program microcontrollers long before there was any such thing as an Arduino, and loves to spread the knowledge. Most recently, he is author of the Maker Media book "Make: AVR Programming, Learning to Write Software for Hardware", which is chock full of microcontroller-programming tidbits and thick enough to stun a rhino.

Web App of Node.js to control Raspberry Pi connected Arduino

This is a example to implement a web app with Node.js running on Raspberry Pi, to receive command from client, and control connected Arduino Esplora's LED. All clients share a common hardware: when a client toggle the LED, all clients will be updated accordingly.


This example should be run on any other Node.js supported platform, with changing SerialPort name. The tablet is used to log-in Raspberry Pi to start the app, for demonstrate only, not a part of the example.

You have to install socket.io and serialport modules for Node.js:
$ npm install socket.io
$ npm install serialport

app.js
var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app), 
    fs = require('fs'),
    os = require('os'),
    sp = require("serialport");
  
//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
    });
    
serialPort.on("open", function () {
    console.log('serialPort open');
    serialPort.write("LEDOFF\n");
});
    
//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);  
        }
    });
}

//All clients have a common status
var commonStatus = 'ON';

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.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
            });
    });
    
    //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
<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>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);
var myId;

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";
    }
});

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' });
 }
}
</script>

</body>
</html>

Arduino code, same as in last post.
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

int MAX_CMD_LENGTH = 10;
char cmd[10];
int cmdIndex;
char incomingByte;

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;
        
        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{
          Serial.println("Command received: unknown!");
        }
        
      }else{
        if(cmdIndex++ >= MAX_CMD_LENGTH){
          cmdIndex = 0;
        }
      }
    }
    
}

Cross-post with Hello Raspberry Pi

Next: Implement bi-directiuonal communication between Node.js and Arduino.

Tuesday, March 18, 2014

Arduino detect string command from serial port

This example receive char and detect command terminal '\n', and compare with predefined command ("LEDON" and "LEDOFF") with strcmp() function, to turn on/off Esplora's on-board LED accordingly.



serialReadCmd.ino
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

int MAX_CMD_LENGTH = 10;
char cmd[10];
int cmdIndex;
char incomingByte;

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;
        
        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{
          Serial.println("Command received: unknown!");
        }
        
      }else{
        if(cmdIndex++ >= MAX_CMD_LENGTH){
          cmdIndex = 0;
        }
      }
    }
    
}


Sunday, March 16, 2014

What Is Open Source Hardware?

This video describes the attributes of open source hardware to the general public. This video is officially released by the Open Source Hardware Association.

Friday, March 14, 2014

Software / Hardware / Everywhere

Tim O'Reilly & Jim Stogdill Explore Software - Hardware - Everywhere



We've reached another tipping point in history. The collision of hardware and software—the confluence of the virtual and physical—changes everything from products, industrial practices, and business models to appliances, automobiles, and job opportunities. Today's Internet of Everything is a classic market disruption, with immense unimagined opportunities and more than a few thorny challenges.

Join Tim O'Reilly, founder and CEO of O'Reilly Media, and Jim Stogdill, who leads O'Reilly's Solid, in a live-streamed conversation about the current state of the convergence of hardware and software, what this means beyond the Internet of Things, new promises and pitfalls, some opportunities we may not have thought of yet, and a vision for the future. Register free to get the livestream link and join this conversation.

http://solidcon.com/


Monday, March 10, 2014

Arduino + Raspberry Pi + Node.js

Cross-post with Hello Raspberry Pi: Communication between RAspberry Pi and Arduino, using Node.js.

This example demonstrate how to send data between Raspberry Pi and Arduino Esplora board via USB, using Node.js.


Node.js script run on Raspberry Pi.
//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);
        });
});

Arduino side, (same as in the post "Serial communication between Arduino Esplora and PC").
#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 = "";
    }
}

3D Printing For Dummies

3D Printing For Dummies

3D Printing For Dummies (For Dummies (Computer/Tech))

Get started printing out 3D objects quickly and inexpensively!
3D printing is no longer just a figment of your imagination. This remarkable technology is coming to the masses with the growing availability of 3D printers. 3D printers create 3-dimensional layered models and they allow users to create prototypes that use multiple materials and colors.  This friendly-but-straightforward guide examines each type of 3D printing technology available today and gives artists, entrepreneurs, engineers, and hobbyists insight into the amazing things 3D printing has to offer. You’ll discover methods for the creation of 3D printable objects using software, 3D scanners, and even photographs with the help of this timely For Dummies  guide.
  • Includes information on stereolithography, selective sintering, fused deposition, and granular binding techniques
  • Covers the potential for the transformation of production and manufacturing, reuse and recycling, intellectual property design controls, and the commoditization of traditional products from magazines to material goods
  • Walks you through the process of creating a RepRap printer using open-source designs, software, and hardware
  • Addresses the limitations of current 3D printing technologies and provides strategies for improved success
3D Printing For Dummies is the must-have guide to make manufacturing your own dynamic designs a dream come true!

Saturday, March 8, 2014

Exploring Arduino: Tools and Techniques for Engineering Wizardry

Exploring Arduino: Tools and Techniques for Engineering Wizardry

Exploring Arduino: Tools and Techniques for Engineering Wizardry

Learn to easily build gadgets, gizmos, robots, and more using Arduino
Written by Arduino expert Jeremy Blum, this unique book uses the popular Arduino microcontroller platform as an instrument to teach you about topics in electrical engineering, programming, and human-computer interaction. Whether you're a budding hobbyist or an engineer, you'll benefit from the perfectly paced lessons that walk you through useful, artistic, and educational exercises that gradually get more advanced. In addition to specific projects, the book shares best practices in programming and design that you can apply to your own projects. Code snippets and schematics will serve as a useful reference for future projects even after you've mastered all the topics in the book.
  • Includes a number of projects that utilize different capabilities of the Arduino, while interfacing with external hardware
  • Features chapters that build upon each other, tying in concepts from previous chapters to illustrate new ones
  • Includes aspects that are accompanied by video tutorials and other multimedia content 
  • Covers electrical engineering and programming concepts, interfacing with the world through analog and digital sensors, communicating with a computer and other devices, and internet connectivity
  • Explains how to combine smaller topics into more complex projects
  • Shares downloadable materials and source code for everything covered in the book
  • Projects compatible with many official Arduino boards including Arduino Uno; Arduino Leonardo; Arduino Mega 2560; Arduino Due; Arduino Nano; Arduino Mega ADK; LilyPad Arduino and may work with Arduino-compatible boards such as Freeduino and new third party certified boards such as the Intel Galileo
Exploring Arduino takes you on an adventure and provides you with exclusive access to materials not found anywhere else!


Tuesday, March 4, 2014

Bi-direction serial communication using java-simple-serial-connector

Last post "JavaFX + java-simple-serial-connector + Arduino" implement simple one way communication from PC run JavaFX to Arduino. This example implement bi-direction sending and receiving between PC and Arduino, using java-simple-serial-connector.



To implement receiving, we have to implement SerialPortEventListener, and add it with serialPort.addEventListener().

package javafx_jssc;

import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import jssc.SerialPort;
import jssc.SerialPortEvent;
import jssc.SerialPortEventListener;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class JavaFX_jSSC extends Application {

    SerialPort serialPort;
    ObservableList<String> portList;

    ComboBox comboBoxPorts;
    TextField textFieldOut, textFieldIn;
    Button btnOpenSerial, btnCloseSerial, btnSend;

    private void detectPort() {

        portList = FXCollections.observableArrayList();

        String[] serialPortNames = SerialPortList.getPortNames();
        for (String name : serialPortNames) {
            System.out.println(name);
            portList.add(name);
        }
    }

    @Override
    public void start(Stage primaryStage) {

        detectPort();

        comboBoxPorts = new ComboBox(portList);
        textFieldOut = new TextField();
        textFieldIn = new TextField();

        btnOpenSerial = new Button("Open Serial Port");
        btnCloseSerial = new Button("Close Serial Port");
        btnSend = new Button("Send");
        btnSend.setDisable(true);   //default disable before serial port open
        
        btnOpenSerial.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                closeSerialPort();              //close serial port before open
                if(openSerialPort()){
                    btnSend.setDisable(false);
                }else{
                    btnSend.setDisable(true);
                }
            }
        });
        
        btnCloseSerial.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                closeSerialPort();
                btnSend.setDisable(true);
            }
        });

        btnSend.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {
                
                if(serialPort != null && serialPort.isOpened()){
                    try {
                        String stringOut = textFieldOut.getText();
                        serialPort.writeBytes(stringOut.getBytes());
                    } catch (SerialPortException ex) {
                        Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }else{
                    System.out.println("Something wrong!");
                }
            }
        });

        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                comboBoxPorts,
                textFieldOut,
                textFieldIn,
                btnOpenSerial,
                btnCloseSerial,
                btnSend);

        StackPane root = new StackPane();
        root.getChildren().add(vBox);

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {

            @Override
            public void handle(WindowEvent t) {
                closeSerialPort();
            }
        });

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private boolean openSerialPort() {
        boolean success = false;
        
        if (comboBoxPorts.getValue() != null
                && !comboBoxPorts.getValue().toString().isEmpty()) {
            try {
                serialPort = new SerialPort(comboBoxPorts.getValue().toString());
                
                serialPort.openPort();
                serialPort.setParams(
                        SerialPort.BAUDRATE_9600,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
                
                serialPort.addEventListener(new MySerialPortEventListener());
                
                success = true;
            } catch (SerialPortException ex) {
                Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return success;
    }

    private void closeSerialPort() {
        if (serialPort != null && serialPort.isOpened()) {
            try {
                serialPort.closePort();
            } catch (SerialPortException ex) {
                Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
        serialPort = null;
    }
    
    class MySerialPortEventListener implements SerialPortEventListener {

        @Override
        public void serialEvent(SerialPortEvent serialPortEvent) {
            
            if(serialPortEvent.isRXCHAR()){
                try {
                    int byteCount = serialPortEvent.getEventValue();
                    byte bufferIn[] = serialPort.readBytes(byteCount);
                    
                    String stringIn = "";
                    try {
                        stringIn = new String(bufferIn, "UTF-8");
                    } catch (UnsupportedEncodingException ex) {
                        Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    textFieldIn.setText(stringIn);
                    
                } catch (SerialPortException ex) {
                    Logger.getLogger(JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                }
                
            }
            
        }
        
    }
}

Arduino Esplora side, refer to previous post.

Monday, March 3, 2014

bateske Arduboy:The Interactive Digital Business Card



A revolution in minimalist circuit board art design.
  • Barebones Arduino
  • OLED Screen
  • Piezo Speaker
  • Capacitive Input Buttons
  • 9+ Hours Playtime
  • 1.6 millimeters total thickness
http://www.bateske.com/Arduboy/

Arduino for Beginners: Essential Skills Every Maker Needs

Arduino for Beginners: Essential Skills Every Maker Needs
Arduino for Beginners: Essential Skills Every Maker Needs

Arduino for Beginners: Essential Skills Every Maker Needs

ARDUINO for BEGINNERS
ESSENTIAL SKILLS EVERY MAKER NEEDS
Loaded with full-color step-by-step illustrations!

Absolutely no experience needed!

Learn Arduino from the ground up, hands-on, in full color!

Discover Arduino, join the DIY movement, and build an amazing spectrum of projects… limited only by your imagination!

No “geekitude” needed: This full-color guide assumes you know nothing about Arduino or programming with the Arduino IDE. John Baichtal is an expert on getting newcomers up to speed with DIY hardware. First, he guides you gently up the learning curve, teaching you all you need to know about Arduino boards, basic electronics, safety, tools, soldering, and a whole lot more. Then, you walk step-by-step through projects that reveal Arduino’s incredible potential for sensing and controlling the environment–projects that inspire you to create, invent, and build the future!

·         Use breadboards to quickly create circuits without soldering
·         Create a laser/infrared trip beam to protect your home from intruders
·         Use Bluetooth wireless connections and XBee to build doorbells and more
·         Write useful, reliable Arduino programs from scratch
·         Use Arduino’s ultrasonic, temperature, flex, and light sensors
·         Build projects that react to a changing environment
·         Create your own plant-watering robot
·         Control DC motors, servos, and stepper motors
·         Create projects that keep track of time
·         Safely control high-voltage circuits
·         Harvest useful parts from junk electronics
·         Build pro-quality enclosures that fit comfortably in your home


JavaFX + java-simple-serial-connector + Arduino

This example implement a simple Java application using java-simple-serial-connector library (jSSC) , with JavaFX user interface, send bytes to Arduino Esplora via USB.



package javafx_jssc;

import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;

public class JavaFX_jSSC extends Application {
    
    ObservableList<String> portList;
    
    private void detectPort(){
        
        portList = FXCollections.observableArrayList();

        String[] serialPortNames = SerialPortList.getPortNames();
        for(String name: serialPortNames){
            System.out.println(name);
            portList.add(name);
        }
    }
    
    @Override
    public void start(Stage primaryStage) {
        
        detectPort();

        final ComboBox comboBoxPorts = new ComboBox(portList);
        final TextField textFieldOut = new TextField();
        Button btnSend = new Button("Send");
        
        btnSend.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent t) {

                if(comboBoxPorts.getValue() != null && 
                    !comboBoxPorts.getValue().toString().isEmpty()){
                    
                    String stringOut = textFieldOut.getText();
                    
                    try {
                        SerialPort serialPort = 
                            new SerialPort(comboBoxPorts.getValue().toString());                        
                        
                        serialPort.openPort();
                        serialPort.setParams(
                                SerialPort.BAUDRATE_9600,
                                SerialPort.DATABITS_8,
                                SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                        serialPort.writeBytes(stringOut.getBytes());
                        serialPort.closePort();
                        
                    } catch (SerialPortException ex) {
                        Logger.getLogger(
                            JavaFX_jSSC.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    
                }else{
                    System.out.println("No SerialPort selected!");
                }
            }
        });
        
        VBox vBox = new VBox();
        vBox.getChildren().addAll(
                comboBoxPorts, 
                textFieldOut, 
                btnSend);
        
        StackPane root = new StackPane();
        root.getChildren().add(vBox);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
    
}


Arduino code in Esplora side (same as in the post "Serial communication between Arduino Esplora and PC").
#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 = "";
    }
}

Read last post for Install and test java-simple-serial-connector with Arduino.

Next:
- Bi-direction serial communication using java-simple-serial-connector


Install and test java-simple-serial-connector with Arduino, on Ubuntu

As the new Arduino 1.5.6 BETA replaced RXTX library with JSSC (https://code.google.com/p/java-simple-serial-connector/), this video show how to install JSSC and setup on Netbeans, build a Hello World run on Ubuntu Linux, to send data to Arduino Esplora board. Actually the setup steps and example code follow https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_Start_Working.


The last version of jSSC can be downloaded here: http://code.google.com/p/java-simple-serial-connector/downloads/list

In order to work on Ubuntu, modify the example code to change SerialPort to "/dev/ttyACM0".

package java_testjssc;

import jssc.SerialPort;
import jssc.SerialPortException;

public class Java_testjSSC {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Hello World!!!".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
    }
    
}

The Arduino side code, refer to the post "Serial communication between Arduino Esplora and PC".

Next: A simple Java application using java-simple-serial-connector library (jSSC) , with JavaFX user interface, send bytes to Arduino Esplora via USB.

Related: Use jSSC (Java Simple Serial Connector) on Windows 8.1