Notes for using Firmata
- Description for the statements to use firmata
Pre-requisite:
- Tested Firmata example programs
Objectives:
- To understand what each statements does.
Descriptions:
Declaring an Arduino Firmata variable
// Firmata is using serial library, so you will need it to be included import processing.serial.*; // Also Firmata library needs to be included import cc.arduino.*; // Create an arduino object Arduino arduino; // If you need additional object (you have more than 1 arduinos connected) // Arduino arduino2; // You can name your own name or even make it array // Arduino arduinos[];
Create the Arduino Firmata object
// In setup because it only need to be created once // If you want to create it dynamically, you can also put it in draw() // But if you do this, you need some logic to prevent it from being created over and over again void setup() { // Your window setup stuff // ... // Prints out the available serial ports. println(Arduino.list()); // Modify this line, by changing the "0" to the index of the serial // port corresponding to your Arduino board (as it appears in the list // printed by the line above). arduino = new Arduino(this, Arduino.list()[0], 57600); // Alternatively, use the name of the serial port corresponding to your // Arduino (in double-quotes), as in the following line. // arduino = new Arduino(this, "/dev/tty.usbmodem621", 57600); // In addition, mac also can use arduino = new Arduino(this, Arduino.list()[5], 57600); // But the number is usually 5 for the first Arduino. When you run Arduino.list(), // it will print out all the serial ports available. The 1st one being indexed 0 as all arrays. // Other codes // ... }
Setting pin modes
// You don't need to set pin mode for AD converter as they are usable by default // Suppose you declared the Arduino as "arduino" same as the examples // Set pin mode of pin x into Input arduino.pinMode(x, Arduino.INPUT); // Set pin mode of pin x into Output / PWM arduino.pinMode(x, Arduino.OUTPUT); // Set pin mode of pin x into Servo // Note that as PWM, the pin number has to have "~" arduino.pinMode(x, Arduino.SERVO);
Reading and Writing Values
// Read from pin x into i int i = arduino.digitalRead(x); if( i == Arduino.HIGH ){ // if the input is HIGH // ... } if( i == Arduino.LOW ){ // if the input is LOW // ... } // Read from Analog in x int i = arduino.analogRead(x); // i will be from 0 ~ 1023 // Write value i to servo pin x int i = 90; // i can be 0 ~ 180 for normal servos arduino.servoWrite(x, i);