Tuesday, January 28, 2014

Send data to Arduino from Linux PC, program in C with GUI of GTK+3, as ColorChooser

In this example, we are going to develop a GUI program on Ubuntu Linux using C with GTK+3, select color to set LCD screen and LED on Arduino Esplora via USB serial.


In order to program with GTK+3, we have to install it on our PC, read last post "Install GTK+3 and compile with gcc in Linux". For the USB Serial communication part, refer to the post "Serial communication between Arduino and PC using C with termios".

Here is the code combine the termios and GTK+3 GtkColorChooser to build GUI for user to choice color, and send to Arduino Esplora via USB serial.

GtkEsploraColor.c:
#include <gtk/gtk.h>

#include <string.h>
#include <fcntl.h>
#include <termios.h>

int tty_fd;
struct termios old_stdio;

static void 
chooser_color_activated(GtkColorChooser *chooser, 
 GdkRGBA *color, gpointer user_data)
{
 GtkWidget *window = user_data;
 
 int intR = (int)((color->red)*65535);
 int intG = (int)((color->green)*65535);
 int intB = (int)((color->blue)*65535);
 GdkColor gColor = {
  0,
  intR, 
  intG, 
  intB};
 gtk_widget_modify_bg(GTK_WIDGET(window), GTK_STATE_NORMAL, &gColor);
 
 char bytes[] = {
  (char)(intB>>8), 
  (char)(intG>>8), 
  (char)(intR>>8)};
 
 write(tty_fd, bytes, 3);
}

void destroy( GtkWidget *widget,
              gpointer   data )
{
 close(tty_fd);
 tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
 
 g_print ("Bye!\n");
    gtk_main_quit();
}

int main( int argc, char *argv[])
{
 //Prepare for termios
 struct termios tio;
 struct termios stdio;
 //struct termios old_stdio;
 //int tty_fd;
 
 unsigned char c='D';
 tcgetattr(STDOUT_FILENO,&old_stdio);
 
 printf("Please start with %s /dev/ttyACM0 (for example)\n",argv[0]);
 memset(&stdio,0,sizeof(stdio));
 stdio.c_iflag=0;
 stdio.c_oflag=0;
 stdio.c_cflag=0;
 stdio.c_lflag=0;
 stdio.c_cc[VMIN]=1;
 stdio.c_cc[VTIME]=0;
 tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
 tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
 
 memset(&tio,0,sizeof(tio));
 tio.c_iflag=0;
 tio.c_oflag=0;
 tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
 tio.c_lflag=0;
 tio.c_cc[VMIN]=1;
 tio.c_cc[VTIME]=5;
 
 tty_fd=open(argv[1], O_RDWR | O_NONBLOCK);
 cfsetospeed(&tio,B9600); // 9600 baud
 cfsetispeed(&tio,B9600); // 9600 baud
 
 tcsetattr(tty_fd,TCSANOW,&tio);
 //---
 
    GtkWidget *window;
    GtkWidget *box;
    GtkWidget *label;
    GtkWidget *chooser;

    gtk_init(&argc, &argv);
    window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
    gtk_window_set_default_size(GTK_WINDOW(window), 400, 250);
    gtk_window_set_title(GTK_WINDOW(window), "arduino-er.blogspot.com");

    box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);

 label = gtk_label_new("GtkColorChooser to Arduino Esplora");
    gtk_box_pack_start(GTK_BOX(box), label, FALSE, FALSE, 3);

 //Create GtkColorChooser
    chooser = gtk_color_chooser_widget_new();
    gtk_box_pack_start(GTK_BOX(box), chooser, FALSE, FALSE, 3);
    g_signal_connect (GTK_COLOR_CHOOSER(chooser),
                    "color-activated", 
                    G_CALLBACK (chooser_color_activated), 
                    window);

    g_signal_connect(G_OBJECT(window), "destroy", 
        G_CALLBACK(destroy), NULL);

    gtk_container_add(GTK_CONTAINER(window), box);
    gtk_widget_show_all(window);
    gtk_main();

    return 0;
}

Compile it with command:
$ gcc GtkEsploraColor.c -o GtkEsploraColor `pkg-config --cflags --libs gtk+-3.0`

Arduino Esplora code, SerialColor.ino:
It's same as in the post "Serial communication between Arduino Esplora and PC")
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

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() {
    
    if(Serial.available()){
      char bytesIn[3] = {0x00, 0x00, 0x00};
      int i = 0;
      while(Serial.available()){
        bytesIn[i] = Serial.read();
        i++;
        if(i==3)
          break;
      }
      
      EsploraTFT.background(bytesIn[0], bytesIn[1], bytesIn[2]);
      Esplora.writeRGB(bytesIn[0], bytesIn[1], bytesIn[2]);
    }
}


Before run GtkEsploraColor, determine the connect USB port with dmesg:
- Insert Arduino Esploar to USB port
- Enter the command to check the port
$ dmesg
- The attached port should be listed in last lines. It's ttyACM0 in my setup
- Enter the command to run:
$ ./GtkEsploraColor /dev/ttyACM0
- Double Click on the color buttons to set color. The LCD screen and LED on Arduino Esplora should be changed accordingly.

Download source codes in this example Here.

Install GTK+3 and compile with gcc in Linux

To install GTK+3 to develop GUI program on Linux (eg.Ubuntu), you have to install libgtk-3-dev, enter the command in Terminal:
$ sudo apt-get install libgtk-3-dev

To compile your souce code using gcc, with GTK+3:
$ gcc <your_code>.c -o <your_code> `pkg-config --cflags --libs gtk+-3.0`

where <your_code>.c is your c source code. <your_code> is the generated program.

Notice the symbol `, not ' or ".

Then run it with:
$ ./<your_code>

Check a example: Send data to Arduino from Linux PC, program in C with GUI of GTK+3, as ColorChooser

Monday, January 27, 2014

Serial communication between Arduino and PC using C with termios

This example show how to implement Serial communication using C language with termios.h. It run on Ubuntu, and send and receive data to and from Arduino Esplora connected with USB cable.


The C program, testTermios.c, in Ubuntu side copy from example in http://en.wikibooks.org/wiki/Serial_Programming/Serial_Linux#termios, it is a simple terminal program with termios.h.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
 
int main(int argc,char** argv)
{
 struct termios tio;
 struct termios stdio;
 struct termios old_stdio;
 int tty_fd;
 
 unsigned char c='D';
 tcgetattr(STDOUT_FILENO,&old_stdio);
 
 printf("Please start with %s /dev/ttyS1 (for example)\n",argv[0]);
 memset(&stdio,0,sizeof(stdio));
 stdio.c_iflag=0;
 stdio.c_oflag=0;
 stdio.c_cflag=0;
 stdio.c_lflag=0;
 stdio.c_cc[VMIN]=1;
 stdio.c_cc[VTIME]=0;
 tcsetattr(STDOUT_FILENO,TCSANOW,&stdio);
 tcsetattr(STDOUT_FILENO,TCSAFLUSH,&stdio);
 fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); // make the reads non-blocking
 
 memset(&tio,0,sizeof(tio));
 tio.c_iflag=0;
 tio.c_oflag=0;
 tio.c_cflag=CS8|CREAD|CLOCAL; // 8n1, see termios.h for more information
 tio.c_lflag=0;
 tio.c_cc[VMIN]=1;
 tio.c_cc[VTIME]=5;
 
 tty_fd=open(argv[1], O_RDWR | O_NONBLOCK);
 cfsetospeed(&tio,B115200); // 115200 baud
 cfsetispeed(&tio,B115200); // 115200 baud
 
 tcsetattr(tty_fd,TCSANOW,&tio);
 while (c!='q')
 {
  if (read(tty_fd,&c,1)>0)        write(STDOUT_FILENO,&c,1);
  // if new data is available on the serial port, print it out
  if (read(STDIN_FILENO,&c,1)>0)  write(tty_fd,&c,1);
  // if new data is available on the console, send it to the serial port
 }
 
 close(tty_fd);
 tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);
 
 return EXIT_SUCCESS;
}

Compile it with the command:
$ gcc testTermios.c -o testTermios

To run it with specified device port, run the command dmesg to check the Arduino Esplora connected post:
$ dmesg

It's ttyACM0 in my case.

Run:
$ ./testTermios /dev/ttyACM0

Press any key will send to ttyACM0, press 'q' to quit.

In Arduino Esplora side, testSerial.ino. (It is same as the example in "Serial communication between Arduino Esplora and PC", using Arduino IDE's Serial Monitor.)
#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 = "";
    }
}


Next:
- Send data to Arduino from Linux PC, program in C with GUI of GTK+3, as ColorChooser

Sunday, January 26, 2014

Serial Communication: Arduino Esplora and Java with Swing - ColorPicker

It's a example to show communication between Arduino and PC running Java with RxTx library. The PC side implement javax.swing.JColorChooser to choice color, then send to Arduino Esplora via USB serial, then set LCD screen and RGB LED color accordingly. (It's another example using JavaFX interface)


In the PC side, it's JColorChooser (copied from http://examples.oreilly.com/jswing2/code/ch12/ColorPicker.java), once user selected color, the RGB bytes will be sent to Arduino using RXTX Java Library.

Before start coding, read the posts "Setup RxTx for Arduino and Java example" and "Create Java project using librxtx-java in Netbeans, work with Arduino".

Java code using Swing in PC side:
package javaswingcolorpicker;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;

public class JavaSwingColorPicker extends JFrame {
    
    MyRxTx myRxTx;

    public JavaSwingColorPicker() {
        super("JColorChooser Test Frame");
        setSize(200, 100);
        final Container contentPane = getContentPane();
        final JButton go = new JButton("Show JColorChooser");
        go.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Color c;
                c = JColorChooser.showDialog(
                        ((Component) e.getSource()).getParent(),
                        "Demo", Color.blue);
                contentPane.setBackground(c);

                byte byteR = (byte)(c.getRed());
                byte byteG = (byte)(c.getGreen());
                byte byteB = (byte)(c.getBlue() );
                
                try {
                    byte[] bytesToSent = 
                            new byte[]{byteB, byteG, byteR};
                    myRxTx.output.write(bytesToSent);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        });
        contentPane.add(go, BorderLayout.SOUTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

    public static void main(String[] args) {
        JavaSwingColorPicker myColorPicker = new JavaSwingColorPicker();
        myColorPicker.setVisible(true);
        
    }

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId
                        = (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                System.out.println("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();
                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }

}
For the source code in Arduino Esplora, refer to last post "Send array of byte from PC to Arduino Esplora, in JavaFX - ColorPicker".


download filesDownload the files.

Saturday, January 25, 2014

Send array of byte from PC to Arduino Esplora, in JavaFX - ColorPicker

This example show how to send array of byte from PC running Ubuntu Linux using JavaFX, to Arduino Esplora via USB serial. To act as ColorPicker to choice color from PC, then set screen color/RGB LED on Arduino Esplora.

In the PC side, it's JavaFX ColorPicker (copied from JavaFX Documentation Home > Using JavaFX UI Controls > Color Picker), once user selected color, the RGB bytes will be sent to Arduino using RXTX Java Library.

In Arduino Esplora side, once data received, it will set color of LCD screen and RGB LED accordingly.



Before start coding, read the posts "Setup RxTx for Arduino and Java example" and "Create Java project using librxtx-java in Netbeans, work with Arduino".

Example code in Arduino Esplora:
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

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() {
    
    if(Serial.available()){
      char bytesIn[3] = {0x00, 0x00, 0x00};
      int i = 0;
      while(Serial.available()){
        bytesIn[i] = Serial.read();
        i++;
        if(i==3)
          break;
      }
      
      EsploraTFT.background(bytesIn[0], bytesIn[1], bytesIn[2]);
      Esplora.writeRGB(bytesIn[0], bytesIn[1], bytesIn[2]);
    }
}

JavaFX code in PC side
package javafxcolorpicker;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavaFXColorPicker extends Application {

    MyRxTx myRxTx;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("ColorPicker");
        final Scene scene = new Scene(new HBox(20), 400, 100);
        HBox box = (HBox) scene.getRoot();
        box.setPadding(new Insets(5, 5, 5, 5));

        final ColorPicker colorPicker = new ColorPicker();
        //colorPicker.setValue(Color.CORAL);

        colorPicker.setOnAction(new EventHandler() {
            public void handle(Event t) {
                scene.setFill(colorPicker.getValue());
                
                Color color = colorPicker.getValue();
                byte byteR = (byte)(color.getRed() * 255);
                byte byteG = (byte)(color.getGreen() * 255);
                byte byteB = (byte)(color.getBlue() * 255);
                
                try {
                    byte[] bytesToSent = 
                            new byte[]{byteB, byteG, byteR};
                    myRxTx.output.write(bytesToSent);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        });

        box.getChildren().add(colorPicker);

        primaryStage.setScene(scene);
        primaryStage.show();
        
        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

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

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId
                        = (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                System.out.println("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();
                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }

}

download filesDownload the files.

It's another example implement with Java Swing, Serial Communication: Arduino Esplora and Java with Swing - ColorPicker.

Determine attached port and send data to Arduino in Terminal, on Linux

In Linux, to determine Arduino attached port, can use dmesg command:

  • Insert the USB cable connected with Arduino to PC USB port.
  • Enter command:
    $ dmesg
  • The new attached device should be list in last.
    It's ttyACM0 in my case. So /dev/ttyACM0 is the port of the device attached.
To send data to USB port, use the command:
$ echo "Hello Arduino-er" > /dev/ttyACM0

Determine attached port and send data to Arduino in Terminal
Determine attached port and send data to Arduino in Terminal
In the video below, the Arduino Esplora run the program in last post "Serial communication between Arduino Esplora and PC" to display char received from Serial to LCD screen.


Serial communication between Arduino Esplora and PC

This example show bi-direction serial communication between Arduino Esplora and PC. In PC side, the Serial Monitor can be used as terminal to send data to and receive data from Arduino Esplora.


Arduino Esplora sample code:
#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 = "";
    }
}

Related:
Serial communication between Arduino and PC using C with termios

Wednesday, January 22, 2014

Arduino Esplora example for Accelerometer

This example read Accelerometer senser on Esplora board, and display on LCD screen accordingly; such that you can know how Accelerometer work.


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

const int MAX_W = 160;
const int MAX_H = 128;
int xCenter = MAX_W/2;
int yCenter = MAX_H/2;

int xPos = xCenter; 
int yPos = yCenter;
int xPrev = xCenter;
int yPrev = yCenter;
char printoutX[5];
char printoutY[5];
char printoutZ[5];


void setup(){
  Serial.begin(9600);
  Mouse.begin();
  
  EsploraTFT.begin();  
  EsploraTFT.background(0,0,0);

  //preset dummy reading to print
  String dummy = "0";
  dummy.toCharArray(printoutX,5);
  dummy.toCharArray(printoutY,5);
  dummy.toCharArray(printoutZ,5);
}

void loop(){
  
  if(Esplora.readButton(SWITCH_1) == LOW){
    EsploraTFT.background(0,0,0);
  }
  
  int xValue = Esplora.readAccelerometer(X_AXIS);
  int yValue = Esplora.readAccelerometer(Y_AXIS);
  int zValue = Esplora.readAccelerometer(Z_AXIS);
  
  
  xPos = map(xValue, -512, 512, MAX_H, 0);
  yPos = map(yValue, -512, 512, 0, MAX_H);
  
  //clear previous print of reading
  EsploraTFT.stroke(0,0,0);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutZ,0,30);
  
  String(xValue).toCharArray(printoutX,5);
  String(yValue).toCharArray(printoutY,5);
  String(zValue).toCharArray(printoutZ,5);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutZ,0,30);
  
  if(xPos!=xPrev || yPos!=yPrev){
    
    EsploraTFT.line(xPrev, yPrev, xPos, yPos);
    
    xPrev=xPos;
    yPrev=yPos;
  }
  
  delay(10);
}

Insert LCD screen on Arduino Esplora

This post show how to insert optional LCD screen on Arduino Esplora board in right direction.

Refer to "Esplora Pinout Diagram", there are two connectors on Esplora board, the TFT display connector is located on the right side, for optional color LCD screen, SD card, or other devices that use the SPI protocol. On your LCD board, there should be some marking, something GND, BL, RESET...+5V... on the LCD connector. Just insert the LCD screen in the direction to match the connectors.

Unofficial Esplora Pinout Diagram

It's a nice unofficial Esplora Pinout Diagram, PDF version is available to download HERE.

Unofficial Esplora Pinout Diagram
Unofficial Esplora Pinout Diagram

How to use Simulink to Program your Arduino-based robot

Webinar announcement: How to use Simulink to Program your Arduino-based robot

This webinar will introduce you to Simulink, a graphical modeling tool that enables you to program Arduino, Raspberry-Pi and many other hardware boards. Simulink will be used to program an Arduino-based robotics platform to illustrate the capabilities. The webinar will end with a live Q&A session and pointers to tools and resources.

When and Where
Start Time: 2/5/14 7:00 AM PST (America/Los_Angeles)
End Time: 2/5/14 8:00 AM PST (America/Los_Angeles)
Location: Online - Webex

Event Info
Event Type: Webinar
Event Visibility & Attendance Policy: Open

details: http://www.element14.com/community/events/3934


http://www.element14.com/simulink - A new webinar is hosted by element14 and Mathworks to introduce the Simulink visual programming and simulation tool on February 5th. Learn to program your Arduino or Rasperry Pi project. The webinar training is done with an Arduino base robot and will demonstrate how to program motion. Simulink programming is a visual tool used in many professional industries, with drag and drop interface to create system diagrams which are then tested with the simulation tool and flashed directly onto your project. Register for the webinar and find out more at http://www.element14.com/simulink

Sunday, January 19, 2014

Netduino Home Automation Projects

Netduino Home Automation Projects
Netduino Home Automation Projects
Netduino Home Automation Projects 
Automate your house, save lives, and survive the apocalypse with .NET on a Netduino!
Overview
  • Automate your house using a Netduino and a bunch of common components
  • Learn the fundamentals of Netduino to implement them in almost any project
  • Create cool projects ranging from self-watering plants to a homemade breathalyzer
In Detail
In recent years, electronics have gone from something that only electronic engineers can understand, to a common hobby that is accessible to all. Netduino has grown to be a part of this revolution, providing a development board that is both easy to use, and allows existing .NET developers to build on knowledge they already have.
Most developers have wild ideas about all the gadgets they would develop to make the world a better (or easier) place, but have no idea how to get beyond blinking an LED. The topics contained go beyond what most books cover, taking an in-depth look at how to use Netduino for practical projects.
This book starts off by showing you how to do the “hello world” of electronics – fade an LED in and out. It will take you right through all the fundamentals, including how to control a wide range of electronic sensors.
You will learn how easy it is to automate various parts of your home. You will learn how to open your gate with your smartphone, automatically water your plants, get emailed when someone invades your territory, connect up a keypad to unlock your door, make your own breathalyzer, control your home theatre, and much more!
What you will learn from this book
  • Write some simple code for a Netduino
  • Use a microphone to determine the noise level of the room
  • Power the sensors and components with external power supplies
  • Control existing technology and appliances around your house with transistors and relays
  • Link your smartphone to your Netduino with Bluetooth as a controller
  • Determine alcohol on your breath
  • Use servos to control physical objects
  • Use a matrix keypad to secure your house and much more
Approach
Netduino Home Automation Projects for Lazy Boys is written in a practical and friendly style. Reading this book will be an experience full of fun and learning as well.
Who this book is written for
This book is ideally suited for someone who is interested in home automation, has some experience in C#, and has used a Netduino before but wants to explore more advanced topics. However, the book starts from the very basics so it can be 

Saturday, January 18, 2014

Arduino Esplora Joystick Mouse with Button function

This example work on last post "Auto center Arduino Esplora Joystick Mouse of Arduino Esplora", with button function added.

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

const int MAX_W = 160;
const int MAX_H = 128;
int xCenter = MAX_W/2;
int yCenter = MAX_H/2;

int xPos = xCenter; 
int yPos = yCenter;
int xPrev = xCenter;
int yPrev = yCenter;
char printoutX[5];
char printoutY[5];
char printoutSlider[5];

int centerJoystickX, centerJoystickY;

int JoystickButton;
int prevJoystickButton;

void setup(){
  Serial.begin(9600);
  Mouse.begin();
  
  EsploraTFT.begin();  
  EsploraTFT.background(0,0,0);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.line(xCenter, 0, xCenter, MAX_H);
  EsploraTFT.line(0, yCenter, MAX_W, yCenter);

  //preset dummy reading to print
  String dummy = "0";
  dummy.toCharArray(printoutX,5);
  dummy.toCharArray(printoutY,5);
  dummy.toCharArray(printoutSlider,5);
  
  //Read Joystick center position at start-up
  centerJoystickX = Esplora.readJoystickX();
  centerJoystickY = Esplora.readJoystickY();
  
  //preset JoystickSwitch states
  JoystickButton = HIGH;
  prevJoystickButton = HIGH;
}

void loop(){
  int xValue = Esplora.readJoystickX();
  int yValue = Esplora.readJoystickY();
  int sliderValue = Esplora.readSlider();
  
  //map stick value to TFT screen position
  if(xValue >= centerJoystickX){
    xPos = map(xValue, 512, centerJoystickX, 0, xCenter);
  }else{
    xPos = map(xValue, centerJoystickX, -512, xCenter, MAX_W);
  }
  
  int mouseX, mouseY;
  
  if(xValue >= centerJoystickX){
    xPos = map(xValue, 512, centerJoystickX, 0, xCenter);
    
    //report mouse position only if position offset > slider
    if((xValue - centerJoystickX) >= sliderValue){
      mouseX = map( xValue, 512, centerJoystickX, -10, 0);
    }else{
      mouseX = 0;
    }
  }else{
    xPos = map(xValue, centerJoystickX, -512, xCenter, MAX_W);
    
    //report mouse position only if position offset > slider
    if((centerJoystickX - xValue) >= sliderValue){
      mouseX = map( xValue, centerJoystickX, 512, 0, -10);
    }else{
      mouseX = 0;
    }
  }
  
  if(yValue >= centerJoystickY){
    yPos = map(yValue, 512, centerJoystickY, MAX_H, yCenter);
    
    //report mouse position only if position offset > slider
    if((yValue - centerJoystickY) >= sliderValue){
      mouseY = map( yValue, 512, centerJoystickY, 10, 0);
    }else{
      mouseY = 0;
    }
  }else{
    yPos = map(yValue, centerJoystickY, -512, yCenter, 0);
    
    //report mouse position only if position offset > slider
    if((centerJoystickY - yValue) >= sliderValue){
      mouseY = map( yValue, centerJoystickY, 512, 0, 10);
    }else{
      mouseY = 0;
    }
  }
  
  Mouse.move(mouseX, mouseY, 0);
  
  //clear previous print of reading
  EsploraTFT.stroke(0,0,0);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutSlider,0,30);
  
  String(xPos).toCharArray(printoutX,5);
  String(yPos).toCharArray(printoutY,5);
  String(sliderValue).toCharArray(printoutSlider,5);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutSlider,0,30);
  
  if(xPos!=xPrev || yPos!=yPrev){
    
    EsploraTFT.line(xPrev, yPrev, xPos, yPos);
    EsploraTFT.stroke(0,0,255);
    EsploraTFT.point(xPos, yPos);
    
    xPrev=xPos;
    yPrev=yPos;
  }
  
  //Read JoystickButton
  //send Mouse.press()/.release() if JoystickButton changed
  JoystickButton = Esplora.readJoystickButton();
  if(JoystickButton != prevJoystickButton){

    if(JoystickButton == LOW){
      Mouse.press();
      Esplora.writeRed(100);
    }else{
      Mouse.release();
      Esplora.writeRed(0);
    }
    prevJoystickButton = JoystickButton;
  }
  
  delay(10);
}

Friday, January 17, 2014

Auto center Arduino Esplora Joystick Mouse of Arduino Esplora

This example is a Arduino Esplora Joystick Mouse with auto center, and you can adjust the sensitivity using the Esplora's slider (the Linear Potentiometer).



Arduino IDE come with a EsploraJoystickMouse example (in Arduino IDE > File > Examples > Esplora > Beginners > EsploraJoystickMouse, or here), it will report mouse position to your PC base on Esplora's Joystick.

WARNING: this sketch will take over your mouse movement. If you lose control of your mouse do the following:
 1) unplug the Esplora.
 2) open the EsploraBlink sketch
 3) hold the reset button down while plugging your Esplora back in
 4) while holding reset, click "Upload"
 5) when you see the message "Done compiling", release the reset button.

It is possible that your mouse will auto-run when the joystick is in rest position. Because it assume the function Esplora.readJoystickX() and Esplora.readJoystickY() return 0 at center rest position. But it is not the actual case, most probably it return non-0 even the Joystick is in rest position.

The below example, modified from last example Read joystick and display on TFT, read the actual center postion at power up (assume it is in rest), to offset the x, y postion accordingly. And also it will compare the x, y values with the slider value to adjust the sensitivity. If the movement of x, y postion is less than slider, it will return no movement to PC.

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

const int MAX_W = 160;
const int MAX_H = 128;
int xCenter = MAX_W/2;
int yCenter = MAX_H/2;

int xPos = xCenter; 
int yPos = yCenter;
int xPrev = xCenter;
int yPrev = yCenter;
char printoutX[5];
char printoutY[5];
char printoutSlider[5];

int centerJoystickX, centerJoystickY;

int JoystickButton;
int prevJoystickButton;

void setup(){
  Serial.begin(9600);
  Mouse.begin();
  
  EsploraTFT.begin();  
  EsploraTFT.background(0,0,0);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.line(xCenter, 0, xCenter, MAX_H);
  EsploraTFT.line(0, yCenter, MAX_W, yCenter);

  //preset dummy reading to print
  String dummy = "0";
  dummy.toCharArray(printoutX,5);
  dummy.toCharArray(printoutY,5);
  dummy.toCharArray(printoutSlider,5);
  
  //Read Joystick center position at start-up
  centerJoystickX = Esplora.readJoystickX();
  centerJoystickY = Esplora.readJoystickY();
  
  //preset JoystickSwitch states
  JoystickButton = HIGH;
  prevJoystickButton = HIGH;
}

void loop(){
  int xValue = Esplora.readJoystickX();
  int yValue = Esplora.readJoystickY();
  int sliderValue = Esplora.readSlider();
  
  //map stick value to TFT screen position
  if(xValue >= centerJoystickX){
    xPos = map(xValue, 512, centerJoystickX, 0, xCenter);
  }else{
    xPos = map(xValue, centerJoystickX, -512, xCenter, MAX_W);
  }
  
  int mouseX, mouseY;
  
  if(xValue >= centerJoystickX){
    xPos = map(xValue, 512, centerJoystickX, 0, xCenter);
    
    //report mouse position only if position offset > slider
    if((xValue - centerJoystickX) >= sliderValue){
      mouseX = map( xValue, 512, centerJoystickX, -10, 0);
    }else{
      mouseX = 0;
    }
  }else{
    xPos = map(xValue, centerJoystickX, -512, xCenter, MAX_W);
    
    //report mouse position only if position offset > slider
    if((centerJoystickX - xValue) >= sliderValue){
      mouseX = map( xValue, centerJoystickX, 512, 0, -10);
    }else{
      mouseX = 0;
    }
  }
  
  if(yValue >= centerJoystickY){
    yPos = map(yValue, 512, centerJoystickY, MAX_H, yCenter);
    
    //report mouse position only if position offset > slider
    if((yValue - centerJoystickY) >= sliderValue){
      mouseY = map( yValue, 512, centerJoystickY, 10, 0);
    }else{
      mouseY = 0;
    }
  }else{
    yPos = map(yValue, centerJoystickY, -512, yCenter, 0);
    
    //report mouse position only if position offset > slider
    if((centerJoystickY - yValue) >= sliderValue){
      mouseY = map( yValue, centerJoystickY, 512, 0, 10);
    }else{
      mouseY = 0;
    }
  }
  
  Mouse.move(mouseX, mouseY, 0);
  
  //clear previous print of reading
  EsploraTFT.stroke(0,0,0);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutSlider,0,30);
  
  String(xPos).toCharArray(printoutX,5);
  String(yPos).toCharArray(printoutY,5);
  String(sliderValue).toCharArray(printoutSlider,5);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  EsploraTFT.text(printoutSlider,0,30);
  
  if(xPos!=xPrev || yPos!=yPrev){
    
    EsploraTFT.line(xPrev, yPrev, xPos, yPos);
    EsploraTFT.stroke(0,0,255);
    EsploraTFT.point(xPos, yPos);
    
    xPrev=xPos;
    yPrev=yPos;
  }
  
  delay(10);
}

Next: Arduino Esplora Joystick Mouse with Button function

Tuesday, January 14, 2014

Arduino Esplora example: read joystick and display on TFT

This example read joystick on Arduino Esplora, and display on TFT shield.


The function Esplora.readJoystickX() and Esplora.readJoystickY().
  • Esplora.readJoystickX() read the position of the X-axis of the joystick. When the joystick is in the center, it returns zero. Positive values indicate the joystick has moved to the right and negative values when moved to the left.
  • Esplora.readJoystickY() read the position of the Y-axis of the joystick. When the joystick is in the center, it returns zero. Positive values indicate the joystick has moved up and negative values when moved down.
With function map(value, fromLow, fromHigh, toLow, toHigh), it's easy to map value from joysticks to screen coordinates. It re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between.

Example code:
#include <TFT.h>
#include <SPI.h>
#include <Esplora.h>

const int MAX_W = 160;
const int MAX_H = 128;
int xCenter = MAX_W/2;
int yCenter = MAX_H/2;

int xPos = xCenter; 
int yPos = yCenter;
int xPrev = xCenter;
int yPrev = yCenter;
char printoutX[5];
char printoutY[5];

void setup(){
  EsploraTFT.begin();  
  EsploraTFT.background(0,0,0);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.line(xCenter, 0, xCenter, MAX_H);
  EsploraTFT.line(0, yCenter, MAX_W, yCenter);

  //preset dummy reading to print
  String dummy = "0";
  dummy.toCharArray(printoutX,5);
  dummy.toCharArray(printoutY,5);
}

void loop(){
  int xValue = Esplora.readJoystickX();
  int yValue = Esplora.readJoystickY();

  //clear previous print of reading
  EsploraTFT.stroke(0,0,0);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  
  String(xValue).toCharArray(printoutX,5);
  String(yValue).toCharArray(printoutY,5);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.text(printoutX,0,10);
  EsploraTFT.text(printoutY,0,20);
  
  //map stick value to TFT screen position
  xPos = map( xValue, 512, -512, 0, MAX_W);
  yPos = map( yValue, 512, -512, MAX_H, 0);
  
  if(xPos!=xPrev || yPos!=yPrev){
    
    EsploraTFT.line(xPrev, yPrev, xPos, yPos);
    EsploraTFT.stroke(0,0,255);
    EsploraTFT.point(xPos, yPos);
    
    xPrev=xPos;
    yPrev=yPos;
  }
  
  delay(50);
}

Next example: Auto center Arduino Esplora Joystick Mouse

Monday, January 13, 2014

Arduino Esplora example: read slider and display on TFT

The example run on Esplora, read from slider, and display on TFT.

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

const int MAX_W = 160;
const int MAX_H = 128;
unsigned long ul_MAX_H = (unsigned long)MAX_H;
const int MAX_SLIDER = 1023;

int xPos = 0; 
int yPos = 0;
int xPrev = 0;
int yPrev = MAX_H;
char printout[5];

void setup(){
  EsploraTFT.begin();  
  EsploraTFT.background(0,0,0);

  //preset dummy reading to print
  String dummy = "0";
  dummy.toCharArray(printout,5);
}

void loop(){
  int slider = Esplora.readSlider();

  //clear previous print of reading
  EsploraTFT.stroke(0,0,0);
  EsploraTFT.text(printout,0,10);
  //update reading
  String(slider).toCharArray(printout,5);
  EsploraTFT.stroke(255,255,255);
  EsploraTFT.text(printout,0,10);

  // update the location of the dot
  xPos++;
  //align y-position
  yPos = MAX_H - slider * ul_MAX_H/MAX_SLIDER;
  EsploraTFT.line(xPrev, yPrev, xPos, yPos);

  // if the x position reach screen edges, 
  // clear screen
  if(xPos >= MAX_W){
    EsploraTFT.background(0,0,0);
    xPos = 0;
  }

  // update the point's previous location
  xPrev=xPos;
  yPrev=yPos;

  delay(50);
}

Friday, January 10, 2014

Free download: “Soldering is Easy” Comic Book!

“Soldering is Easy” is a comic book that will teach anyone the basics of soldering. This seven page comic book explains in detail and with pictures how to make a good solder connection. It also teaches you all the other bits and pieces of knowledge that you need to successfully solder together an electronic kit, even if you’ve never soldered before!

“Soldering is Easy”
Download available with various languages.


Tuesday, January 7, 2014

Intel's new Edison chip

CES 2014: Intel's new chip embedded into...a baby's onesie?
The new system on a chip called Edison offers a PC processor that is the size of an SD card.