Tuesday, June 25, 2013

Communication between Arduino and PC running Java, with JavaFX UI

Last posts "Setup RxTx for Arduino and Java example" and "Create Java project using librxtx-java in Netbeans, work with Arduino" describe basic setup to program Java with RxTx library in Netbeans, to receive data from Arduino Due. In this post, I will show bi-direction communication between Arduino Due and PC running Java, with JavaFX user interface.

Communication between Arduino and PC running Java, with JavaFX UI
Communication between Arduino and PC running Java, with JavaFX UI
User enter message in JavaFX and click the button, the message will be sent to Arduino via Serial. In Arduino side, it loop back the message to PC. Then, if received in PC side, it will be displayed in JavaFX.



It's a very simple code in Arduino side:
void setup() {
  Serial.begin(9600);
}

void loop() {
  if(Serial.available() > 0){
    Serial.print((char)Serial.read());
  }
}


In PC side, it's modified from last post, implement in JavaFX, with bi-direction communication.
package javafx_arduinotestserial;

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 java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

/**
 * @web arduino-er.blogspot.com
 */
public class JavaFX_ArduinoTestSerial extends Application {

    MyRxTx myRxTx;
    Label textInfo, textIn;

    @Override
    public void start(Stage primaryStage) {

        final TextField textOut = new TextField();
        textOut.setText("Hello Arduino-er!");

        textInfo = new Label();
        textIn = new Label();

        Button btn = new Button();
        btn.setText("Say 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                String stringOut = textOut.getText() + "\r\n";

                try {
                    myRxTx.output.write(stringOut.getBytes());
                } catch (IOException ex) {
                    Logger.getLogger(
                            JavaFX_ArduinoTestSerial.class.getName())
                            .log(Level.SEVERE, null, ex);
                }
            }
        });

        VBox panel = new VBox(10);
        panel.setPadding(new Insets(10, 10, 10, 10));
        panel.getChildren().addAll(textInfo, textOut, btn, textIn);

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

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

        primaryStage.setTitle("Hello World!");
        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 {
                textInfo.setText("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();

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {
                            textIn.setText(inputLine);
                        }
                    });

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

Sunday, June 23, 2013

Create Java project using librxtx-java in Netbeans, work with Arduino

remark: This example work on Ubuntu.

Before create our Java project using librxtx-java, we have to setup something in our PC, refer to lastr post "Setup RxTx for Arduino and Java example".

Create Netbeans Java Project:

- Start Netbeans, Click File -> New Project..., to create a project of Java Application in Java categories.


- with Project Name of SerialTest


Modify the code:

Basically, it's same as the example code in Arduino Playground of Arduino and Java, except the package, and PORT_NAMES of "/dev/ttyACM0".

package serialtest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier; 
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent; 
import gnu.io.SerialPortEventListener; 
import java.util.Enumeration;


public class SerialTest implements SerialPortEventListener {
 SerialPort serialPort;
        /** The port we're normally going to use. */
 private static final String PORT_NAMES[] = { 
                        "/dev/ttyACM0", //for Ubuntu
   "/dev/tty.usbserial-A9007UX1", // Mac OS X
   "/dev/ttyUSB0", // Linux
   "COM3", // Windows
 };
 /**
 * A BufferedReader which will be fed by a InputStreamReader 
 * converting the bytes into characters 
 * making the displayed results codepage independent
 */
 private BufferedReader input;
 /** The output stream to the port */
 private OutputStream output;
 /** Milliseconds to block while waiting for port open */
 private static final int TIME_OUT = 2000;
 /** Default bits per second for COM port. */
 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;
  }

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

 /**
  * 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();
  }
 }

 /**
  * Handle an event on the serial port. Read the data and print it.
  */
 public synchronized void serialEvent(SerialPortEvent oEvent) {
  if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
   try {
    String inputLine=input.readLine();
    System.out.println(inputLine);
   } catch (Exception e) {
    System.err.println(e.toString());
   }
  }
  // Ignore all the other eventTypes, but you should consider the other ones.
 }

 public static void main(String[] args) throws Exception {
  SerialTest main = new SerialTest();
  main.initialize();
  Thread t=new Thread() {
   public void run() {
    //the following line will keep this app alive for 1000 seconds,
    //waiting for events to occur and responding to them (printing incoming messages to console).
    try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
   }
  };
  t.start();
  System.out.println("Started");
 }
}

In order to access Serial port in Ubuntu, you have to setup the right of the port. Refer to the post Fixed the problem of "No device found on COM1" for /dev/ttyACM0. You have to enter the following command before run the code:

$sudo chmod a+rw /dev/ttyACM0

If everything OK, you can run the program as shown below, the message "Hello world" will be printed every second in Output windows.



Next:
- Communication between Arduino and PC running Java, with JavaFX UI

Setup RxTx for Arduino and Java example

Refer to the post "Arduino and Java", Arduino Playground provide a example of Java code work with Arduino with RxTx library. I will create it work in Netbeans in next post, "Create Java project using librxtx-java in Netbeans, work with Arduino".

In Arduino side, you can 100% copy the provided sample and download to Arduino board, tested on Arduino Due.

List here:
void setup(){
  Serial.begin(9600);
}

void loop(){
  Serial.println("Hello world");
  delay(1000);
}


In PC side, you have to install librxtx-java, setup JAR in Netbeans, and copy librxtxSerial.so to your java library path. Refer to the post of "Install RXTX on Ubuntu" and "Setup RxTx jar and .so for Ubuntu".

The steps to build java program with NetBeans will be in next post. Finally, it will run as shown below.

running


Next:
- Create Java project using librxtx-java in Netbeans, work with Arduino
- Communication between Arduino and PC running Java, with JavaFX UI


Monday, June 17, 2013

Import and setup Android ADK terminal emulator, to work with Arduino ADKTerminalTest example

Last post introduced "Modified ADKTerminalTest example of Arduino 1.5.2", it work with "http://labs.arduino.cc/uploads/ADK/ArduinoTerminal/ThibaultTerminal_ICS_0001.apk" in default. Alternatively, Circuits@Home provide a project "Android ADK terminal emulator for Arduino" with source code, it can work with the modified ADKTerminalTest. This post descript how to import and setup in Eclipse of Android Developer Tools.

Prepare:

- It's assumed you have Android SDK installed on your PC.

- Download and unzip source code of ArduinoTerminalSrc.zip from "Android ADK terminal emulator for Arduino page", it can also be download here directly.

- Make sure Android 2.3.3 (API 10) and associated Google APIs are installed in your Android Developer Tools. In Eclipse, select Window in menu bar, -> Android SDK Manager.


Import downloaded ArduinoTerminalSrc:

- Click File -> Import...


-  Select "Existing Android Code into Workspace" under Android section.



- Browse to select downloaded and unziped folder.


- Optionally check "Copy projects into workspace" and click Finish.


- After a moment of auto-build, many error of something like "The import com.android.future cannot be resolved" will be reported.


- Right click your project - > Properties.


- Select Target Google APIs of Platform 2.3.3, and click OK.


- After finished and re-built, you can download it to your Android device. It can work with the modified ADKTerminalTest.

remark:
- Tested on Nexus One with Android 2.3.6. But not work on HTC One X with Android 4.1.1, dur to issues of Theme!


Test ADKTerminalTest example of Arduino 1.5.2, with Android ADK terminal emulator for Arduino

Arduino 1.5.2 provide a ADKTerminalTest example to demonstrates USB Host connectivity between an Android phone and an Arduino Due. It provide source code in Arduino Due side, and url to load Android APK from "http://labs.arduino.cc/uploads/ADK/ArduinoTerminal/ThibaultTerminal_ICS_0001.apk". But I can't find the source code of ThibaultTerminal_ICS_0001. Alternatively, I found "Android ADK terminal emulator for Arduino (ArduinoTerminal)" with source code provided.

In this post, I will describe how to make ADKTerminalTest example work with ArduinoTerminal. In next post, I will show how to import and setup ArduinoTerminalSrc in Android Developer Tools. After finished, you can connect and send text between Arduino Due and Nexus One running Android 2.3.6.

Arduino Due work with Nexus One
Arduino Due work with Nexus One
To load ADKTerminalTest example of Arduino 1.5.2, select File -> Examples -> USBHost -> ADKTerminalTest.

ADKTerminalTest example in Arduino 1.5.2
ADKTerminalTest example in Arduino 1.5.2

Modify on Arduino code:
  • Modify adk() parameters to match with Android side. To acknowledge the originator of Android ADK terminal emulator for Arduino, I use the original counter part.
  • Add the code Serial.begin(9600) in setup() method.
/*

 ADK Terminal Test

 This demonstrates USB Host connectivity between an 
 Android phone and an Arduino Due.

 The ADK for the Arduino Due is a work in progress
 For additional information on the Arduino ADK visit 
 http://labs.arduino.cc/ADK/Index

 created 27 June 2012
 by Cristian Maglie

*/

#include "variant.h"
#include <stdio.h>
#include <adk.h>
/*
// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "Arduino_Terminal"; // the app on your phone
char accessoryName[] = "Arduino Due"; // your Arduino board
char companyName[] = "Arduino SA";

// Make up anything you want for these
char versionNumber[] = "1.0";
char serialNumber[] = "1";
char url[] = "http://labs.arduino.cc/uploads/ADK/ArduinoTerminal/ThibaultTerminal_ICS_0001.apk";
*/

USBHost Usb;
//ADK adk(&Usb, companyName, applicationName, accessoryName,versionNumber,url,serialNumber);

ADK adk(&Usb,"Circuits@Home, ltd.",
            "USB Host Shield",
            "Arduino Terminal for Android",
            "1.0",
            "http://www.circuitsathome.com",
            "0000000000000001");

void setup()
{
  
      Serial.begin(9600);  //<-- need to add
      
 cpu_irq_enable();
 printf("\r\nADK demo start\r\n");
 delay(200);
}

#define RCVSIZE 128

void loop()
{
 uint8_t buf[RCVSIZE];
 uint32_t nbread = 0;
 char helloworld[] = "Hello World!\r\n";

 Usb.Task();

 if (adk.isReady())
 {
  /* Write hello string to ADK */
  adk.write(strlen(helloworld), (uint8_t *)helloworld);

  delay(1000);

  /* Read data from ADK and print to UART */
  adk.read(&nbread, RCVSIZE, buf);
  if (nbread > 0)
  {
   printf("RCV: ");
   for (uint32_t i = 0; i < nbread; ++i)
   {
    printf("%c", (char)buf[i]);
   }
   printf("\r\n");
  }
 }
}


Next:
- Import and setup Android ADK terminal emulator, to work with Arduino ADKTerminalTest example

Sunday, June 16, 2013

RXTX Java library


RXTX is the Java library Arduino IDE used to communicate to the serial. It can be used by developers to develop applications communicating with Arduino board.

Visit RXTX home page

Arduino and Java


The Arduino IDE itself is written in Java, and it can communicate to the serial port via the RXTX Java library. That library is very similar to the Java Communications API extension.

The document "Arduino Playground - Arduino and Java" provide set up and sample java code to develop Java application working with Arduino.

Saturday, June 15, 2013

Processing code sample: draw Text with Fonts

Example to draw text with installed fonts.

draw Text with Fonts
draw Text with Fonts


PFont fontBitstreamCharter20;
PFont fontBitstreamCharterBoldItalic20;
PFont fontDejaVuSans16;

void setup() {
  size(600, 300);
  background(255);
  
  //Create fonts
  fontBitstreamCharter20 = createFont("Bitstream Charter", 20, true);  //name, size, smooth
  fontBitstreamCharterBoldItalic20 = createFont("Bitstream Charter Bold Italic", 20);    //name, size
  fontDejaVuSans16 = createFont("DejaVu Sans", 16);          //name, size
  
  fill(0); 
  
  textFont(fontBitstreamCharter20);
  text("fontBitstreamCharter20", 10, 25);
  textFont(fontBitstreamCharter20, 16);
  text("fontBitstreamCharter20, 16", 10, 50);
  
  textFont(fontBitstreamCharterBoldItalic20);
  text("fontBitstreamCharterBoldItalic20", 10, 75);
  textFont(fontBitstreamCharterBoldItalic20, 32);
  text("fontBitstreamCharterBoldItalic20, 32", 10, 100);
  
  textFont(fontDejaVuSans16);
  text("fontDejaVuSans16", 10, 125);
  textFont(fontDejaVuSans16, 32);
  text("fontDejaVuSans16, 32", 10, 150);
}

void draw() {
}

Processing code sample: list available fonts

To list installed fonts in Processing, call the function PFont.list().

list installed fonts in Processing
list installed fonts in Processing


void setup() {
  size(400, 300);
  background(255);

  String[] fontList = PFont.list();
  println(fontList);
}

void draw() {
}

Friday, June 14, 2013

Make: Analog Synthesizers


Make: Analog Synthesizers


Dive hands-on into the tools, techniques, and information for making your own analog synthesizer. If you’re a musician or a hobbyist with experience in building electronic projects from kits or schematics, this do-it-yourself guide will walk you through the parts and schematics you need, and how to tailor them for your needs. Author Ray Wilson shares his decades of experience in synth-DIY, including the popular Music From Outer Space (MFOS) website and analog synth community.

At the end of the book, you’ll apply everything you’ve learned by building an analog synthesizer, using the MFOS Noise Toaster kit. You’ll also learn what it takes to create synth-DIY electronic music studio. Get started in the fun and engaging hobby of synth-DIY without delay.

With this book, you’ll learn:
  • The differences between analog and digital synthesizers
  • Analog synthesizer building blocks, including VCOs, VCFs, VCAs, and LFOs
  • How to tool up for synth-DIY, including electronic instruments and suggestions for home-made equipment
  • Foundational circuits for amplification, biasing, and signal mixing
  • How to work with the MFOS Noise Toaster kit
  • Setting up a synth-DIY electronic music studio on a budget

Download ADK Source in Ubuntu

The document "Downloading the ADK Source" describe how to obtain the source material for the ADK. Before that, we have to install curl, git and repo. The steps below show how to install the tools and also ADK source in Ubuntu (13.04).

- Open Terminal.

- Install curl
$sudo apt-get install curl

- Install git
$sudo apt-get install git

- Then create bin/ directory in home directory, and include it in your path.
$mkdir ~/bin
$PATH=~/bin:$PATH

- Install Repo
$curl https://dl-ssl.google.com/dl/googlesource/git-repo/repo > ~/bin/repo
$chmod a+x ~/bin/repo

- Finally, create a new directory for the downloaded ADK source files, initialize and synchronize a local repository:
$mkdir android-accessories
$cd android-accessories
$repo init -u https://android.googlesource.com/accessories/manifest
$repo sync

After successfully completing this process, you should have the source code and tools for working with the ADK 2012:

adk2012/board - Source code and hardware design files for the ADK 2012
adk2012/app - Source code for the ADK 2012 Android companion application
external/ide - Source code for the ADK 2012 Integrated Development Environment (IDE)
external/toolchain - The toolchain used by the ADK 2012 IDE

Wednesday, June 12, 2013

Amarino: new interface between Android And Arduino





Amarino is a toolkit, basically consisting of an Android application and an Arduino library which will help you to interface with your phone in a new dimension. You can build your own interfaces almost without any programming experience.


Processing 2.0 communication with Arduino via serial

This example demonstrate how to send date via serial with Processing 2.0. It work with Arduino Due with code in last post, to send command from PC running Processing 2.0, to Arduino Due.

Processing 2.0 communication with Arduino via serial
Processing 2.0 communication with Arduino via serial


import processing.serial.*;

Serial myArduinoPort;

int buttonA_x = 300;
int buttonA_y = 50;
int buttonA_width = 50;
int buttonA_height = 50;
int buttonA_colorR = 0xff;
int buttonA_colorG = 0x00;
int buttonA_colorB = 0x00;
 
int buttonB_x = 300;
int buttonB_y = 150;
int buttonB_width = 50;
int buttonB_height = 50;
int buttonB_r = 10;
int buttonB_color = 200;
 
int defaultColor = 150;
 
boolean buttonA_clicked = false;
boolean buttonB_clicked = false;
 
void setup() {  // setup() runs once
  size(400, 300);
  background(255);
  
  //Get serial port for Arduino
  String arduinoPort = Serial.list()[0];
  println(arduinoPort);
  myArduinoPort = new Serial(this, arduinoPort, 9600);
  
}
  
void draw() {
   
  if(buttonA_clicked){
    fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  }else if(buttonB_clicked){
    fill(buttonB_color);
  }else{
    fill(defaultColor);
  }
  ellipse(width/2, height/2, 100, 100);
 
  fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  rect(buttonA_x, buttonA_y, buttonA_width, buttonA_height);
   
  fill(buttonB_color);
  rect(buttonB_x, buttonB_y, buttonB_width, buttonB_height, buttonB_r);
}
 
/* The mouseClicked() function is called once after a mouse button 
 * has been pressed and then released.
 */
void mouseClicked(){
  // mouseX = x of mouse click position
  // mouseY = y of mouse click position
   
  if (mouseX >= buttonA_x && mouseX <= buttonA_x + buttonA_width && 
      mouseY >= buttonA_y && mouseY <= buttonA_y + buttonA_height) {
     buttonA_clicked = true;
     
     myArduinoPort.write("H");
   } else {
     buttonA_clicked = false;
   }
    
   if (mouseX >= buttonB_x && mouseX <= buttonB_x + buttonB_width && 
       mouseY >= buttonB_y && mouseY <= buttonB_y + buttonB_height) {
     buttonB_clicked = true;
     
     myArduinoPort.write("L");
   } else {
     buttonB_clicked = false;
   }
}


Arduino Due communication with PC running Processing 2.0

Similar to the example "Read byte from Serial port and set pin", this example demonstrate how to control LED on Arduino Due board with PC running Processing 2.0.


It's the code in the Arduino Due side, the PC side Processing code will be in next post.

int led = 13;
int incomingByte = 0;
 
void setup() {
    pinMode(led, OUTPUT);
     
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    Serial.println("Press H to turn LED ON");
    Serial.println("Press L to turn LED OFF");
}
 
void loop() {
    if (Serial.available() > 0) {
        // read the incoming byte:
        incomingByte = Serial.read();
     
        if(incomingByte == 'H'){
            digitalWrite(led, HIGH);
            Serial.println("LED ON");
        }else if(incomingByte == 'L'){
            digitalWrite(led, LOW);
            Serial.println("LED OFF");
        }else{
            Serial.println("invalid!");
        }
       
    }
}

Saturday, June 8, 2013

Processing code sample: detect mouse event

To detect mouse event implement mouse related callback function; mouseClicked(), mouseDragged(), mouseMoved(), mousePressed() and mouseReleased(). The system variable mouseX and mouseY contain the current X and Y coordinate of the mouse.

void setup(){
  size(400, 300);
  background(255);
}

void draw(){
}

// The mouseClicked() function is called once after a 
// mouse button has been pressed and then released.
void mouseClicked(){
  fill(0xFF, 0x00, 0x00);
  ellipse(mouseX, mouseY, 50, 50);
}

// The mouseDragged() function is called once every 
// time the mouse moves and a mouse button is pressed.
void mouseDragged(){
  fill(0x00, 0xFF, 0x00);
  ellipse(mouseX, mouseY, 50, 50);
}

// The mouseMoved() function is called every time the 
// mouse moves and a mouse button is not pressed.
void mouseMoved(){
  fill(0xFF, 0xFF, 0xFF);
  ellipse(mouseX, mouseY, 50, 50);
}

// The mousePressed() function is called once after 
// every time a mouse button is pressed. The mouseButton 
// variable (see the related reference entry) can be used 
// to determine which button has been pressed.
void mousePressed(){
  fill(0xFF, 0x00, 0xFF);
  rect(mouseX, mouseY, 50, 50);
}

// The mouseReleased() function is called every time a 
// mouse button is released.
void mouseReleased(){
  fill(0x00, 0xFF, 0xFF);
  rect(mouseX, mouseY, 50, 50);
}

detect mouse event in Processing
detect mouse event in Processing


Friday, June 7, 2013

Processing code: implement button

The example implement two rect as button, and fill the circle with corresponding color.

implement button in Processing
implement button in Processing


int buttonA_x = 300;
int buttonA_y = 50;
int buttonA_width = 50;
int buttonA_height = 50;
int buttonA_colorR = 0xff;
int buttonA_colorG = 0x00;
int buttonA_colorB = 0x00;

int buttonB_x = 300;
int buttonB_y = 150;
int buttonB_width = 50;
int buttonB_height = 50;
int buttonB_r = 10;
int buttonB_color = 200;

int defaultColor = 150;

boolean buttonA_clicked = false;
boolean buttonB_clicked = false;

void setup() {  // setup() runs once
  size(400, 300);
  background(255);
}
 
void draw() {
  
  if(buttonA_clicked){
    fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  }else if(buttonB_clicked){
    fill(buttonB_color);
  }else{
    fill(defaultColor);
  }
  ellipse(width/2, height/2, 100, 100);

  fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  rect(buttonA_x, buttonA_y, buttonA_width, buttonA_height);
  
  fill(buttonB_color);
  rect(buttonB_x, buttonB_y, buttonB_width, buttonB_height, buttonB_r);
}

/* The mouseClicked() function is called once after a mouse button 
 * has been pressed and then released.
 */
void mouseClicked(){
  // mouseX = x of mouse click position
  // mouseY = y of mouse click position
  
  if (mouseX >= buttonA_x && mouseX <= buttonA_x + buttonA_width && 
      mouseY >= buttonA_y && mouseY <= buttonA_y + buttonA_height) {
     buttonA_clicked = true;
   } else {
     buttonA_clicked = false;
   }
   
   if (mouseX >= buttonB_x && mouseX <= buttonB_x + buttonB_width && 
       mouseY >= buttonB_y && mouseY <= buttonB_y + buttonB_height) {
     buttonB_clicked = true;
   } else {
     buttonB_clicked = false;
   }
}

Processing code: fill shapes with color, using fill() method

Example to fill shapes with color in Processing 2.0+, using fill() method:

fill shapes with color in Processing
fill shapes with color in Processing


int buttonA_x = 300;
int buttonA_y = 50;
int buttonA_width = 50;
int buttonA_height = 50;
int buttonA_colorR = 0xff;
int buttonA_colorG = 0x00;
int buttonA_colorB = 0x00;

int buttonB_x = 300;
int buttonB_y = 150;
int buttonB_width = 50;
int buttonB_height = 50;
int buttonB_r = 10;
int buttonB_color = 200;

int defaultColor = 150;

void setup() {  // setup() runs once
  size(400, 300);
  background(255);
}
 
void draw() {
  
  line(0, 0, width, height);
  
  fill(defaultColor);
  ellipse(width/2, height/2, 100, 100);
  
  fill(buttonA_colorR, buttonA_colorG, buttonA_colorB);
  rect(buttonA_x, buttonA_y, buttonA_width, buttonA_height);
  
  fill(buttonB_color);
  rect(buttonB_x, buttonB_y, buttonB_width, buttonB_height, buttonB_r);
}

MagPi June available for download now

MagPi issue 13 June available for download now, PDF provided.

http://www.themagpi.com/en/issue/13

Thursday, June 6, 2013

Hello Processing 2.0 - draw something

It's my first try of using Processing 2.0, to draw something.

draw something in Processing

draw something in Processing


void setup() {  // setup() runs once
  size(400, 300);
  background(200);
}
 
void draw() {
  line(0, 0, width, height);
  ellipse(width/2, height/2, 100, 100);
  rect(300, 50, 50, 50);
  rect(300, 150, 50, 50, 10);
}

Wednesday, June 5, 2013

Processing 2.0 released


The Processing 2.0 release focuses on faster graphics, new infrastructure for working with data, and enhanced video playback and capture. It also expands the potential of the programming environment. The new Modes feature allows other programming systems, such as JavaScript and Android, to be easily used from within the development environment. The new Contributions Manager makes it simple to distribute and install extensions developed by the community. The P2D and P3D renderers are now built using modern OpenGL, and programs can now utilize custom GLSL shaders.

Website: http://processing.org/

Tuesday, June 4, 2013

write failed: ENODEV (No such device)



In this previous exercise "Android code for Communication between Android and Arduino Due", it work as expected after plug in Android device into Arduino Due board.



The problem is:

Once I switch out and back the app, and perform onResume()... The app can get fileDescriptor, myAdkInputStream and myAdkOutputStream. But when it try to write to myAdkOutputStream in WriteAdk(String text) method, IOException of "write failed: ENODEV (No such device)" thrown!

Anybody can advise?