From 13fa1f7672e586e80bf6ba43e3b3f2e98dc99222 Mon Sep 17 00:00:00 2001 From: panoptes Date: Wed, 2 Oct 2013 14:21:47 -0700 Subject: [PATCH 01/79] Initial commit --- README.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..3c0f2669c --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +PACE +==== + +Panoptes Arduino Code for Electronics From ab5550a0d4e7741c1a5517c378291672ce83873a Mon Sep 17 00:00:00 2001 From: Josh Walawender Date: Fri, 25 Oct 2013 13:19:59 -1000 Subject: [PATCH 02/79] Added WeatherStation.ino file which Hannah Dalgliesch and Josh Walawender wrote in June 2013. --- WeatherStation.ino | 207 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 207 insertions(+) create mode 100644 WeatherStation.ino diff --git a/WeatherStation.ino b/WeatherStation.ino new file mode 100644 index 000000000..00cb953b0 --- /dev/null +++ b/WeatherStation.ino @@ -0,0 +1,207 @@ +// This script is for a Weather Station that contains two RG-11 Rain Gauges, +// a DHT22 Humidity and Temperature Sensor, two TMP36 Temperature Sensors, +// a TSL235R Light to Frequency Sensor, and an MLX90614 Infrared Thermometer. +// +// Program will read sensors and periodically print out a line of text via +// serial with the readings. + + +#include +#include + + +// Pin Constants +const int WarningLEDpin = 13; // This LED turns on when the weather conditions are not good for observing. +const int RainSensor1 = 7; // The Rain Gauges can be connected to any of the digital pins. +const int RainSensor2 = 8; +const int TMP36pin1 = 2; // The TMP36 sensors must be connected to analogue pins. +const int TMP36pin2 = 3; +#define DHTPIN 5 // The DHT22 is connected to a digital pin. +#define DHTTYPE DHT22 +DHT dht(DHTPIN, DHTTYPE); + + +// Thresholds for Warnings +// --> These need to be modified after experience in the field +const float Threshold_VeryCloudy = -20.0; +const float Threshold_Cloudy = -40.0; +const float Threshold_Humidity = 80.0; + + +// Constants for TSL235R +volatile unsigned long cnt = 0; +unsigned long oldcnt = 0; +unsigned long t = 0; +unsigned long last; + +void irq1() +{ + cnt++; +} + + +void setup() { + Serial.begin(9600); + + Serial.print("Setup LED Pin..."); + pinMode(WarningLEDpin, OUTPUT); + Serial.println("done!"); + + Serial.print("Setup DHT22..."); + dht.begin(); + Serial.println("done!"); + + Serial.print("Setup I2C..."); + i2c_init(); // Initialise the i2c bus + PORTC = (1 << PORTC4) | (1 << PORTC5); // Enable pullups + Serial.println("done!"); + + Serial.print("Setup TSL235R..."); + pinMode(2, INPUT); // TSL235R must use digital pin 2. + digitalWrite(2, HIGH); + attachInterrupt(0, irq1, RISING); + Serial.println("done!"); + + Serial.print("Setup first RG-11..."); + pinMode(RainSensor1, INPUT); + Serial.println("done!"); + + Serial.print("Setup second RG-11..."); + pinMode(RainSensor2, INPUT); + Serial.println("done!"); + + + // print header to Serial + Serial.print("Light "); + Serial.print("SkyTemp "); + Serial.print("AmbTemp "); + Serial.print("Humidity "); + Serial.print("HW "); + Serial.print("TempDiff "); + Serial.print("CW "); + Serial.print("CaseTemp 1 "); + Serial.print("CaseTemp 2 "); + Serial.print("Rain1? "); + Serial.print("Rain2? "); + Serial.print("Safe? "); + Serial.println(""); +} + +void loop() { + + // Read light level TSL235R in mW/m2 + last = millis(); + t = cnt; + unsigned long hz = t - oldcnt; + oldcnt = t; + float Light = (hz+50)/100; // +50 == rounding last digit + // print output to Serial + Serial.print(Light); + Serial.print(" mW/m2 "); + + // Read sky temperature MLX90614 in Celsius + float SkyTemp_C = readMLX90614() - 273.15; // Converting from Kelvin to Celsius + // print output to Serial + Serial.print(SkyTemp_C); + Serial.print(" C "); + + // Read ambient temperature and humidity DHT22 + float Humidity = dht.readHumidity(); + float AmbTemp_C = dht.readTemperature(); + // check if returns are valid, if they are NaN (not a number) then something went wrong! + if (isnan(AmbTemp_C) || isnan(Humidity)) { + Serial.println("Failed to read from DHT"); + } + int HumidityWarning = 0; + if (Humidity > Threshold_Humidity) { HumidityWarning = 1; } + // print output to Serial + Serial.print(AmbTemp_C); + Serial.print(" C "); + Serial.print(Humidity); + Serial.print(" % "); + Serial.print(HumidityWarning); + Serial.print(" "); + + // Determine Sky / Ambient Temperature Difference + float TempDiff = SkyTemp_C - AmbTemp_C; + int Cloudiness; + // print output to Serial + Serial.print(TempDiff); + Serial.print(" C "); + if (TempDiff >= Threshold_VeryCloudy) { Cloudiness = 2; } + if (TempDiff >= Threshold_Cloudy && TempDiff < Threshold_VeryCloudy) { Cloudiness = 1; } + if (TempDiff < Threshold_Cloudy) { Cloudiness = 0; } + // print output to Serial + Serial.print(Cloudiness); + Serial.print(" "); + + // Read case temperature from TMP36 primary + int TMP36reading1 = analogRead(TMP36pin1); + float TMP36voltage1 = (TMP36reading1 / 1024.0) * 5000; + float CaseTemp_C1 = (TMP36voltage1 -500) / 10.0; + // print output to Serial + Serial.print(CaseTemp_C1); + Serial.print(" C "); + + // Read case temperature from TMP36 secondary + int TMP36reading2 = analogRead(TMP36pin2); + float TMP36voltage2 = (TMP36reading2 / 1024.0) * 5000; + float CaseTemp_C2 = (TMP36voltage2 -500) / 10.0; + // print output to Serial + Serial.print(CaseTemp_C2); + Serial.print(" C "); + + // Are the RG-11 Rain Gauges on? + int rain1; + rain1 = digitalRead(RainSensor1); // read the input pin + // print output to Serial + Serial.print(rain1); + Serial.print(" "); + + int rain2; + rain2 = digitalRead(RainSensor2); // read the input pin + // print output to Serial + Serial.print(rain2); + Serial.print(" "); + + // Are conditions safe? + bool Safe = false; + if (HumidityWarning == 0 && Cloudiness <= 1) { Safe = true; } + if (Safe) { digitalWrite(WarningLEDpin, LOW); } + else { digitalWrite(WarningLEDpin, HIGH); } + // print output to Serial + Serial.print(Safe); + Serial.print(" "); + + Serial.println(""); +} + +// Read MLX90614 IR thermometer and return temperature in Kelvin +float readMLX90614(void){ + int dev = 0x5A<<1; + int data_low = 0; + int data_high = 0; + int pec = 0; + + i2c_start_wait(dev+I2C_WRITE); + i2c_write(0x07); + + i2c_rep_start(dev+I2C_READ); + data_low = i2c_readAck(); // Read 1 byte and then send ack + data_high = i2c_readAck(); // Read 1 byte and then send ack + pec = i2c_readNak(); + i2c_stop(); + + // This converts high and low bytes together and processes temperature, MSB is an error bit and is ignored for temps + double tempFactor = 0.02; // 0.02 degrees per LSB (measurement resolution of the MLX90614) + double tempData = 0x0000; // Zero out the data + int frac; // Data past the decimal point + + // This masks off the error bit of the high byte, then moves it left 8 bits and adds the low byte. + tempData = (double)(((data_high & 0x007F) << 8) + data_low); + tempData = (tempData * tempFactor) - 0.01; + + float kelvin = tempData; + + return kelvin; +} From 57f9c015550c74ca0daa66dda2c4b00ee298fdee Mon Sep 17 00:00:00 2001 From: Josh Walawender Date: Tue, 17 Dec 2013 16:44:24 -1000 Subject: [PATCH 03/79] Added DSLR_Controller.ino, has skeleton of code for three commands (expose, cancel, query), but needs query and cancel to be written. --- DSLR_Controller.ino | 92 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 DSLR_Controller.ino diff --git a/DSLR_Controller.ino b/DSLR_Controller.ino new file mode 100644 index 000000000..160358b67 --- /dev/null +++ b/DSLR_Controller.ino @@ -0,0 +1,92 @@ +/* +Canon DSLR Camera Control + +To activate cameras send a serial tring to the board. The string should +consist of three integers. The first and second indicate which cameras +should be activated. Any non-zero, positive integer in the first field +will activate the first camera and any non-zero integer in the second +field will activate the second camera. The third value is the exposure +time in milliseconds. + +Serial Commands to Board: +E,n,n,nnn -- Expose camera. +C,n,n -- Cancel exposure. +Q -- Query which cameras are exposing. +*/ + +// Constants for Camera Relay +const int camera1_pin = 2; +const int camera2_pin = 3; + +//----------------------------------------------------------------------------- +// SETUP +//----------------------------------------------------------------------------- +void setup() { + // Open serial communications and wait for port to open: + Serial.begin(9600); + while (!Serial) { + ; // wait for serial port to connect. Needed for Leonardo only + } + + Serial.print("Setup Camera Relay Pins ... "); + pinMode(camera1_pin, OUTPUT); + pinMode(camera2_pin, OUTPUT); + digitalWrite(camera1_pin, LOW); + digitalWrite(camera2_pin, LOW); + Serial.println("done!"); +} + +//----------------------------------------------------------------------------- +// MAIN LOOP +//----------------------------------------------------------------------------- +void loop() { + // if there's any serial available, read it: + while (Serial.available() > 0) { + int command = Serial.parseInt(); + // Based on the command, parse the rest of the serial string differently. + if (command == 69) { + // Expose (E=69) command + int camera1 = Serial.parseInt(); + int camera2 = Serial.parseInt(); + int exptime_ms = Serial.parseInt(); + // look for the newline. That's the end of your + // sentence: + if (Serial.read() == '\n') { + // expose camera for exptime_ms milliseconds + Serial.print("Starting "); + Serial.print(exptime_ms/1000.0); + Serial.print(" second exposure"); + if (camera1 >= 1) { + Serial.print(" on camera1 "); + digitalWrite(camera1_pin, HIGH); + if (camera2 >= 1) { Serial.print("and"); } + } + if (camera2 >= 1) { + Serial.print(" on camera2 "); + digitalWrite(camera2_pin, HIGH); + } + Serial.print("... "); + // Now go in to loop waiting for exposure time to finish + // If a cancel command is received, cancel exposure. + int total_exptime = 0 + int remainder = total_exptime % 100; + int n_loops = (total_exptime - remainder) / 100; + for (int index = 0; index < n_loops; index++) { + delay(100); + total_exptime = total_exptime + 100; + // Look for cancel command + } + delay(remainder); + // Set pins low (stop exposure) + digitalWrite(camera1_pin, LOW); + digitalWrite(camera2_pin, LOW); + Serial.println("done"); + } + } + if (command == 67) or (command == 81) { + // Cancel (C=67) or Query (Q=81) command + } + } + delay(100); +} + From 7c5360a6e9fab318b1f880c7074c2d50233e2b9e Mon Sep 17 00:00:00 2001 From: Josh Walawender Date: Thu, 19 Dec 2013 22:19:25 -1000 Subject: [PATCH 04/79] Moved DSLR_Controller.ino to folder named DSLR_Controller to make Arduino software happy. --- DSLR_Controller.ino => DSLR_Controller/DSLR_Controller.ino | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DSLR_Controller.ino => DSLR_Controller/DSLR_Controller.ino (100%) diff --git a/DSLR_Controller.ino b/DSLR_Controller/DSLR_Controller.ino similarity index 100% rename from DSLR_Controller.ino rename to DSLR_Controller/DSLR_Controller.ino From a69a680803f4011ed25a2a17bcf00f3a76e30f6e Mon Sep 17 00:00:00 2001 From: Josh Walawender Date: Thu, 19 Dec 2013 23:03:20 -1000 Subject: [PATCH 05/79] Changes to DSLR_Controller.ino to handle commands. Added Test_DSLR.py python script to send command string to Arduino. --- DSLR_Controller/DSLR_Controller.ino | 9 ++-- Test_DSLR.py | 73 +++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+), 3 deletions(-) create mode 100755 Test_DSLR.py diff --git a/DSLR_Controller/DSLR_Controller.ino b/DSLR_Controller/DSLR_Controller.ino index 160358b67..e48e39ba8 100644 --- a/DSLR_Controller/DSLR_Controller.ino +++ b/DSLR_Controller/DSLR_Controller.ino @@ -68,7 +68,7 @@ void loop() { Serial.print("... "); // Now go in to loop waiting for exposure time to finish // If a cancel command is received, cancel exposure. - int total_exptime = 0 + int total_exptime = 0; int remainder = total_exptime % 100; int n_loops = (total_exptime - remainder) / 100; for (int index = 0; index < n_loops; index++) { @@ -83,8 +83,11 @@ void loop() { Serial.println("done"); } } - if (command == 67) or (command == 81) { - // Cancel (C=67) or Query (Q=81) command + if (command == 67) { + // Cancel (C=67) command + } + if (command == 81) { + // Query (Q=81) command } } delay(100); diff --git a/Test_DSLR.py b/Test_DSLR.py new file mode 100755 index 000000000..78ac1f383 --- /dev/null +++ b/Test_DSLR.py @@ -0,0 +1,73 @@ +#!/usr/env/python + +# from __future__ import division, print_function + +## Import General Tools +import sys +import os +import argparse +import logging + +import serial + +##------------------------------------------------------------------------- +## Main Program +##------------------------------------------------------------------------- +def main(): + + ##------------------------------------------------------------------------- + ## Parse Command Line Arguments + ##------------------------------------------------------------------------- + ## create a parser object for understanding command-line arguments + parser = argparse.ArgumentParser( + description="Program description.") + ## add flags + parser.add_argument("-v", "--verbose", + action="store_true", dest="verbose", + default=False, help="Be verbose! (default = False)") + ## add arguments + parser.add_argument("--command", "-c", + type=str, dest="command", + help="Command string to send to Arduino.") + args = parser.parse_args() + + ##------------------------------------------------------------------------- + ## Create logger object + ##------------------------------------------------------------------------- + logger = logging.getLogger('MyLogger') + logger.setLevel(logging.DEBUG) + ## Set up console output + LogConsoleHandler = logging.StreamHandler() + if args.verbose: + LogConsoleHandler.setLevel(logging.DEBUG) + else: + LogConsoleHandler.setLevel(logging.INFO) + LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s') + LogConsoleHandler.setFormatter(LogFormat) + logger.addHandler(LogConsoleHandler) + ## Set up file output +# LogFileName = None +# LogFileHandler = logging.FileHandler(LogFileName) +# LogFileHandler.setLevel(logging.DEBUG) +# LogFileHandler.setFormatter(LogFormat) +# logger.addHandler(LogFileHandler) + + + ##------------------------------------------------------------------------- + ## Send command over serial + ##------------------------------------------------------------------------- + connection = serial.Serial('/dev/tty.usbmodemfd1251', 9600, timeout=3.5) + send_string = str(args.command + '/n') + connection.write(send_string) + response = connection.readline() + if response != '': + print(response) + else: + print("No response from Arduino.") + connection.close() + + + + +if __name__ == '__main__': + main() From e5177208259ab243d1ed56ebb4478361af27be90 Mon Sep 17 00:00:00 2001 From: Josh Walawender Date: Thu, 19 Dec 2013 23:04:06 -1000 Subject: [PATCH 06/79] Moved WeatherStation.ino to WeatherStation folder to make Arduino IDE happy. --- WeatherStation.ino => WeatherStation/WeatherStation.ino | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename WeatherStation.ino => WeatherStation/WeatherStation.ino (100%) diff --git a/WeatherStation.ino b/WeatherStation/WeatherStation.ino similarity index 100% rename from WeatherStation.ino rename to WeatherStation/WeatherStation.ino From 71553e5e0238c3df894491977b2480ccb3e4a9a8 Mon Sep 17 00:00:00 2001 From: Josh Walawender Date: Thu, 30 Jan 2014 10:02:03 -1000 Subject: [PATCH 07/79] Complete refactoring to handle serial exchanges differently. This commit has a timing problem and the exposure times are way off. --- DSLR_Controller/DSLR_Controller.ino | 215 +++++++++++++++++++++------- 1 file changed, 162 insertions(+), 53 deletions(-) diff --git a/DSLR_Controller/DSLR_Controller.ino b/DSLR_Controller/DSLR_Controller.ino index e48e39ba8..98da95cae 100644 --- a/DSLR_Controller/DSLR_Controller.ino +++ b/DSLR_Controller/DSLR_Controller.ino @@ -9,14 +9,52 @@ field will activate the second camera. The third value is the exposure time in milliseconds. Serial Commands to Board: -E,n,n,nnn -- Expose camera. -C,n,n -- Cancel exposure. -Q -- Query which cameras are exposing. +Enn,mmmmmm -- Expose camera for mmmmmm milliseconds. +C -- Cancel exposure. Cancels exposure on both cameras. +Q -- Query which cameras are exposing. +T -- Query temperature and humidity from DHT22 (only works if camera not exposing) +O -- Query orientation (only works if camera not exposing) */ -// Constants for Camera Relay -const int camera1_pin = 2; -const int camera2_pin = 3; +char Command[3]; +char Data[7]; +const int bSize = 20; +char Buffer[bSize]; // Serial buffer +int ByteCount; + +int camera1_pin = 2; +int camera2_pin = 4; + +//Analog read pins +const int xPin = 0; +const int yPin = 1; +const int zPin = 2; + +//The minimum and maximum values that came from +//the accelerometer while standing still +//You very well may need to change these +int minVal = 265; +int maxVal = 402; + +//to hold the caculated values +double x; +double y; +double z; + +//----------------------------------------------------------------------------- +// SerialParser +//----------------------------------------------------------------------------- +void SerialParser(void) { + ByteCount = -1; + ByteCount = Serial.readBytesUntil('\n',Buffer,bSize); + if (ByteCount > 0) { + strcpy(Command,strtok(Buffer,",")); + strcpy(Data,strtok(NULL,",")); + } + memset(Buffer, 0, sizeof(Buffer)); // Clear contents of Buffer + Serial.flush(); +} + //----------------------------------------------------------------------------- // SETUP @@ -27,7 +65,6 @@ void setup() { while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } - Serial.print("Setup Camera Relay Pins ... "); pinMode(camera1_pin, OUTPUT); pinMode(camera2_pin, OUTPUT); @@ -36,60 +73,132 @@ void setup() { Serial.println("done!"); } + //----------------------------------------------------------------------------- // MAIN LOOP //----------------------------------------------------------------------------- void loop() { - // if there's any serial available, read it: - while (Serial.available() > 0) { - int command = Serial.parseInt(); - // Based on the command, parse the rest of the serial string differently. - if (command == 69) { - // Expose (E=69) command - int camera1 = Serial.parseInt(); - int camera2 = Serial.parseInt(); - int exptime_ms = Serial.parseInt(); - // look for the newline. That's the end of your - // sentence: - if (Serial.read() == '\n') { - // expose camera for exptime_ms milliseconds - Serial.print("Starting "); - Serial.print(exptime_ms/1000.0); - Serial.print(" second exposure"); - if (camera1 >= 1) { - Serial.print(" on camera1 "); - digitalWrite(camera1_pin, HIGH); - if (camera2 >= 1) { Serial.print("and"); } + boolean cam1 = false; + boolean cam2 = false; + SerialParser(); + if (Command[0] == 'E') { + if (Command[1] == '1') {cam1 = true;} + if (Command[1] == '2') {cam2 = true;} + if (Command[2] == '1') {cam1 = true;} + if (Command[2] == '2') {cam2 = true;} + String exptime_ms_string = String(Data); + unsigned long exptime_ms = exptime_ms_string.toInt(); + float exptime_sec = exptime_ms/1000.0; + Serial.print("EXP"); + if (cam1 == true) {Serial.print("1");} + if (cam2 == true) {Serial.print("2");} + Serial.print(","); + Serial.print(exptime_ms); + Serial.println('#'); + if (cam1 == true) {digitalWrite(camera1_pin, HIGH);} + if (cam2 == true) {digitalWrite(camera2_pin, HIGH);} + // Now go in to loop waiting for exposure time to finish + // If a cancel command is received, cancel exposure. + unsigned long total_exptime = 0; + unsigned long remainder = exptime_ms % 100; + unsigned long startTime = millis(); + while (total_exptime < exptime_ms - remainder) { + delay(100); + total_exptime = total_exptime + 100; + Serial.println(total_exptime); + // Look for cancel or query status commands + SerialParser(); + if (ByteCount > 0) { + if (Command[0] == 'Q') { + Serial.print("EXP"); + if (cam1 == true) {Serial.print("1");} + if (cam2 == true) {Serial.print("2");} + Serial.println('#'); + } else if (Command[0] == 'X') { + cam1 = false; + cam2 = false; + digitalWrite(camera1_pin, LOW); + digitalWrite(camera2_pin, LOW); + Serial.print("EXP"); + if (cam1 == true) {Serial.print("1");} + if (cam2 == true) {Serial.print("2");} + Serial.println('X#'); + total_exptime = exptime_ms; + } else { + Serial.println('?#'); } - if (camera2 >= 1) { - Serial.print(" on camera2 "); - digitalWrite(camera2_pin, HIGH); - } - Serial.print("... "); - // Now go in to loop waiting for exposure time to finish - // If a cancel command is received, cancel exposure. - int total_exptime = 0; - int remainder = total_exptime % 100; - int n_loops = (total_exptime - remainder) / 100; - for (int index = 0; index < n_loops; index++) { - delay(100); - total_exptime = total_exptime + 100; - // Look for cancel command - } - delay(remainder); - // Set pins low (stop exposure) - digitalWrite(camera1_pin, LOW); - digitalWrite(camera2_pin, LOW); - Serial.println("done"); } } - if (command == 67) { - // Cancel (C=67) command - } - if (command == 81) { - // Query (Q=81) command - } + delay(remainder); + total_exptime = total_exptime + remainder; + // Set pins low (stop exposure) + cam1 = false; + cam2 = false; + digitalWrite(camera1_pin, LOW); + digitalWrite(camera2_pin, LOW); + unsigned long elapsed = millis() - startTime; + Serial.println(elapsed); + } else if (Command[0] == 'Q') { + Serial.print("EXP"); + Serial.println('#'); + } else if (Command[0] == 'X') { + Serial.print("EXP"); + Serial.println('#'); + } else if (Command[0] == 'T') { + // + } else if (Command[0] == 'O') { + queryOrientation(); + } else if (Command[0] != ' ') { + Serial.println('#'); } + Command[0] = ' '; + Command[1] = '0'; + Command[2] = '0'; + Data[0] = '0'; + Data[1] = '0'; + Data[2] = '0'; + Data[3] = '0'; + Data[4] = '0'; + Data[5] = '0'; + Data[6] = '0'; delay(100); } + +//----------------------------------------------------------------------------- +// Query Temperature +//----------------------------------------------------------------------------- +float queryTemperature(void) { + +} + + +//----------------------------------------------------------------------------- +// Query Orientation +//----------------------------------------------------------------------------- +float queryOrientation(void) { + //read the analog values from the accelerometer + int xRead = analogRead(xPin); + int yRead = analogRead(yPin); + int zRead = analogRead(zPin); + + //convert read values to degrees -90 to 90 - Needed for atan2 + int xAng = map(xRead, minVal, maxVal, -90, 90); + int yAng = map(yRead, minVal, maxVal, -90, 90); + int zAng = map(zRead, minVal, maxVal, -90, 90); + + //Caculate 360deg values like so: atan2(-yAng, -zAng) + //atan2 outputs the value of -π to π (radians) + //We are then converting the radians to degrees + x = RAD_TO_DEG * (atan2(-yAng, -zAng) + PI); + y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI); + z = RAD_TO_DEG * (atan2(-yAng, -xAng) + PI); + + //Output the caculations + Serial.print("x: "); + Serial.print(x); + Serial.print(" | y: "); + Serial.print(y); + Serial.print(" | z: "); + Serial.println(z); +} From 2050628d7db4fdbae67c2cccf53a9b7a958bf287 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sat, 6 Sep 2014 17:18:59 -1000 Subject: [PATCH 08/79] Basic accelerometer output for camera box --- CameraBox/camera_box.ino | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 CameraBox/camera_box.ino diff --git a/CameraBox/camera_box.ino b/CameraBox/camera_box.ino new file mode 100644 index 000000000..970de45a1 --- /dev/null +++ b/CameraBox/camera_box.ino @@ -0,0 +1,47 @@ +#include +#include +#include +#include + +Adafruit_MMA8451 mma = Adafruit_MMA8451(); + +void setup(void) { + Serial.begin(9600); + + Serial.println("PANOPTES Arduino Code for Electronics"); + + if (! mma.begin()) { + Serial.println("Couldnt start Accelerometer"); + while (1); + } + Serial.println("MMA8451 Accelerometer found"); + + mma.setRange(MMA8451_RANGE_2_G); + + Serial.print("Range = "); Serial.print(2 << mma.getRange()); + Serial.println("G"); + +} + +void loop() { + + read_accelerometer(); + + Serial.println(); + + delay(1000); // One second +} + + +void read_accelerometer() { + /* ACCELEROMETER */ + /* Get a new sensor event */ + sensors_event_t event; + mma.getEvent(&event); + uint8_t o = mma.getOrientation(); // Orientation + + Serial.print(event.acceleration.x); Serial.print(':'); + Serial.print(event.acceleration.y); Serial.print(':'); + Serial.print(event.acceleration.z); Serial.print(':'); + Serial.print(o); +} \ No newline at end of file From dd23deca066ae7f3134c7980203411ccd4687a0c Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sat, 6 Sep 2014 18:01:10 -1000 Subject: [PATCH 09/79] Adding DHT22 temp & humidity; output in valid json --- CameraBox/camera_box.ino | 56 ++++++++++++++++++++++++++++++++-------- 1 file changed, 45 insertions(+), 11 deletions(-) diff --git a/CameraBox/camera_box.ino b/CameraBox/camera_box.ino index 970de45a1..c0b367aa6 100644 --- a/CameraBox/camera_box.ino +++ b/CameraBox/camera_box.ino @@ -2,37 +2,51 @@ #include #include #include +#include + +#define DHTPIN 2 // DHT Temp & Humidity Pin +#define DHTTYPE DHT22 // DHT 22 (AM2302) Adafruit_MMA8451 mma = Adafruit_MMA8451(); +DHT dht(DHTPIN, DHTTYPE); + void setup(void) { Serial.begin(9600); Serial.println("PANOPTES Arduino Code for Electronics"); if (! mma.begin()) { - Serial.println("Couldnt start Accelerometer"); + Serial.println("Couldn't start Accelerometer"); while (1); } Serial.println("MMA8451 Accelerometer found"); - mma.setRange(MMA8451_RANGE_2_G); + dht.begin(); + Serial.println("DHT22found"); - Serial.print("Range = "); Serial.print(2 << mma.getRange()); + // Check Accelerometer range + mma.setRange(MMA8451_RANGE_2_G); + Serial.print("Accelerometer Range = "); Serial.print(2 << mma.getRange()); Serial.println("G"); + Serial.println("Data output is:"); + } void loop() { - read_accelerometer(); + Serial.print("{"); + read_accelerometer(); + Serial.print(','); + read_temperature(); + Serial.print("}"); - Serial.println(); + Serial.println(); - delay(1000); // One second + delay(3000); // Three second } - void read_accelerometer() { /* ACCELEROMETER */ /* Get a new sensor event */ @@ -40,8 +54,28 @@ void read_accelerometer() { mma.getEvent(&event); uint8_t o = mma.getOrientation(); // Orientation - Serial.print(event.acceleration.x); Serial.print(':'); - Serial.print(event.acceleration.y); Serial.print(':'); - Serial.print(event.acceleration.z); Serial.print(':'); - Serial.print(o); + Serial.print("\"accelerometer\":{"); + Serial.print("\"x\":"); Serial.print(event.acceleration.x); Serial.print(','); + Serial.print("\"y\":"); Serial.print(event.acceleration.y); Serial.print(','); + Serial.print("\"z\":"); Serial.print(event.acceleration.z); Serial.print(','); + Serial.print("\"o\": "); Serial.print(o); + Serial.print('}'); +} + +// Reading temperature or humidity takes about 250 milliseconds! +// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) +void read_temperature() { + float h = dht.readHumidity(); + float c = dht.readTemperature(); // Celsius + + // Check if any reads failed and exit early (to try again). + // if (isnan(h) || isnan(t)) { + // Serial.println("Failed to read from DHT sensor!"); + // return; + // } + + Serial.print("\"temperature\":{"); + Serial.print("\"h\":"); Serial.print(h); Serial.print(','); + Serial.print("\"c\":"); Serial.print(c); + Serial.print('}'); } \ No newline at end of file From 827738009505f936f639d00892144b6e14910c7a Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sat, 6 Sep 2014 18:01:46 -1000 Subject: [PATCH 10/79] Adding support libraries --- .../Adafruit_MMA8451/Adafruit_MMA8451.cpp | 258 ++++++++++++++++++ libraries/Adafruit_MMA8451/Adafruit_MMA8451.h | 106 +++++++ libraries/Adafruit_MMA8451/README.md | 29 ++ .../examples/MMA8451demo/MMA8451demo.ino | 95 +++++++ libraries/Adafruit_MMA8451/license.txt | 26 ++ libraries/Adafruit_Sensor/Adafruit_Sensor.cpp | 5 + libraries/Adafruit_Sensor/Adafruit_Sensor.h | 153 +++++++++++ libraries/Adafruit_Sensor/README.md | 214 +++++++++++++++ libraries/DHT/DHT.cpp | 179 ++++++++++++ libraries/DHT/DHT.h | 41 +++ libraries/DHT/README.txt | 3 + .../DHT/examples/DHTtester/DHTtester.ino | 71 +++++ 12 files changed, 1180 insertions(+) create mode 100644 libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp create mode 100644 libraries/Adafruit_MMA8451/Adafruit_MMA8451.h create mode 100644 libraries/Adafruit_MMA8451/README.md create mode 100644 libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino create mode 100644 libraries/Adafruit_MMA8451/license.txt create mode 100644 libraries/Adafruit_Sensor/Adafruit_Sensor.cpp create mode 100644 libraries/Adafruit_Sensor/Adafruit_Sensor.h create mode 100644 libraries/Adafruit_Sensor/README.md create mode 100644 libraries/DHT/DHT.cpp create mode 100644 libraries/DHT/DHT.h create mode 100644 libraries/DHT/README.txt create mode 100644 libraries/DHT/examples/DHTtester/DHTtester.ino diff --git a/libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp b/libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp new file mode 100644 index 000000000..74f1556d6 --- /dev/null +++ b/libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp @@ -0,0 +1,258 @@ +/**************************************************************************/ +/*! + @file Adafruit_MMA8451.h + @author K. Townsend (Adafruit Industries) + @license BSD (see license.txt) + + This is a library for the Adafruit MMA8451 Accel breakout board + ----> https://www.adafruit.com/products/2019 + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + @section HISTORY + + v1.0 - First release +*/ +/**************************************************************************/ + +#if ARDUINO >= 100 + #include "Arduino.h" +#else + #include "WProgram.h" +#endif + +#include +#include + +/**************************************************************************/ +/*! + @brief Abstract away platform differences in Arduino wire library +*/ +/**************************************************************************/ +static inline uint8_t i2cread(void) { + #if ARDUINO >= 100 + return Wire.read(); + #else + return Wire.receive(); + #endif +} + +static inline void i2cwrite(uint8_t x) { + #if ARDUINO >= 100 + Wire.write((uint8_t)x); + #else + Wire.send(x); + #endif +} + + +/**************************************************************************/ +/*! + @brief Writes 8-bits to the specified destination register +*/ +/**************************************************************************/ +void Adafruit_MMA8451::writeRegister8(uint8_t reg, uint8_t value) { + Wire.beginTransmission(_i2caddr); + i2cwrite((uint8_t)reg); + i2cwrite((uint8_t)(value)); + Wire.endTransmission(); +} + +/**************************************************************************/ +/*! + @brief Reads 8-bits from the specified register +*/ +/**************************************************************************/ +uint8_t Adafruit_MMA8451::readRegister8(uint8_t reg) { + Wire.beginTransmission(_i2caddr); + i2cwrite(reg); + Wire.endTransmission(false); // MMA8451 + friends uses repeated start!! + + Wire.requestFrom(_i2caddr, 1); + if (! Wire.available()) return -1; + return (i2cread()); +} + +/**************************************************************************/ +/*! + @brief Instantiates a new MMA8451 class in I2C mode +*/ +/**************************************************************************/ +Adafruit_MMA8451::Adafruit_MMA8451(int32_t sensorID) { + _sensorID = sensorID; +} + +/**************************************************************************/ +/*! + @brief Setups the HW (reads coefficients values, etc.) +*/ +/**************************************************************************/ +bool Adafruit_MMA8451::begin(uint8_t i2caddr) { + Wire.begin(); + _i2caddr = i2caddr; + + /* Check connection */ + uint8_t deviceid = readRegister8(MMA8451_REG_WHOAMI); + if (deviceid != 0x1A) + { + /* No MMA8451 detected ... return false */ + //Serial.println(deviceid, HEX); + return false; + } + + writeRegister8(MMA8451_REG_CTRL_REG2, 0x40); // reset + + while (readRegister8(MMA8451_REG_CTRL_REG2) & 0x40); + + // enable 4G range + writeRegister8(MMA8451_REG_XYZ_DATA_CFG, MMA8451_RANGE_4_G); + // High res + writeRegister8(MMA8451_REG_CTRL_REG2, 0x02); + // Low noise! + writeRegister8(MMA8451_REG_CTRL_REG4, 0x01); + // DRDY on INT1 + writeRegister8(MMA8451_REG_CTRL_REG4, 0x01); + writeRegister8(MMA8451_REG_CTRL_REG5, 0x01); + + // Turn on orientation config + writeRegister8(MMA8451_REG_PL_CFG, 0x40); + + // Activate! + writeRegister8(MMA8451_REG_CTRL_REG1, 0x01); // active, max rate + + /* + for (uint8_t i=0; i<0x30; i++) { + Serial.print("$"); + Serial.print(i, HEX); Serial.print(" = 0x"); + Serial.println(readRegister8(i), HEX); + } + */ + + return true; +} + + +void Adafruit_MMA8451::read(void) { + // read x y z at once + Wire.beginTransmission(_i2caddr); + i2cwrite(MMA8451_REG_OUT_X_MSB); + Wire.endTransmission(false); // MMA8451 + friends uses repeated start!! + + Wire.requestFrom(_i2caddr, 6); + x = Wire.read(); x <<= 8; x |= Wire.read(); x >>= 2; + y = Wire.read(); y <<= 8; y |= Wire.read(); y >>= 2; + z = Wire.read(); z <<= 8; z |= Wire.read(); z >>= 2; + + + uint8_t range = getRange(); + uint16_t divider = 1; + if (range == MMA8451_RANGE_8_G) divider = 1024; + if (range == MMA8451_RANGE_4_G) divider = 2048; + if (range == MMA8451_RANGE_2_G) divider = 4096; + + x_g = (float)x / divider; + y_g = (float)y / divider; + z_g = (float)z / divider; + +} + +/**************************************************************************/ +/*! + @brief Read the orientation: + Portrait/Landscape + Up/Down/Left/Right + Front/Back +*/ +/**************************************************************************/ +uint8_t Adafruit_MMA8451::getOrientation(void) { + return readRegister8(MMA8451_REG_PL_STATUS) & 0x07; +} + +/**************************************************************************/ +/*! + @brief Sets the g range for the accelerometer +*/ +/**************************************************************************/ +void Adafruit_MMA8451::setRange(mma8451_range_t range) +{ + // lower bits are range + writeRegister8(MMA8451_REG_CTRL_REG1, 0x00); // deactivate + writeRegister8(MMA8451_REG_XYZ_DATA_CFG, range & 0x3); + writeRegister8(MMA8451_REG_CTRL_REG1, 0x01); // active, max rate +} + +/**************************************************************************/ +/*! + @brief Sets the g range for the accelerometer +*/ +/**************************************************************************/ +mma8451_range_t Adafruit_MMA8451::getRange(void) +{ + /* Read the data format register to preserve bits */ + return (mma8451_range_t)(readRegister8(MMA8451_REG_XYZ_DATA_CFG) & 0x03); +} + +/**************************************************************************/ +/*! + @brief Sets the data rate for the MMA8451 (controls power consumption) +*/ +/**************************************************************************/ +void Adafruit_MMA8451::setDataRate(mma8451_dataRate_t dataRate) +{ + uint8_t ctl1 = readRegister8(MMA8451_REG_CTRL_REG1); + ctl1 &= ~(0x28); // mask off bits + ctl1 |= (dataRate << 3); + writeRegister8(MMA8451_REG_CTRL_REG1, ctl1); +} + +/**************************************************************************/ +/*! + @brief Sets the data rate for the MMA8451 (controls power consumption) +*/ +/**************************************************************************/ +mma8451_dataRate_t Adafruit_MMA8451::getDataRate(void) +{ + return (mma8451_dataRate_t)((readRegister8(MMA8451_REG_CTRL_REG1) >> 3)& 0x07); +} + +/**************************************************************************/ +/*! + @brief Gets the most recent sensor event +*/ +/**************************************************************************/ +void Adafruit_MMA8451::getEvent(sensors_event_t *event) { + /* Clear the event */ + memset(event, 0, sizeof(sensors_event_t)); + + event->version = sizeof(sensors_event_t); + event->sensor_id = _sensorID; + event->type = SENSOR_TYPE_ACCELEROMETER; + event->timestamp = 0; + + read(); + + event->acceleration.x = x_g; + event->acceleration.y = y_g; + event->acceleration.z = z_g; +} + +/**************************************************************************/ +/*! + @brief Gets the sensor_t data +*/ +/**************************************************************************/ +void Adafruit_MMA8451::getSensor(sensor_t *sensor) { + /* Clear the sensor_t object */ + memset(sensor, 0, sizeof(sensor_t)); + + /* Insert the sensor name in the fixed length char array */ + strncpy (sensor->name, "MMA8451", sizeof(sensor->name) - 1); + sensor->name[sizeof(sensor->name)- 1] = 0; + sensor->version = 1; + sensor->sensor_id = _sensorID; + sensor->type = SENSOR_TYPE_ACCELEROMETER; + sensor->min_delay = 0; + sensor->max_value = 0; + sensor->min_value = 0; + sensor->resolution = 0; +} diff --git a/libraries/Adafruit_MMA8451/Adafruit_MMA8451.h b/libraries/Adafruit_MMA8451/Adafruit_MMA8451.h new file mode 100644 index 000000000..54040bff5 --- /dev/null +++ b/libraries/Adafruit_MMA8451/Adafruit_MMA8451.h @@ -0,0 +1,106 @@ +/**************************************************************************/ +/*! + @file Adafruit_MMA8451.h + @author K. Townsend (Adafruit Industries) + @license BSD (see license.txt) + + This is a library for the Adafruit MMA8451 Accel breakout board + ----> https://www.adafruit.com/products/2019 + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + @section HISTORY + + v1.0 - First release +*/ +/**************************************************************************/ + +#if ARDUINO >= 100 + #include "Arduino.h" +#else + #include "WProgram.h" +#endif + +#include +#include + +/*========================================================================= + I2C ADDRESS/BITS + -----------------------------------------------------------------------*/ + #define MMA8451_DEFAULT_ADDRESS (0x1D) // if A is GND, its 0x1C +/*=========================================================================*/ + +#define MMA8451_REG_OUT_X_MSB 0x01 +#define MMA8451_REG_SYSMOD 0x0B +#define MMA8451_REG_WHOAMI 0x0D +#define MMA8451_REG_XYZ_DATA_CFG 0x0E +#define MMA8451_REG_PL_STATUS 0x10 +#define MMA8451_REG_PL_CFG 0x11 +#define MMA8451_REG_CTRL_REG1 0x2A +#define MMA8451_REG_CTRL_REG2 0x2B +#define MMA8451_REG_CTRL_REG4 0x2D +#define MMA8451_REG_CTRL_REG5 0x2E + + + +#define MMA8451_PL_PUF 0 +#define MMA8451_PL_PUB 1 +#define MMA8451_PL_PDF 2 +#define MMA8451_PL_PDB 3 +#define MMA8451_PL_LRF 4 +#define MMA8451_PL_LRB 5 +#define MMA8451_PL_LLF 6 +#define MMA8451_PL_LLB 7 + +typedef enum +{ + MMA8451_RANGE_8_G = 0b10, // +/- 8g + MMA8451_RANGE_4_G = 0b01, // +/- 4g + MMA8451_RANGE_2_G = 0b00 // +/- 2g (default value) +} mma8451_range_t; + + +/* Used with register 0x2A (MMA8451_REG_CTRL_REG1) to set bandwidth */ +typedef enum +{ + MMA8451_DATARATE_800_HZ = 0b000, // 400Hz + MMA8451_DATARATE_400_HZ = 0b001, // 200Hz + MMA8451_DATARATE_200_HZ = 0b010, // 100Hz + MMA8451_DATARATE_100_HZ = 0b011, // 50Hz + MMA8451_DATARATE_50_HZ = 0b100, // 25Hz + MMA8451_DATARATE_12_5_HZ = 0b101, // 6.25Hz + MMA8451_DATARATE_6_25HZ = 0b110, // 3.13Hz + MMA8451_DATARATE_1_56_HZ = 0b111, // 1.56Hz +} mma8451_dataRate_t; + +class Adafruit_MMA8451 : public Adafruit_Sensor { + public: + Adafruit_MMA8451(int32_t id = -1); + + + bool begin(uint8_t addr = MMA8451_DEFAULT_ADDRESS); + + void read(); + + void setRange(mma8451_range_t range); + mma8451_range_t getRange(void); + + void setDataRate(mma8451_dataRate_t dataRate); + mma8451_dataRate_t getDataRate(void); + + void getEvent(sensors_event_t *event); + void getSensor(sensor_t *sensor); + + uint8_t getOrientation(void); + + int16_t x, y, z; + float x_g, y_g, z_g; + + void writeRegister8(uint8_t reg, uint8_t value); + private: + uint8_t readRegister8(uint8_t reg); + int32_t _sensorID; + int8_t _i2caddr; +}; diff --git a/libraries/Adafruit_MMA8451/README.md b/libraries/Adafruit_MMA8451/README.md new file mode 100644 index 000000000..fff9086ec --- /dev/null +++ b/libraries/Adafruit_MMA8451/README.md @@ -0,0 +1,29 @@ +#Adafruit MMA8451 Accelerometer Driver # + +This driver is for the Adafruit MMA8451 Accelerometer Breakout (http://www.adafruit.com/products/2019), and is based on Adafruit's Unified Sensor Library (Adafruit_Sensor). + +## About the MMA8451 ## + +The MMA8451 is a low-cost but high-precision digital accelerometer that uses repeated-start I2C mode, with adjustable data rata and 'range' (+/-2/4/8). + +More information on the MMA8451 can be found in the datasheet: http://www.adafruit.com/datasheets/MMA8451Q-1.pdf + +## What is the Adafruit Unified Sensor Library? ## + +The Adafruit Unified Sensor Library (https://github.com/adafruit/Adafruit_Sensor) provides a common interface and data type for any supported sensor. It defines some basic information about the sensor (sensor limits, etc.), and returns standard SI units of a specific type and scale for each supported sensor type. + +It provides a simple abstraction layer between your application and the actual sensor HW, allowing you to drop in any comparable sensor with only one or two lines of code to change in your project (essentially the constructor since the functions to read sensor data and get information about the sensor are defined in the base Adafruit_Sensor class). + +This is imporant useful for two reasons: + +1.) You can use the data right away because it's already converted to SI units that you understand and can compare, rather than meaningless values like 0..1023. + +2.) Because SI units are standardised in the sensor library, you can also do quick sanity checks working with new sensors, or drop in any comparable sensor if you need better sensitivity or if a lower cost unit becomes available, etc. + +Light sensors will always report units in lux, gyroscopes will always report units in rad/s, etc. ... freeing you up to focus on the data, rather than digging through the datasheet to understand what the sensor's raw numbers really mean. + +## About this Driver ## + +Adafruit invests time and resources providing this open source code. Please support Adafruit and open-source hardware by purchasing products from Adafruit! + +Written by Kevin (KTOWN) Townsend & Limor (LADYADA) Fried for Adafruit Industries. diff --git a/libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino b/libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino new file mode 100644 index 000000000..e035a18bd --- /dev/null +++ b/libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino @@ -0,0 +1,95 @@ +/**************************************************************************/ +/*! + @file Adafruit_MMA8451.h + @author K. Townsend (Adafruit Industries) + @license BSD (see license.txt) + + This is an example for the Adafruit MMA8451 Accel breakout board + ----> https://www.adafruit.com/products/2019 + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + @section HISTORY + + v1.0 - First release +*/ +/**************************************************************************/ + +#include +#include +#include + +Adafruit_MMA8451 mma = Adafruit_MMA8451(); + +void setup(void) { + Serial.begin(9600); + + Serial.println("Adafruit MMA8451 test!"); + + + if (! mma.begin()) { + Serial.println("Couldnt start"); + while (1); + } + Serial.println("MMA8451 found!"); + + mma.setRange(MMA8451_RANGE_2_G); + + Serial.print("Range = "); Serial.print(2 << mma.getRange()); + Serial.println("G"); + +} + +void loop() { + // Read the 'raw' data in 14-bit counts + mma.read(); + Serial.print("X:\t"); Serial.print(mma.x); + Serial.print("\tY:\t"); Serial.print(mma.y); + Serial.print("\tZ:\t"); Serial.print(mma.z); + Serial.println(); + + /* Get a new sensor event */ + sensors_event_t event; + mma.getEvent(&event); + + /* Display the results (acceleration is measured in m/s^2) */ + Serial.print("X: \t"); Serial.print(event.acceleration.x); Serial.print("\t"); + Serial.print("Y: \t"); Serial.print(event.acceleration.y); Serial.print("\t"); + Serial.print("Z: \t"); Serial.print(event.acceleration.z); Serial.print("\t"); + Serial.println("m/s^2 "); + + /* Get the orientation of the sensor */ + uint8_t o = mma.getOrientation(); + + switch (o) { + case MMA8451_PL_PUF: + Serial.println("Portrait Up Front"); + break; + case MMA8451_PL_PUB: + Serial.println("Portrait Up Back"); + break; + case MMA8451_PL_PDF: + Serial.println("Portrait Down Front"); + break; + case MMA8451_PL_PDB: + Serial.println("Portrait Down Back"); + break; + case MMA8451_PL_LRF: + Serial.println("Landscape Right Front"); + break; + case MMA8451_PL_LRB: + Serial.println("Landscape Right Back"); + break; + case MMA8451_PL_LLF: + Serial.println("Landscape Left Front"); + break; + case MMA8451_PL_LLB: + Serial.println("Landscape Left Back"); + break; + } + Serial.println(); + delay(500); + +} \ No newline at end of file diff --git a/libraries/Adafruit_MMA8451/license.txt b/libraries/Adafruit_MMA8451/license.txt new file mode 100644 index 000000000..f6a0f22b8 --- /dev/null +++ b/libraries/Adafruit_MMA8451/license.txt @@ -0,0 +1,26 @@ +Software License Agreement (BSD License) + +Copyright (c) 2012, Adafruit Industries +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. +3. Neither the name of the copyright holders nor the +names of its contributors may be used to endorse or promote products +derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY +EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/libraries/Adafruit_Sensor/Adafruit_Sensor.cpp b/libraries/Adafruit_Sensor/Adafruit_Sensor.cpp new file mode 100644 index 000000000..2977b275c --- /dev/null +++ b/libraries/Adafruit_Sensor/Adafruit_Sensor.cpp @@ -0,0 +1,5 @@ +#include "Adafruit_Sensor.h" +#include + +void Adafruit_Sensor::constructor() { +} diff --git a/libraries/Adafruit_Sensor/Adafruit_Sensor.h b/libraries/Adafruit_Sensor/Adafruit_Sensor.h new file mode 100644 index 000000000..7c0db4fa1 --- /dev/null +++ b/libraries/Adafruit_Sensor/Adafruit_Sensor.h @@ -0,0 +1,153 @@ +/* +* Copyright (C) 2008 The Android Open Source Project +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software< /span> +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +/* Update by K. Townsend (Adafruit Industries) for lighter typedefs, and + * extended sensor support to include color, voltage and current */ + +#ifndef _ADAFRUIT_SENSOR_H +#define _ADAFRUIT_SENSOR_H + +#if ARDUINO >= 100 + #include "Arduino.h" + #include "Print.h" +#else + #include "WProgram.h" +#endif + +/* Intentionally modeled after sensors.h in the Android API: + * https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */ + +/* Constants */ +#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */ +#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */ +#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */ +#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH) +#define SENSORS_MAGFIELD_EARTH_MAX (60.0F) /**< Maximum magnetic field on Earth's surface */ +#define SENSORS_MAGFIELD_EARTH_MIN (30.0F) /**< Minimum magnetic field on Earth's surface */ +#define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) /**< Average sea level pressure is 1013.25 hPa */ +#define SENSORS_DPS_TO_RADS (0.017453293F) /**< Degrees/s to rad/s multiplier */ +#define SENSORS_GAUSS_TO_MICROTESLA (100) /**< Gauss to micro-Tesla multiplier */ + +/** Sensor types */ +typedef enum +{ + SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */ + SENSOR_TYPE_MAGNETIC_FIELD = (2), + SENSOR_TYPE_ORIENTATION = (3), + SENSOR_TYPE_GYROSCOPE = (4), + SENSOR_TYPE_LIGHT = (5), + SENSOR_TYPE_PRESSURE = (6), + SENSOR_TYPE_PROXIMITY = (8), + SENSOR_TYPE_GRAVITY = (9), + SENSOR_TYPE_LINEAR_ACCELERATION = (10), /**< Acceleration not including gravity */ + SENSOR_TYPE_ROTATION_VECTOR = (11), + SENSOR_TYPE_RELATIVE_HUMIDITY = (12), + SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), + SENSOR_TYPE_VOLTAGE = (15), + SENSOR_TYPE_CURRENT = (16), + SENSOR_TYPE_COLOR = (17) +} sensors_type_t; + +/** struct sensors_vec_s is used to return a vector in a common format. */ +typedef struct { + union { + float v[3]; + struct { + float x; + float y; + float z; + }; + /* Orientation sensors */ + struct { + float roll; /**< Rotation around the longitudinal axis (the plane body, 'X axis'). Roll is positive and increasing when moving downward. -90�<=roll<=90� */ + float pitch; /**< Rotation around the lateral axis (the wing span, 'Y axis'). Pitch is positive and increasing when moving upwards. -180�<=pitch<=180�) */ + float heading; /**< Angle between the longitudinal axis (the plane body) and magnetic north, measured clockwise when viewing from the top of the device. 0-359� */ + }; + }; + int8_t status; + uint8_t reserved[3]; +} sensors_vec_t; + +/** struct sensors_color_s is used to return color data in a common format. */ +typedef struct { + union { + float c[3]; + /* RGB color space */ + struct { + float r; /**< Red component */ + float g; /**< Green component */ + float b; /**< Blue component */ + }; + }; + uint32_t rgba; /**< 24-bit RGBA value */ +} sensors_color_t; + +/* Sensor event (36 bytes) */ +/** struct sensor_event_s is used to provide a single sensor event in a common format. */ +typedef struct +{ + int32_t version; /**< must be sizeof(struct sensors_event_t) */ + int32_t sensor_id; /**< unique sensor identifier */ + int32_t type; /**< sensor type */ + int32_t reserved0; /**< reserved */ + int32_t timestamp; /**< time is in milliseconds */ + union + { + float data[4]; + sensors_vec_t acceleration; /**< acceleration values are in meter per second per second (m/s^2) */ + sensors_vec_t magnetic; /**< magnetic vector values are in micro-Tesla (uT) */ + sensors_vec_t orientation; /**< orientation values are in degrees */ + sensors_vec_t gyro; /**< gyroscope values are in rad/s */ + float temperature; /**< temperature is in degrees centigrade (Celsius) */ + float distance; /**< distance in centimeters */ + float light; /**< light in SI lux units */ + float pressure; /**< pressure in hectopascal (hPa) */ + float relative_humidity; /**< relative humidity in percent */ + float current; /**< current in milliamps (mA) */ + float voltage; /**< voltage in volts (V) */ + sensors_color_t color; /**< color in RGB component values */ + }; +} sensors_event_t; + +/* Sensor details (40 bytes) */ +/** struct sensor_s is used to describe basic information about a specific sensor. */ +typedef struct +{ + char name[12]; /**< sensor name */ + int32_t version; /**< version of the hardware + driver */ + int32_t sensor_id; /**< unique sensor identifier */ + int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */ + float max_value; /**< maximum value of this sensor's value in SI units */ + float min_value; /**< minimum value of this sensor's value in SI units */ + float resolution; /**< smallest difference between two values reported by this sensor */ + int32_t min_delay; /**< min delay in microseconds between events. zero = not a constant rate */ +} sensor_t; + +class Adafruit_Sensor { + public: + // Constructor(s) + void constructor(); + + // These must be defined by the subclass + virtual void enableAutoRange(bool enabled) {}; + virtual void getEvent(sensors_event_t*); + virtual void getSensor(sensor_t*); + + private: + bool _autoRange; +}; + +#endif diff --git a/libraries/Adafruit_Sensor/README.md b/libraries/Adafruit_Sensor/README.md new file mode 100644 index 000000000..068028607 --- /dev/null +++ b/libraries/Adafruit_Sensor/README.md @@ -0,0 +1,214 @@ +# Adafruit Unified Sensor Driver # + +Many small embedded systems exist to collect data from sensors, analyse the data, and either take an appropriate action or send that sensor data to another system for processing. + +One of the many challenges of embedded systems design is the fact that parts you used today may be out of production tomorrow, or system requirements may change and you may need to choose a different sensor down the road. + +Creating new drivers is a relatively easy task, but integrating them into existing systems is both error prone and time consuming since sensors rarely use the exact same units of measurement. + +By reducing all data to a single **sensors\_event\_t** 'type' and settling on specific, **standardised SI units** for each sensor family the same sensor types return values that are comparable with any other similar sensor. This enables you to switch sensor models with very little impact on the rest of the system, which can help mitigate some of the risks and problems of sensor availability and code reuse. + +The unified sensor abstraction layer is also useful for data-logging and data-transmission since you only have one well-known type to log or transmit over the air or wire. + +## Unified Sensor Drivers ## + +The following drivers are based on the Adafruit Unified Sensor Driver: + +**Accelerometers** + - [Adafruit\_ADXL345](https://github.com/adafruit/Adafruit_ADXL345) + - [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC) + +**Gyroscope** + - [Adafruit\_L3GD20\_U](https://github.com/adafruit/Adafruit_L3GD20_U) + +**Light** + - [Adafruit\_TSL2561](https://github.com/adafruit/Adafruit_TSL2561) + +**Magnetometers** + - [Adafruit\_LSM303DLHC](https://github.com/adafruit/Adafruit_LSM303DLHC) + +**Barometric Pressure** + - [Adafruit\_BMP085\_Unified](https://github.com/adafruit/Adafruit_BMP085_Unified) + +**Humidity & Temperature** + - [Adafruit\_DHT\_Unified](https://github.com/adafruit/Adafruit_DHT_Unified) + +## How Does it Work? ## + +Any driver that supports the Adafruit unified sensor abstraction layer will implement the Adafruit\_Sensor base class. There are two main typedefs and one enum defined in Adafruit_Sensor.h that are used to 'abstract' away the sensor details and values: + +**Sensor Types (sensors\_type\_t)** + +These pre-defined sensor types are used to properly handle the two related typedefs below, and allows us determine what types of units the sensor uses, etc. + +``` +/** Sensor types */ +typedef enum +{ + SENSOR_TYPE_ACCELEROMETER = (1), + SENSOR_TYPE_MAGNETIC_FIELD = (2), + SENSOR_TYPE_ORIENTATION = (3), + SENSOR_TYPE_GYROSCOPE = (4), + SENSOR_TYPE_LIGHT = (5), + SENSOR_TYPE_PRESSURE = (6), + SENSOR_TYPE_PROXIMITY = (8), + SENSOR_TYPE_GRAVITY = (9), + SENSOR_TYPE_LINEAR_ACCELERATION = (10), + SENSOR_TYPE_ROTATION_VECTOR = (11), + SENSOR_TYPE_RELATIVE_HUMIDITY = (12), + SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), + SENSOR_TYPE_VOLTAGE = (15), + SENSOR_TYPE_CURRENT = (16), + SENSOR_TYPE_COLOR = (17) +} sensors_type_t; +``` + +**Sensor Details (sensor\_t)** + +This typedef describes the specific capabilities of this sensor, and allows us to know what sensor we are using beneath the abstraction layer. + +``` +/* Sensor details (40 bytes) */ +/** struct sensor_s is used to describe basic information about a specific sensor. */ +typedef struct +{ + char name[12]; + int32_t version; + int32_t sensor_id; + int32_t type; + float max_value; + float min_value; + float resolution; + int32_t min_delay; +} sensor_t; +``` + +The individual fields are intended to be used as follows: + +- **name**: The sensor name or ID, up to a maximum of twelve characters (ex. "MPL115A2") +- **version**: The version of the sensor HW and the driver to allow us to differentiate versions of the board or driver +- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network +- **type**: The sensor type, based on **sensors\_type\_t** in sensors.h +- **max\_value**: The maximum value that this sensor can return (in the appropriate SI unit) +- **min\_value**: The minimum value that this sensor can return (in the appropriate SI unit) +- **resolution**: The smallest difference between two values that this sensor can report (in the appropriate SI unit) +- **min\_delay**: The minimum delay in microseconds between two sensor events, or '0' if there is no constant sensor rate + +**Sensor Data/Events (sensors\_event\_t)** + +This typedef is used to return sensor data from any sensor supported by the abstraction layer, using standard SI units and scales. + +``` +/* Sensor event (36 bytes) */ +/** struct sensor_event_s is used to provide a single sensor event in a common format. */ +typedef struct +{ + int32_t version; + int32_t sensor_id; + int32_t type; + int32_t reserved0; + int32_t timestamp; + union + { + float data[4]; + sensors_vec_t acceleration; + sensors_vec_t magnetic; + sensors_vec_t orientation; + sensors_vec_t gyro; + float temperature; + float distance; + float light; + float pressure; + float relative_humidity; + float current; + float voltage; + sensors_color_t color; + }; +} sensors_event_t; +``` +It includes the following fields: + +- **version**: Contain 'sizeof(sensors\_event\_t)' to identify which version of the API we're using in case this changes in the future +- **sensor\_id**: A unique sensor identifier that is used to differentiate this specific sensor instance from any others that are present on the system or in the sensor network (must match the sensor\_id value in the corresponding sensor\_t enum above!) +- **type**: the sensor type, based on **sensors\_type\_t** in sensors.h +- **timestamp**: time in milliseconds when the sensor value was read +- **data[4]**: An array of four 32-bit values that allows us to encapsulate any type of sensor data via a simple union (further described below) + +**Required Functions** + +In addition to the two standard types and the sensor type enum, all drivers based on Adafruit_Sensor must also implement the following two functions: + +``` +void getEvent(sensors_event_t*); +``` +Calling this function will populate the supplied sensors\_event\_t reference with the latest available sensor data. You should call this function as often as you want to update your data. + +``` +void getSensor(sensor_t*); +``` +Calling this function will provide some basic information about the sensor (the sensor name, driver version, min and max values, etc. + +**Standardised SI values for sensors\_event\_t** + +A key part of the abstraction layer is the standardisation of values on SI units of a particular scale, which is accomplished via the data[4] union in sensors\_event\_t above. This 16 byte union includes fields for each main sensor type, and uses the following SI units and scales: + +- **acceleration**: values are in **meter per second per second** (m/s^2) +- **magnetic**: values are in **micro-Tesla** (uT) +- **orientation**: values are in **degrees** +- **gyro**: values are in **rad/s** +- **temperature**: values in **degrees centigrade** (Celsius) +- **distance**: values are in **centimeters** +- **light**: values are in **SI lux** units +- **pressure**: values are in **hectopascal** (hPa) +- **relative\_humidity**: values are in **percent** +- **current**: values are in **milliamps** (mA) +- **voltage**: values are in **volts** (V) +- **color**: values are in 0..1.0 RGB channel luminosity and 32-bit RGBA format + +## The Unified Driver Abstraction Layer in Practice ## + +Using the unified sensor abstraction layer is relatively easy once a compliant driver has been created. + +Every compliant sensor can now be read using a single, well-known 'type' (sensors\_event\_t), and there is a standardised way of interrogating a sensor about its specific capabilities (via sensor\_t). + +An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561) light sensor can be seen below: + +``` + Adafruit_TSL2561 tsl = Adafruit_TSL2561(TSL2561_ADDR_FLOAT, 12345); + ... + /* Get a new sensor event */ + sensors_event_t event; + tsl.getEvent(&event); + + /* Display the results (light is measured in lux) */ + if (event.light) + { + Serial.print(event.light); Serial.println(" lux"); + } + else + { + /* If event.light = 0 lux the sensor is probably saturated + and no reliable data could be generated! */ + Serial.println("Sensor overload"); + } +``` + +Similarly, we can get the basic technical capabilities of this sensor with the following code: + +``` + sensor_t sensor; + + sensor_t sensor; + tsl.getSensor(&sensor); + + /* Display the sensor details */ + Serial.println("------------------------------------"); + Serial.print ("Sensor: "); Serial.println(sensor.name); + Serial.print ("Driver Ver: "); Serial.println(sensor.version); + Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); + Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" lux"); + Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" lux"); + Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" lux"); + Serial.println("------------------------------------"); + Serial.println(""); +``` diff --git a/libraries/DHT/DHT.cpp b/libraries/DHT/DHT.cpp new file mode 100644 index 000000000..2ef244c35 --- /dev/null +++ b/libraries/DHT/DHT.cpp @@ -0,0 +1,179 @@ +/* DHT library + +MIT license +written by Adafruit Industries +*/ + +#include "DHT.h" + +DHT::DHT(uint8_t pin, uint8_t type, uint8_t count) { + _pin = pin; + _type = type; + _count = count; + firstreading = true; +} + +void DHT::begin(void) { + // set up the pins! + pinMode(_pin, INPUT); + digitalWrite(_pin, HIGH); + _lastreadtime = 0; +} + +//boolean S == Scale. True == Farenheit; False == Celcius +float DHT::readTemperature(bool S) { + float f; + + if (read()) { + switch (_type) { + case DHT11: + f = data[2]; + if(S) + f = convertCtoF(f); + + return f; + case DHT22: + case DHT21: + f = data[2] & 0x7F; + f *= 256; + f += data[3]; + f /= 10; + if (data[2] & 0x80) + f *= -1; + if(S) + f = convertCtoF(f); + + return f; + } + } + return NAN; +} + +float DHT::convertCtoF(float c) { + return c * 9 / 5 + 32; +} + +float DHT::convertFtoC(float f) { + return (f - 32) * 5 / 9; +} + +float DHT::readHumidity(void) { + float f; + if (read()) { + switch (_type) { + case DHT11: + f = data[0]; + return f; + case DHT22: + case DHT21: + f = data[0]; + f *= 256; + f += data[1]; + f /= 10; + return f; + } + } + return NAN; +} + +float DHT::computeHeatIndex(float tempFahrenheit, float percentHumidity) { + // Adapted from equation at: https://github.com/adafruit/DHT-sensor-library/issues/9 and + // Wikipedia: http://en.wikipedia.org/wiki/Heat_index + return -42.379 + + 2.04901523 * tempFahrenheit + + 10.14333127 * percentHumidity + + -0.22475541 * tempFahrenheit*percentHumidity + + -0.00683783 * pow(tempFahrenheit, 2) + + -0.05481717 * pow(percentHumidity, 2) + + 0.00122874 * pow(tempFahrenheit, 2) * percentHumidity + + 0.00085282 * tempFahrenheit*pow(percentHumidity, 2) + + -0.00000199 * pow(tempFahrenheit, 2) * pow(percentHumidity, 2); +} + + +boolean DHT::read(void) { + uint8_t laststate = HIGH; + uint8_t counter = 0; + uint8_t j = 0, i; + unsigned long currenttime; + + // Check if sensor was read less than two seconds ago and return early + // to use last reading. + currenttime = millis(); + if (currenttime < _lastreadtime) { + // ie there was a rollover + _lastreadtime = 0; + } + if (!firstreading && ((currenttime - _lastreadtime) < 2000)) { + return true; // return last correct measurement + //delay(2000 - (currenttime - _lastreadtime)); + } + firstreading = false; + /* + Serial.print("Currtime: "); Serial.print(currenttime); + Serial.print(" Lasttime: "); Serial.print(_lastreadtime); + */ + _lastreadtime = millis(); + + data[0] = data[1] = data[2] = data[3] = data[4] = 0; + + // pull the pin high and wait 250 milliseconds + digitalWrite(_pin, HIGH); + delay(250); + + // now pull it low for ~20 milliseconds + pinMode(_pin, OUTPUT); + digitalWrite(_pin, LOW); + delay(20); + noInterrupts(); + digitalWrite(_pin, HIGH); + delayMicroseconds(40); + pinMode(_pin, INPUT); + + // read in timings + for ( i=0; i< MAXTIMINGS; i++) { + counter = 0; + while (digitalRead(_pin) == laststate) { + counter++; + delayMicroseconds(1); + if (counter == 255) { + break; + } + } + laststate = digitalRead(_pin); + + if (counter == 255) break; + + // ignore first 3 transitions + if ((i >= 4) && (i%2 == 0)) { + // shove each bit into the storage bytes + data[j/8] <<= 1; + if (counter > _count) + data[j/8] |= 1; + j++; + } + + } + + interrupts(); + + /* + Serial.println(j, DEC); + Serial.print(data[0], HEX); Serial.print(", "); + Serial.print(data[1], HEX); Serial.print(", "); + Serial.print(data[2], HEX); Serial.print(", "); + Serial.print(data[3], HEX); Serial.print(", "); + Serial.print(data[4], HEX); Serial.print(" =? "); + Serial.println(data[0] + data[1] + data[2] + data[3], HEX); + */ + + // check we read 40 bits and that the checksum matches + if ((j >= 40) && + (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) { + return true; + } + + + return false; + +} diff --git a/libraries/DHT/DHT.h b/libraries/DHT/DHT.h new file mode 100644 index 000000000..5280f9c12 --- /dev/null +++ b/libraries/DHT/DHT.h @@ -0,0 +1,41 @@ +#ifndef DHT_H +#define DHT_H +#if ARDUINO >= 100 + #include "Arduino.h" +#else + #include "WProgram.h" +#endif + +/* DHT library + +MIT license +written by Adafruit Industries +*/ + +// how many timing transitions we need to keep track of. 2 * number bits + extra +#define MAXTIMINGS 85 + +#define DHT11 11 +#define DHT22 22 +#define DHT21 21 +#define AM2301 21 + +class DHT { + private: + uint8_t data[6]; + uint8_t _pin, _type, _count; + unsigned long _lastreadtime; + boolean firstreading; + + public: + DHT(uint8_t pin, uint8_t type, uint8_t count=6); + void begin(void); + float readTemperature(bool S=false); + float convertCtoF(float); + float convertFtoC(float); + float computeHeatIndex(float tempFahrenheit, float percentHumidity); + float readHumidity(void); + boolean read(void); + +}; +#endif diff --git a/libraries/DHT/README.txt b/libraries/DHT/README.txt new file mode 100644 index 000000000..4dfcbab3c --- /dev/null +++ b/libraries/DHT/README.txt @@ -0,0 +1,3 @@ +This is an Arduino library for the DHT series of low cost temperature/humidity sensors. + +To download. click the DOWNLOADS button in the top right corner, rename the uncompressed folder DHT. Check that the DHT folder contains DHT.cpp and DHT.h. Place the DHT library folder your /libraries/ folder. You may need to create the libraries subfolder if its your first library. Restart the IDE. \ No newline at end of file diff --git a/libraries/DHT/examples/DHTtester/DHTtester.ino b/libraries/DHT/examples/DHTtester/DHTtester.ino new file mode 100644 index 000000000..021107faf --- /dev/null +++ b/libraries/DHT/examples/DHTtester/DHTtester.ino @@ -0,0 +1,71 @@ +// Example testing sketch for various DHT humidity/temperature sensors +// Written by ladyada, public domain + +#include "DHT.h" + +#define DHTPIN 2 // what pin we're connected to + +// Uncomment whatever type you're using! +//#define DHTTYPE DHT11 // DHT 11 +#define DHTTYPE DHT22 // DHT 22 (AM2302) +//#define DHTTYPE DHT21 // DHT 21 (AM2301) + +// Connect pin 1 (on the left) of the sensor to +5V +// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 +// to 3.3V instead of 5V! +// Connect pin 2 of the sensor to whatever your DHTPIN is +// Connect pin 4 (on the right) of the sensor to GROUND +// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor + +// Initialize DHT sensor for normal 16mhz Arduino +DHT dht(DHTPIN, DHTTYPE); +// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you +// might need to increase the threshold for cycle counts considered a 1 or 0. +// You can do this by passing a 3rd parameter for this threshold. It's a bit +// of fiddling to find the right value, but in general the faster the CPU the +// higher the value. The default for a 16mhz AVR is a value of 6. For an +// Arduino Due that runs at 84mhz a value of 30 works. +// Example to initialize DHT sensor for Arduino Due: +//DHT dht(DHTPIN, DHTTYPE, 30); + +void setup() { + Serial.begin(9600); + Serial.println("DHTxx test!"); + + dht.begin(); +} + +void loop() { + // Wait a few seconds between measurements. + delay(2000); + + // Reading temperature or humidity takes about 250 milliseconds! + // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) + float h = dht.readHumidity(); + // Read temperature as Celsius + float t = dht.readTemperature(); + // Read temperature as Fahrenheit + float f = dht.readTemperature(true); + + // Check if any reads failed and exit early (to try again). + if (isnan(h) || isnan(t) || isnan(f)) { + Serial.println("Failed to read from DHT sensor!"); + return; + } + + // Compute heat index + // Must send in temp in Fahrenheit! + float hi = dht.computeHeatIndex(f, h); + + Serial.print("Humidity: "); + Serial.print(h); + Serial.print(" %\t"); + Serial.print("Temperature: "); + Serial.print(t); + Serial.print(" *C "); + Serial.print(f); + Serial.print(" *F\t"); + Serial.print("Heat index: "); + Serial.print(hi); + Serial.println(" *F"); +} From d0920619b898acb25990c71628ace214a83f6fa1 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 7 Dec 2014 15:21:19 -1000 Subject: [PATCH 11/79] Updates to Arduino code; reading all sensors --- CameraBox/{ => camera_box}/camera_box.ino | 24 +- CameraBox/camera_box/stino.settings | 8 + CameraBox/stino.settings | 10 + WeatherStation/stino.settings | 7 + libraries/OneWire/OneWire.cpp | 557 ++++++++++++++++++ libraries/OneWire/OneWire.h | 229 +++++++ .../DS18x20_Temperature.pde | 112 ++++ .../examples/DS2408_Switch/DS2408_Switch.pde | 77 +++ .../examples/DS250x_PROM/DS250x_PROM.pde | 90 +++ libraries/OneWire/keywords.txt | 38 ++ test_arduino/test_arduino.ino | 216 +++++++ 11 files changed, 1362 insertions(+), 6 deletions(-) rename CameraBox/{ => camera_box}/camera_box.ino (75%) create mode 100644 CameraBox/camera_box/stino.settings create mode 100644 CameraBox/stino.settings create mode 100644 WeatherStation/stino.settings create mode 100644 libraries/OneWire/OneWire.cpp create mode 100644 libraries/OneWire/OneWire.h create mode 100644 libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde create mode 100644 libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde create mode 100644 libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde create mode 100644 libraries/OneWire/keywords.txt create mode 100644 test_arduino/test_arduino.ino diff --git a/CameraBox/camera_box.ino b/CameraBox/camera_box/camera_box.ino similarity index 75% rename from CameraBox/camera_box.ino rename to CameraBox/camera_box/camera_box.ino index c0b367aa6..c9774d078 100644 --- a/CameraBox/camera_box.ino +++ b/CameraBox/camera_box/camera_box.ino @@ -4,7 +4,7 @@ #include #include -#define DHTPIN 2 // DHT Temp & Humidity Pin +#define DHTPIN 4 // DHT Temp & Humidity Pin #define DHTTYPE DHT22 // DHT 22 (AM2302) Adafruit_MMA8451 mma = Adafruit_MMA8451(); @@ -13,6 +13,13 @@ DHT dht(DHTPIN, DHTTYPE); void setup(void) { Serial.begin(9600); + + pinMode(5, OUTPUT); + pinMode(6, OUTPUT); + pinMode(13, OUTPUT); + + digitalWrite(5, HIGH); + digitalWrite(6, HIGH); Serial.println("PANOPTES Arduino Code for Electronics"); @@ -36,6 +43,11 @@ void setup(void) { void loop() { + digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) + delay(1000); // wait for a second + digitalWrite(13, LOW); // turn the LED off by making the voltage LOW + delay(1000); // wait for a second + Serial.print("{"); read_accelerometer(); Serial.print(','); @@ -44,7 +56,7 @@ void loop() { Serial.println(); - delay(3000); // Three second +// delay(3000); // Three second } void read_accelerometer() { @@ -61,9 +73,9 @@ void read_accelerometer() { Serial.print("\"o\": "); Serial.print(o); Serial.print('}'); } - -// Reading temperature or humidity takes about 250 milliseconds! -// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) +// +//// Reading temperature or humidity takes about 250 milliseconds! +//// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) void read_temperature() { float h = dht.readHumidity(); float c = dht.readTemperature(); // Celsius @@ -78,4 +90,4 @@ void read_temperature() { Serial.print("\"h\":"); Serial.print(h); Serial.print(','); Serial.print("\"c\":"); Serial.print(c); Serial.print('}'); -} \ No newline at end of file +} diff --git a/CameraBox/camera_box/stino.settings b/CameraBox/camera_box/stino.settings new file mode 100644 index 000000000..bc199434d --- /dev/null +++ b/CameraBox/camera_box/stino.settings @@ -0,0 +1,8 @@ +{ + "arduino_folder": "/home/wtgee/arduino-1.5.8", + "board": 7, + "full_compilation": true, + "platform": 1, + "platform_name": "Arduino AVR Boards", + "serial_port": 0 +} \ No newline at end of file diff --git a/CameraBox/stino.settings b/CameraBox/stino.settings new file mode 100644 index 000000000..1e2aebdea --- /dev/null +++ b/CameraBox/stino.settings @@ -0,0 +1,10 @@ +{ + "arduino_folder": "/home/wtgee/arduino-1.0.6", + "board": 9, + "build_folder": "/home/wtgee/Arduino_Build", + "full_compilation": true, + "platform": 1, + "platform_name": "Arduino AVR Boards", + "serial_port": 0, + "set_bare_gcc_only": true +} \ No newline at end of file diff --git a/WeatherStation/stino.settings b/WeatherStation/stino.settings new file mode 100644 index 000000000..014af2ffd --- /dev/null +++ b/WeatherStation/stino.settings @@ -0,0 +1,7 @@ +{ + "arduino_folder": "/home/wtgee/arduino-1.5.8", + "full_compilation": true, + "platform": 1, + "platform_name": "Arduino AVR Boards", + "serial_port": 0 +} \ No newline at end of file diff --git a/libraries/OneWire/OneWire.cpp b/libraries/OneWire/OneWire.cpp new file mode 100644 index 000000000..631813f8e --- /dev/null +++ b/libraries/OneWire/OneWire.cpp @@ -0,0 +1,557 @@ +/* +Copyright (c) 2007, Jim Studt (original old version - many contributors since) + +The latest version of this library may be found at: + http://www.pjrc.com/teensy/td_libs_OneWire.html + +OneWire has been maintained by Paul Stoffregen (paul@pjrc.com) since +January 2010. At the time, it was in need of many bug fixes, but had +been abandoned the original author (Jim Studt). None of the known +contributors were interested in maintaining OneWire. Paul typically +works on OneWire every 6 to 12 months. Patches usually wait that +long. If anyone is interested in more actively maintaining OneWire, +please contact Paul. + +Version 2.2: + Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com + Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030 + Fix DS18B20 example negative temperature + Fix DS18B20 example's low res modes, Ken Butcher + Improve reset timing, Mark Tillotson + Add const qualifiers, Bertrik Sikken + Add initial value input to crc16, Bertrik Sikken + Add target_search() function, Scott Roberts + +Version 2.1: + Arduino 1.0 compatibility, Paul Stoffregen + Improve temperature example, Paul Stoffregen + DS250x_PROM example, Guillermo Lovato + PIC32 (chipKit) compatibility, Jason Dangel, dangel.jason AT gmail.com + Improvements from Glenn Trewitt: + - crc16() now works + - check_crc16() does all of calculation/checking work. + - Added read_bytes() and write_bytes(), to reduce tedious loops. + - Added ds2408 example. + Delete very old, out-of-date readme file (info is here) + +Version 2.0: Modifications by Paul Stoffregen, January 2010: +http://www.pjrc.com/teensy/td_libs_OneWire.html + Search fix from Robin James + http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + Use direct optimized I/O in all cases + Disable interrupts during timing critical sections + (this solves many random communication errors) + Disable interrupts during read-modify-write I/O + Reduce RAM consumption by eliminating unnecessary + variables and trimming many to 8 bits + Optimize both crc8 - table version moved to flash + +Modified to work with larger numbers of devices - avoids loop. +Tested in Arduino 11 alpha with 12 sensors. +26 Sept 2008 -- Robin James +http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1238032295/27#27 + +Updated to work with arduino-0008 and to include skip() as of +2007/07/06. --RJL20 + +Modified to calculate the 8-bit CRC directly, avoiding the need for +the 256-byte lookup table to be loaded in RAM. Tested in arduino-0010 +-- Tom Pollard, Jan 23, 2008 + +Jim Studt's original library was modified by Josh Larios. + +Tom Pollard, pollard@alum.mit.edu, contributed around May 20, 2008 + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Much of the code was inspired by Derek Yerger's code, though I don't +think much of that remains. In any event that was.. + (copyleft) 2006 by Derek Yerger - Free to distribute freely. + +The CRC code was excerpted and inspired by the Dallas Semiconductor +sample code bearing this copyright. +//--------------------------------------------------------------------------- +// Copyright (C) 2000 Dallas Semiconductor Corporation, All Rights Reserved. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the "Software"), +// to deal in the Software without restriction, including without limitation +// the rights to use, copy, modify, merge, publish, distribute, sublicense, +// and/or sell copies of the Software, and to permit persons to whom the +// Software is furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +// IN NO EVENT SHALL DALLAS SEMICONDUCTOR BE LIABLE FOR ANY CLAIM, DAMAGES +// OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +// OTHER DEALINGS IN THE SOFTWARE. +// +// Except as contained in this notice, the name of Dallas Semiconductor +// shall not be used except as stated in the Dallas Semiconductor +// Branding Policy. +//-------------------------------------------------------------------------- +*/ + +#include "OneWire.h" + + +OneWire::OneWire(uint8_t pin) +{ + pinMode(pin, INPUT); + bitmask = PIN_TO_BITMASK(pin); + baseReg = PIN_TO_BASEREG(pin); +#if ONEWIRE_SEARCH + reset_search(); +#endif +} + + +// Perform the onewire reset function. We will wait up to 250uS for +// the bus to come high, if it doesn't then it is broken or shorted +// and we return a 0; +// +// Returns 1 if a device asserted a presence pulse, 0 otherwise. +// +uint8_t OneWire::reset(void) +{ + IO_REG_TYPE mask = bitmask; + volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg; + uint8_t r; + uint8_t retries = 125; + + noInterrupts(); + DIRECT_MODE_INPUT(reg, mask); + interrupts(); + // wait until the wire is high... just in case + do { + if (--retries == 0) return 0; + delayMicroseconds(2); + } while ( !DIRECT_READ(reg, mask)); + + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + interrupts(); + delayMicroseconds(480); + noInterrupts(); + DIRECT_MODE_INPUT(reg, mask); // allow it to float + delayMicroseconds(70); + r = !DIRECT_READ(reg, mask); + interrupts(); + delayMicroseconds(410); + return r; +} + +// +// Write a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +void OneWire::write_bit(uint8_t v) +{ + IO_REG_TYPE mask=bitmask; + volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg; + + if (v & 1) { + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + delayMicroseconds(10); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + interrupts(); + delayMicroseconds(55); + } else { + noInterrupts(); + DIRECT_WRITE_LOW(reg, mask); + DIRECT_MODE_OUTPUT(reg, mask); // drive output low + delayMicroseconds(65); + DIRECT_WRITE_HIGH(reg, mask); // drive output high + interrupts(); + delayMicroseconds(5); + } +} + +// +// Read a bit. Port and bit is used to cut lookup time and provide +// more certain timing. +// +uint8_t OneWire::read_bit(void) +{ + IO_REG_TYPE mask=bitmask; + volatile IO_REG_TYPE *reg IO_REG_ASM = baseReg; + uint8_t r; + + noInterrupts(); + DIRECT_MODE_OUTPUT(reg, mask); + DIRECT_WRITE_LOW(reg, mask); + delayMicroseconds(3); + DIRECT_MODE_INPUT(reg, mask); // let pin float, pull up will raise + delayMicroseconds(10); + r = DIRECT_READ(reg, mask); + interrupts(); + delayMicroseconds(53); + return r; +} + +// +// Write a byte. The writing code uses the active drivers to raise the +// pin high, if you need power after the write (e.g. DS18S20 in +// parasite power mode) then set 'power' to 1, otherwise the pin will +// go tri-state at the end of the write to avoid heating in a short or +// other mishap. +// +void OneWire::write(uint8_t v, uint8_t power /* = 0 */) { + uint8_t bitMask; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + OneWire::write_bit( (bitMask & v)?1:0); + } + if ( !power) { + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + DIRECT_WRITE_LOW(baseReg, bitmask); + interrupts(); + } +} + +void OneWire::write_bytes(const uint8_t *buf, uint16_t count, bool power /* = 0 */) { + for (uint16_t i = 0 ; i < count ; i++) + write(buf[i]); + if (!power) { + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + DIRECT_WRITE_LOW(baseReg, bitmask); + interrupts(); + } +} + +// +// Read a byte +// +uint8_t OneWire::read() { + uint8_t bitMask; + uint8_t r = 0; + + for (bitMask = 0x01; bitMask; bitMask <<= 1) { + if ( OneWire::read_bit()) r |= bitMask; + } + return r; +} + +void OneWire::read_bytes(uint8_t *buf, uint16_t count) { + for (uint16_t i = 0 ; i < count ; i++) + buf[i] = read(); +} + +// +// Do a ROM select +// +void OneWire::select(const uint8_t rom[8]) +{ + uint8_t i; + + write(0x55); // Choose ROM + + for (i = 0; i < 8; i++) write(rom[i]); +} + +// +// Do a ROM skip +// +void OneWire::skip() +{ + write(0xCC); // Skip ROM +} + +void OneWire::depower() +{ + noInterrupts(); + DIRECT_MODE_INPUT(baseReg, bitmask); + interrupts(); +} + +#if ONEWIRE_SEARCH + +// +// You need to use this function to start a search again from the beginning. +// You do not need to do it for the first search, though you could. +// +void OneWire::reset_search() +{ + // reset the search state + LastDiscrepancy = 0; + LastDeviceFlag = FALSE; + LastFamilyDiscrepancy = 0; + for(int i = 7; ; i--) { + ROM_NO[i] = 0; + if ( i == 0) break; + } +} + +// Setup the search to find the device type 'family_code' on the next call +// to search(*newAddr) if it is present. +// +void OneWire::target_search(uint8_t family_code) +{ + // set the search state to find SearchFamily type devices + ROM_NO[0] = family_code; + for (uint8_t i = 1; i < 8; i++) + ROM_NO[i] = 0; + LastDiscrepancy = 64; + LastFamilyDiscrepancy = 0; + LastDeviceFlag = FALSE; +} + +// +// Perform a search. If this function returns a '1' then it has +// enumerated the next device and you may retrieve the ROM from the +// OneWire::address variable. If there are no devices, no further +// devices, or something horrible happens in the middle of the +// enumeration then a 0 is returned. If a new device is found then +// its address is copied to newAddr. Use OneWire::reset_search() to +// start over. +// +// --- Replaced by the one from the Dallas Semiconductor web site --- +//-------------------------------------------------------------------------- +// Perform the 1-Wire Search Algorithm on the 1-Wire bus using the existing +// search state. +// Return TRUE : device found, ROM number in ROM_NO buffer +// FALSE : device not found, end of search +// +uint8_t OneWire::search(uint8_t *newAddr) +{ + uint8_t id_bit_number; + uint8_t last_zero, rom_byte_number, search_result; + uint8_t id_bit, cmp_id_bit; + + unsigned char rom_byte_mask, search_direction; + + // initialize for search + id_bit_number = 1; + last_zero = 0; + rom_byte_number = 0; + rom_byte_mask = 1; + search_result = 0; + + // if the last call was not the last one + if (!LastDeviceFlag) + { + // 1-Wire reset + if (!reset()) + { + // reset the search + LastDiscrepancy = 0; + LastDeviceFlag = FALSE; + LastFamilyDiscrepancy = 0; + return FALSE; + } + + // issue the search command + write(0xF0); + + // loop to do the search + do + { + // read a bit and its complement + id_bit = read_bit(); + cmp_id_bit = read_bit(); + + // check for no devices on 1-wire + if ((id_bit == 1) && (cmp_id_bit == 1)) + break; + else + { + // all devices coupled have 0 or 1 + if (id_bit != cmp_id_bit) + search_direction = id_bit; // bit write value for search + else + { + // if this discrepancy if before the Last Discrepancy + // on a previous next then pick the same as last time + if (id_bit_number < LastDiscrepancy) + search_direction = ((ROM_NO[rom_byte_number] & rom_byte_mask) > 0); + else + // if equal to last pick 1, if not then pick 0 + search_direction = (id_bit_number == LastDiscrepancy); + + // if 0 was picked then record its position in LastZero + if (search_direction == 0) + { + last_zero = id_bit_number; + + // check for Last discrepancy in family + if (last_zero < 9) + LastFamilyDiscrepancy = last_zero; + } + } + + // set or clear the bit in the ROM byte rom_byte_number + // with mask rom_byte_mask + if (search_direction == 1) + ROM_NO[rom_byte_number] |= rom_byte_mask; + else + ROM_NO[rom_byte_number] &= ~rom_byte_mask; + + // serial number search direction write bit + write_bit(search_direction); + + // increment the byte counter id_bit_number + // and shift the mask rom_byte_mask + id_bit_number++; + rom_byte_mask <<= 1; + + // if the mask is 0 then go to new SerialNum byte rom_byte_number and reset mask + if (rom_byte_mask == 0) + { + rom_byte_number++; + rom_byte_mask = 1; + } + } + } + while(rom_byte_number < 8); // loop until through all ROM bytes 0-7 + + // if the search was successful then + if (!(id_bit_number < 65)) + { + // search successful so set LastDiscrepancy,LastDeviceFlag,search_result + LastDiscrepancy = last_zero; + + // check for last device + if (LastDiscrepancy == 0) + LastDeviceFlag = TRUE; + + search_result = TRUE; + } + } + + // if no device found then reset counters so next 'search' will be like a first + if (!search_result || !ROM_NO[0]) + { + LastDiscrepancy = 0; + LastDeviceFlag = FALSE; + LastFamilyDiscrepancy = 0; + search_result = FALSE; + } + for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; + return search_result; + } + +#endif + +#if ONEWIRE_CRC +// The 1-Wire CRC scheme is described in Maxim Application Note 27: +// "Understanding and Using Cyclic Redundancy Checks with Maxim iButton Products" +// + +#if ONEWIRE_CRC8_TABLE +// This table comes from Dallas sample code where it is freely reusable, +// though Copyright (C) 2000 Dallas Semiconductor Corporation +static const uint8_t PROGMEM dscrc_table[] = { + 0, 94,188,226, 97, 63,221,131,194,156,126, 32,163,253, 31, 65, + 157,195, 33,127,252,162, 64, 30, 95, 1,227,189, 62, 96,130,220, + 35,125,159,193, 66, 28,254,160,225,191, 93, 3,128,222, 60, 98, + 190,224, 2, 92,223,129, 99, 61,124, 34,192,158, 29, 67,161,255, + 70, 24,250,164, 39,121,155,197,132,218, 56,102,229,187, 89, 7, + 219,133,103, 57,186,228, 6, 88, 25, 71,165,251,120, 38,196,154, + 101, 59,217,135, 4, 90,184,230,167,249, 27, 69,198,152,122, 36, + 248,166, 68, 26,153,199, 37,123, 58,100,134,216, 91, 5,231,185, + 140,210, 48,110,237,179, 81, 15, 78, 16,242,172, 47,113,147,205, + 17, 79,173,243,112, 46,204,146,211,141,111, 49,178,236, 14, 80, + 175,241, 19, 77,206,144,114, 44,109, 51,209,143, 12, 82,176,238, + 50,108,142,208, 83, 13,239,177,240,174, 76, 18,145,207, 45,115, + 202,148,118, 40,171,245, 23, 73, 8, 86,180,234,105, 55,213,139, + 87, 9,235,181, 54,104,138,212,149,203, 41,119,244,170, 72, 22, + 233,183, 85, 11,136,214, 52,106, 43,117,151,201, 74, 20,246,168, + 116, 42,200,150, 21, 75,169,247,182,232, 10, 84,215,137,107, 53}; + +// +// Compute a Dallas Semiconductor 8 bit CRC. These show up in the ROM +// and the registers. (note: this might better be done without to +// table, it would probably be smaller and certainly fast enough +// compared to all those delayMicrosecond() calls. But I got +// confused, so I use this table from the examples.) +// +uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { + crc = pgm_read_byte(dscrc_table + (crc ^ *addr++)); + } + return crc; +} +#else +// +// Compute a Dallas Semiconductor 8 bit CRC directly. +// this is much slower, but much smaller, than the lookup table. +// +uint8_t OneWire::crc8(const uint8_t *addr, uint8_t len) +{ + uint8_t crc = 0; + + while (len--) { + uint8_t inbyte = *addr++; + for (uint8_t i = 8; i; i--) { + uint8_t mix = (crc ^ inbyte) & 0x01; + crc >>= 1; + if (mix) crc ^= 0x8C; + inbyte >>= 1; + } + } + return crc; +} +#endif + +#if ONEWIRE_CRC16 +bool OneWire::check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc) +{ + crc = ~crc16(input, len, crc); + return (crc & 0xFF) == inverted_crc[0] && (crc >> 8) == inverted_crc[1]; +} + +uint16_t OneWire::crc16(const uint8_t* input, uint16_t len, uint16_t crc) +{ + static const uint8_t oddparity[16] = + { 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0 }; + + for (uint16_t i = 0 ; i < len ; i++) { + // Even though we're just copying a byte from the input, + // we'll be doing 16-bit computation with it. + uint16_t cdata = input[i]; + cdata = (cdata ^ crc) & 0xff; + crc >>= 8; + + if (oddparity[cdata & 0x0F] ^ oddparity[cdata >> 4]) + crc ^= 0xC001; + + cdata <<= 6; + crc ^= cdata; + cdata <<= 1; + crc ^= cdata; + } + return crc; +} +#endif + +#endif diff --git a/libraries/OneWire/OneWire.h b/libraries/OneWire/OneWire.h new file mode 100644 index 000000000..916c52907 --- /dev/null +++ b/libraries/OneWire/OneWire.h @@ -0,0 +1,229 @@ +#ifndef OneWire_h +#define OneWire_h + +#include + +#if ARDUINO >= 100 +#include "Arduino.h" // for delayMicroseconds, digitalPinToBitMask, etc +#else +#include "WProgram.h" // for delayMicroseconds +#include "pins_arduino.h" // for digitalPinToBitMask, etc +#endif + +// You can exclude certain features from OneWire. In theory, this +// might save some space. In practice, the compiler automatically +// removes unused code (technically, the linker, using -fdata-sections +// and -ffunction-sections when compiling, and Wl,--gc-sections +// when linking), so most of these will not result in any code size +// reduction. Well, unless you try to use the missing features +// and redesign your program to not need them! ONEWIRE_CRC8_TABLE +// is the exception, because it selects a fast but large algorithm +// or a small but slow algorithm. + +// you can exclude onewire_search by defining that to 0 +#ifndef ONEWIRE_SEARCH +#define ONEWIRE_SEARCH 1 +#endif + +// You can exclude CRC checks altogether by defining this to 0 +#ifndef ONEWIRE_CRC +#define ONEWIRE_CRC 1 +#endif + +// Select the table-lookup method of computing the 8-bit CRC +// by setting this to 1. The lookup table enlarges code size by +// about 250 bytes. It does NOT consume RAM (but did in very +// old versions of OneWire). If you disable this, a slower +// but very compact algorithm is used. +#ifndef ONEWIRE_CRC8_TABLE +#define ONEWIRE_CRC8_TABLE 1 +#endif + +// You can allow 16-bit CRC checks by defining this to 1 +// (Note that ONEWIRE_CRC must also be 1.) +#ifndef ONEWIRE_CRC16 +#define ONEWIRE_CRC16 1 +#endif + +#define FALSE 0 +#define TRUE 1 + +// Platform specific I/O definitions + +#if defined(__AVR__) +#define PIN_TO_BASEREG(pin) (portInputRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM asm("r30") +#define DIRECT_READ(base, mask) (((*(base)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+1)) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask)) + +#elif defined(__MK20DX128__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (1) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (*((base)+512)) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+640) = 0) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+640) = 1) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1) + +#elif defined(__SAM3X8E__) +// Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due. +// http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268 +// If you have trouble with OneWire on Arduino Due, please check the +// status of delayMicroseconds() before reporting a bug in OneWire! +#define PIN_TO_BASEREG(pin) (&(digitalPinToPort(pin)->PIO_PER)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*((base)+15)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+4)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+13)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+12)) = (mask)) +#ifndef PROGMEM +#define PROGMEM +#endif +#ifndef pgm_read_byte +#define pgm_read_byte(addr) (*(const uint8_t *)(addr)) +#endif + +#elif defined(__PIC32MX__) +#define PIN_TO_BASEREG(pin) (portModeRegister(digitalPinToPort(pin))) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*(base+4)) & (mask)) ? 1 : 0) //PORTX + 0x10 +#define DIRECT_MODE_INPUT(base, mask) ((*(base+2)) = (mask)) //TRISXSET + 0x08 +#define DIRECT_MODE_OUTPUT(base, mask) ((*(base+1)) = (mask)) //TRISXCLR + 0x04 +#define DIRECT_WRITE_LOW(base, mask) ((*(base+8+1)) = (mask)) //LATXCLR + 0x24 +#define DIRECT_WRITE_HIGH(base, mask) ((*(base+8+2)) = (mask)) //LATXSET + 0x28 + +#else +#error "Please define I/O register types here" +#endif + + +class OneWire +{ + private: + IO_REG_TYPE bitmask; + volatile IO_REG_TYPE *baseReg; + +#if ONEWIRE_SEARCH + // global search state + unsigned char ROM_NO[8]; + uint8_t LastDiscrepancy; + uint8_t LastFamilyDiscrepancy; + uint8_t LastDeviceFlag; +#endif + + public: + OneWire( uint8_t pin); + + // Perform a 1-Wire reset cycle. Returns 1 if a device responds + // with a presence pulse. Returns 0 if there is no device or the + // bus is shorted or otherwise held low for more than 250uS + uint8_t reset(void); + + // Issue a 1-Wire rom select command, you do the reset first. + void select(const uint8_t rom[8]); + + // Issue a 1-Wire rom skip command, to address all on bus. + void skip(void); + + // Write a byte. If 'power' is one then the wire is held high at + // the end for parasitically powered devices. You are responsible + // for eventually depowering it by calling depower() or doing + // another read or write. + void write(uint8_t v, uint8_t power = 0); + + void write_bytes(const uint8_t *buf, uint16_t count, bool power = 0); + + // Read a byte. + uint8_t read(void); + + void read_bytes(uint8_t *buf, uint16_t count); + + // Write a bit. The bus is always left powered at the end, see + // note in write() about that. + void write_bit(uint8_t v); + + // Read a bit. + uint8_t read_bit(void); + + // Stop forcing power onto the bus. You only need to do this if + // you used the 'power' flag to write() or used a write_bit() call + // and aren't about to do another read or write. You would rather + // not leave this powered if you don't have to, just in case + // someone shorts your bus. + void depower(void); + +#if ONEWIRE_SEARCH + // Clear the search state so that if will start from the beginning again. + void reset_search(); + + // Setup the search to find the device type 'family_code' on the next call + // to search(*newAddr) if it is present. + void target_search(uint8_t family_code); + + // Look for the next device. Returns 1 if a new address has been + // returned. A zero might mean that the bus is shorted, there are + // no devices, or you have already retrieved all of them. It + // might be a good idea to check the CRC to make sure you didn't + // get garbage. The order is deterministic. You will always get + // the same devices in the same order. + uint8_t search(uint8_t *newAddr); +#endif + +#if ONEWIRE_CRC + // Compute a Dallas Semiconductor 8 bit CRC, these are used in the + // ROM and scratchpad registers. + static uint8_t crc8(const uint8_t *addr, uint8_t len); + +#if ONEWIRE_CRC16 + // Compute the 1-Wire CRC16 and compare it against the received CRC. + // Example usage (reading a DS2408): + // // Put everything in a buffer so we can compute the CRC easily. + // uint8_t buf[13]; + // buf[0] = 0xF0; // Read PIO Registers + // buf[1] = 0x88; // LSB address + // buf[2] = 0x00; // MSB address + // WriteBytes(net, buf, 3); // Write 3 cmd bytes + // ReadBytes(net, buf+3, 10); // Read 6 data bytes, 2 0xFF, 2 CRC16 + // if (!CheckCRC16(buf, 11, &buf[11])) { + // // Handle error. + // } + // + // @param input - Array of bytes to checksum. + // @param len - How many bytes to use. + // @param inverted_crc - The two CRC16 bytes in the received data. + // This should just point into the received data, + // *not* at a 16-bit integer. + // @param crc - The crc starting value (optional) + // @return True, iff the CRC matches. + static bool check_crc16(const uint8_t* input, uint16_t len, const uint8_t* inverted_crc, uint16_t crc = 0); + + // Compute a Dallas Semiconductor 16 bit CRC. This is required to check + // the integrity of data received from many 1-Wire devices. Note that the + // CRC computed here is *not* what you'll get from the 1-Wire network, + // for two reasons: + // 1) The CRC is transmitted bitwise inverted. + // 2) Depending on the endian-ness of your processor, the binary + // representation of the two-byte return value may have a different + // byte order than the two bytes you get from 1-Wire. + // @param input - Array of bytes to checksum. + // @param len - How many bytes to use. + // @param crc - The crc starting value (optional) + // @return The CRC16, as defined by Dallas Semiconductor. + static uint16_t crc16(const uint8_t* input, uint16_t len, uint16_t crc = 0); +#endif +#endif +}; + +#endif diff --git a/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde b/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde new file mode 100644 index 000000000..68ca19432 --- /dev/null +++ b/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde @@ -0,0 +1,112 @@ +#include + +// OneWire DS18S20, DS18B20, DS1822 Temperature Example +// +// http://www.pjrc.com/teensy/td_libs_OneWire.html +// +// The DallasTemperature library can do all this work for you! +// http://milesburton.com/Dallas_Temperature_Control_Library + +OneWire ds(10); // on pin 10 (a 4.7K resistor is necessary) + +void setup(void) { + Serial.begin(9600); +} + +void loop(void) { + byte i; + byte present = 0; + byte type_s; + byte data[12]; + byte addr[8]; + float celsius, fahrenheit; + + if ( !ds.search(addr)) { + Serial.println("No more addresses."); + Serial.println(); + ds.reset_search(); + delay(250); + return; + } + + Serial.print("ROM ="); + for( i = 0; i < 8; i++) { + Serial.write(' '); + Serial.print(addr[i], HEX); + } + + if (OneWire::crc8(addr, 7) != addr[7]) { + Serial.println("CRC is not valid!"); + return; + } + Serial.println(); + + // the first ROM byte indicates which chip + switch (addr[0]) { + case 0x10: + Serial.println(" Chip = DS18S20"); // or old DS1820 + type_s = 1; + break; + case 0x28: + Serial.println(" Chip = DS18B20"); + type_s = 0; + break; + case 0x22: + Serial.println(" Chip = DS1822"); + type_s = 0; + break; + default: + Serial.println("Device is not a DS18x20 family device."); + return; + } + + ds.reset(); + ds.select(addr); + ds.write(0x44, 1); // start conversion, with parasite power on at the end + + delay(1000); // maybe 750ms is enough, maybe not + // we might do a ds.depower() here, but the reset will take care of it. + + present = ds.reset(); + ds.select(addr); + ds.write(0xBE); // Read Scratchpad + + Serial.print(" Data = "); + Serial.print(present, HEX); + Serial.print(" "); + for ( i = 0; i < 9; i++) { // we need 9 bytes + data[i] = ds.read(); + Serial.print(data[i], HEX); + Serial.print(" "); + } + Serial.print(" CRC="); + Serial.print(OneWire::crc8(data, 8), HEX); + Serial.println(); + + // Convert the data to actual temperature + // because the result is a 16 bit signed integer, it should + // be stored to an "int16_t" type, which is always 16 bits + // even when compiled on a 32 bit processor. + int16_t raw = (data[1] << 8) | data[0]; + if (type_s) { + raw = raw << 3; // 9 bit resolution default + if (data[7] == 0x10) { + // "count remain" gives full 12 bit resolution + raw = (raw & 0xFFF0) + 12 - data[6]; + } + } else { + byte cfg = (data[4] & 0x60); + // at lower res, the low bits are undefined, so let's zero them + if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms + else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms + else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms + //// default is 12 bit resolution, 750 ms conversion time + } + celsius = (float)raw / 16.0; + fahrenheit = celsius * 1.8 + 32.0; + Serial.print(" Temperature = "); + Serial.print(celsius); + Serial.print(" Celsius, "); + Serial.print(fahrenheit); + Serial.println(" Fahrenheit"); +} diff --git a/libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde b/libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde new file mode 100644 index 000000000..d171f9ba0 --- /dev/null +++ b/libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde @@ -0,0 +1,77 @@ +#include + +/* + * DS2408 8-Channel Addressable Switch + * + * Writte by Glenn Trewitt, glenn at trewitt dot org + * + * Some notes about the DS2408: + * - Unlike most input/output ports, the DS2408 doesn't have mode bits to + * set whether the pins are input or output. If you issue a read command, + * they're inputs. If you write to them, they're outputs. + * - For reading from a switch, you should use 10K pull-up resisters. + */ + +void PrintBytes(uint8_t* addr, uint8_t count, bool newline=0) { + for (uint8_t i = 0; i < count; i++) { + Serial.print(addr[i]>>4, HEX); + Serial.print(addr[i]&0x0f, HEX); + } + if (newline) + Serial.println(); +} + +void ReadAndReport(OneWire* net, uint8_t* addr) { + Serial.print(" Reading DS2408 "); + PrintBytes(addr, 8); + Serial.println(); + + uint8_t buf[13]; // Put everything in the buffer so we can compute CRC easily. + buf[0] = 0xF0; // Read PIO Registers + buf[1] = 0x88; // LSB address + buf[2] = 0x00; // MSB address + net->write_bytes(buf, 3); + net->read_bytes(buf+3, 10); // 3 cmd bytes, 6 data bytes, 2 0xFF, 2 CRC16 + net->reset(); + + if (!OneWire::check_crc16(buf, 11, &buf[11])) { + Serial.print("CRC failure in DS2408 at "); + PrintBytes(addr, 8, true); + return; + } + Serial.print(" DS2408 data = "); + // First 3 bytes contain command, register address. + Serial.println(buf[3], BIN); +} + +OneWire net(10); // on pin 10 + +void setup(void) { + Serial.begin(9600); +} + +void loop(void) { + byte i; + byte present = 0; + byte addr[8]; + + if (!net.search(addr)) { + Serial.print("No more addresses.\n"); + net.reset_search(); + delay(1000); + return; + } + + if (OneWire::crc8(addr, 7) != addr[7]) { + Serial.print("CRC is not valid!\n"); + return; + } + + if (addr[0] != 0x29) { + PrintBytes(addr, 8); + Serial.print(" is not a DS2408.\n"); + return; + } + + ReadAndReport(&net, addr); +} diff --git a/libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde b/libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde new file mode 100644 index 000000000..baa51c8f3 --- /dev/null +++ b/libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde @@ -0,0 +1,90 @@ +/* +DS250x add-only programmable memory reader w/SKIP ROM. + + The DS250x is a 512/1024bit add-only PROM(you can add data but cannot change the old one) that's used mainly for device identification purposes + like serial number, mfgr data, unique identifiers, etc. It uses the Maxim 1-wire bus. + + This sketch will use the SKIP ROM function that skips the 1-Wire search phase since we only have one device connected in the bus on digital pin 6. + If more than one device is connected to the bus, it will fail. + Sketch will not verify if device connected is from the DS250x family since the skip rom function effectively skips the family-id byte readout. + thus it is possible to run this sketch with any Maxim OneWire device in which case the command CRC will most likely fail. + Sketch will only read the first page of memory(32bits) starting from the lower address(0000h), if more than 1 device is present, then use the sketch with search functions. + Remember to put a 4.7K pullup resistor between pin 6 and +Vcc + + To change the range or ammount of data to read, simply change the data array size, LSB/MSB addresses and for loop iterations + + This example code is in the public domain and is provided AS-IS. + + Built with Arduino 0022 and PJRC OneWire 2.0 library http://www.pjrc.com/teensy/td_libs_OneWire.html + + created by Guillermo Lovato + march/2011 + + */ + +#include +OneWire ds(6); // OneWire bus on digital pin 6 +void setup() { + Serial.begin (9600); +} + +void loop() { + byte i; // This is for the for loops + boolean present; // device present var + byte data[32]; // container for the data from device + byte leemem[3] = { // array with the commands to initiate a read, DS250x devices expect 3 bytes to start a read: command,LSB&MSB adresses + 0xF0 , 0x00 , 0x00 }; // 0xF0 is the Read Data command, followed by 00h 00h as starting address(the beginning, 0000h) + byte ccrc; // Variable to store the command CRC + byte ccrc_calc; + + present = ds.reset(); // OneWire bus reset, always needed to start operation on the bus, returns a 1/TRUE if there's a device present. + ds.skip(); // Skip ROM search + + if (present == TRUE){ // We only try to read the data if there's a device present + Serial.println("DS250x device present"); + ds.write(leemem[0],1); // Read data command, leave ghost power on + ds.write(leemem[1],1); // LSB starting address, leave ghost power on + ds.write(leemem[2],1); // MSB starting address, leave ghost power on + + ccrc = ds.read(); // DS250x generates a CRC for the command we sent, we assign a read slot and store it's value + ccrc_calc = OneWire::crc8(leemem, 3); // We calculate the CRC of the commands we sent using the library function and store it + + if ( ccrc_calc != ccrc) { // Then we compare it to the value the ds250x calculated, if it fails, we print debug messages and abort + Serial.println("Invalid command CRC!"); + Serial.print("Calculated CRC:"); + Serial.println(ccrc_calc,HEX); // HEX makes it easier to observe and compare + Serial.print("DS250x readback CRC:"); + Serial.println(ccrc,HEX); + return; // Since CRC failed, we abort the rest of the loop and start over + } + Serial.println("Data is: "); // For the printout of the data + for ( i = 0; i < 32; i++) { // Now it's time to read the PROM data itself, each page is 32 bytes so we need 32 read commands + data[i] = ds.read(); // we store each read byte to a different position in the data array + Serial.print(data[i]); // printout in ASCII + Serial.print(" "); // blank space + } + Serial.println(); + delay(5000); // Delay so we don't saturate the serial output + } + else { // Nothing is connected in the bus + Serial.println("Nothing connected"); + delay(3000); + } +} + + + + + + + + + + + + + + + + + diff --git a/libraries/OneWire/keywords.txt b/libraries/OneWire/keywords.txt new file mode 100644 index 000000000..bee5d90b2 --- /dev/null +++ b/libraries/OneWire/keywords.txt @@ -0,0 +1,38 @@ +####################################### +# Syntax Coloring Map For OneWire +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +OneWire KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +reset KEYWORD2 +write_bit KEYWORD2 +read_bit KEYWORD2 +write KEYWORD2 +write_bytes KEYWORD2 +read KEYWORD2 +read_bytes KEYWORD2 +select KEYWORD2 +skip KEYWORD2 +depower KEYWORD2 +reset_search KEYWORD2 +search KEYWORD2 +crc8 KEYWORD2 +crc16 KEYWORD2 +check_crc16 KEYWORD2 + +####################################### +# Instances (KEYWORD2) +####################################### + + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/test_arduino/test_arduino.ino b/test_arduino/test_arduino.ino new file mode 100644 index 000000000..aa682a1af --- /dev/null +++ b/test_arduino/test_arduino.ino @@ -0,0 +1,216 @@ +#include +#include + +#include + +#define DHTPIN 3 // DHT Temp & Humidity Pin +#define DHTTYPE DHT22 // DHT 22 (AM2302) + +int ac_probe = 0; +int dc_probe = 1; + +int led_pin = 13; +int led_value = LOW; + +int fan_pin = 4; + +int ds18_01_pin = 2; +const int num_ds18 = 3; // Number of DS18B20 Sensors +uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use + +//Temperature chip i/o +OneWire sensor_bus(ds18_01_pin); // on digital pin 2 +float get_temperature (uint8_t *address); + +DHT dht(DHTPIN, DHTTYPE); + +void setup() { + Serial.begin(9600); + + pinMode(led_pin, OUTPUT); + pinMode(ds18_01_pin, OUTPUT); + pinMode(fan_pin, OUTPUT); + + dht.begin(); + Serial.println("DHT22found"); + + int x, y, c = 0; + Serial.println("Starting to look for sensors..."); + for (x = 0; x < num_ds18; x++) { + if (sensor_bus.search(sensors_address[x])) + c++; + } + if (c > 0) { + Serial.println("Found this sensors : "); + for (x = 0; x < num_ds18; x++) { + Serial.print("\tSensor "); + Serial.print(x + 1); + Serial.print(" at address : "); + for (y = 0; y < 8; y++) { + Serial.print(sensors_address[x][y], HEX); + Serial.print(" "); + } + Serial.println(); + } + } else + Serial.println("Didn't find any sensors"); +} + +void loop() { + Serial.print("{"); + read_voltages(); + Serial.print(","); + read_temperature(); + Serial.println("}"); + + // Blink lights + blink_led(); +} + +void blink_led() { + led_value = ! led_value; + digitalWrite(led_pin, led_value); + delay(1000); +} + +void toggle_fan() { + // Turn Fan On + if (digitalRead(fan_pin) == 'HIGH') { + digitalWrite(fan_pin, LOW); + } else { + digitalWrite(fan_pin, HIGH); + } +} + +/* + +DC Probe: ~730 = 11.53 + +*/ +void read_voltages() { + int ac_reading = analogRead(ac_probe); + float ac_voltage = ac_reading / 1023 * 5; + + int dc_reading = analogRead(dc_probe); + float dc_voltage = dc_reading * 0.0158; + + Serial.print("\"voltages\":{"); + Serial.print("\"ac\":"); Serial.print(ac_voltage); Serial.print(','); + Serial.print("\"dc\":"); Serial.print(dc_voltage); + Serial.print('}'); +} + +//// Reading temperature or humidity takes about 250 milliseconds! +//// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) +void read_temperature() { + float h = dht.readHumidity(); + float c = dht.readTemperature(); // Celsius + + // Check if any reads failed and exit early (to try again). + // if (isnan(h) || isnan(t)) { + // Serial.println("Failed to read from DHT sensor!"); + // return; + // } + + // DS18 Temp 01 +// float temp_01 = get_ds18b20_temp(); + + // Turn on the fan if it is hot +// if (temp_01 > 31.0) { +// toggle_fan(); +// } + + Serial.print("\"temperature\":{"); + Serial.print("\"h\":"); Serial.print(h); Serial.print(','); + Serial.print("\"c\":"); Serial.print(c); Serial.print(','); + + for (int x = 0; x < num_ds18; x++) { + Serial.print("\"temp_"); + Serial.print(x + 1); + Serial.print("\":"); + Serial.print(get_temperature(sensors_address[x])); + Serial.print(","); + } + +// Serial.print("\"electronics_01\":"); Serial.print(temp_01); + Serial.print('}'); +} + +/* +float get_ds18b20_temp() { + //returns the temperature from one DS18S20 in DEG Celsius + + byte data[12]; + byte addr[8]; + + if ( !ds.search(addr)) { + //no more sensors on chain, reset search + ds.reset_search(); + Serial.println("No sensors on chain"); + return -1000; + } + + if ( OneWire::crc8( addr, 7) != addr[7]) { + Serial.println("CRC is not valid!"); + return -1000; + } + + if ( addr[0] != 0x10 && addr[0] != 0x28) { + Serial.print("Device is not recognized"); + return -1000; + } + + ds.reset(); + ds.select(addr); + ds.write(0x44, 1); // start conversion, with parasite power on at the end + + byte present = ds.reset(); + ds.select(addr); + ds.write(0xBE); // Read Scratchpad + + + for (int i = 0; i < 9; i++) { // we need 9 bytes + data[i] = ds.read(); + } + + ds.reset_search(); + + byte MSB = data[1]; + byte LSB = data[0]; + + float tempRead = ((MSB << 8) | LSB); //using two's compliment + float TemperatureSum = tempRead / 16; + + return TemperatureSum; + +} +*/ + +float get_temperature(uint8_t *address) { + byte data[12]; + int x; + sensor_bus.reset(); + sensor_bus.select(address); + sensor_bus.write(0x44,1); + + sensor_bus.reset(); + sensor_bus.select(address); + sensor_bus.write(0xBE,1); + + for(x=0;x<9;x++) + data[x] = sensor_bus.read(); + + int tr = data[0]; + if(data[1] > 0x80) { + tr = !tr+1; + tr = tr*-1; + } + int cpc = data[7]; + int cr = data[6]; + + tr = tr>>1; + + float temperature = tr - (float)0.25+(cpc-cr)/(float)cpc; + + return temperature; +} From e5e230087a0c3a96591bdc3847c578660ab22e09 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 7 Dec 2014 15:22:07 -1000 Subject: [PATCH 12/79] Renaming files --- test_arduino/test_arduino.ino => ComputerBox/ComputerBox.ino | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename test_arduino/test_arduino.ino => ComputerBox/ComputerBox.ino (100%) diff --git a/test_arduino/test_arduino.ino b/ComputerBox/ComputerBox.ino similarity index 100% rename from test_arduino/test_arduino.ino rename to ComputerBox/ComputerBox.ino From d6d992b4a5a3dc986879b740d5a2e56864c2b2fb Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 11 Dec 2014 16:14:26 -1000 Subject: [PATCH 13/79] Organizing arudino files better --- CameraBox/stino.settings | 10 ---------- {CameraBox/camera_box => camera_box}/camera_box.ino | 0 {CameraBox/camera_box => camera_box}/stino.settings | 0 .../ComputerBox.ino => computer_box/computer_box.ino | 0 4 files changed, 10 deletions(-) delete mode 100644 CameraBox/stino.settings rename {CameraBox/camera_box => camera_box}/camera_box.ino (100%) rename {CameraBox/camera_box => camera_box}/stino.settings (100%) rename ComputerBox/ComputerBox.ino => computer_box/computer_box.ino (100%) diff --git a/CameraBox/stino.settings b/CameraBox/stino.settings deleted file mode 100644 index 1e2aebdea..000000000 --- a/CameraBox/stino.settings +++ /dev/null @@ -1,10 +0,0 @@ -{ - "arduino_folder": "/home/wtgee/arduino-1.0.6", - "board": 9, - "build_folder": "/home/wtgee/Arduino_Build", - "full_compilation": true, - "platform": 1, - "platform_name": "Arduino AVR Boards", - "serial_port": 0, - "set_bare_gcc_only": true -} \ No newline at end of file diff --git a/CameraBox/camera_box/camera_box.ino b/camera_box/camera_box.ino similarity index 100% rename from CameraBox/camera_box/camera_box.ino rename to camera_box/camera_box.ino diff --git a/CameraBox/camera_box/stino.settings b/camera_box/stino.settings similarity index 100% rename from CameraBox/camera_box/stino.settings rename to camera_box/stino.settings diff --git a/ComputerBox/ComputerBox.ino b/computer_box/computer_box.ino similarity index 100% rename from ComputerBox/ComputerBox.ino rename to computer_box/computer_box.ino From 80159a0759f13ce9c90a3ca8b3ca876a52ccd052 Mon Sep 17 00:00:00 2001 From: Wilfred T Gee Date: Thu, 11 Dec 2014 18:03:04 -1000 Subject: [PATCH 14/79] Turn on fan --- ComputerBox/ComputerBox.ino | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ComputerBox/ComputerBox.ino b/ComputerBox/ComputerBox.ino index aa682a1af..0bee64396 100644 --- a/ComputerBox/ComputerBox.ino +++ b/ComputerBox/ComputerBox.ino @@ -34,6 +34,10 @@ void setup() { dht.begin(); Serial.println("DHT22found"); + // Turn on the fan + digitalWrite(fan_pin, HIGH); + Serial.println("Fan turned on"); + int x, y, c = 0; Serial.println("Starting to look for sensors..."); for (x = 0; x < num_ds18; x++) { From 09a94cb1011b4cb57b539cff760a3fdfc00b44a2 Mon Sep 17 00:00:00 2001 From: Wilfred T Gee Date: Thu, 11 Dec 2014 18:06:02 -1000 Subject: [PATCH 15/79] Removing old code, removing comma for proper json --- computer_box/computer_box.ino | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 0bee64396..5280f68c9 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -116,14 +116,6 @@ void read_temperature() { // return; // } - // DS18 Temp 01 -// float temp_01 = get_ds18b20_temp(); - - // Turn on the fan if it is hot -// if (temp_01 > 31.0) { -// toggle_fan(); -// } - Serial.print("\"temperature\":{"); Serial.print("\"h\":"); Serial.print(h); Serial.print(','); Serial.print("\"c\":"); Serial.print(c); Serial.print(','); @@ -133,10 +125,11 @@ void read_temperature() { Serial.print(x + 1); Serial.print("\":"); Serial.print(get_temperature(sensors_address[x])); - Serial.print(","); + + if x < num_ds18 - 1: + Serial.print(","); } -// Serial.print("\"electronics_01\":"); Serial.print(temp_01); Serial.print('}'); } From d5f6ed38475368a363a87d04282e3722a7fa9e40 Mon Sep 17 00:00:00 2001 From: Wilfred T Gee Date: Wed, 17 Dec 2014 00:17:20 -1000 Subject: [PATCH 16/79] Update to serial output --- computer_box/computer_box.ino | 38 ++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 5280f68c9..7e70ff7af 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -61,11 +61,11 @@ void setup() { } void loop() { - Serial.print("{"); + Serial.print("{ \"computer\": { "); read_voltages(); Serial.print(","); read_temperature(); - Serial.println("}"); + Serial.println("} }"); // Blink lights blink_led(); @@ -116,7 +116,7 @@ void read_temperature() { // return; // } - Serial.print("\"temperature\":{"); + Serial.print("\"temp\":{"); Serial.print("\"h\":"); Serial.print(h); Serial.print(','); Serial.print("\"c\":"); Serial.print(c); Serial.print(','); @@ -126,8 +126,9 @@ void read_temperature() { Serial.print("\":"); Serial.print(get_temperature(sensors_address[x])); - if x < num_ds18 - 1: + if (x < num_ds18 - 1) { Serial.print(","); + } } Serial.print('}'); @@ -188,26 +189,27 @@ float get_temperature(uint8_t *address) { int x; sensor_bus.reset(); sensor_bus.select(address); - sensor_bus.write(0x44,1); - + sensor_bus.write(0x44, 1); + sensor_bus.reset(); sensor_bus.select(address); - sensor_bus.write(0xBE,1); - - for(x=0;x<9;x++) + sensor_bus.write(0xBE, 1); + + for (x = 0; x < 9; x++) data[x] = sensor_bus.read(); - + int tr = data[0]; - if(data[1] > 0x80) { - tr = !tr+1; - tr = tr*-1; + if (data[1] > 0x80) { + tr = !tr + 1; + tr = tr * -1; } int cpc = data[7]; int cr = data[6]; - - tr = tr>>1; - - float temperature = tr - (float)0.25+(cpc-cr)/(float)cpc; - + + tr = tr >> 1; + + float temperature = tr - (float)0.25 + (cpc - cr) / (float)cpc; + return temperature; } + From 848c1aa0856a44fe31c231fc2e70db139005fb75 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 17 Dec 2014 01:01:49 -1000 Subject: [PATCH 17/79] Renaming some of the sensors --- computer_box/computer_box.ino | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 7e70ff7af..6e866f9d5 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -116,12 +116,11 @@ void read_temperature() { // return; // } - Serial.print("\"temp\":{"); - Serial.print("\"h\":"); Serial.print(h); Serial.print(','); - Serial.print("\"c\":"); Serial.print(c); Serial.print(','); + Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); + Serial.print("\"temp_01\":"); Serial.print(c); Serial.print(','); - for (int x = 0; x < num_ds18; x++) { - Serial.print("\"temp_"); + for (int x = 1; x < num_ds18; x++) { + Serial.print("\"temp_0"); Serial.print(x + 1); Serial.print("\":"); Serial.print(get_temperature(sensors_address[x])); @@ -131,7 +130,6 @@ void read_temperature() { } } - Serial.print('}'); } /* From 27f653ea4949a8faf8aaa4c5b6bbadf02487b8d5 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 17 Dec 2014 10:51:51 -1000 Subject: [PATCH 18/79] Cleaning up arduino file --- computer_box/computer_box.ino | 55 ++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 24 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 6e866f9d5..d5e26b97c 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -61,36 +61,23 @@ void setup() { } void loop() { - Serial.print("{ \"computer\": { "); + Serial.print("{"); + read_voltages(); + Serial.print(","); - read_temperature(); - Serial.println("} }"); - // Blink lights - blink_led(); -} + read_dht_temp(); + read_ds18b20_temp(); -void blink_led() { - led_value = ! led_value; - digitalWrite(led_pin, led_value); - delay(1000); -} + Serial.println("}"); -void toggle_fan() { - // Turn Fan On - if (digitalRead(fan_pin) == 'HIGH') { - digitalWrite(fan_pin, LOW); - } else { - digitalWrite(fan_pin, HIGH); - } + // Blink lights + blink_led(); } -/* - -DC Probe: ~730 = 11.53 -*/ +/* DC Probe: ~730 = 11.53 */ void read_voltages() { int ac_reading = analogRead(ac_probe); float ac_voltage = ac_reading / 1023 * 5; @@ -106,7 +93,7 @@ void read_voltages() { //// Reading temperature or humidity takes about 250 milliseconds! //// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) -void read_temperature() { +void read_dht_temp() { float h = dht.readHumidity(); float c = dht.readTemperature(); // Celsius @@ -118,6 +105,9 @@ void read_temperature() { Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); Serial.print("\"temp_01\":"); Serial.print(c); Serial.print(','); +} + +void read_ds18b20_temp() { for (int x = 1; x < num_ds18; x++) { Serial.print("\"temp_0"); @@ -125,11 +115,11 @@ void read_temperature() { Serial.print("\":"); Serial.print(get_temperature(sensors_address[x])); + // Append a comma to all but last if (x < num_ds18 - 1) { Serial.print(","); } } - } /* @@ -211,3 +201,20 @@ float get_temperature(uint8_t *address) { return temperature; } +/************************************ +* Utitlity Methods +*************************************/ + +void blink_led() { + led_value = ! led_value; + digitalWrite(led_pin, led_value); + delay(1000); +} + +void fan_on() { + digitalWrite(fan_pin, HIGH); +} + +void fan_off() { + digitalWrite(fan_pin, LOW); +} From 41b556372547039797398a8ed871d2451b589486 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 17 Dec 2014 10:57:32 -1000 Subject: [PATCH 19/79] Comment out reporting on ds18b20 --- computer_box/computer_box.ino | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index d5e26b97c..8ea86781c 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -44,20 +44,22 @@ void setup() { if (sensor_bus.search(sensors_address[x])) c++; } - if (c > 0) { - Serial.println("Found this sensors : "); - for (x = 0; x < num_ds18; x++) { - Serial.print("\tSensor "); - Serial.print(x + 1); - Serial.print(" at address : "); - for (y = 0; y < 8; y++) { - Serial.print(sensors_address[x][y], HEX); - Serial.print(" "); - } - Serial.println(); - } - } else - Serial.println("Didn't find any sensors"); + // Report on which sensors were found + // if (c > 0) { + // Serial.println("Found this sensors : "); + // for (x = 0; x < num_ds18; x++) { + // Serial.print("\tSensor "); + // Serial.print(x + 1); + // Serial.print(" at address : "); + // for (y = 0; y < 8; y++) { + // Serial.print(sensors_address[x][y], HEX); + // Serial.print(" "); + // } + // Serial.println(); + // } + // } else { + // Serial.println("Didn't find any sensors"); + // } } void loop() { From 3c7051b7b602c5d8db47f547d3f97a25c7f9c81e Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 17 Dec 2014 11:30:22 -1000 Subject: [PATCH 20/79] Comment cleanup --- computer_box/computer_box.ino | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 8ea86781c..9ed0309ea 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -18,10 +18,11 @@ int ds18_01_pin = 2; const int num_ds18 = 3; // Number of DS18B20 Sensors uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use -//Temperature chip i/o +// Temperature chip I/O OneWire sensor_bus(ds18_01_pin); // on digital pin 2 float get_temperature (uint8_t *address); +// Setup DHT22 DHT dht(DHTPIN, DHTTYPE); void setup() { From f1fe69df63d40f01a7a9a3e4c0c500e214999e0f Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 17 Dec 2014 11:31:37 -1000 Subject: [PATCH 21/79] Move delay into main loop instead of blink_lead; rename blink_led to toggle_led --- computer_box/computer_box.ino | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 9ed0309ea..219ad9946 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -45,22 +45,6 @@ void setup() { if (sensor_bus.search(sensors_address[x])) c++; } - // Report on which sensors were found - // if (c > 0) { - // Serial.println("Found this sensors : "); - // for (x = 0; x < num_ds18; x++) { - // Serial.print("\tSensor "); - // Serial.print(x + 1); - // Serial.print(" at address : "); - // for (y = 0; y < 8; y++) { - // Serial.print(sensors_address[x][y], HEX); - // Serial.print(" "); - // } - // Serial.println(); - // } - // } else { - // Serial.println("Didn't find any sensors"); - // } } void loop() { @@ -75,8 +59,9 @@ void loop() { Serial.println("}"); - // Blink lights - blink_led(); + toggle_led(); + + delay(1000); } @@ -208,10 +193,9 @@ float get_temperature(uint8_t *address) { * Utitlity Methods *************************************/ -void blink_led() { +void toggle_led() { led_value = ! led_value; digitalWrite(led_pin, led_value); - delay(1000); } void fan_on() { From b29ef22f98b13261779212bba958662b5f8feb29 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 17 Dec 2014 11:40:57 -1000 Subject: [PATCH 22/79] Fixing the temperature readout for ds18b20 --- computer_box/computer_box.ino | 82 +++++++---------------------------- 1 file changed, 15 insertions(+), 67 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 219ad9946..21294df79 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -36,10 +36,9 @@ void setup() { Serial.println("DHT22found"); // Turn on the fan - digitalWrite(fan_pin, HIGH); - Serial.println("Fan turned on"); + turn_fan_on(); - int x, y, c = 0; + int x, c = 0; Serial.println("Starting to look for sensors..."); for (x = 0; x < num_ds18; x++) { if (sensor_bus.search(sensors_address[x])) @@ -110,44 +109,22 @@ void read_ds18b20_temp() { } } -/* -float get_ds18b20_temp() { - //returns the temperature from one DS18S20 in DEG Celsius - +float get_temperature(uint8_t *addr) { byte data[12]; - byte addr[8]; - - if ( !ds.search(addr)) { - //no more sensors on chain, reset search - ds.reset_search(); - Serial.println("No sensors on chain"); - return -1000; - } - - if ( OneWire::crc8( addr, 7) != addr[7]) { - Serial.println("CRC is not valid!"); - return -1000; - } - if ( addr[0] != 0x10 && addr[0] != 0x28) { - Serial.print("Device is not recognized"); - return -1000; - } - - ds.reset(); - ds.select(addr); - ds.write(0x44, 1); // start conversion, with parasite power on at the end - - byte present = ds.reset(); - ds.select(addr); - ds.write(0xBE); // Read Scratchpad + sensor_bus.reset(); + sensor_bus.select(addr); + sensor_bus.write(0x44, 1); // start conversion, with parasite power on at the end + byte present = sensor_bus.reset(); + sensor_bus.select(addr); + sensor_bus.write(0xBE); // Read Scratchpad for (int i = 0; i < 9; i++) { // we need 9 bytes - data[i] = ds.read(); + data[i] = sensor_bus.read(); } - ds.reset_search(); + sensor_bus.reset_search(); byte MSB = data[1]; byte LSB = data[0]; @@ -156,37 +133,6 @@ float get_ds18b20_temp() { float TemperatureSum = tempRead / 16; return TemperatureSum; - -} -*/ - -float get_temperature(uint8_t *address) { - byte data[12]; - int x; - sensor_bus.reset(); - sensor_bus.select(address); - sensor_bus.write(0x44, 1); - - sensor_bus.reset(); - sensor_bus.select(address); - sensor_bus.write(0xBE, 1); - - for (x = 0; x < 9; x++) - data[x] = sensor_bus.read(); - - int tr = data[0]; - if (data[1] > 0x80) { - tr = !tr + 1; - tr = tr * -1; - } - int cpc = data[7]; - int cr = data[6]; - - tr = tr >> 1; - - float temperature = tr - (float)0.25 + (cpc - cr) / (float)cpc; - - return temperature; } /************************************ @@ -198,10 +144,12 @@ void toggle_led() { digitalWrite(led_pin, led_value); } -void fan_on() { +void turn_fan_on() { digitalWrite(fan_pin, HIGH); + Serial.println("Fan turned on"); } -void fan_off() { +void turn_fan_off() { digitalWrite(fan_pin, LOW); + Serial.println("Fan turned off"); } From 6e978931a6daaa917a2abdf416723d12bccb0d77 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 17 Dec 2014 11:43:50 -1000 Subject: [PATCH 23/79] Cleaning up arduino code --- camera_box/camera_box.ino | 62 +++++++++++++++++++++-------------- computer_box/computer_box.ino | 6 ++-- 2 files changed, 40 insertions(+), 28 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index c9774d078..0e2f48215 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -1,5 +1,4 @@ #include -#include #include #include #include @@ -7,27 +6,32 @@ #define DHTPIN 4 // DHT Temp & Humidity Pin #define DHTTYPE DHT22 // DHT 22 (AM2302) +int CAM_01_PIN = 5; +int CAM_02_PIN = 6; + Adafruit_MMA8451 mma = Adafruit_MMA8451(); DHT dht(DHTPIN, DHTTYPE); void setup(void) { Serial.begin(9600); - - pinMode(5, OUTPUT); - pinMode(6, OUTPUT); - pinMode(13, OUTPUT); - digitalWrite(5, HIGH); - digitalWrite(6, HIGH); + // Setup Camera relays + pinMode(CAM_01_PIN, OUTPUT); + pinMode(CAM_02_PIN, OUTPUT); + + // Turn on Camera relays + turn_camera_on(CAM_01_PIN); + turn_camera_on(CAM_02_PIN); Serial.println("PANOPTES Arduino Code for Electronics"); if (! mma.begin()) { Serial.println("Couldn't start Accelerometer"); while (1); + } else { + Serial.println("MMA8451 Accelerometer found"); } - Serial.println("MMA8451 Accelerometer found"); dht.begin(); Serial.println("DHT22found"); @@ -37,30 +41,23 @@ void setup(void) { Serial.print("Accelerometer Range = "); Serial.print(2 << mma.getRange()); Serial.println("G"); - Serial.println("Data output is:"); - } void loop() { - digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) - delay(1000); // wait for a second - digitalWrite(13, LOW); // turn the LED off by making the voltage LOW - delay(1000); // wait for a second - Serial.print("{"); read_accelerometer(); Serial.print(','); read_temperature(); - Serial.print("}"); + Serial.println("}"); - Serial.println(); + toggle_led(); -// delay(3000); // Three second + delay(1000); } +/* ACCELEROMETER */ void read_accelerometer() { - /* ACCELEROMETER */ /* Get a new sensor event */ sensors_event_t event; mma.getEvent(&event); @@ -73,10 +70,10 @@ void read_accelerometer() { Serial.print("\"o\": "); Serial.print(o); Serial.print('}'); } -// + //// Reading temperature or humidity takes about 250 milliseconds! //// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) -void read_temperature() { +void read_dht_temp() { float h = dht.readHumidity(); float c = dht.readTemperature(); // Celsius @@ -86,8 +83,23 @@ void read_temperature() { // return; // } - Serial.print("\"temperature\":{"); - Serial.print("\"h\":"); Serial.print(h); Serial.print(','); - Serial.print("\"c\":"); Serial.print(c); - Serial.print('}'); + Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); + Serial.print("\"temp_01\":"); Serial.print(c); Serial.print(','); } + +/************************************ +* Utitlity Methods +*************************************/ + +void toggle_led() { + led_value = ! led_value; + digitalWrite(led_pin, led_value); +} + +void turn_camera_on(int camera_pin) { + digitalWrite(camera_pin, HIGH); +} + +void turn_camera_off(int camera_pin) { + digitalWrite(camera_pin, LOW); +} \ No newline at end of file diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 21294df79..eba50d404 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -20,7 +20,7 @@ uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses fo // Temperature chip I/O OneWire sensor_bus(ds18_01_pin); // on digital pin 2 -float get_temperature (uint8_t *address); +float get_ds18b20_temp (uint8_t *address); // Setup DHT22 DHT dht(DHTPIN, DHTTYPE); @@ -100,7 +100,7 @@ void read_ds18b20_temp() { Serial.print("\"temp_0"); Serial.print(x + 1); Serial.print("\":"); - Serial.print(get_temperature(sensors_address[x])); + Serial.print(get_ds18b20_temp(sensors_address[x])); // Append a comma to all but last if (x < num_ds18 - 1) { @@ -109,7 +109,7 @@ void read_ds18b20_temp() { } } -float get_temperature(uint8_t *addr) { +float get_ds18b20_temp(uint8_t *addr) { byte data[12]; sensor_bus.reset(); From 956e722f567f16b1f7c572a4e1d7cebaf15ff9cc Mon Sep 17 00:00:00 2001 From: Wilfred T Gee Date: Wed, 17 Dec 2014 13:31:46 -1000 Subject: [PATCH 24/79] Fixing arduino sensors --- camera_box/camera_box.ino | 10 +++++++--- computer_box/computer_box.ino | 4 ++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index 0e2f48215..502385faf 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -1,3 +1,4 @@ +#include #include #include #include @@ -9,6 +10,9 @@ int CAM_01_PIN = 5; int CAM_02_PIN = 6; +int led_pin = 13; +int led_value = LOW; + Adafruit_MMA8451 mma = Adafruit_MMA8451(); DHT dht(DHTPIN, DHTTYPE); @@ -48,7 +52,7 @@ void loop() { Serial.print("{"); read_accelerometer(); Serial.print(','); - read_temperature(); + read_dht_temp(); Serial.println("}"); toggle_led(); @@ -84,7 +88,7 @@ void read_dht_temp() { // } Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); - Serial.print("\"temp_01\":"); Serial.print(c); Serial.print(','); + Serial.print("\"temp_01\":"); Serial.print(c); } /************************************ @@ -102,4 +106,4 @@ void turn_camera_on(int camera_pin) { void turn_camera_off(int camera_pin) { digitalWrite(camera_pin, LOW); -} \ No newline at end of file +} diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index eba50d404..8991bb2fb 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -91,12 +91,12 @@ void read_dht_temp() { // } Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); - Serial.print("\"temp_01\":"); Serial.print(c); Serial.print(','); + Serial.print("\"temp_00\":"); Serial.print(c); Serial.print(','); } void read_ds18b20_temp() { - for (int x = 1; x < num_ds18; x++) { + for (int x = 0; x < num_ds18; x++) { Serial.print("\"temp_0"); Serial.print(x + 1); Serial.print("\":"); From 5052312b8e63a186da037d68358e7f7b80ca8e64 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 21 Dec 2014 07:58:41 -1000 Subject: [PATCH 25/79] Add the fan status to the arduino output message --- computer_box/computer_box.ino | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 8991bb2fb..19bda3369 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -56,6 +56,8 @@ void loop() { read_dht_temp(); read_ds18b20_temp(); + read_fan_status(); + Serial.println("}"); toggle_led(); @@ -109,6 +111,12 @@ void read_ds18b20_temp() { } } +void read_fan_status(4) { + int fan_status digitalRead(fan_pin); + + Serial.print("\"fan\":"); Serial.print(fan_status); Serial.print(','); +} + float get_ds18b20_temp(uint8_t *addr) { byte data[12]; @@ -134,7 +142,6 @@ float get_ds18b20_temp(uint8_t *addr) { return TemperatureSum; } - /************************************ * Utitlity Methods *************************************/ From 198a0736e44e7fdc2a4af910f181450026c7319e Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 21 Dec 2014 08:04:10 -1000 Subject: [PATCH 26/79] Adding a simple counter --- computer_box/computer_box.ino | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 19bda3369..1300b9ac2 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -18,6 +18,9 @@ int ds18_01_pin = 2; const int num_ds18 = 3; // Number of DS18B20 Sensors uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use +// Simple counter +int counter = 0; + // Temperature chip I/O OneWire sensor_bus(ds18_01_pin); // on digital pin 2 float get_ds18b20_temp (uint8_t *address); @@ -58,6 +61,8 @@ void loop() { read_fan_status(); + Serial.print("\"count\":"); Serial.print(++counter); + Serial.println("}"); toggle_led(); From 98e591617c71ebe275a66a53ed20dd8da4e270dc Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 21 Dec 2014 08:04:45 -1000 Subject: [PATCH 27/79] Reset counter if it gets (arbitrarily) too large --- computer_box/computer_box.ino | 3 +++ 1 file changed, 3 insertions(+) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 1300b9ac2..2cf270d72 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -62,6 +62,9 @@ void loop() { read_fan_status(); Serial.print("\"count\":"); Serial.print(++counter); + if(counter > 65000){ + counter = 0; + } Serial.println("}"); From 2f7de4650cf5cc3e584d500573f5a97bee1966b1 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 21 Dec 2014 08:05:40 -1000 Subject: [PATCH 28/79] Format --- computer_box/computer_box.ino | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 2cf270d72..7c1f36f02 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -18,8 +18,7 @@ int ds18_01_pin = 2; const int num_ds18 = 3; // Number of DS18B20 Sensors uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use -// Simple counter -int counter = 0; +int counter = 0; // Simple counter // Temperature chip I/O OneWire sensor_bus(ds18_01_pin); // on digital pin 2 @@ -45,7 +44,7 @@ void setup() { Serial.println("Starting to look for sensors..."); for (x = 0; x < num_ds18; x++) { if (sensor_bus.search(sensors_address[x])) - c++; + c++; } } From 20a593c25b4435a5f822cbe17467b16e84c96735 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 21 Dec 2014 08:10:31 -1000 Subject: [PATCH 29/79] Adding simple counter; adding commas to fix some readout; turning off green led flash inside camera --- camera_box/camera_box.ino | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index 502385faf..d2c396e7e 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -13,6 +13,8 @@ int CAM_02_PIN = 6; int led_pin = 13; int led_value = LOW; +int counter = 0; // Simple counter + Adafruit_MMA8451 mma = Adafruit_MMA8451(); DHT dht(DHTPIN, DHTTYPE); @@ -20,6 +22,10 @@ DHT dht(DHTPIN, DHTTYPE); void setup(void) { Serial.begin(9600); + // Turn off LED inside camera box + pinMode(led_pin, OUTPUT); + digitalWrite(led_pin, LOW); + // Setup Camera relays pinMode(CAM_01_PIN, OUTPUT); pinMode(CAM_02_PIN, OUTPUT); @@ -50,12 +56,17 @@ void setup(void) { void loop() { Serial.print("{"); - read_accelerometer(); - Serial.print(','); - read_dht_temp(); - Serial.println("}"); - toggle_led(); + read_accelerometer(); Serial.print(','); + + read_dht_temp(); Serial.print(","); + + Serial.print("\"count\":"); Serial.print(++counter); + if(counter > 65000){ + counter = 0; + } + + Serial.println("}"); delay(1000); } @@ -81,14 +92,8 @@ void read_dht_temp() { float h = dht.readHumidity(); float c = dht.readTemperature(); // Celsius - // Check if any reads failed and exit early (to try again). - // if (isnan(h) || isnan(t)) { - // Serial.println("Failed to read from DHT sensor!"); - // return; - // } - Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); - Serial.print("\"temp_01\":"); Serial.print(c); + Serial.print("\"temp_01\":"); Serial.print(c); } /************************************ From d00087cb29e6291f6db9d51c2f844162320a362a Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 21 Dec 2014 08:10:40 -1000 Subject: [PATCH 30/79] Fixing comma erroa --- computer_box/computer_box.ino | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 7c1f36f02..084a812eb 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -51,14 +51,13 @@ void setup() { void loop() { Serial.print("{"); - read_voltages(); + read_voltages(); Serial.print(","); - Serial.print(","); + read_dht_temp(); Serial.print(","); - read_dht_temp(); - read_ds18b20_temp(); + read_ds18b20_temp(); Serial.print(","); - read_fan_status(); + read_fan_status(); Serial.print(","); Serial.print("\"count\":"); Serial.print(++counter); if(counter > 65000){ From d21e7d7d267288e27d04acbc26ea1f8b7ae6016c Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 22 Dec 2014 08:47:38 -1000 Subject: [PATCH 31/79] Changing counter reset value --- camera_box/camera_box.ino | 2 +- computer_box/computer_box.ino | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index d2c396e7e..1543b6ad0 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -62,7 +62,7 @@ void loop() { read_dht_temp(); Serial.print(","); Serial.print("\"count\":"); Serial.print(++counter); - if(counter > 65000){ + if(counter > 30000){ counter = 0; } diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 084a812eb..e9fafba69 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -60,7 +60,7 @@ void loop() { read_fan_status(); Serial.print(","); Serial.print("\"count\":"); Serial.print(++counter); - if(counter > 65000){ + if(counter > 30000){ counter = 0; } From fa6024241bdd2485cadb00e95a25afd004a56e07 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 25 Dec 2014 11:43:04 -1000 Subject: [PATCH 32/79] Use millis() instead of counter --- computer_box/computer_box.ino | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index e9fafba69..772df497f 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -18,8 +18,6 @@ int ds18_01_pin = 2; const int num_ds18 = 3; // Number of DS18B20 Sensors uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use -int counter = 0; // Simple counter - // Temperature chip I/O OneWire sensor_bus(ds18_01_pin); // on digital pin 2 float get_ds18b20_temp (uint8_t *address); @@ -59,10 +57,7 @@ void loop() { read_fan_status(); Serial.print(","); - Serial.print("\"count\":"); Serial.print(++counter); - if(counter > 30000){ - counter = 0; - } + Serial.print("\"count\":"); Serial.print(millis()); Serial.println("}"); From 9afc4381813c663448ebbddf359b5cef1082954e Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 25 Dec 2014 11:43:13 -1000 Subject: [PATCH 33/79] Use millis() intead of counter --- camera_box/camera_box.ino | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index 1543b6ad0..27b2e41ef 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -13,8 +13,6 @@ int CAM_02_PIN = 6; int led_pin = 13; int led_value = LOW; -int counter = 0; // Simple counter - Adafruit_MMA8451 mma = Adafruit_MMA8451(); DHT dht(DHTPIN, DHTTYPE); @@ -61,10 +59,7 @@ void loop() { read_dht_temp(); Serial.print(","); - Serial.print("\"count\":"); Serial.print(++counter); - if(counter > 30000){ - counter = 0; - } + Serial.print("\"count\":"); Serial.print(millis()); Serial.println("}"); From 9634be9945f6b8a7f4fbd3649df1230f1dca26eb Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 25 Dec 2014 12:35:17 -1000 Subject: [PATCH 34/79] Adding serial input support to control fan --- computer_box/computer_box.ino | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 772df497f..c0134935e 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -27,19 +27,19 @@ DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); + Serial.flush(); pinMode(led_pin, OUTPUT); pinMode(ds18_01_pin, OUTPUT); pinMode(fan_pin, OUTPUT); dht.begin(); - Serial.println("DHT22found"); // Turn on the fan turn_fan_on(); + // Search for attached DS18B20 sensors int x, c = 0; - Serial.println("Starting to look for sensors..."); for (x = 0; x < num_ds18; x++) { if (sensor_bus.search(sensors_address[x])) c++; @@ -47,6 +47,27 @@ void setup() { } void loop() { + + // Read any serial input + // - Input will be two comma separated integers, the + // first specifying the pin and the second the status + // to change to (1/0). Only the fan and the debug led + // are currently supported. + // Example serial input: + // 4,1 # Turn fan on + // 13,0 # Turn led off + while(Serial.available() > 0){ + int pin_num = Serial.parseInt(); + int pin_status = Serial.parseInt(); + + switch(pin_num){ + case 4: + case 13: + digitalWrite(pin_num, pin_status); + break; + } + } + Serial.print("{"); read_voltages(); Serial.print(","); @@ -61,8 +82,8 @@ void loop() { Serial.println("}"); + // Simple heartbeat toggle_led(); - delay(1000); } From 8440a0f76061abd895c7e092e82439b9fd6fba34 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 25 Dec 2014 12:41:36 -1000 Subject: [PATCH 35/79] Support reading serial in so we can toggle cameras (and led); cleaning up debug statements --- camera_box/camera_box.ino | 47 ++++++++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 10 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index 27b2e41ef..b893106f5 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -19,6 +19,7 @@ DHT dht(DHTPIN, DHTTYPE); void setup(void) { Serial.begin(9600); + Serial.flush(); // Turn off LED inside camera box pinMode(led_pin, OUTPUT); @@ -32,27 +33,53 @@ void setup(void) { turn_camera_on(CAM_01_PIN); turn_camera_on(CAM_02_PIN); - Serial.println("PANOPTES Arduino Code for Electronics"); - if (! mma.begin()) { - Serial.println("Couldn't start Accelerometer"); while (1); - } else { - Serial.println("MMA8451 Accelerometer found"); } dht.begin(); - Serial.println("DHT22found"); // Check Accelerometer range - mma.setRange(MMA8451_RANGE_2_G); - Serial.print("Accelerometer Range = "); Serial.print(2 << mma.getRange()); - Serial.println("G"); - + // mma.setRange(MMA8451_RANGE_2_G); + // Serial.print("Accelerometer Range = "); Serial.print(2 << mma.getRange()); + // Serial.println("G"); } void loop() { + // Read any serial input + // - Input will be two comma separated integers, the + // first specifying the pin and the second the status + // to change to (1/0). Cameras and debug led are + // supported. + // Example serial input: + // 4,1 # Turn fan on + // 13,0 # Turn led off + while(Serial.available() > 0){ + int pin_num = Serial.parseInt(); + int pin_status = Serial.parseInt(); + + switch(pin_num){ + case CAM_01_PIN: + if(pin_status == 1){ + turn_camera_on(CAM_01_PIN); + } else { + turn_camera_off(CAM_01_PIN); + } + break; + case CAM_02_PIN: + if(pin_status == 1){ + turn_camera_on(CAM_02_PIN); + } else { + turn_camera_off(CAM_02_PIN); + } + break; + case led_pin: + digitalWrite(pin_num, pin_status); + break; + } + } + Serial.print("{"); read_accelerometer(); Serial.print(','); From 099c0f3af124611d444520fcf1d679cbb34c10c6 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 25 Dec 2014 13:21:15 -1000 Subject: [PATCH 36/79] Use pin names --- computer_box/computer_box.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index c0134935e..670b9caec 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -61,8 +61,8 @@ void loop() { int pin_status = Serial.parseInt(); switch(pin_num){ - case 4: - case 13: + case fan_pin: + case led_pin: digitalWrite(pin_num, pin_status); break; } From 73897496b0b87002835e54d6c7b411e501851d12 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 31 Dec 2014 22:58:27 -0700 Subject: [PATCH 37/79] Pin variables are const; using LED_BUILTIN --- camera_box/camera_box.ino | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index b893106f5..37db6c760 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -7,10 +7,10 @@ #define DHTPIN 4 // DHT Temp & Humidity Pin #define DHTTYPE DHT22 // DHT 22 (AM2302) -int CAM_01_PIN = 5; -int CAM_02_PIN = 6; -int led_pin = 13; +const int CAM_01_PIN = 5; +const int CAM_02_PIN = 6; + int led_value = LOW; Adafruit_MMA8451 mma = Adafruit_MMA8451(); @@ -22,8 +22,8 @@ void setup(void) { Serial.flush(); // Turn off LED inside camera box - pinMode(led_pin, OUTPUT); - digitalWrite(led_pin, LOW); + pinMode(LED_BUILTIN, OUTPUT); + digitalWrite(LED_BUILTIN, LOW); // Setup Camera relays pinMode(CAM_01_PIN, OUTPUT); @@ -74,7 +74,7 @@ void loop() { turn_camera_off(CAM_02_PIN); } break; - case led_pin: + case LED_BUILTIN: digitalWrite(pin_num, pin_status); break; } @@ -124,7 +124,7 @@ void read_dht_temp() { void toggle_led() { led_value = ! led_value; - digitalWrite(led_pin, led_value); + digitalWrite(LED_BUILTIN, led_value); } void turn_camera_on(int camera_pin) { From 80c70beac11a8c181cae5cea3bd49ec2c78cd6b4 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 31 Dec 2014 22:58:50 -0700 Subject: [PATCH 38/79] Format --- camera_box/camera_box.ino | 55 +++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 28 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index 37db6c760..bb217a77e 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -7,7 +7,6 @@ #define DHTPIN 4 // DHT Temp & Humidity Pin #define DHTTYPE DHT22 // DHT 22 (AM2302) - const int CAM_01_PIN = 5; const int CAM_02_PIN = 6; @@ -56,48 +55,48 @@ void loop() { // 4,1 # Turn fan on // 13,0 # Turn led off while(Serial.available() > 0){ - int pin_num = Serial.parseInt(); - int pin_status = Serial.parseInt(); - - switch(pin_num){ - case CAM_01_PIN: - if(pin_status == 1){ - turn_camera_on(CAM_01_PIN); - } else { - turn_camera_off(CAM_01_PIN); - } - break; + int pin_num = Serial.parseInt(); + int pin_status = Serial.parseInt(); + + switch(pin_num){ + case CAM_01_PIN: + if(pin_status == 1){ + turn_camera_on(CAM_01_PIN); + } else { + turn_camera_off(CAM_01_PIN); + } + break; case CAM_02_PIN: - if(pin_status == 1){ - turn_camera_on(CAM_02_PIN); + if(pin_status == 1){ + turn_camera_on(CAM_02_PIN); } else { turn_camera_off(CAM_02_PIN); } break; - case LED_BUILTIN: + case LED_BUILTIN: digitalWrite(pin_num, pin_status); break; + } } - } - Serial.print("{"); + Serial.print("{"); - read_accelerometer(); Serial.print(','); + read_accelerometer(); Serial.print(','); - read_dht_temp(); Serial.print(","); + read_dht_temp(); Serial.print(","); - Serial.print("\"count\":"); Serial.print(millis()); + Serial.print("\"count\":"); Serial.print(millis()); - Serial.println("}"); + Serial.println("}"); - delay(1000); -} + delay(1000); + } -/* ACCELEROMETER */ -void read_accelerometer() { - /* Get a new sensor event */ - sensors_event_t event; - mma.getEvent(&event); + /* ACCELEROMETER */ + void read_accelerometer() { + /* Get a new sensor event */ + sensors_event_t event; + mma.getEvent(&event); uint8_t o = mma.getOrientation(); // Orientation Serial.print("\"accelerometer\":{"); From b1e9b2a8086fafe164ed6a78d7927fd2d5f3211c Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 31 Dec 2014 23:07:11 -0700 Subject: [PATCH 39/79] define to const; organize --- computer_box/computer_box.ino | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 670b9caec..4b894e308 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -3,19 +3,18 @@ #include -#define DHTPIN 3 // DHT Temp & Humidity Pin #define DHTTYPE DHT22 // DHT 22 (AM2302) -int ac_probe = 0; -int dc_probe = 1; +const int dht_pin = 3; // DHT Temp & Humidity Pin +const int ac_probe = 0; +const int dc_probe = 1; +const int fan_pin = 4; +const int ds18_01_pin = 2; -int led_pin = 13; -int led_value = LOW; +const int num_ds18 = 3; // Number of DS18B20 Sensors -int fan_pin = 4; +int led_value = LOW; -int ds18_01_pin = 2; -const int num_ds18 = 3; // Number of DS18B20 Sensors uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use // Temperature chip I/O @@ -23,13 +22,13 @@ OneWire sensor_bus(ds18_01_pin); // on digital pin 2 float get_ds18b20_temp (uint8_t *address); // Setup DHT22 -DHT dht(DHTPIN, DHTTYPE); +DHT dht(dht_pin, DHTTYPE); void setup() { Serial.begin(9600); Serial.flush(); - pinMode(led_pin, OUTPUT); + pinMode(LED_BUILTIN, OUTPUT); pinMode(ds18_01_pin, OUTPUT); pinMode(fan_pin, OUTPUT); @@ -62,7 +61,7 @@ void loop() { switch(pin_num){ case fan_pin: - case led_pin: + case LED_BUILTIN: digitalWrite(pin_num, pin_status); break; } @@ -133,8 +132,8 @@ void read_ds18b20_temp() { } } -void read_fan_status(4) { - int fan_status digitalRead(fan_pin); +void read_fan_status() { + int fan_status = digitalRead(fan_pin); Serial.print("\"fan\":"); Serial.print(fan_status); Serial.print(','); } @@ -170,7 +169,7 @@ float get_ds18b20_temp(uint8_t *addr) { void toggle_led() { led_value = ! led_value; - digitalWrite(led_pin, led_value); + digitalWrite(LED_BUILTIN, led_value); } void turn_fan_on() { From a2fc7d56aed2b19c68cd17869f0d0ae032c5dd73 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 31 Dec 2014 23:07:32 -0700 Subject: [PATCH 40/79] format --- computer_box/computer_box.ino | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index 4b894e308..f2b945536 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -56,15 +56,15 @@ void loop() { // 4,1 # Turn fan on // 13,0 # Turn led off while(Serial.available() > 0){ - int pin_num = Serial.parseInt(); - int pin_status = Serial.parseInt(); - - switch(pin_num){ - case fan_pin: - case LED_BUILTIN: - digitalWrite(pin_num, pin_status); - break; - } + int pin_num = Serial.parseInt(); + int pin_status = Serial.parseInt(); + + switch(pin_num){ + case fan_pin: + case LED_BUILTIN: + digitalWrite(pin_num, pin_status); + break; + } } Serial.print("{"); From a23442664f51919af33d886f55d95cdc963eb1ac Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 31 Dec 2014 23:50:33 -0700 Subject: [PATCH 41/79] Getting rid of extra commas --- computer_box/computer_box.ino | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index f2b945536..d9ccfa2c2 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -114,7 +114,7 @@ void read_dht_temp() { // } Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); - Serial.print("\"temp_00\":"); Serial.print(c); Serial.print(','); + Serial.print("\"temp_00\":"); Serial.print(c); } void read_ds18b20_temp() { @@ -135,7 +135,7 @@ void read_ds18b20_temp() { void read_fan_status() { int fan_status = digitalRead(fan_pin); - Serial.print("\"fan\":"); Serial.print(fan_status); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(fan_status); } float get_ds18b20_temp(uint8_t *addr) { From daf67ec5fc6fd5e8182331bf98c8ea65657d4f77 Mon Sep 17 00:00:00 2001 From: Wilfred T Gee Date: Thu, 12 Mar 2015 17:51:13 -1000 Subject: [PATCH 42/79] Updated values for the computer box --- computer_box/computer_box.ino | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index d9ccfa2c2..bbecb70d6 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -5,20 +5,21 @@ #define DHTTYPE DHT22 // DHT 22 (AM2302) -const int dht_pin = 3; // DHT Temp & Humidity Pin -const int ac_probe = 0; +const int ac_probe = 2; const int dc_probe = 1; + const int fan_pin = 4; +const int dht_pin = 3; // DHT Temp & Humidity Pin const int ds18_01_pin = 2; - const int num_ds18 = 3; // Number of DS18B20 Sensors +//const int LED_BUILTIN = 13; int led_value = LOW; -uint8_t sensors_address[num_ds18][8]; //here will store the sensors addresses for later use +uint8_t sensors_address[num_ds18][8]; // Temperature chip I/O -OneWire sensor_bus(ds18_01_pin); // on digital pin 2 +OneWire sensor_bus(ds18_01_pin); float get_ds18b20_temp (uint8_t *address); // Setup DHT22 From 733313607171763bc8f0b0df0385c64f67f55b6a Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 26 Jun 2015 15:32:59 -1000 Subject: [PATCH 43/79] Format --- camera_box/camera_box.ino | 62 +++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index bb217a77e..be17068ad 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -54,49 +54,49 @@ void loop() { // Example serial input: // 4,1 # Turn fan on // 13,0 # Turn led off - while(Serial.available() > 0){ + while (Serial.available() > 0) { int pin_num = Serial.parseInt(); int pin_status = Serial.parseInt(); - switch(pin_num){ - case CAM_01_PIN: - if(pin_status == 1){ + switch (pin_num) { + case CAM_01_PIN: + if (pin_status == 1) { turn_camera_on(CAM_01_PIN); - } else { - turn_camera_off(CAM_01_PIN); - } - break; - case CAM_02_PIN: - if(pin_status == 1){ - turn_camera_on(CAM_02_PIN); - } else { - turn_camera_off(CAM_02_PIN); - } - break; - case LED_BUILTIN: - digitalWrite(pin_num, pin_status); - break; - } + } else { + turn_camera_off(CAM_01_PIN); } + break; + case CAM_02_PIN: + if (pin_status == 1) { + turn_camera_on(CAM_02_PIN); + } else { + turn_camera_off(CAM_02_PIN); + } + break; + case LED_BUILTIN: + digitalWrite(pin_num, pin_status); + break; + } + } - Serial.print("{"); + Serial.print("{"); - read_accelerometer(); Serial.print(','); + read_accelerometer(); Serial.print(','); - read_dht_temp(); Serial.print(","); + read_dht_temp(); Serial.print(","); - Serial.print("\"count\":"); Serial.print(millis()); + Serial.print("\"count\":"); Serial.print(millis()); - Serial.println("}"); + Serial.println("}"); - delay(1000); - } + delay(1000); +} - /* ACCELEROMETER */ - void read_accelerometer() { - /* Get a new sensor event */ - sensors_event_t event; - mma.getEvent(&event); +/* ACCELEROMETER */ +void read_accelerometer() { + /* Get a new sensor event */ + sensors_event_t event; + mma.getEvent(&event); uint8_t o = mma.getOrientation(); // Orientation Serial.print("\"accelerometer\":{"); From e548b31fa707b01104bee4e516fda630112c8683 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 26 Jun 2015 15:34:06 -1000 Subject: [PATCH 44/79] Cleanup --- camera_box/camera_box.ino | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index be17068ad..bee2df45c 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -4,17 +4,17 @@ #include #include -#define DHTPIN 4 // DHT Temp & Humidity Pin -#define DHTTYPE DHT22 // DHT 22 (AM2302) +#define DHT_PIN 4 // DHT Temp & Humidity Pin +#define DHT_TYPE DHT22 // DHT 22 (AM2302) const int CAM_01_PIN = 5; const int CAM_02_PIN = 6; int led_value = LOW; -Adafruit_MMA8451 mma = Adafruit_MMA8451(); +Adafruit_MMA8451 accelerometer = Adafruit_MMA8451(); -DHT dht(DHTPIN, DHTTYPE); +DHT dht(DHT_PIN, DHT_TYPE); void setup(void) { Serial.begin(9600); @@ -32,15 +32,15 @@ void setup(void) { turn_camera_on(CAM_01_PIN); turn_camera_on(CAM_02_PIN); - if (! mma.begin()) { + if (! accelerometer.begin()) { while (1); } dht.begin(); // Check Accelerometer range - // mma.setRange(MMA8451_RANGE_2_G); - // Serial.print("Accelerometer Range = "); Serial.print(2 << mma.getRange()); + // accelerometer.setRange(MMA8451_RANGE_2_G); + // Serial.print("Accelerometer Range = "); Serial.print(2 << accelerometer.getRange()); // Serial.println("G"); } @@ -96,8 +96,8 @@ void loop() { void read_accelerometer() { /* Get a new sensor event */ sensors_event_t event; - mma.getEvent(&event); - uint8_t o = mma.getOrientation(); // Orientation + accelerometer.getEvent(&event); + uint8_t o = accelerometer.getOrientation(); // Orientation Serial.print("\"accelerometer\":{"); Serial.print("\"x\":"); Serial.print(event.acceleration.x); Serial.print(','); From 0a56ae5c1fb5bc6d8930f34f9309e38438b8240d Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 26 Jun 2015 15:35:02 -1000 Subject: [PATCH 45/79] Cleanup and docs --- camera_box/camera_box.ino | 1 + 1 file changed, 1 insertion(+) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index bee2df45c..c75ca7312 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -79,6 +79,7 @@ void loop() { } } + // Begin reading values and outputting as JSON string Serial.print("{"); read_accelerometer(); Serial.print(','); From d88008800a0e9e80191c331714decdb3ece11c83 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 26 Jun 2015 15:40:28 -1000 Subject: [PATCH 46/79] Formatting --- computer_box/computer_box.ino | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index bbecb70d6..bd7873106 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -13,7 +13,7 @@ const int dht_pin = 3; // DHT Temp & Humidity Pin const int ds18_01_pin = 2; const int num_ds18 = 3; // Number of DS18B20 Sensors -//const int LED_BUILTIN = 13; +//const int LED_BUILTIN = 13; int led_value = LOW; uint8_t sensors_address[num_ds18][8]; @@ -42,7 +42,7 @@ void setup() { int x, c = 0; for (x = 0; x < num_ds18; x++) { if (sensor_bus.search(sensors_address[x])) - c++; + c++; } } @@ -56,13 +56,13 @@ void loop() { // Example serial input: // 4,1 # Turn fan on // 13,0 # Turn led off - while(Serial.available() > 0){ + while (Serial.available() > 0) { int pin_num = Serial.parseInt(); int pin_status = Serial.parseInt(); - switch(pin_num){ - case fan_pin: - case LED_BUILTIN: + switch (pin_num) { + case fan_pin: + case LED_BUILTIN: digitalWrite(pin_num, pin_status); break; } From fa4ba6946c004a05d502ef05d67815a9f38c7ab4 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 26 Jun 2015 15:42:00 -1000 Subject: [PATCH 47/79] Giving costants all-caps names --- computer_box/computer_box.ino | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index bd7873106..e757bfbf6 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -8,30 +8,30 @@ const int ac_probe = 2; const int dc_probe = 1; -const int fan_pin = 4; -const int dht_pin = 3; // DHT Temp & Humidity Pin -const int ds18_01_pin = 2; -const int num_ds18 = 3; // Number of DS18B20 Sensors +const int FAN_PIN = 4; +const int DHT_PIN = 3; // DHT Temp & Humidity Pin +const int DS18_PIN = 2; +const int NUM_DS18 = 3; // Number of DS18B20 Sensors //const int LED_BUILTIN = 13; int led_value = LOW; -uint8_t sensors_address[num_ds18][8]; +uint8_t sensors_address[NUM_DS18][8]; // Temperature chip I/O -OneWire sensor_bus(ds18_01_pin); +OneWire sensor_bus(DS18_PIN); float get_ds18b20_temp (uint8_t *address); // Setup DHT22 -DHT dht(dht_pin, DHTTYPE); +DHT dht(DHT_PIN, DHTTYPE); void setup() { Serial.begin(9600); Serial.flush(); pinMode(LED_BUILTIN, OUTPUT); - pinMode(ds18_01_pin, OUTPUT); - pinMode(fan_pin, OUTPUT); + pinMode(DS18_PIN, OUTPUT); + pinMode(FAN_PIN, OUTPUT); dht.begin(); @@ -40,7 +40,7 @@ void setup() { // Search for attached DS18B20 sensors int x, c = 0; - for (x = 0; x < num_ds18; x++) { + for (x = 0; x < NUM_DS18; x++) { if (sensor_bus.search(sensors_address[x])) c++; } @@ -61,7 +61,7 @@ void loop() { int pin_status = Serial.parseInt(); switch (pin_num) { - case fan_pin: + case FAN_PIN: case LED_BUILTIN: digitalWrite(pin_num, pin_status); break; @@ -120,21 +120,21 @@ void read_dht_temp() { void read_ds18b20_temp() { - for (int x = 0; x < num_ds18; x++) { + for (int x = 0; x < NUM_DS18; x++) { Serial.print("\"temp_0"); Serial.print(x + 1); Serial.print("\":"); Serial.print(get_ds18b20_temp(sensors_address[x])); // Append a comma to all but last - if (x < num_ds18 - 1) { + if (x < NUM_DS18 - 1) { Serial.print(","); } } } void read_fan_status() { - int fan_status = digitalRead(fan_pin); + int fan_status = digitalRead(FAN_PIN); Serial.print("\"fan\":"); Serial.print(fan_status); } @@ -174,11 +174,11 @@ void toggle_led() { } void turn_fan_on() { - digitalWrite(fan_pin, HIGH); + digitalWrite(FAN_PIN, HIGH); Serial.println("Fan turned on"); } void turn_fan_off() { - digitalWrite(fan_pin, LOW); + digitalWrite(FAN_PIN, LOW); Serial.println("Fan turned off"); } From 800e422a19126a62046eb3674414a937207ecf3b Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 26 Jun 2015 15:42:43 -1000 Subject: [PATCH 48/79] Consts gets caps --- computer_box/computer_box.ino | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/computer_box/computer_box.ino b/computer_box/computer_box.ino index e757bfbf6..609b919bf 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/computer_box.ino @@ -5,8 +5,8 @@ #define DHTTYPE DHT22 // DHT 22 (AM2302) -const int ac_probe = 2; -const int dc_probe = 1; +const int AC_PROBE = 2; +const int DC_PROBE = 1; const int FAN_PIN = 4; const int DHT_PIN = 3; // DHT Temp & Humidity Pin @@ -90,10 +90,10 @@ void loop() { /* DC Probe: ~730 = 11.53 */ void read_voltages() { - int ac_reading = analogRead(ac_probe); + int ac_reading = analogRead(AC_PROBE); float ac_voltage = ac_reading / 1023 * 5; - int dc_reading = analogRead(dc_probe); + int dc_reading = analogRead(DC_PROBE); float dc_voltage = dc_reading * 0.0158; Serial.print("\"voltages\":{"); From af95be24ff1f1aba1330cce3a91c1696de6679dd Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 9 Mar 2016 11:56:37 -1000 Subject: [PATCH 49/79] Updating libraries --- libraries/Bridge/README.adoc | 24 + libraries/Bridge/examples/Bridge/Bridge.ino | 185 +++ .../ConsoleAsciiTable/ConsoleAsciiTable.ino | 95 ++ .../examples/ConsolePixel/ConsolePixel.ino | 64 ++ .../examples/ConsoleRead/ConsoleRead.ino | 60 + .../Bridge/examples/Datalogger/Datalogger.ino | 102 ++ .../FileWriteScript/FileWriteScript.ino | 84 ++ .../Bridge/examples/HttpClient/HttpClient.ino | 53 + .../HttpClientConsole/HttpClientConsole.ino | 55 + .../MailboxReadMessage/MailboxReadMessage.ino | 58 + libraries/Bridge/examples/Process/Process.ino | 72 ++ .../RemoteDueBlink/RemoteDueBlink.ino | 33 + .../examples/ShellCommands/ShellCommands.ino | 55 + .../SpacebrewYun/inputOutput/inputOutput.ino | 134 +++ .../spacebrewBoolean/spacebrewBoolean.ino | 94 ++ .../spacebrewRange/spacebrewRange.ino | 88 ++ .../spacebrewString/spacebrewString.ino | 86 ++ .../TemperatureWebPanel.ino | 125 ++ .../TemperatureWebPanel/www/index.html | 16 + .../TemperatureWebPanel/www/zepto.min.js | 2 + .../Bridge/examples/TimeCheck/TimeCheck.ino | 88 ++ .../Bridge/examples/WiFiStatus/WiFiStatus.ino | 52 + .../YunSerialTerminal/YunSerialTerminal.ino | 82 ++ libraries/Bridge/keywords.txt | 90 ++ libraries/Bridge/library.properties | 10 + libraries/Bridge/src/Bridge.cpp | 281 +++++ libraries/Bridge/src/Bridge.h | 125 ++ libraries/Bridge/src/BridgeClient.cpp | 173 +++ libraries/Bridge/src/BridgeClient.h | 70 ++ libraries/Bridge/src/BridgeServer.cpp | 54 + libraries/Bridge/src/BridgeServer.h | 51 + libraries/Bridge/src/BridgeUdp.cpp | 198 ++++ libraries/Bridge/src/BridgeUdp.h | 65 ++ libraries/Bridge/src/Console.cpp | 150 +++ libraries/Bridge/src/Console.h | 71 ++ libraries/Bridge/src/FileIO.cpp | 283 +++++ libraries/Bridge/src/FileIO.h | 120 ++ libraries/Bridge/src/HttpClient.cpp | 204 ++++ libraries/Bridge/src/HttpClient.h | 59 + libraries/Bridge/src/Mailbox.cpp | 56 + libraries/Bridge/src/Mailbox.h | 53 + libraries/Bridge/src/Process.cpp | 142 +++ libraries/Bridge/src/Process.h | 71 ++ libraries/Bridge/src/YunClient.h | 27 + libraries/Bridge/src/YunServer.h | 27 + libraries/Firmata/Boards.h | 764 ++++++++++++ libraries/Firmata/Firmata.cpp | 668 +++++++++++ libraries/Firmata/Firmata.h | 224 ++++ .../AllInputsFirmata/AllInputsFirmata.ino | 90 ++ .../examples/AnalogFirmata/AnalogFirmata.ino | 94 ++ .../examples/EchoString/EchoString.ino | 44 + .../examples/OldStandardFirmata/LICENSE.txt | 458 ++++++++ .../OldStandardFirmata/OldStandardFirmata.ino | 239 ++++ .../examples/ServoFirmata/ServoFirmata.ino | 65 ++ .../SimpleAnalogFirmata.ino | 46 + .../SimpleDigitalFirmata.ino | 72 ++ .../examples/StandardFirmata/LICENSE.txt | 458 ++++++++ .../StandardFirmata/StandardFirmata.ino | 815 +++++++++++++ .../StandardFirmataChipKIT/LICENSE.txt | 458 ++++++++ .../StandardFirmataChipKIT.ino | 793 +++++++++++++ .../StandardFirmataEthernet/LICENSE.txt | 458 ++++++++ .../StandardFirmataEthernet.ino | 910 +++++++++++++++ .../StandardFirmataEthernet/ethernetConfig.h | 85 ++ .../StandardFirmataEthernetPlus/LICENSE.txt | 458 ++++++++ .../StandardFirmataEthernetPlus.ino | 909 +++++++++++++++ .../ethernetConfig.h | 55 + .../examples/StandardFirmataPlus/LICENSE.txt | 458 ++++++++ .../StandardFirmataPlus.ino | 838 ++++++++++++++ .../examples/StandardFirmataWiFi/LICENSE.txt | 458 ++++++++ .../StandardFirmataWiFi.ino | 1023 +++++++++++++++++ .../examples/StandardFirmataWiFi/wifiConfig.h | 155 +++ libraries/Firmata/extras/LICENSE.txt | 458 ++++++++ libraries/Firmata/extras/revisions.txt | 202 ++++ libraries/Firmata/keywords.txt | 90 ++ libraries/Firmata/library.properties | 9 + libraries/Firmata/readme.md | 177 +++ libraries/Firmata/release.sh | 35 + .../test/firmata_test/firmata_test.ino | 136 +++ libraries/Firmata/test/readme.md | 13 + .../Firmata/utility/EthernetClientStream.cpp | 114 ++ .../Firmata/utility/EthernetClientStream.h | 52 + libraries/Firmata/utility/FirmataFeature.h | 38 + libraries/Firmata/utility/SerialFirmata.cpp | 328 ++++++ libraries/Firmata/utility/SerialFirmata.h | 167 +++ libraries/Firmata/utility/WiFi101Stream.cpp | 4 + libraries/Firmata/utility/WiFi101Stream.h | 259 +++++ libraries/Firmata/utility/WiFiStream.cpp | 4 + libraries/Firmata/utility/WiFiStream.h | 258 +++++ libraries/Firmata/utility/firmataDebug.h | 14 + libraries/Keyboard/README.adoc | 25 + libraries/Keyboard/keywords.txt | 24 + libraries/Keyboard/library.properties | 9 + libraries/Keyboard/src/Keyboard.cpp | 322 ++++++ libraries/Keyboard/src/Keyboard.h | 99 ++ libraries/Mouse/README.adoc | 25 + libraries/Mouse/keywords.txt | 24 + libraries/Mouse/library.properties | 9 + libraries/Mouse/src/Mouse.cpp | 123 ++ libraries/Mouse/src/Mouse.h | 60 + libraries/OneWire/OneWire.cpp | 16 +- libraries/OneWire/OneWire.h | 144 ++- libraries/OneWire/library.json | 58 + libraries/OneWire/library.properties | 10 + 103 files changed, 18482 insertions(+), 6 deletions(-) create mode 100644 libraries/Bridge/README.adoc create mode 100644 libraries/Bridge/examples/Bridge/Bridge.ino create mode 100644 libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino create mode 100644 libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino create mode 100644 libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino create mode 100644 libraries/Bridge/examples/Datalogger/Datalogger.ino create mode 100644 libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino create mode 100644 libraries/Bridge/examples/HttpClient/HttpClient.ino create mode 100644 libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino create mode 100644 libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino create mode 100644 libraries/Bridge/examples/Process/Process.ino create mode 100644 libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino create mode 100644 libraries/Bridge/examples/ShellCommands/ShellCommands.ino create mode 100644 libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino create mode 100644 libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino create mode 100644 libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino create mode 100644 libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino create mode 100644 libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino create mode 100644 libraries/Bridge/examples/TemperatureWebPanel/www/index.html create mode 100644 libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js create mode 100644 libraries/Bridge/examples/TimeCheck/TimeCheck.ino create mode 100644 libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino create mode 100644 libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino create mode 100644 libraries/Bridge/keywords.txt create mode 100644 libraries/Bridge/library.properties create mode 100644 libraries/Bridge/src/Bridge.cpp create mode 100644 libraries/Bridge/src/Bridge.h create mode 100644 libraries/Bridge/src/BridgeClient.cpp create mode 100644 libraries/Bridge/src/BridgeClient.h create mode 100644 libraries/Bridge/src/BridgeServer.cpp create mode 100644 libraries/Bridge/src/BridgeServer.h create mode 100644 libraries/Bridge/src/BridgeUdp.cpp create mode 100644 libraries/Bridge/src/BridgeUdp.h create mode 100644 libraries/Bridge/src/Console.cpp create mode 100644 libraries/Bridge/src/Console.h create mode 100644 libraries/Bridge/src/FileIO.cpp create mode 100644 libraries/Bridge/src/FileIO.h create mode 100644 libraries/Bridge/src/HttpClient.cpp create mode 100644 libraries/Bridge/src/HttpClient.h create mode 100644 libraries/Bridge/src/Mailbox.cpp create mode 100644 libraries/Bridge/src/Mailbox.h create mode 100644 libraries/Bridge/src/Process.cpp create mode 100644 libraries/Bridge/src/Process.h create mode 100644 libraries/Bridge/src/YunClient.h create mode 100644 libraries/Bridge/src/YunServer.h create mode 100644 libraries/Firmata/Boards.h create mode 100644 libraries/Firmata/Firmata.cpp create mode 100644 libraries/Firmata/Firmata.h create mode 100644 libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino create mode 100644 libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino create mode 100644 libraries/Firmata/examples/EchoString/EchoString.ino create mode 100644 libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt create mode 100644 libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino create mode 100644 libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino create mode 100644 libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino create mode 100644 libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino create mode 100644 libraries/Firmata/examples/StandardFirmata/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino create mode 100644 libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino create mode 100644 libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino create mode 100644 libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h create mode 100644 libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino create mode 100644 libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h create mode 100644 libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino create mode 100644 libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt create mode 100644 libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino create mode 100644 libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h create mode 100644 libraries/Firmata/extras/LICENSE.txt create mode 100644 libraries/Firmata/extras/revisions.txt create mode 100644 libraries/Firmata/keywords.txt create mode 100644 libraries/Firmata/library.properties create mode 100644 libraries/Firmata/readme.md create mode 100644 libraries/Firmata/release.sh create mode 100644 libraries/Firmata/test/firmata_test/firmata_test.ino create mode 100644 libraries/Firmata/test/readme.md create mode 100644 libraries/Firmata/utility/EthernetClientStream.cpp create mode 100644 libraries/Firmata/utility/EthernetClientStream.h create mode 100644 libraries/Firmata/utility/FirmataFeature.h create mode 100644 libraries/Firmata/utility/SerialFirmata.cpp create mode 100644 libraries/Firmata/utility/SerialFirmata.h create mode 100644 libraries/Firmata/utility/WiFi101Stream.cpp create mode 100644 libraries/Firmata/utility/WiFi101Stream.h create mode 100644 libraries/Firmata/utility/WiFiStream.cpp create mode 100644 libraries/Firmata/utility/WiFiStream.h create mode 100644 libraries/Firmata/utility/firmataDebug.h create mode 100644 libraries/Keyboard/README.adoc create mode 100644 libraries/Keyboard/keywords.txt create mode 100644 libraries/Keyboard/library.properties create mode 100644 libraries/Keyboard/src/Keyboard.cpp create mode 100644 libraries/Keyboard/src/Keyboard.h create mode 100644 libraries/Mouse/README.adoc create mode 100644 libraries/Mouse/keywords.txt create mode 100644 libraries/Mouse/library.properties create mode 100644 libraries/Mouse/src/Mouse.cpp create mode 100644 libraries/Mouse/src/Mouse.h create mode 100644 libraries/OneWire/library.json create mode 100644 libraries/OneWire/library.properties diff --git a/libraries/Bridge/README.adoc b/libraries/Bridge/README.adoc new file mode 100644 index 000000000..c660f86ee --- /dev/null +++ b/libraries/Bridge/README.adoc @@ -0,0 +1,24 @@ += Bridge Library for Arduino = + +The Bridge library simplifies communication between the ATmega32U4 and the AR9331. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/YunBridgeLibrary + +== License == + +Copyright (c) 2014 Arduino LLC. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/Bridge/examples/Bridge/Bridge.ino b/libraries/Bridge/examples/Bridge/Bridge.ino new file mode 100644 index 000000000..c6c7be3af --- /dev/null +++ b/libraries/Bridge/examples/Bridge/Bridge.ino @@ -0,0 +1,185 @@ +/* + Arduino Yún Bridge example + + This example for the Arduino Yún shows how to use the + Bridge library to access the digital and analog pins + on the board through REST calls. It demonstrates how + you can create your own API when using REST style + calls through the browser. + + Possible commands created in this shetch: + + "/arduino/digital/13" -> digitalRead(13) + "/arduino/digital/13/1" -> digitalWrite(13, HIGH) + "/arduino/analog/2/123" -> analogWrite(2, 123) + "/arduino/analog/2" -> analogRead(2) + "/arduino/mode/13/input" -> pinMode(13, INPUT) + "/arduino/mode/13/output" -> pinMode(13, OUTPUT) + + This example code is part of the public domain + + http://www.arduino.cc/en/Tutorial/Bridge + +*/ + +#include +#include +#include + +// Listen to the default port 5555, the Yún webserver +// will forward there all the HTTP requests you send +BridgeServer server; + +void setup() { + // Bridge startup + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + // Listen for incoming connection only from localhost + // (no one from the external network could connect) + server.listenOnLocalhost(); + server.begin(); +} + +void loop() { + // Get clients coming from server + BridgeClient client = server.accept(); + + // There is a new client? + if (client) { + // Process request + process(client); + + // Close connection and free resources. + client.stop(); + } + + delay(50); // Poll every 50ms +} + +void process(BridgeClient client) { + // read the command + String command = client.readStringUntil('/'); + + // is "digital" command? + if (command == "digital") { + digitalCommand(client); + } + + // is "analog" command? + if (command == "analog") { + analogCommand(client); + } + + // is "mode" command? + if (command == "mode") { + modeCommand(client); + } +} + +void digitalCommand(BridgeClient client) { + int pin, value; + + // Read pin number + pin = client.parseInt(); + + // If the next character is a '/' it means we have an URL + // with a value like: "/digital/13/1" + if (client.read() == '/') { + value = client.parseInt(); + digitalWrite(pin, value); + } else { + value = digitalRead(pin); + } + + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" set to ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "D"; + key += pin; + Bridge.put(key, String(value)); +} + +void analogCommand(BridgeClient client) { + int pin, value; + + // Read pin number + pin = client.parseInt(); + + // If the next character is a '/' it means we have an URL + // with a value like: "/analog/5/120" + if (client.read() == '/') { + // Read value and execute command + value = client.parseInt(); + analogWrite(pin, value); + + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" set to analog ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "D"; + key += pin; + Bridge.put(key, String(value)); + } else { + // Read analog pin + value = analogRead(pin); + + // Send feedback to client + client.print(F("Pin A")); + client.print(pin); + client.print(F(" reads analog ")); + client.println(value); + + // Update datastore key with the current pin value + String key = "A"; + key += pin; + Bridge.put(key, String(value)); + } +} + +void modeCommand(BridgeClient client) { + int pin; + + // Read pin number + pin = client.parseInt(); + + // If the next character is not a '/' we have a malformed URL + if (client.read() != '/') { + client.println(F("error")); + return; + } + + String mode = client.readStringUntil('\r'); + + if (mode == "input") { + pinMode(pin, INPUT); + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" configured as INPUT!")); + return; + } + + if (mode == "output") { + pinMode(pin, OUTPUT); + // Send feedback to client + client.print(F("Pin D")); + client.print(pin); + client.print(F(" configured as OUTPUT!")); + return; + } + + client.print(F("error: invalid mode ")); + client.print(mode); +} + + diff --git a/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino b/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino new file mode 100644 index 000000000..79d5aff7e --- /dev/null +++ b/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino @@ -0,0 +1,95 @@ +/* + ASCII table + + Prints out byte values in all possible formats: + * as raw binary values + * as ASCII-encoded decimal, hex, octal, and binary values + + For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII + + The circuit: No external hardware needed. + + created 2006 + by Nicholas Zambetti + http://www.zambetti.com + modified 9 Apr 2012 + by Tom Igoe + modified 22 May 2013 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsoleAsciiTable + + */ + +#include + +void setup() { + //Initialize Console and wait for port to open: + Bridge.begin(); + Console.begin(); + + // Uncomment the following line to enable buffering: + // - better transmission speed and efficiency + // - needs to call Console.flush() to ensure that all + // transmitted data is sent + + //Console.buffer(64); + + while (!Console) { + ; // wait for Console port to connect. + } + + // prints title with ending line break + Console.println("ASCII Table ~ Character Map"); +} + +// first visible ASCIIcharacter '!' is number 33: +int thisByte = 33; +// you can also write ASCII characters in single quotes. +// for example. '!' is the same as 33, so you could also use this: +//int thisByte = '!'; + +void loop() { + // prints value unaltered, i.e. the raw binary version of the + // byte. The Console monitor interprets all bytes as + // ASCII, so 33, the first number, will show up as '!' + Console.write(thisByte); + + Console.print(", dec: "); + // prints value as string as an ASCII-encoded decimal (base 10). + // Decimal is the default format for Console.print() and Console.println(), + // so no modifier is needed: + Console.print(thisByte); + // But you can declare the modifier for decimal if you want to. + //this also works if you uncomment it: + + // Console.print(thisByte, DEC); + + Console.print(", hex: "); + // prints value as string in hexadecimal (base 16): + Console.print(thisByte, HEX); + + Console.print(", oct: "); + // prints value as string in octal (base 8); + Console.print(thisByte, OCT); + + Console.print(", bin: "); + // prints value as string in binary (base 2) + // also prints ending line break: + Console.println(thisByte, BIN); + + // if printed last visible character '~' or 126, stop: + if (thisByte == 126) { // you could also use if (thisByte == '~') { + // ensure the latest bit of data is sent + Console.flush(); + + // This loop loops forever and does nothing + while (true) { + continue; + } + } + // go on to the next character + thisByte++; +} diff --git a/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino b/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino new file mode 100644 index 000000000..ee78f4c61 --- /dev/null +++ b/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino @@ -0,0 +1,64 @@ +/* + Console Pixel + + An example of using the Arduino board to receive data from the + Console on the Arduino Yún. In this case, the Arduino boards turns on an LED when + it receives the character 'H', and turns off the LED when it + receives the character 'L'. + + To see the Console, pick your Yún's name and IP address in the Port menu + then open the Port Monitor. You can also see it by opening a terminal window + and typing + ssh root@ yourYunsName.local 'telnet localhost 6571' + then pressing enter. When prompted for the password, enter it. + + + The circuit: + * LED connected from digital pin 13 to ground + + created 2006 + by David A. Mellis + modified 25 Jun 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsolePixel + + */ + +#include + +const int ledPin = 13; // the pin that the LED is attached to +char incomingByte; // a variable to read incoming Console data into + +void setup() { + Bridge.begin(); // Initialize Bridge + Console.begin(); // Initialize Console + + // Wait for the Console port to connect + while (!Console); + + Console.println("type H or L to turn pin 13 on or off"); + + // initialize the LED pin as an output: + pinMode(ledPin, OUTPUT); +} + +void loop() { + // see if there's incoming Console data: + if (Console.available() > 0) { + // read the oldest byte in the Console buffer: + incomingByte = Console.read(); + Console.println(incomingByte); + // if it's a capital H (ASCII 72), turn on the LED: + if (incomingByte == 'H') { + digitalWrite(ledPin, HIGH); + } + // if it's an L (ASCII 76) turn off the LED: + if (incomingByte == 'L') { + digitalWrite(ledPin, LOW); + } + } +} + diff --git a/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino b/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino new file mode 100644 index 000000000..8fc37fbe6 --- /dev/null +++ b/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino @@ -0,0 +1,60 @@ +/* + Console Read example + + Read data coming from bridge using the Console.read() function + and store it in a string. + + To see the Console, pick your Yún's name and IP address in the Port menu + then open the Port Monitor. You can also see it by opening a terminal window + and typing: + ssh root@ yourYunsName.local 'telnet localhost 6571' + then pressing enter. When prompted for the password, enter it. + + created 13 Jun 2013 + by Angelo Scialabba + modified 16 June 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ConsoleRead + + */ + +#include + +String name; + +void setup() { + // Initialize Console and wait for port to open: + Bridge.begin(); + Console.begin(); + + // Wait for Console port to connect + while (!Console); + + Console.println("Hi, what's your name?"); +} + +void loop() { + if (Console.available() > 0) { + char c = Console.read(); // read the next char received + // look for the newline character, this is the last character in the string + if (c == '\n') { + //print text with the name received + Console.print("Hi "); + Console.print(name); + Console.println("! Nice to meet you!"); + Console.println(); + // Ask again for name and clear the old name + Console.println("Hi, what's your name?"); + name = ""; // clear the name string + } else { // if the buffer is empty Cosole.read() returns -1 + name += c; // append the read char from Console to the name string + } + } else { + delay(100); + } +} + + diff --git a/libraries/Bridge/examples/Datalogger/Datalogger.ino b/libraries/Bridge/examples/Datalogger/Datalogger.ino new file mode 100644 index 000000000..367cd7226 --- /dev/null +++ b/libraries/Bridge/examples/Datalogger/Datalogger.ino @@ -0,0 +1,102 @@ +/* + SD card datalogger + + This example shows how to log data from three analog sensors + to an SD card mounted on the Arduino Yún using the Bridge library. + + The circuit: + * analog sensors on analog pins 0, 1 and 2 + * SD card attached to SD card slot of the Arduino Yún + + Prepare your SD card creating an empty folder in the SD root + named "arduino". This will ensure that the Yún will create a link + to the SD to the "/mnt/sd" path. + + You can remove the SD card while the Linux and the + sketch are running but be careful not to remove it while + the system is writing to it. + + created 24 Nov 2010 + modified 9 Apr 2012 + by Tom Igoe + adapted to the Yún Bridge library 20 Jun 2013 + by Federico Vanzati + modified 21 Jun 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunDatalogger + + */ + +#include + +void setup() { + // Initialize the Bridge and the Serial + Bridge.begin(); + Serial.begin(9600); + FileSystem.begin(); + + while (!SerialUSB); // wait for Serial port to connect. + SerialUSB.println("Filesystem datalogger\n"); +} + + +void loop() { + // make a string that start with a timestamp for assembling the data to log: + String dataString; + dataString += getTimeStamp(); + dataString += " = "; + + // read three sensors and append to the string: + for (int analogPin = 0; analogPin < 3; analogPin++) { + int sensor = analogRead(analogPin); + dataString += String(sensor); + if (analogPin < 2) { + dataString += ","; // separate the values with a comma + } + } + + // open the file. note that only one file can be open at a time, + // so you have to close this one before opening another. + // The FileSystem card is mounted at the following "/mnt/FileSystema1" + File dataFile = FileSystem.open("/mnt/sd/datalog.txt", FILE_APPEND); + + // if the file is available, write to it: + if (dataFile) { + dataFile.println(dataString); + dataFile.close(); + // print to the serial port too: + SerialUSB.println(dataString); + } + // if the file isn't open, pop up an error: + else { + SerialUSB.println("error opening datalog.txt"); + } + + delay(15000); + +} + +// This function return a string with the time stamp +String getTimeStamp() { + String result; + Process time; + // date is a command line utility to get the date and the time + // in different formats depending on the additional parameter + time.begin("date"); + time.addParameter("+%D-%T"); // parameters: D for the complete date mm/dd/yy + // T for the time hh:mm:ss + time.run(); // run the command + + // read the output of the command + while (time.available() > 0) { + char c = time.read(); + if (c != '\n') { + result += c; + } + } + + return result; +} diff --git a/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino b/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino new file mode 100644 index 000000000..99899c080 --- /dev/null +++ b/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino @@ -0,0 +1,84 @@ +/* + Write to file using FileIO classes. + + This sketch demonstrate how to write file into the Yún filesystem. + A shell script file is created in /tmp, and it is executed afterwards. + + created 7 June 2010 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/FileWriteScript + + */ + +#include + +void setup() { + // Setup Bridge (needed every time we communicate with the Arduino Yún) + Bridge.begin(); + // Initialize the Serial + SerialUSB.begin(9600); + + while (!SerialUSB); // wait for Serial port to connect. + SerialUSB.println("File Write Script example\n\n"); + + // Setup File IO + FileSystem.begin(); + + // Upload script used to gain network statistics + uploadScript(); +} + +void loop() { + // Run stats script every 5 secs. + runScript(); + delay(5000); +} + +// this function creates a file into the linux processor that contains a shell script +// to check the network traffic of the WiFi interface +void uploadScript() { + // Write our shell script in /tmp + // Using /tmp stores the script in RAM this way we can preserve + // the limited amount of FLASH erase/write cycles + File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE); + // Shell script header + script.print("#!/bin/sh\n"); + // shell commands: + // ifconfig: is a command line utility for controlling the network interfaces. + // wlan0 is the interface we want to query + // grep: search inside the output of the ifconfig command the "RX bytes" keyword + // and extract the line that contains it + script.print("ifconfig wlan0 | grep 'RX bytes'\n"); + script.close(); // close the file + + // Make the script executable + Process chmod; + chmod.begin("chmod"); // chmod: change mode + chmod.addParameter("+x"); // x stays for executable + chmod.addParameter("/tmp/wlan-stats.sh"); // path to the file to make it executable + chmod.run(); +} + + +// this function run the script and read the output data +void runScript() { + // Run the script and show results on the Serial + Process myscript; + myscript.begin("/tmp/wlan-stats.sh"); + myscript.run(); + + String output = ""; + + // read the output of the script + while (myscript.available()) { + output += (char)myscript.read(); + } + // remove the blank spaces at the beginning and the ending of the string + output.trim(); + SerialUSB.println(output); + SerialUSB.flush(); +} + diff --git a/libraries/Bridge/examples/HttpClient/HttpClient.ino b/libraries/Bridge/examples/HttpClient/HttpClient.ino new file mode 100644 index 000000000..a3a5429af --- /dev/null +++ b/libraries/Bridge/examples/HttpClient/HttpClient.ino @@ -0,0 +1,53 @@ +/* + Yún HTTP Client + + This example for the Arduino Yún shows how create a basic + HTTP client that connects to the internet and downloads + content. In this case, you'll connect to the Arduino + website and download a version of the logo as ASCII text. + + created by Tom igoe + May 2013 + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/HttpClient + + */ + +#include +#include + +void setup() { + // Bridge takes about two seconds to start up + // it can be helpful to use the on-board LED + // as an indicator for when it has initialized + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + SerialUSB.begin(9600); + + while (!SerialUSB); // wait for a serial connection +} + +void loop() { + // Initialize the client library + HttpClient client; + + // Make a HTTP request: + client.get("http://www.arduino.cc/asciilogo.txt"); + + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + SerialUSB.print(c); + } + SerialUSB.flush(); + + delay(5000); +} + + diff --git a/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino b/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino new file mode 100644 index 000000000..6d8c0eeb8 --- /dev/null +++ b/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino @@ -0,0 +1,55 @@ +/* + Yún HTTP Client Console version for Arduino Uno and Mega using Yún Shield + + This example for the Arduino Yún shows how create a basic + HTTP client that connects to the internet and downloads + content. In this case, you'll connect to the Arduino + website and download a version of the logo as ASCII text. + + created by Tom igoe + May 2013 + modified by Marco Brianza to use Console + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/HttpClient + + */ + +#include +#include +#include + +void setup() { + // Bridge takes about two seconds to start up + // it can be helpful to use the on-board LED + // as an indicator for when it has initialized + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + Console.begin(); + + while (!Console); // wait for a serial connection +} + +void loop() { + // Initialize the client library + HttpClient client; + + // Make a HTTP request: + client.get("http://www.arduino.cc/asciilogo.txt"); + + // if there are incoming bytes available + // from the server, read them and print them: + while (client.available()) { + char c = client.read(); + Console.print(c); + } + Console.flush(); + + delay(5000); +} + + diff --git a/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino b/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino new file mode 100644 index 000000000..b7cbe8ad8 --- /dev/null +++ b/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino @@ -0,0 +1,58 @@ +/* + Read Messages from the Mailbox + + This example for the Arduino Yún shows how to + read the messages queue, called Mailbox, using the + Bridge library. + The messages can be sent to the queue through REST calls. + Appen the message in the URL after the keyword "/mailbox". + Example + + "/mailbox/hello" + + created 3 Feb 2014 + by Federico Vanzati & Federico Fissore + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/MailboxReadMessage + + */ + +#include + +void setup() { + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + // Initialize Bridge and Mailbox + Bridge.begin(); + Mailbox.begin(); + digitalWrite(13, HIGH); + + // Initialize Serial + SerialUSB.begin(9600); + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); + + SerialUSB.println("Mailbox Read Message\n"); + SerialUSB.println("The Mailbox is checked every 10 seconds. The incoming messages will be shown below.\n"); +} + +void loop() { + String message; + + // if there is a message in the Mailbox + if (Mailbox.messageAvailable()) { + // read all the messages present in the queue + while (Mailbox.messageAvailable()) { + Mailbox.readMessage(message); + SerialUSB.println(message); + } + + SerialUSB.println("Waiting 10 seconds before checking the Mailbox again"); + } + + // wait 10 seconds + delay(10000); +} diff --git a/libraries/Bridge/examples/Process/Process.ino b/libraries/Bridge/examples/Process/Process.ino new file mode 100644 index 000000000..ad5b86944 --- /dev/null +++ b/libraries/Bridge/examples/Process/Process.ino @@ -0,0 +1,72 @@ +/* + Running process using Process class. + + This sketch demonstrate how to run linux processes + using an Arduino Yún. + + created 5 Jun 2013 + by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/Process + + */ + +#include + +void setup() { + // Initialize Bridge + Bridge.begin(); + + // Initialize Serial + SerialUSB.begin(9600); + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); + + // run various example processes + runCurl(); + runCpuInfo(); +} + +void loop() { + // Do nothing here. +} + +void runCurl() { + // Launch "curl" command and get Arduino ascii art logo from the network + // curl is command line program for transferring data using different internet protocols + Process p; // Create a process and call it "p" + p.begin("curl"); // Process that launch the "curl" command + p.addParameter("http://www.arduino.cc/asciilogo.txt"); // Add the URL parameter to "curl" + p.run(); // Run the process and wait for its termination + + // Print arduino logo over the Serial + // A process output can be read with the stream methods + while (p.available() > 0) { + char c = p.read(); + SerialUSB.print(c); + } + // Ensure the last bit of data is sent. + SerialUSB.flush(); +} + +void runCpuInfo() { + // Launch "cat /proc/cpuinfo" command (shows info on Atheros CPU) + // cat is a command line utility that shows the content of a file + Process p; // Create a process and call it "p" + p.begin("cat"); // Process that launch the "cat" command + p.addParameter("/proc/cpuinfo"); // Add the cpuifo file path as parameter to cut + p.run(); // Run the process and wait for its termination + + // Print command output on the SerialUSB. + // A process output can be read with the stream methods + while (p.available() > 0) { + char c = p.read(); + SerialUSB.print(c); + } + // Ensure the last bit of data is sent. + SerialUSB.flush(); +} + diff --git a/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino b/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino new file mode 100644 index 000000000..4b5d2713c --- /dev/null +++ b/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino @@ -0,0 +1,33 @@ +/* + Blink + Turns on an LED on for one second, then off for one second, repeatedly. + + Most Arduinos have an on-board LED you can control. On the Uno and + Leonardo, it is attached to digital pin 13. If you're unsure what + pin the on-board LED is connected to on your Arduino model, check + the documentation at http://www.arduino.cc + + This example code is in the public domain. + + modified 8 May 2014 + by Scott Fitzgerald + + modified by Marco Brianza to show the remote sketch update feature on Arduino Due using Yún Shield + */ + +#include + +// the setup function runs once when you press reset or power the board +void setup() { + checkForRemoteSketchUpdate(); + // initialize digital pin 13 as an output. + pinMode(13, OUTPUT); +} + +// the loop function runs over and over again forever +void loop() { + digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) + delay(100); // wait for a second + digitalWrite(13, LOW); // turn the LED off by making the voltage LOW + delay(100); // wait for a second +} diff --git a/libraries/Bridge/examples/ShellCommands/ShellCommands.ino b/libraries/Bridge/examples/ShellCommands/ShellCommands.ino new file mode 100644 index 000000000..a90c6974f --- /dev/null +++ b/libraries/Bridge/examples/ShellCommands/ShellCommands.ino @@ -0,0 +1,55 @@ +/* + Running shell commands using Process class. + + This sketch demonstrate how to run linux shell commands + using an Arduino Yún. It runs the wifiCheck script on the Linux side + of the Yún, then uses grep to get just the signal strength line. + Then it uses parseInt() to read the wifi signal strength as an integer, + and finally uses that number to fade an LED using analogWrite(). + + The circuit: + * Arduino Yún with LED connected to pin 9 + + created 12 Jun 2013 + by Cristian Maglie + modified 25 June 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/ShellCommands + + */ + +#include + +void setup() { + Bridge.begin(); // Initialize the Bridge + SerialUSB.begin(9600); // Initialize the Serial + + // Wait until a Serial Monitor is connected. + while (!SerialUSB); +} + +void loop() { + Process p; + // This command line runs the WifiStatus script, (/usr/bin/pretty-wifi-info.lua), then + // sends the result to the grep command to look for a line containing the word + // "Signal:" the result is passed to this sketch: + p.runShellCommand("/usr/bin/pretty-wifi-info.lua | grep Signal"); + + // do nothing until the process finishes, so you get the whole output: + while (p.running()); + + // Read command output. runShellCommand() should have passed "Signal: xx&": + while (p.available()) { + int result = p.parseInt(); // look for an integer + int signal = map(result, 0, 100, 0, 255); // map result from 0-100 range to 0-255 + analogWrite(9, signal); // set the brightness of LED on pin 9 + SerialUSB.println(result); // print the number as well + } + delay(5000); // wait 5 seconds before you do it again +} + + + diff --git a/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino b/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino new file mode 100644 index 000000000..0f259ede6 --- /dev/null +++ b/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino @@ -0,0 +1,134 @@ +/* + Input Output + + Demonstrates how to create a sketch that sends and receives all standard + spacebrew data types, and a custom data type. Every time data is + received it is output to the Serial monitor. + + Make sure that your Yún is connected to the internet for this example + to function properly. + + The circuit: + - No circuit required + + created 2013 + by Julio Terra + + This example code is in the public domain. + + More information about Spacebrew is available at: + http://spacebrew.cc/ + + */ + +#include +#include + +// create a variable of type SpacebrewYun and initialize it with the constructor +SpacebrewYun sb = SpacebrewYun("aYun", "Arduino Yun spacebrew test"); + +// create variables to manage interval between each time we send a string +long last = 0; +int interval = 2000; + +int counter = 0; + +void setup() { + + // start the serial port + SerialUSB.begin(57600); + + // for debugging, wait until a serial console is connected + delay(4000); + while (!SerialUSB) { + ; + } + + // start-up the bridge + Bridge.begin(); + + // configure the spacebrew object to print status messages to serial + sb.verbose(true); + + // configure the spacebrew publisher and subscriber + sb.addPublish("string test", "string"); + sb.addPublish("range test", "range"); + sb.addPublish("boolean test", "boolean"); + sb.addPublish("custom test", "crazy"); + sb.addSubscribe("string test", "string"); + sb.addSubscribe("range test", "range"); + sb.addSubscribe("boolean test", "boolean"); + sb.addSubscribe("custom test", "crazy"); + + // register the string message handler method + sb.onRangeMessage(handleRange); + sb.onStringMessage(handleString); + sb.onBooleanMessage(handleBoolean); + sb.onCustomMessage(handleCustom); + + // connect to cloud spacebrew server at "sandbox.spacebrew.cc" + sb.connect("sandbox.spacebrew.cc"); + // we give some time to arduino to connect to sandbox, otherwise the first sb.monitor(); call will give an error + delay(1000); +} + + +void loop() { + // monitor spacebrew connection for new data + sb.monitor(); + + // connected to spacebrew then send a string every 2 seconds + if (sb.connected()) { + + // check if it is time to send a new message + if ((millis() - last) > interval) { + String test_str_msg = "testing, testing, "; + test_str_msg += counter; + counter ++; + + sb.send("string test", test_str_msg); + sb.send("range test", 500); + sb.send("boolean test", true); + sb.send("custom test", "youre loco"); + + last = millis(); + + } + } + delay(1000); +} + +// define handler methods, all standard data type handlers take two appropriate arguments + +void handleRange(String route, int value) { + SerialUSB.print("Range msg "); + SerialUSB.print(route); + SerialUSB.print(", value "); + SerialUSB.println(value); +} + +void handleString(String route, String value) { + SerialUSB.print("String msg "); + SerialUSB.print(route); + SerialUSB.print(", value "); + SerialUSB.println(value); +} + +void handleBoolean(String route, boolean value) { + SerialUSB.print("Boolen msg "); + SerialUSB.print(route); + SerialUSB.print(", value "); + SerialUSB.println(value ? "true" : "false"); +} + +// custom data type handlers takes three String arguments + +void handleCustom(String route, String value, String type) { + SerialUSB.print("Custom msg "); + SerialUSB.print(route); + SerialUSB.print(" of type "); + SerialUSB.print(type); + SerialUSB.print(", value "); + SerialUSB.println(value); +} + diff --git a/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino b/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino new file mode 100644 index 000000000..c63314d7c --- /dev/null +++ b/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino @@ -0,0 +1,94 @@ +/* + Spacebrew Boolean + + Demonstrates how to create a sketch that sends and receives a + boolean value to and from Spacebrew. Every time the buttton is + pressed (or other digital input component) a spacebrew message + is sent. The sketch also accepts analog range messages from + other Spacebrew apps. + + Make sure that your Yún is connected to the internet for this example + to function properly. + + The circuit: + - Button connected to Yún, using the Arduino's internal pullup resistor. + + created 2013 + by Julio Terra + + This example code is in the public domain. + + More information about Spacebrew is available at: + http://spacebrew.cc/ + + */ + +#include +#include + +// create a variable of type SpacebrewYun and initialize it with the constructor +SpacebrewYun sb = SpacebrewYun("spacebrewYun Boolean", "Boolean sender and receiver"); + +// variable that holds the last potentiometer value +int last_value = 0; + +// create variables to manage interval between each time we send a string +void setup() { + + // start the serial port + SerialUSB.begin(57600); + + // for debugging, wait until a serial console is connected + delay(4000); + while (!SerialUSB) { + ; + } + + // start-up the bridge + Bridge.begin(); + + // configure the spacebrew object to print status messages to serial + sb.verbose(true); + + // configure the spacebrew publisher and subscriber + sb.addPublish("physical button", "boolean"); + sb.addSubscribe("virtual button", "boolean"); + + // register the string message handler method + sb.onBooleanMessage(handleBoolean); + + // connect to cloud spacebrew server at "sandbox.spacebrew.cc" + sb.connect("sandbox.spacebrew.cc"); + + pinMode(3, INPUT); + digitalWrite(3, HIGH); +} + + +void loop() { + // monitor spacebrew connection for new data + sb.monitor(); + + // connected to spacebrew then send a new value whenever the pot value changes + if (sb.connected()) { + int cur_value = digitalRead(3); + if (last_value != cur_value) { + if (cur_value == HIGH) { + sb.send("physical button", false); + } else { + sb.send("physical button", true); + } + last_value = cur_value; + } + } +} + +// handler method that is called whenever a new string message is received +void handleBoolean(String route, boolean value) { + // print the message that was received + SerialUSB.print("From "); + SerialUSB.print(route); + SerialUSB.print(", received msg: "); + SerialUSB.println(value ? "true" : "false"); +} + diff --git a/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino b/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino new file mode 100644 index 000000000..eda2d17a9 --- /dev/null +++ b/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino @@ -0,0 +1,88 @@ +/* + Spacebrew Range + + Demonstrates how to create a sketch that sends and receives analog + range value to and from Spacebrew. Every time the state of the + potentiometer (or other analog input component) change a spacebrew + message is sent. The sketch also accepts analog range messages from + other Spacebrew apps. + + Make sure that your Yún is connected to the internet for this example + to function properly. + + The circuit: + - Potentiometer connected to Yún. Middle pin connected to analog pin A0, + other pins connected to 5v and GND pins. + + created 2013 + by Julio Terra + + This example code is in the public domain. + + More information about Spacebrew is available at: + http://spacebrew.cc/ + + */ + +#include +#include + +// create a variable of type SpacebrewYun and initialize it with the constructor +SpacebrewYun sb = SpacebrewYun("spacebrewYun Range", "Range sender and receiver"); + +// variable that holds the last potentiometer value +int last_value = 0; + +// create variables to manage interval between each time we send a string +void setup() { + + // start the serial port + SerialUSB.begin(57600); + + // for debugging, wait until a serial console is connected + delay(4000); + while (!SerialUSB) { + ; + } + + // start-up the bridge + Bridge.begin(); + + // configure the spacebrew object to print status messages to serial + sb.verbose(true); + + // configure the spacebrew publisher and subscriber + sb.addPublish("physical pot", "range"); + sb.addSubscribe("virtual pot", "range"); + + // register the string message handler method + sb.onRangeMessage(handleRange); + + // connect to cloud spacebrew server at "sandbox.spacebrew.cc" + sb.connect("sandbox.spacebrew.cc"); +} + + +void loop() { + // monitor spacebrew connection for new data + sb.monitor(); + + // connected to spacebrew then send a new value whenever the pot value changes + if (sb.connected()) { + int cur_value = analogRead(A0); + if (last_value != cur_value) { + sb.send("physical pot", cur_value); + last_value = cur_value; + } + } +} + +// handler method that is called whenever a new string message is received +void handleRange(String route, int value) { + // print the message that was received + SerialUSB.print("From "); + SerialUSB.print(route); + SerialUSB.print(", received msg: "); + SerialUSB.println(value); +} + diff --git a/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino b/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino new file mode 100644 index 000000000..189d31129 --- /dev/null +++ b/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino @@ -0,0 +1,86 @@ +/* + Spacebrew String + + Demonstrates how to create a sketch that sends and receives strings + to and from Spacebrew. Every time string data is received it + is output to the Serial monitor. + + Make sure that your Yún is connected to the internet for this example + to function properly. + + The circuit: + - No circuit required + + created 2013 + by Julio Terra + + This example code is in the public domain. + + More information about Spacebrew is available at: + http://spacebrew.cc/ + + */ + +#include +#include + +// create a variable of type SpacebrewYun and initialize it with the constructor +SpacebrewYun sb = SpacebrewYun("spacebrewYun Strings", "String sender and receiver"); + +// create variables to manage interval between each time we send a string +long last_time = 0; +int interval = 2000; + +void setup() { + + // start the serial port + SerialUSB.begin(57600); + + // for debugging, wait until a serial console is connected + delay(4000); + while (!SerialUSB) { + ; + } + + // start-up the bridge + Bridge.begin(); + + // configure the spacebrew object to print status messages to serial + sb.verbose(true); + + // configure the spacebrew publisher and subscriber + sb.addPublish("speak", "string"); + sb.addSubscribe("listen", "string"); + + // register the string message handler method + sb.onStringMessage(handleString); + + // connect to cloud spacebrew server at "sandbox.spacebrew.cc" + sb.connect("sandbox.spacebrew.cc"); +} + + +void loop() { + // monitor spacebrew connection for new data + sb.monitor(); + + // connected to spacebrew then send a string every 2 seconds + if (sb.connected()) { + + // check if it is time to send a new message + if ((millis() - last_time) > interval) { + sb.send("speak", "is anybody out there?"); + last_time = millis(); + } + } +} + +// handler method that is called whenever a new string message is received +void handleString(String route, String value) { + // print the message that was received + SerialUSB.print("From "); + SerialUSB.print(route); + SerialUSB.print(", received msg: "); + SerialUSB.println(value); +} + diff --git a/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino b/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino new file mode 100644 index 000000000..3a3ba6701 --- /dev/null +++ b/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino @@ -0,0 +1,125 @@ +/* + Temperature web interface + + This example shows how to serve data from an analog input + via the Arduino Yún's built-in webserver using the Bridge library. + + The circuit: + * TMP36 temperature sensor on analog pin A1 + * SD card attached to SD card slot of the Arduino Yún + + This sketch must be uploaded via wifi. REST API must be set to "open". + + Prepare your SD card with an empty folder in the SD root + named "arduino" and a subfolder of that named "www". + This will ensure that the Yún will create a link + to the SD to the "/mnt/sd" path. + + In this sketch folder is a basic webpage and a copy of zepto.js, a + minimized version of jQuery. When you upload your sketch, these files + will be placed in the /arduino/www/TemperatureWebPanel folder on your SD card. + + You can then go to http://arduino.local/sd/TemperatureWebPanel + to see the output of this sketch. + + You can remove the SD card while the Linux and the + sketch are running but be careful not to remove it while + the system is writing to it. + + created 6 July 2013 + by Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/TemperatureWebPanel + + */ + +#include +#include +#include + +// Listen on default port 5555, the webserver on the Yún +// will forward there all the HTTP requests for us. +BridgeServer server; +String startString; +long hits = 0; + +void setup() { + SerialUSB.begin(9600); + + // Bridge startup + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); + digitalWrite(13, HIGH); + + // using A0 and A2 as vcc and gnd for the TMP36 sensor: + pinMode(A0, OUTPUT); + pinMode(A2, OUTPUT); + digitalWrite(A0, HIGH); + digitalWrite(A2, LOW); + + // Listen for incoming connection only from localhost + // (no one from the external network could connect) + server.listenOnLocalhost(); + server.begin(); + + // get the time that this sketch started: + Process startTime; + startTime.runShellCommand("date"); + while (startTime.available()) { + char c = startTime.read(); + startString += c; + } +} + +void loop() { + // Get clients coming from server + BridgeClient client = server.accept(); + + // There is a new client? + if (client) { + // read the command + String command = client.readString(); + command.trim(); //kill whitespace + SerialUSB.println(command); + // is "temperature" command? + if (command == "temperature") { + + // get the time from the server: + Process time; + time.runShellCommand("date"); + String timeString = ""; + while (time.available()) { + char c = time.read(); + timeString += c; + } + SerialUSB.println(timeString); + int sensorValue = analogRead(A1); + // convert the reading to millivolts: + float voltage = sensorValue * (5000.0f / 1024.0f); + // convert the millivolts to temperature celsius: + float temperature = (voltage - 500.0f) / 10.0f; + // print the temperature: + client.print("Current time on the Yún: "); + client.println(timeString); + client.print("
Current temperature: "); + client.print(temperature); + client.print(" °C"); + client.print("
This sketch has been running since "); + client.print(startString); + client.print("
Hits so far: "); + client.print(hits); + } + + // Close connection and free resources. + client.stop(); + hits++; + } + + delay(50); // Poll every 50ms +} + + + diff --git a/libraries/Bridge/examples/TemperatureWebPanel/www/index.html b/libraries/Bridge/examples/TemperatureWebPanel/www/index.html new file mode 100644 index 000000000..c6b674771 --- /dev/null +++ b/libraries/Bridge/examples/TemperatureWebPanel/www/index.html @@ -0,0 +1,16 @@ + + + + + + + + + 0 + + + diff --git a/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js b/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js new file mode 100644 index 000000000..dbe4e3c3f --- /dev/null +++ b/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js @@ -0,0 +1,2 @@ +/* Zepto v1.0-1-ga3cab6c - polyfill zepto detect event ajax form fx - zeptojs.com/license */ +(function(a){String.prototype.trim===a&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),Array.prototype.reduce===a&&(Array.prototype.reduce=function(b){if(this===void 0||this===null)throw new TypeError;var c=Object(this),d=c.length>>>0,e=0,f;if(typeof b!="function")throw new TypeError;if(d==0&&arguments.length==1)throw new TypeError;if(arguments.length>=2)f=arguments[1];else do{if(e in c){f=c[e++];break}if(++e>=d)throw new TypeError}while(!0);while(e0?c.fn.concat.apply([],a):a}function O(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function P(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function Q(a,b){return typeof b=="number"&&!l[O(a)]?b+"px":b}function R(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=k(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function S(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function T(c,d,e){for(b in d)e&&(J(d[b])||K(d[b]))?(J(d[b])&&!J(c[b])&&(c[b]={}),K(d[b])&&!K(c[b])&&(c[b]=[]),T(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function U(b,d){return d===a?c(b):c(b).filter(d)}function V(a,b,c,d){return F(b)?b.call(a,c,d):b}function W(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function X(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function Y(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:isNaN(b=Number(a))?/^[\[\{]/.test(a)?c.parseJSON(a):a:b):a}catch(d){return a}}function Z(a,b){b(a);for(var c in a.childNodes)Z(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k=h.defaultView.getComputedStyle,l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},m=/^\s*<(\w+|!)[^>]*>/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=["val","css","html","text","data","width","height","offset"],q=["after","prepend","before","append"],r=h.createElement("table"),s=h.createElement("tr"),t={tr:h.createElement("tbody"),tbody:r,thead:r,tfoot:r,td:s,th:s,"*":h.createElement("div")},u=/complete|loaded|interactive/,v=/^\.([\w-]+)$/,w=/^#([\w-]*)$/,x=/^[\w-]+$/,y={},z=y.toString,A={},B,C,D=h.createElement("div");return A.matches=function(a,b){if(!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=D).appendChild(a),d=~A.qsa(e,b).indexOf(a),f&&D.removeChild(a),d},B=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},C=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},A.fragment=function(b,d,e){b.replace&&(b=b.replace(n,"<$1>")),d===a&&(d=m.test(b)&&RegExp.$1),d in t||(d="*");var g,h,i=t[d];return i.innerHTML=""+b,h=c.each(f.call(i.childNodes),function(){i.removeChild(this)}),J(e)&&(g=c(h),c.each(e,function(a,b){p.indexOf(a)>-1?g[a](b):g.attr(a,b)})),h},A.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},A.isZ=function(a){return a instanceof A.Z},A.init=function(b,d){if(!b)return A.Z();if(F(b))return c(h).ready(b);if(A.isZ(b))return b;var e;if(K(b))e=M(b);else if(I(b))e=[J(b)?c.extend({},b):b],b=null;else if(m.test(b))e=A.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=A.qsa(h,b)}return A.Z(e,b)},c=function(a,b){return A.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){T(a,c,b)}),a},A.qsa=function(a,b){var c;return H(a)&&w.test(b)?(c=a.getElementById(RegExp.$1))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(v.test(b)?a.getElementsByClassName(RegExp.$1):x.test(b)?a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=E,c.isFunction=F,c.isWindow=G,c.isArray=K,c.isPlainObject=J,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=B,c.trim=function(a){return a.trim()},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(L(a))for(e=0;e=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return F(a)?this.not(this.not(a)):c(g.call(this,function(b){return A.matches(b,a)}))},add:function(a,b){return c(C(this.concat(c(a,b))))},is:function(a){return this.length>0&&A.matches(this[0],a)},not:function(b){var d=[];if(F(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):L(b)&&F(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return I(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!I(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!I(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(A.qsa(this[0],a)):b=this.map(function(){return A.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:A.matches(d,a)))d=d!==b&&!H(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!H(a)&&b.indexOf(a)<0)return b.push(a),a});return U(b,a)},parent:function(a){return U(C(this.pluck("parentNode")),a)},children:function(a){return U(this.map(function(){return S(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return U(this.map(function(a,b){return g.call(S(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=null),k(this,"").getPropertyValue("display")=="none"&&(this.style.display=R(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=F(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=F(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(b){return b===a?this.length>0?this[0].innerHTML:null:this.each(function(a){var d=this.innerHTML;c(this).empty().append(V(this,b,a,d))})},text:function(b){return b===a?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(I(c))for(b in c)W(this,b,c[b]);else W(this,c,V(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&W(this,a)})},prop:function(b,c){return c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=V(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+O(b),c);return d!==null?Y(d):a},val:function(b){return b===a?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(a){return this.selected}).pluck("value"):this[0].value):this.each(function(a){this.value=V(this,b,a,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=V(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,c){if(arguments.length<2&&typeof a=="string")return this[0]&&(this[0].style[B(a)]||k(this[0],"").getPropertyValue(a));var d="";if(E(a)=="string")!c&&c!==0?this.each(function(){this.style.removeProperty(O(a))}):d=O(a)+":"+Q(a,c);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(O(b))}):d+=O(b)+":"+Q(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+d})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return e.some.call(this,function(a){return this.test(X(a))},P(a))},addClass:function(a){return this.each(function(b){d=[];var e=X(this),f=V(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&X(this,e+(e?" ":"")+d.join(" "))})},removeClass:function(b){return this.each(function(c){if(b===a)return X(this,"");d=X(this),V(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(P(a)," ")}),X(this,d.trim())})},toggleClass:function(b,d){return this.each(function(e){var f=c(this),g=V(this,b,e,X(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})})},scrollTop:function(){if(!this.length)return;return"scrollTop"in this[0]?this[0].scrollTop:this[0].scrollY},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){c.fn[b]=function(d){var e,f=this[0],g=b.replace(/./,function(a){return a[0].toUpperCase()});return d===a?G(f)?f["inner"+g]:H(f)?f.documentElement["offset"+g]:(e=this.offset())&&e[b]:this.each(function(a){f=c(this),f.css(b,V(this,d,a,f[b]()))})}}),q.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=E(b),a=="object"||a=="array"||b==null?b:A.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();Z(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),A.Z.prototype=c.fn,A.uniq=C,A.deserializeValue=Y,c.zepto=A,c}();window.Zepto=Zepto,"$"in window||(window.$=Zepto),function(a){function b(a){var b=this.os={},c=this.browser={},d=a.match(/WebKit\/([\d.]+)/),e=a.match(/(Android)\s+([\d.]+)/),f=a.match(/(iPad).*OS\s([\d_]+)/),g=!f&&a.match(/(iPhone\sOS)\s([\d_]+)/),h=a.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),i=h&&a.match(/TouchPad/),j=a.match(/Kindle\/([\d.]+)/),k=a.match(/Silk\/([\d._]+)/),l=a.match(/(BlackBerry).*Version\/([\d.]+)/),m=a.match(/(BB10).*Version\/([\d.]+)/),n=a.match(/(RIM\sTablet\sOS)\s([\d.]+)/),o=a.match(/PlayBook/),p=a.match(/Chrome\/([\d.]+)/)||a.match(/CriOS\/([\d.]+)/),q=a.match(/Firefox\/([\d.]+)/);if(c.webkit=!!d)c.version=d[1];e&&(b.android=!0,b.version=e[2]),g&&(b.ios=b.iphone=!0,b.version=g[2].replace(/_/g,".")),f&&(b.ios=b.ipad=!0,b.version=f[2].replace(/_/g,".")),h&&(b.webos=!0,b.version=h[2]),i&&(b.touchpad=!0),l&&(b.blackberry=!0,b.version=l[2]),m&&(b.bb10=!0,b.version=m[2]),n&&(b.rimtabletos=!0,b.version=n[2]),o&&(c.playbook=!0),j&&(b.kindle=!0,b.version=j[1]),k&&(c.silk=!0,c.version=k[1]),!k&&b.android&&a.match(/Kindle Fire/)&&(c.silk=!0),p&&(c.chrome=!0,c.version=p[1]),q&&(c.firefox=!0,c.version=q[1]),b.tablet=!!(f||o||e&&!a.match(/Mobile/)||q&&a.match(/Tablet/)),b.phone=!b.tablet&&!!(e||g||h||l||m||p&&a.match(/Android/)||p&&a.match(/CriOS\/([\d.]+)/)||q&&a.match(/Mobile/))}b.call(a,navigator.userAgent),a.__detect=b}(Zepto),function(a){function g(a){return a._zid||(a._zid=d++)}function h(a,b,d,e){b=i(b);if(b.ns)var f=j(b.ns);return(c[g(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||f.test(a.ns))&&(!d||g(a.fn)===g(d))&&(!e||a.sel==e)})}function i(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function j(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function k(b,c,d){a.type(b)!="string"?a.each(b,d):b.split(/\s/).forEach(function(a){d(a,c)})}function l(a,b){return a.del&&(a.e=="focus"||a.e=="blur")||!!b}function m(a){return f[a]||a}function n(b,d,e,h,j,n){var o=g(b),p=c[o]||(c[o]=[]);k(d,e,function(c,d){var e=i(c);e.fn=d,e.sel=h,e.e in f&&(d=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return e.fn.apply(this,arguments)}),e.del=j&&j(d,c);var g=e.del||d;e.proxy=function(a){var c=g.apply(b,[a].concat(a.data));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},e.i=p.length,p.push(e),b.addEventListener(m(e.e),e.proxy,l(e,n))})}function o(a,b,d,e,f){var i=g(a);k(b||"",d,function(b,d){h(a,b,d,e).forEach(function(b){delete c[i][b.i],a.removeEventListener(m(b.e),b.proxy,l(b,f))})})}function t(b){var c,d={originalEvent:b};for(c in b)!r.test(c)&&b[c]!==undefined&&(d[c]=b[c]);return a.each(s,function(a,c){d[a]=function(){return this[c]=p,b[a].apply(b,arguments)},d[c]=q}),d}function u(a){if(!("defaultPrevented"in a)){a.defaultPrevented=!1;var b=a.preventDefault;a.preventDefault=function(){this.defaultPrevented=!0,b.call(this)}}}var b=a.zepto.qsa,c={},d=1,e={},f={mouseenter:"mouseover",mouseleave:"mouseout"};e.click=e.mousedown=e.mouseup=e.mousemove="MouseEvents",a.event={add:n,remove:o},a.proxy=function(b,c){if(a.isFunction(b)){var d=function(){return b.apply(c,arguments)};return d._zid=g(b),d}if(typeof c=="string")return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b){return this.each(function(){n(this,a,b)})},a.fn.unbind=function(a,b){return this.each(function(){o(this,a,b)})},a.fn.one=function(a,b){return this.each(function(c,d){n(this,a,b,null,function(a,b){return function(){var c=a.apply(d,arguments);return o(d,b,a),c}})})};var p=function(){return!0},q=function(){return!1},r=/^([A-Z]|layer[XY]$)/,s={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(b,c,d){return this.each(function(e,f){n(f,c,d,b,function(c){return function(d){var e,g=a(d.target).closest(b,f).get(0);if(g)return e=a.extend(t(d),{currentTarget:g,liveFired:f}),c.apply(g,[e].concat([].slice.call(arguments,1)))}})})},a.fn.undelegate=function(a,b,c){return this.each(function(){o(this,b,c,a)})},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,d){return!c||a.isFunction(c)?this.bind(b,c||d):this.delegate(c,b,d)},a.fn.off=function(b,c,d){return!c||a.isFunction(c)?this.unbind(b,c||d):this.undelegate(c,b,d)},a.fn.trigger=function(b,c){if(typeof b=="string"||a.isPlainObject(b))b=a.Event(b);return u(b),b.data=c,this.each(function(){"dispatchEvent"in this&&this.dispatchEvent(b)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,g){d=t(typeof b=="string"?a.Event(b):b),d.data=c,d.target=g,a.each(h(g,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){typeof a!="string"&&(b=a,a=b.type);var c=document.createEvent(e[a]||"Events"),d=!0;if(b)for(var f in b)f=="bubbles"?d=!!b[f]:c[f]=b[f];return c.initEvent(a,d,!0,null,null,null,null,null,null,null,null,null,null,null,null),c.isDefaultPrevented=function(){return this.defaultPrevented},c}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.defaultPrevented}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c){var d=c.context,e="success";c.success.call(d,a,e,b),triggerGlobal(c,d,"ajaxSuccess",[b,c,a]),ajaxComplete(e,b,c)}function ajaxError(a,b,c,d){var e=d.context;d.error.call(e,c,b,a),triggerGlobal(d,e,"ajaxError",[c,d,a]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data))}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b);$.each(b,function(b,g){e=$.type(g),d&&(b=c?d:d+"["+(f?"":b)+"]"),!d&&f?a.add(g.name,g.value):e=="array"||!c&&e=="object"?serialize(a,g,c,b):a.add(b,g)})}var jsonpID=0,document=window.document,key,name,rscript=/)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a){if("type"in a){var b="jsonp"+ ++jsonpID,c=document.createElement("script"),d=function(){clearTimeout(g),$(c).remove(),delete window[b]},e=function(c){d();if(!c||c=="timeout")window[b]=empty;ajaxError(null,c||"abort",f,a)},f={abort:e},g;return ajaxBeforeSend(f,a)===!1?(e("abort"),!1):(window[b]=function(b){d(),ajaxSuccess(b,f,a)},c.onerror=function(){e("error")},c.src=a.url.replace(/=\?/,"="+b),$("head").append(c),a.timeout>0&&(g=setTimeout(function(){e("timeout")},a.timeout)),f)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{});for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,"callback=?")),$.ajaxJSONP(settings);var mime=settings.accepts[dataType],baseHeaders={},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),abortTimeout;settings.crossDomain||(baseHeaders["X-Requested-With"]="XMLHttpRequest"),mime&&(baseHeaders.Accept=mime,mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime));if(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")baseHeaders["Content-Type"]=settings.contentType||"application/x-www-form-urlencoded";settings.headers=$.extend(baseHeaders,settings.headers||{}),xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings):ajaxSuccess(result,xhr,settings)}else ajaxError(null,xhr.status?"error":"abort",xhr,settings)}};var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async);for(name in settings.headers)xhr.setRequestHeader(name,settings.headers[name]);return ajaxBeforeSend(xhr,settings)===!1?(xhr.abort(),!1):(settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr)},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("
").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a(Array.prototype.slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.defaultPrevented||this.get(0).submit()}return this}}(Zepto),function(a,b){function s(a){return t(a.replace(/([a-z])([A-Z])/,"$1-$2"))}function t(a){return a.toLowerCase()}function u(a){return d?d+a:t(a)}var c="",d,e,f,g={Webkit:"webkit",Moz:"",O:"o",ms:"MS"},h=window.document,i=h.createElement("div"),j=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,k,l,m,n,o,p,q,r={};a.each(g,function(a,e){if(i.style[a+"TransitionProperty"]!==b)return c="-"+t(a)+"-",d=e,!1}),k=c+"transform",r[l=c+"transition-property"]=r[m=c+"transition-duration"]=r[n=c+"transition-timing-function"]=r[o=c+"animation-name"]=r[p=c+"animation-duration"]=r[q=c+"animation-timing-function"]="",a.fx={off:d===b&&i.style.transitionProperty===b,speeds:{_default:400,fast:200,slow:600},cssPrefix:c,transitionEnd:u("TransitionEnd"),animationEnd:u("AnimationEnd")},a.fn.animate=function(b,c,d,e){return a.isPlainObject(c)&&(d=c.easing,e=c.complete,c=c.duration),c&&(c=(typeof c=="number"?c:a.fx.speeds[c]||a.fx.speeds._default)/1e3),this.anim(b,c,d,e)},a.fn.anim=function(c,d,e,f){var g,h={},i,t="",u=this,v,w=a.fx.transitionEnd;d===b&&(d=.4),a.fx.off&&(d=0);if(typeof c=="string")h[o]=c,h[p]=d+"s",h[q]=e||"linear",w=a.fx.animationEnd;else{i=[];for(g in c)j.test(g)?t+=g+"("+c[g]+") ":(h[g]=c[g],i.push(s(g)));t&&(h[k]=t,i.push(k)),d>0&&typeof c=="object"&&(h[l]=i.join(", "),h[m]=d+"s",h[n]=e||"linear")}return v=function(b){if(typeof b!="undefined"){if(b.target!==b.currentTarget)return;a(b.target).unbind(w,v)}a(this).css(r),f&&f.call(this)},d>0&&this.bind(w,v),this.size()&&this.get(0).clientLeft,this.css(h),d<=0&&setTimeout(function(){u.each(function(){v.call(this)})},0),this},i=null}(Zepto) diff --git a/libraries/Bridge/examples/TimeCheck/TimeCheck.ino b/libraries/Bridge/examples/TimeCheck/TimeCheck.ino new file mode 100644 index 000000000..af49b39ba --- /dev/null +++ b/libraries/Bridge/examples/TimeCheck/TimeCheck.ino @@ -0,0 +1,88 @@ +/* + Time Check + + Gets the time from Linux via Bridge then parses out hours, + minutes and seconds for the Arduino using an Arduino Yún. + + created 27 May 2013 + modified 21 June 2013 + By Tom Igoe + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/TimeCheck + + */ + + +#include + +Process date; // process used to get the date +int hours, minutes, seconds; // for the results +int lastSecond = -1; // need an impossible value for comparison + +void setup() { + Bridge.begin(); // initialize Bridge + SerialUSB.begin(9600); // initialize serial + + while (!Serial); // wait for Serial Monitor to open + SerialUSB.println("Time Check"); // Title of sketch + + // run an initial date process. Should return: + // hh:mm:ss : + if (!date.running()) { + date.begin("date"); + date.addParameter("+%T"); + date.run(); + } +} + +void loop() { + + if (lastSecond != seconds) { // if a second has passed + // print the time: + if (hours <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.print(hours); + SerialUSB.print(":"); + if (minutes <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.print(minutes); + SerialUSB.print(":"); + if (seconds <= 9) { + SerialUSB.print("0"); // adjust for 0-9 + } + SerialUSB.println(seconds); + + // restart the date process: + if (!date.running()) { + date.begin("date"); + date.addParameter("+%T"); + date.run(); + } + } + + //if there's a result from the date process, parse it: + while (date.available() > 0) { + // get the result of the date process (should be hh:mm:ss): + String timeString = date.readString(); + + // find the colons: + int firstColon = timeString.indexOf(":"); + int secondColon = timeString.lastIndexOf(":"); + + // get the substrings for hour, minute second: + String hourString = timeString.substring(0, firstColon); + String minString = timeString.substring(firstColon + 1, secondColon); + String secString = timeString.substring(secondColon + 1); + + // convert to ints,saving the previous second: + hours = hourString.toInt(); + minutes = minString.toInt(); + lastSecond = seconds; // save to do a time comparison + seconds = secString.toInt(); + } + +} diff --git a/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino b/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino new file mode 100644 index 000000000..556633ed7 --- /dev/null +++ b/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino @@ -0,0 +1,52 @@ +/* + WiFi Status + + This sketch runs a script called "pretty-wifi-info.lua" + installed on your Yún in folder /usr/bin. + It prints information about the status of your wifi connection. + + It uses Serial to print, so you need to connect your Yún to your + computer using a USB cable and select the appropriate port from + the Port menu + + created 18 June 2013 + By Federico Fissore + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunWiFiStatus + + */ + +#include + +void setup() { + SerialUSB.begin(9600); // initialize serial communication + while (!SerialUSB); // do nothing until the serial monitor is opened + + SerialUSB.println("Starting bridge...\n"); + pinMode(13, OUTPUT); + digitalWrite(13, LOW); + Bridge.begin(); // make contact with the linux processor + digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready + + delay(2000); // wait 2 seconds +} + +void loop() { + Process wifiCheck; // initialize a new process + + wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua"); // command you want to run + + // while there's any characters coming back from the + // process, print them to the serial monitor: + while (wifiCheck.available() > 0) { + char c = wifiCheck.read(); + SerialUSB.print(c); + } + + SerialUSB.println(); + + delay(5000); +} + diff --git a/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino b/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino new file mode 100644 index 000000000..98566d240 --- /dev/null +++ b/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino @@ -0,0 +1,82 @@ +/* + Arduino Yún USB-to-Serial + + Allows you to use the Yún's 32U4 processor as a + serial terminal for the Linux side on the Yún. + + Upload this to an Arduino Yún via serial (not WiFi) then open + the serial monitor at 115200 to see the boot process of Linux. + You can also use the serial monitor as a basic command line + interface for Linux using this sketch. + + From the serial monitor the following commands can be issued: + + '~' followed by '0' -> Set the UART speed to 57600 baud + '~' followed by '1' -> Set the UART speed to 115200 baud + '~' followed by '2' -> Set the UART speed to 250000 baud + '~' followed by '3' -> Set the UART speed to 500000 baud + '~' followed by '~' -> Sends the bridge's shutdown command to + obtain the console. + + The circuit: + Arduino Yún + + created March 2013 + by Massimo Banzi + modified by Cristian Maglie + + This example code is in the public domain. + + http://www.arduino.cc/en/Tutorial/YunSerialTerminal + +*/ + +long linuxBaud = 250000; + +void setup() { + SERIAL_PORT_USBVIRTUAL.begin(115200); // open serial connection via USB-Serial + SERIAL_PORT_HARDWARE.begin(linuxBaud); // open serial connection to Linux +} + +boolean commandMode = false; + +void loop() { + // copy from USB-CDC to UART + int c = SERIAL_PORT_USBVIRTUAL.read(); // read from USB-CDC + if (c != -1) { // got anything? + if (commandMode == false) { // if we aren't in command mode... + if (c == '~') { // Tilde '~' key pressed? + commandMode = true; // enter in command mode + } else { + SERIAL_PORT_HARDWARE.write(c); // otherwise write char to UART + } + } else { // if we are in command mode... + if (c == '0') { // '0' key pressed? + SERIAL_PORT_HARDWARE.begin(57600); // set speed to 57600 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 57600"); + } else if (c == '1') { // '1' key pressed? + SERIAL_PORT_HARDWARE.begin(115200); // set speed to 115200 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 115200"); + } else if (c == '2') { // '2' key pressed? + SERIAL_PORT_HARDWARE.begin(250000); // set speed to 250000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 250000"); + } else if (c == '3') { // '3' key pressed? + SERIAL_PORT_HARDWARE.begin(500000); // set speed to 500000 + SERIAL_PORT_USBVIRTUAL.println("Speed set to 500000"); + } else if (c == '~') { // '~` key pressed? + SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command + SERIAL_PORT_USBVIRTUAL.println("Sending bridge's shutdown command"); + } else { // any other key pressed? + SERIAL_PORT_HARDWARE.write('~'); // write '~' to UART + SERIAL_PORT_HARDWARE.write(c); // write char to UART + } + commandMode = false; // in all cases exit from command mode + } + } + + // copy from UART to USB-CDC + c = SERIAL_PORT_HARDWARE.read(); // read from UART + if (c != -1) { // got anything? + SERIAL_PORT_USBVIRTUAL.write(c); // write to USB-CDC + } +} diff --git a/libraries/Bridge/keywords.txt b/libraries/Bridge/keywords.txt new file mode 100644 index 000000000..1f03feec5 --- /dev/null +++ b/libraries/Bridge/keywords.txt @@ -0,0 +1,90 @@ +####################################### +# Syntax Coloring Map For Bridge +####################################### + +####################################### +# Class (KEYWORD1) +####################################### + +Bridge KEYWORD1 YunBridgeLibrary +FileIO KEYWORD4 YunFileIOConstructor +FileSystem KEYWORD1 YunFileIOConstructor +Console KEYWORD1 YunConsoleConstructor +Process KEYWORD1 YunProcessConstructor +Mailbox KEYWORD1 YunMailboxConstructor +HttpClient KEYWORD1 YunHttpClientConstructor +YunServer KEYWORD1 YunServerConstructor +YunClient KEYWORD1 YunClientConstructor +BridgeServer KEYWORD1 YunServerConstructor +BridgeClient KEYWORD1 YunClientConstructor + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +# methods names in commond +begin KEYWORD2 +end KEYWORD2 +available KEYWORD2 +read KEYWORD2 +peek KEYWORD2 +write KEYWORD2 +flush KEYWORD2 +bool KEYWORD2 + +# Bridge Class +transfer KEYWORD2 +put KEYWORD2 +get KEYWORD2 + +# Console Class +buffer KEYWORD2 +noBuffer KEYWORD2 +connected KEYWORD2 + +# FileIO Class +File KEYWORD2 +BridgeFile KEYWORD2 +seek KEYWORD2 +position KEYWORD2 +size KEYWORD2 +close KEYWORD2 +name KEYWORD2 +isDirectory KEYWORD2 +openNextFile KEYWORD2 +rewindDirectory KEYWORD2 + +# Process Class +addParameter KEYWORD2 +runAsynchronously KEYWORD2 +run KEYWORD2 +running KEYWORD2 +exitValue KEYWORD2 +runShellCommand KEYWORD2 +runShellCommandAsynchronously KEYWORD2 + +# Mailbox Class +readMessage KEYWORD2 +writeMessage KEYWORD2 +writeJSON KEYWORD2 +message Available KEYWORD2 + +# HttpClient Class +getAsynchronously KEYWORD2 +ready KEYWORD2 +getResult KEYWORD2 + +# BridgeServer Class +accept KEYWORD2 +stop KEYWORD2 +connect KEYWORD2 +connected KEYWORD2 + + +####################################### +# Constants (LITERAL1) +####################################### + +FILE_READ LITERAL1 +FILE_WRITE LITERAL1 +FILE_APPEND LITERAL1 diff --git a/libraries/Bridge/library.properties b/libraries/Bridge/library.properties new file mode 100644 index 000000000..e356f1c6a --- /dev/null +++ b/libraries/Bridge/library.properties @@ -0,0 +1,10 @@ +name=Bridge +version=1.6.1 +author=Arduino +maintainer=Arduino +sentence=Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only. +paragraph=The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers. +category=Communication +url=http://www.arduino.cc/en/Reference/YunBridgeLibrary +architectures=* +dot_a_linkage=true diff --git a/libraries/Bridge/src/Bridge.cpp b/libraries/Bridge/src/Bridge.cpp new file mode 100644 index 000000000..02be3805e --- /dev/null +++ b/libraries/Bridge/src/Bridge.cpp @@ -0,0 +1,281 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "Bridge.h" + +BridgeClass::BridgeClass(Stream &_stream) : + index(0), stream(_stream), started(false), max_retries(0) { + // Empty +} + +void BridgeClass::begin() { + if (started) + return; + started = true; + + // Wait for U-boot to finish startup + do { + dropAll(); + delay(1000); + } while (stream.available() > 0); + + while (true) { + // Bridge interrupt: + // - Ask the bridge to close itself + uint8_t quit_cmd[] = {'X', 'X', 'X', 'X', 'X'}; + max_retries = 1; + transfer(quit_cmd, 5); + + // Bridge startup: + // - If the bridge is not running starts it safely + stream.print(CTRL_C); + delay(250); + stream.print(F("\n")); + delay(250); + stream.print(F("\n")); + delay(500); + // Wait for OpenWRT message + // "Press enter to activate console" + stream.print(F("run-bridge\n")); + delay(500); + dropAll(); + + // Reset the brigde to check if it is running + uint8_t cmd[] = {'X', 'X', '1', '0', '0'}; + uint8_t res[4]; + max_retries = 50; + uint16_t l = transfer(cmd, 5, res, 4); + if (l == TRANSFER_TIMEOUT) { + // Bridge didn't start... + // Maybe the board is starting-up? + + // Wait and retry + delay(1000); + continue; + } + if (res[0] != 0) + while (true); + + // Detect bridge version + if (l == 4) { + bridgeVersion = (res[1]-'0')*100 + (res[2]-'0')*10 + (res[3]-'0'); + } else { + // Bridge v1.0.0 didn't send any version info + bridgeVersion = 100; + } + + max_retries = 50; + return; + } +} + +void BridgeClass::put(const char *key, const char *value) { + // TODO: do it in a more efficient way + String cmd = "D"; + uint8_t res[1]; + cmd += key; + cmd += "\xFE"; + cmd += value; + transfer((uint8_t*)cmd.c_str(), cmd.length(), res, 1); +} + +unsigned int BridgeClass::get(const char *key, uint8_t *value, unsigned int maxlen) { + uint8_t cmd[] = {'d'}; + unsigned int l = transfer(cmd, 1, (uint8_t *)key, strlen(key), value, maxlen); + if (l < maxlen) + value[l] = 0; // Zero-terminate string + return l; +} + +#if defined(ARDUINO_ARCH_AVR) +// AVR use an optimized implementation of CRC +#include +#else +// Generic implementation for non-AVR architectures +uint16_t _crc_ccitt_update(uint16_t crc, uint8_t data) +{ + data ^= crc & 0xff; + data ^= data << 4; + return ((((uint16_t)data << 8) | ((crc >> 8) & 0xff)) ^ + (uint8_t)(data >> 4) ^ + ((uint16_t)data << 3)); +} +#endif + +void BridgeClass::crcUpdate(uint8_t c) { + CRC = _crc_ccitt_update(CRC, c); +} + +void BridgeClass::crcReset() { + CRC = 0xFFFF; +} + +void BridgeClass::crcWrite() { + stream.write((char)(CRC >> 8)); + stream.write((char)(CRC & 0xFF)); +} + +bool BridgeClass::crcCheck(uint16_t _CRC) { + return CRC == _CRC; +} + +uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + const uint8_t *buff3, uint16_t len3, + uint8_t *rxbuff, uint16_t rxlen) +{ + uint16_t len = len1 + len2 + len3; + uint8_t retries = 0; + for ( ; retries < max_retries; retries++, delay(100), dropAll() /* Delay for retransmission */) { + // Send packet + crcReset(); + stream.write((char)0xFF); // Start of packet (0xFF) + crcUpdate(0xFF); + stream.write((char)index); // Message index + crcUpdate(index); + stream.write((char)((len >> 8) & 0xFF)); // Message length (hi) + crcUpdate((len >> 8) & 0xFF); + stream.write((char)(len & 0xFF)); // Message length (lo) + crcUpdate(len & 0xFF); + for (uint16_t i = 0; i < len1; i++) { // Payload + stream.write((char)buff1[i]); + crcUpdate(buff1[i]); + } + for (uint16_t i = 0; i < len2; i++) { // Payload + stream.write((char)buff2[i]); + crcUpdate(buff2[i]); + } + for (uint16_t i = 0; i < len3; i++) { // Payload + stream.write((char)buff3[i]); + crcUpdate(buff3[i]); + } + crcWrite(); // CRC + + // Wait for ACK in 100ms + if (timedRead(100) != 0xFF) + continue; + crcReset(); + crcUpdate(0xFF); + + // Check packet index + if (timedRead(5) != index) + continue; + crcUpdate(index); + + // Recv len + int lh = timedRead(10); + if (lh < 0) + continue; + crcUpdate(lh); + int ll = timedRead(10); + if (ll < 0) + continue; + crcUpdate(ll); + uint16_t l = lh; + l <<= 8; + l += ll; + + // Recv data + for (uint16_t i = 0; i < l; i++) { + // Cut received data if rxbuffer is too small + if (i >= rxlen) + break; + int c = timedRead(5); + if (c < 0) + continue; + rxbuff[i] = c; + crcUpdate(c); + } + + // Check CRC + int crc_hi = timedRead(5); + if (crc_hi < 0) + continue; + int crc_lo = timedRead(5); + if (crc_lo < 0) + continue; + if (!crcCheck((crc_hi << 8) + crc_lo)) + continue; + + // Increase index + index++; + + // Return bytes received + if (l > rxlen) + return rxlen; + return l; + } + + // Max retries exceeded + return TRANSFER_TIMEOUT; +} + +int BridgeClass::timedRead(unsigned int timeout) { + int c; + unsigned long _startMillis = millis(); + do { + c = stream.read(); + if (c >= 0) return c; + } while (millis() - _startMillis < timeout); + return -1; // -1 indicates timeout +} + +void BridgeClass::dropAll() { + while (stream.available() > 0) { + stream.read(); + } +} + +#if defined(ARDUINO_ARCH_SAM) +#include +#endif + +#if defined(ARDUINO_ARCH_SAM) +void checkForRemoteSketchUpdate(uint8_t pin) { + // The host force pin LOW to signal that a new sketch is coming + pinMode(pin, INPUT_PULLUP); + delay(50); + if (digitalRead(pin) == LOW) { + initiateReset(1); + while (true) + ; // Wait for reset to SAM-BA + } + + // Restore in standard state + pinMode(pin, INPUT); +} +#else +void checkForRemoteSketchUpdate(uint8_t /* pin */) { + // Empty, bootloader is enough. +} +#endif + +// Bridge instance +#if defined(SERIAL_PORT_LINUXBRIDGE) +SerialBridgeClass Bridge(SERIAL_PORT_LINUXBRIDGE); +#elif defined(SERIAL_PORT_HARDWARE) +SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE); +#elif defined(SERIAL_PORT_HARDWARE_OPEN) +SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE_OPEN); +#elif defined(__AVR_ATmega32U4__) // Legacy fallback +// Leonardo variants (where HardwareSerial is Serial1) +SerialBridgeClass Bridge(Serial1); +#else +SerialBridgeClass Bridge(Serial); +#endif + diff --git a/libraries/Bridge/src/Bridge.h b/libraries/Bridge/src/Bridge.h new file mode 100644 index 000000000..63361f172 --- /dev/null +++ b/libraries/Bridge/src/Bridge.h @@ -0,0 +1,125 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef BRIDGE_H_ +#define BRIDGE_H_ + +#ifndef BRIDGE_BAUDRATE +#define BRIDGE_BAUDRATE 250000 +#endif + +#include +#include + +class BridgeClass { + public: + BridgeClass(Stream &_stream); + void begin(); + + // Methods to handle key/value datastore + void put(const char *key, const char *value); + void put(const String &key, const String &value) + { + put(key.c_str(), value.c_str()); + } + unsigned int get(const char *key, uint8_t *buff, unsigned int size); + unsigned int get(const char *key, char *value, unsigned int maxlen) + { + return get(key, reinterpret_cast(value), maxlen); + } + + // Trasnfer a frame (with error correction and response) + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + const uint8_t *buff3, uint16_t len3, + uint8_t *rxbuff, uint16_t rxlen); + // multiple inline versions of the same function to allow efficient frame concatenation + uint16_t transfer(const uint8_t *buff1, uint16_t len1) + { + return transfer(buff1, len1, NULL, 0); + } + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + uint8_t *rxbuff, uint16_t rxlen) + { + return transfer(buff1, len1, NULL, 0, rxbuff, rxlen); + } + uint16_t transfer(const uint8_t *buff1, uint16_t len1, + const uint8_t *buff2, uint16_t len2, + uint8_t *rxbuff, uint16_t rxlen) + { + return transfer(buff1, len1, buff2, len2, NULL, 0, rxbuff, rxlen); + } + + uint16_t getBridgeVersion() + { + return bridgeVersion; + } + + static const uint16_t TRANSFER_TIMEOUT = 0xFFFF; + + private: + uint8_t index; + int timedRead(unsigned int timeout); + void dropAll(); + uint16_t bridgeVersion; + + private: + void crcUpdate(uint8_t c); + void crcReset(); + void crcWrite(); + bool crcCheck(uint16_t _CRC); + uint16_t CRC; + + private: + static const char CTRL_C = 3; + Stream &stream; + bool started; + uint8_t max_retries; +}; + +// This subclass uses a serial port Stream +class SerialBridgeClass : public BridgeClass { + public: + SerialBridgeClass(HardwareSerial &_serial) + : BridgeClass(_serial), serial(_serial) { + // Empty + } + + void begin(unsigned long baudrate = BRIDGE_BAUDRATE) { + serial.begin(baudrate); + BridgeClass::begin(); + } + + private: + HardwareSerial &serial; +}; + +extern SerialBridgeClass Bridge; + +// Some microcrontrollers don't start the bootloader after a reset. +// This function is intended to let the microcontroller erase its +// flash after checking a specific signal coming from the external +// device without the need to press the erase button on the board. +// The purpose is to enable a software update that does not require +// a manual interaction with the board. +extern void checkForRemoteSketchUpdate(uint8_t pin = 7); + +#endif /* BRIDGE_H_ */ + +#include +#include diff --git a/libraries/Bridge/src/BridgeClient.cpp b/libraries/Bridge/src/BridgeClient.cpp new file mode 100644 index 000000000..72a172b23 --- /dev/null +++ b/libraries/Bridge/src/BridgeClient.cpp @@ -0,0 +1,173 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include + +BridgeClient::BridgeClient(uint8_t _h, BridgeClass &_b) : + bridge(_b), handle(_h), opened(true), buffered(0) { +} + +BridgeClient::BridgeClient(BridgeClass &_b) : + bridge(_b), handle(0), opened(false), buffered(0) { +} + +BridgeClient::~BridgeClient() { +} + +BridgeClient& BridgeClient::operator=(const BridgeClient &_x) { + opened = _x.opened; + handle = _x.handle; + return *this; +} + +void BridgeClient::stop() { + if (opened) { + uint8_t cmd[] = {'j', handle}; + bridge.transfer(cmd, 2); + } + opened = false; + buffered = 0; + readPos = 0; +} + +void BridgeClient::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'K', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +int BridgeClient::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +int BridgeClient::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int BridgeClient::read(uint8_t *buff, size_t size) { + size_t readed = 0; + do { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + return readed; + } + buff[readed++] = buffer[readPos++]; + buffered--; + } while (readed < size); + return readed; +} + +int BridgeClient::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +size_t BridgeClient::write(uint8_t c) { + if (!opened) + return 0; + uint8_t cmd[] = {'l', handle, c}; + bridge.transfer(cmd, 3); + return 1; +} + +size_t BridgeClient::write(const uint8_t *buf, size_t size) { + if (!opened) + return 0; + uint8_t cmd[] = {'l', handle}; + bridge.transfer(cmd, 2, buf, size, NULL, 0); + return size; +} + +void BridgeClient::flush() { +} + +uint8_t BridgeClient::connected() { + if (!opened) + return false; + // Client is "connected" if it has unread bytes + if (available()) + return true; + + uint8_t cmd[] = {'L', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return (res[0] == 1); +} + +int BridgeClient::connect(IPAddress ip, uint16_t port) { + String address; + address.reserve(18); + address += ip[0]; + address += '.'; + address += ip[1]; + address += '.'; + address += ip[2]; + address += '.'; + address += ip[3]; + return connect(address.c_str(), port); +} + +int BridgeClient::connect(const char *host, uint16_t port) { + uint8_t tmp[] = { + 'C', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); + if (l == 0) + return 0; + handle = res[0]; + + // wait for connection + uint8_t tmp2[] = { 'c', handle }; + uint8_t res2[1]; + while (true) { + bridge.transfer(tmp2, 2, res2, 1); + if (res2[0] == 0) + break; + delay(1); + } + opened = true; + + // check for successful connection + if (connected()) + return 1; + + stop(); + handle = 0; + return 0; +} + diff --git a/libraries/Bridge/src/BridgeClient.h b/libraries/Bridge/src/BridgeClient.h new file mode 100644 index 000000000..9dd3ffa91 --- /dev/null +++ b/libraries/Bridge/src/BridgeClient.h @@ -0,0 +1,70 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _BRIDGE_CLIENT_H_ +#define _BRIDGE_CLIENT_H_ + +#include +#include + +class BridgeClient : public Client { + public: + // Constructor with a user provided BridgeClass instance + BridgeClient(uint8_t _h, BridgeClass &_b = Bridge); + BridgeClient(BridgeClass &_b = Bridge); + ~BridgeClient(); + + // Stream methods + // (read message) + virtual int available(); + virtual int read(); + virtual int read(uint8_t *buf, size_t size); + virtual int peek(); + // (write response) + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual void flush(); + // TODO: add optimized function for block write + + virtual operator bool () { + return opened; + } + + BridgeClient& operator=(const BridgeClient &_x); + + virtual void stop(); + virtual uint8_t connected(); + + virtual int connect(IPAddress ip, uint16_t port); + virtual int connect(const char *host, uint16_t port); + + private: + BridgeClass &bridge; + uint8_t handle; + boolean opened; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + +}; + +#endif // _BRIDGE_CLIENT_H_ diff --git a/libraries/Bridge/src/BridgeServer.cpp b/libraries/Bridge/src/BridgeServer.cpp new file mode 100644 index 000000000..a7aa9b0ae --- /dev/null +++ b/libraries/Bridge/src/BridgeServer.cpp @@ -0,0 +1,54 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include + +BridgeServer::BridgeServer(uint16_t _p, BridgeClass &_b) : + bridge(_b), port(_p), listening(false), useLocalhost(false) { +} + +void BridgeServer::begin() { + uint8_t tmp[] = { + 'N', + static_cast(port >> 8), + static_cast(port) + }; + uint8_t res[1]; + String address = F("127.0.0.1"); + if (!useLocalhost) + address = F("0.0.0.0"); + bridge.transfer(tmp, 3, (const uint8_t *)address.c_str(), address.length(), res, 1); + listening = (res[0] == 1); +} + +BridgeClient BridgeServer::accept() { + uint8_t cmd[] = {'k'}; + uint8_t res[1]; + unsigned int l = bridge.transfer(cmd, 1, res, 1); + if (l == 0) + return BridgeClient(); + return BridgeClient(res[0]); +} + +size_t BridgeServer::write(uint8_t c) { + uint8_t cmd[] = { 'b', c }; + bridge.transfer(cmd, 2); + return 1; +} + diff --git a/libraries/Bridge/src/BridgeServer.h b/libraries/Bridge/src/BridgeServer.h new file mode 100644 index 000000000..676a9729b --- /dev/null +++ b/libraries/Bridge/src/BridgeServer.h @@ -0,0 +1,51 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _BRIDGE_SERVER_H_ +#define _BRIDGE_SERVER_H_ + +#include +#include + +class BridgeClient; + +class BridgeServer : public Server { + public: + // Constructor with a user provided BridgeClass instance + BridgeServer(uint16_t port = 5555, BridgeClass &_b = Bridge); + + void begin(); + BridgeClient accept(); + + virtual size_t write(uint8_t c); + + void listenOnLocalhost() { + useLocalhost = true; + } + void noListenOnLocalhost() { + useLocalhost = false; + } + + private: + BridgeClass &bridge; + uint16_t port; + bool listening; + bool useLocalhost; +}; + +#endif // _BRIDGE_SERVER_H_ diff --git a/libraries/Bridge/src/BridgeUdp.cpp b/libraries/Bridge/src/BridgeUdp.cpp new file mode 100644 index 000000000..ae630e3ab --- /dev/null +++ b/libraries/Bridge/src/BridgeUdp.cpp @@ -0,0 +1,198 @@ +/* + Copyright (c) 2015 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "BridgeUdp.h" + +BridgeUDP::BridgeUDP(BridgeClass &_b) : + bridge(_b), opened(false), avail(0), buffered(0), readPos(0) { +} + +/* Start BridgeUDP socket, listening at local port PORT */ +uint8_t BridgeUDP::begin(uint16_t port) { + if (opened) + return 0; + uint8_t cmd[] = {'e', (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[2]; + bridge.transfer(cmd, 3, res, 2); + if (res[1] == 1) // Error... + return 0; + handle = res[0]; + opened = true; + return 1; +} + +/* Release any resources being used by this BridgeUDP instance */ +void BridgeUDP::stop() +{ + if (!opened) + return; + uint8_t cmd[] = {'q', handle}; + bridge.transfer(cmd, 2); + opened = false; +} + +int BridgeUDP::beginPacket(const char *host, uint16_t port) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'E', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[1]; + bridge.transfer(cmd, 4, (const uint8_t *)host, strlen(host), res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::beginBroadcastPacket(uint16_t port) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'v', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; + uint8_t res[1]; + bridge.transfer(cmd, 4, res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::beginPacket(IPAddress ip, uint16_t port) +{ + if (!opened) + return 0; + String address; + address.reserve(18); + address += ip[0]; + address += '.'; + address += ip[1]; + address += '.'; + address += ip[2]; + address += '.'; + address += ip[3]; + return beginPacket(address.c_str(), port); +} + +int BridgeUDP::endPacket() +{ + if (!opened) + return 0; + uint8_t cmd[] = {'H', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return res[0]; // 1=Success, 0=Error +} + +size_t BridgeUDP::write(const uint8_t *buffer, size_t size) +{ + if (!opened) + return 0; + uint8_t cmd[] = {'h', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, buffer, size, res, 1); + return res[0]; // 1=Success, 0=Error +} + +int BridgeUDP::parsePacket() +{ + if (!opened) + return 0; + buffered = 0; + readPos = 0; + uint8_t cmd[] = {'Q', handle}; + uint8_t res[3]; + bridge.transfer(cmd, 2, res, 3); + if (res[0] == 0) { + // There aren't any packets available + return 0; + } + avail = (res[1] << 8) + res[2]; + return 1; +} + +void BridgeUDP::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + if (avail == 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'u', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +int BridgeUDP::read() +{ + if (!opened) + return -1; + doBuffer(); + if (buffered == 0) { + return -1; // no chars available + } + buffered--; + avail--; + return buffer[readPos++]; +} + +int BridgeUDP::read(unsigned char* buff, size_t size) +{ + if (!opened) + return -1; + size_t readed = 0; + do { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + return readed; + } + buff[readed++] = buffer[readPos++]; + buffered--; + avail--; + } while (readed < size); + return readed; +} + +int BridgeUDP::peek() +{ + if (!opened) + return -1; + doBuffer(); + if (buffered == 0) + return -1; // no chars available + return buffer[readPos]; +} + +IPAddress BridgeUDP::remoteIP() +{ + if (!opened) + return -1; + uint8_t cmd[] = {'T', handle}; + uint8_t res[7]; + bridge.transfer(cmd, 2, res, 7); + if (res[0] == 0) + return IPAddress(0,0,0,0); + return IPAddress(res[1], res[2], res[3], res[4]); +} + +uint16_t BridgeUDP::remotePort() +{ + if (!opened) + return -1; + uint8_t cmd[] = {'T', handle}; + uint8_t res[7]; + bridge.transfer(cmd, 2, res, 7); + if (res[0] == 0) + return 0; + return (res[5] << 8) + res[6]; +} diff --git a/libraries/Bridge/src/BridgeUdp.h b/libraries/Bridge/src/BridgeUdp.h new file mode 100644 index 000000000..73cec54ea --- /dev/null +++ b/libraries/Bridge/src/BridgeUdp.h @@ -0,0 +1,65 @@ +/* + Copyright (c) 2015 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#pragma once + +#include +#include "Bridge.h" + +class BridgeUDP : public UDP { + + public: + BridgeUDP(BridgeClass &_b = Bridge); + virtual uint8_t begin(uint16_t); + virtual void stop(); + + virtual int beginPacket(IPAddress ip, uint16_t port); + virtual int beginPacket(const char *host, uint16_t port); + virtual int beginBroadcastPacket(uint16_t port); + virtual int endPacket(); + virtual size_t write(uint8_t d) { return write(&d, 1); } + virtual size_t write(const uint8_t *buffer, size_t size); + + using Print::write; + + virtual int parsePacket(); + /* return number of bytes available in the current packet, + will return zero if parsePacket hasn't been called yet */ + virtual int available() { return avail; } + virtual int read(); + virtual int read(unsigned char* buffer, size_t len); + virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; + virtual int peek(); + virtual void flush() { avail = 0; } + + virtual IPAddress remoteIP(); + virtual uint16_t remotePort(); + + private: + BridgeClass &bridge; + uint8_t handle; + boolean opened; + + private: + void doBuffer(); + uint16_t avail; + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; +}; diff --git a/libraries/Bridge/src/Console.cpp b/libraries/Bridge/src/Console.cpp new file mode 100644 index 000000000..7e8323d45 --- /dev/null +++ b/libraries/Bridge/src/Console.cpp @@ -0,0 +1,150 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include + +// Default constructor uses global Bridge instance +ConsoleClass::ConsoleClass() : + bridge(Bridge), inBuffered(0), inReadPos(0), inBuffer(NULL), + autoFlush(true) +{ + // Empty +} + +// Constructor with a user provided BridgeClass instance +ConsoleClass::ConsoleClass(BridgeClass &_b) : + bridge(_b), inBuffered(0), inReadPos(0), inBuffer(NULL), + autoFlush(true) +{ + // Empty +} + +ConsoleClass::~ConsoleClass() { + end(); +} + +size_t ConsoleClass::write(uint8_t c) { + if (autoFlush) { + uint8_t tmp[] = { 'P', c }; + bridge.transfer(tmp, 2); + } else { + outBuffer[outBuffered++] = c; + if (outBuffered == outBufferSize) + flush(); + } + return 1; +} + +size_t ConsoleClass::write(const uint8_t *buff, size_t size) { + if (autoFlush) { + uint8_t tmp[] = { 'P' }; + bridge.transfer(tmp, 1, buff, size, NULL, 0); + } else { + size_t sent = size; + while (sent > 0) { + outBuffer[outBuffered++] = *buff++; + sent--; + if (outBuffered == outBufferSize) + flush(); + } + } + return size; +} + +void ConsoleClass::flush() { + if (autoFlush) + return; + + bridge.transfer(outBuffer, outBuffered); + outBuffered = 1; +} + +void ConsoleClass::noBuffer() { + if (autoFlush) + return; + delete[] outBuffer; + autoFlush = true; +} + +void ConsoleClass::buffer(uint8_t size) { + noBuffer(); + if (size == 0) + return; + outBuffer = new uint8_t[size + 1]; + outBuffer[0] = 'P'; // WRITE tag + outBufferSize = size + 1; + outBuffered = 1; + autoFlush = false; +} + +bool ConsoleClass::connected() { + uint8_t tmp = 'a'; + bridge.transfer(&tmp, 1, &tmp, 1); + return tmp == 1; +} + +int ConsoleClass::available() { + // Look if there is new data available + doBuffer(); + return inBuffered; +} + +int ConsoleClass::read() { + doBuffer(); + if (inBuffered == 0) + return -1; // no chars available + else { + inBuffered--; + return inBuffer[inReadPos++]; + } +} + +int ConsoleClass::peek() { + doBuffer(); + if (inBuffered == 0) + return -1; // no chars available + else + return inBuffer[inReadPos]; +} + +void ConsoleClass::doBuffer() { + // If there are already char in buffer exit + if (inBuffered > 0) + return; + + // Try to buffer up to 32 characters + inReadPos = 0; + uint8_t tmp[] = { 'p', BUFFER_SIZE }; + inBuffered = bridge.transfer(tmp, 2, inBuffer, BUFFER_SIZE); +} + +void ConsoleClass::begin() { + bridge.begin(); + end(); + inBuffer = new uint8_t[BUFFER_SIZE]; +} + +void ConsoleClass::end() { + noBuffer(); + if (inBuffer) { + delete[] inBuffer; + inBuffer = NULL; + } +} + +ConsoleClass Console; diff --git a/libraries/Bridge/src/Console.h b/libraries/Bridge/src/Console.h new file mode 100644 index 000000000..ca05b08cf --- /dev/null +++ b/libraries/Bridge/src/Console.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef CONSOLE_H_ +#define CONSOLE_H_ + +#include + +class ConsoleClass : public Stream { + public: + // Default constructor uses global Bridge instance + ConsoleClass(); + // Constructor with a user provided BridgeClass instance + ConsoleClass(BridgeClass &_b); + ~ConsoleClass(); + + void begin(); + void end(); + + void buffer(uint8_t size); + void noBuffer(); + + bool connected(); + + // Stream methods + // (read from console socket) + int available(); + int read(); + int peek(); + // (write to console socket) + size_t write(uint8_t); + size_t write(const uint8_t *buffer, size_t size); + void flush(); + + operator bool () { + return connected(); + } + + private: + BridgeClass &bridge; + + void doBuffer(); + uint8_t inBuffered; + uint8_t inReadPos; + static const int BUFFER_SIZE = 32; + uint8_t *inBuffer; + + bool autoFlush; + uint8_t outBuffered; + uint8_t outBufferSize; + uint8_t *outBuffer; +}; + +extern ConsoleClass Console; + +#endif diff --git a/libraries/Bridge/src/FileIO.cpp b/libraries/Bridge/src/FileIO.cpp new file mode 100644 index 000000000..e24a56796 --- /dev/null +++ b/libraries/Bridge/src/FileIO.cpp @@ -0,0 +1,283 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include + +namespace BridgeLib { + +File::File(BridgeClass &b) : bridge(b), mode(255) { + // Empty +} + +File::File(const char *_filename, uint8_t _mode, BridgeClass &b) : bridge(b), mode(_mode) { + filename = _filename; + uint8_t modes[] = {'r', 'w', 'a'}; + uint8_t cmd[] = {'F', modes[mode]}; + uint8_t res[2]; + dirPosition = 1; + bridge.transfer(cmd, 2, (uint8_t*)filename.c_str(), filename.length(), res, 2); + if (res[0] != 0) { // res[0] contains error code + mode = 255; // In case of error keep the file closed + return; + } + handle = res[1]; + buffered = 0; +} + +File::operator bool() { + return (mode != 255); +} + +File::~File() { + close(); +} + +size_t File::write(uint8_t c) { + return write(&c, 1); +} + +size_t File::write(const uint8_t *buf, size_t size) { + if (mode == 255) + return -1; + uint8_t cmd[] = {'g', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, buf, size, res, 1); + if (res[0] != 0) // res[0] contains error code + return -res[0]; + return size; +} + +int File::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int File::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +boolean File::seek(uint32_t position) { + uint8_t cmd[] = { + 's', + handle, + static_cast(position >> 24), + static_cast(position >> 16), + static_cast(position >> 8), + static_cast(position) + }; + uint8_t res[1]; + bridge.transfer(cmd, 6, res, 1); + if (res[0] == 0) { + // If seek succeed then flush buffers + buffered = 0; + return true; + } + return false; +} + +uint32_t File::position() { + uint8_t cmd[] = {'S', handle}; + uint8_t res[5]; + bridge.transfer(cmd, 2, res, 5); + //err = res[0]; // res[0] contains error code + uint32_t pos; + pos = static_cast(res[1]) << 24; + pos += static_cast(res[2]) << 16; + pos += static_cast(res[3]) << 8; + pos += static_cast(res[4]); + return pos - buffered; +} + +void File::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to BUFFER_SIZE characters + readPos = 0; + uint8_t cmd[] = {'G', handle, BUFFER_SIZE - 1}; + uint16_t readed = bridge.transfer(cmd, 3, buffer, BUFFER_SIZE); + //err = buff[0]; // First byte is error code + if (readed == BridgeClass::TRANSFER_TIMEOUT || readed == 0) { + // transfer failed to retrieve any data + buffered = 0; + } else { + // transfer retrieved at least one byte of data so skip the error code character + readPos++; + buffered = readed - 1; + } +} + +int File::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +void File::flush() { +} + +int File::read(void *buff, uint16_t nbyte) { + uint16_t n = 0; + uint8_t *p = reinterpret_cast(buff); + while (n < nbyte) { + if (buffered == 0) { + doBuffer(); + if (buffered == 0) + break; + } + *p++ = buffer[readPos++]; + buffered--; + n++; + } + return n; +} + +uint32_t File::size() { + if (bridge.getBridgeVersion() < 101) + return 0; + uint8_t cmd[] = {'t', handle}; + uint8_t buff[5]; + bridge.transfer(cmd, 2, buff, 5); + //err = res[0]; // First byte is error code + uint32_t res; + res = ((uint32_t)buff[1]) << 24; + res |= ((uint32_t)buff[2]) << 16; + res |= ((uint32_t)buff[3]) << 8; + res |= ((uint32_t)buff[4]); + return res; +} + +void File::close() { + if (mode == 255) + return; + uint8_t cmd[] = {'f', handle}; + uint8_t ret[1]; + bridge.transfer(cmd, 2, ret, 1); + mode = 255; +} + +const char *File::name() { + return filename.c_str(); +} + + +boolean File::isDirectory() { + uint8_t res[1]; + uint8_t cmd[] = {'i'}; + if (mode != 255) + return 0; + + bridge.transfer(cmd, 1, (uint8_t *)filename.c_str(), filename.length(), res, 1); + return res[0]; +} + + +File File::openNextFile(uint8_t mode) { + Process awk; + char tmp; + String command; + String filepath; + if (dirPosition == 0xFFFF) return File(); + + command = "ls "; + command += filename; + command += " | awk 'NR=="; + command += dirPosition; + command += "'"; + + awk.runShellCommand(command); + + while (awk.running()); + + command = ""; + + while (awk.available()) { + tmp = awk.read(); + if (tmp != '\n') command += tmp; + } + if (command.length() == 0) + return File(); + dirPosition++; + filepath = filename + "/" + command; + return File(filepath.c_str(), mode); + +} + +void File::rewindDirectory(void) { + dirPosition = 1; +} + + + + + + +boolean FileSystemClass::begin() { + return true; +} + +File FileSystemClass::open(const char *filename, uint8_t mode) { + return File(filename, mode); +} + +boolean FileSystemClass::exists(const char *filepath) { + Process ls; + ls.begin("ls"); + ls.addParameter(filepath); + int res = ls.run(); + return (res == 0); +} + +boolean FileSystemClass::mkdir(const char *filepath) { + Process mk; + mk.begin("mkdir"); + mk.addParameter("-p"); + mk.addParameter(filepath); + int res = mk.run(); + return (res == 0); +} + +boolean FileSystemClass::remove(const char *filepath) { + Process rm; + rm.begin("rm"); + rm.addParameter(filepath); + int res = rm.run(); + return (res == 0); +} + +boolean FileSystemClass::rmdir(const char *filepath) { + Process rm; + rm.begin("rmdir"); + rm.addParameter(filepath); + int res = rm.run(); + return (res == 0); +} + +FileSystemClass FileSystem; + +} diff --git a/libraries/Bridge/src/FileIO.h b/libraries/Bridge/src/FileIO.h new file mode 100644 index 000000000..c5a8e9eac --- /dev/null +++ b/libraries/Bridge/src/FileIO.h @@ -0,0 +1,120 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef __FILEIO_H__ +#define __FILEIO_H__ + +#include + +#define FILE_READ 0 +#define FILE_WRITE 1 +#define FILE_APPEND 2 + +namespace BridgeLib { + +class File : public Stream { + + public: + File(BridgeClass &b = Bridge); + File(const char *_filename, uint8_t _mode, BridgeClass &b = Bridge); + ~File(); + + virtual size_t write(uint8_t); + virtual size_t write(const uint8_t *buf, size_t size); + virtual int read(); + virtual int peek(); + virtual int available(); + virtual void flush(); + int read(void *buf, uint16_t nbyte); + boolean seek(uint32_t pos); + uint32_t position(); + uint32_t size(); + void close(); + operator bool(); + const char * name(); + boolean isDirectory(); + File openNextFile(uint8_t mode = FILE_READ); + void rewindDirectory(void); + + //using Print::write; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + uint16_t dirPosition; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + + + private: + BridgeClass &bridge; + String filename; + uint8_t mode; + uint8_t handle; + +}; + +class FileSystemClass { + public: + FileSystemClass() : bridge(Bridge) { } + FileSystemClass(BridgeClass &_b) : bridge(_b) { } + + boolean begin(); + + // Open the specified file/directory with the supplied mode (e.g. read or + // write, etc). Returns a File object for interacting with the file. + // Note that currently only one file can be open at a time. + File open(const char *filename, uint8_t mode = FILE_READ); + + // Methods to determine if the requested file path exists. + boolean exists(const char *filepath); + + // Create the requested directory hierarchy--if intermediate directories + // do not exist they will be created. + boolean mkdir(const char *filepath); + + // Delete the file. + boolean remove(const char *filepath); + + boolean rmdir(const char *filepath); + + private: + friend class File; + + BridgeClass &bridge; +}; + +extern FileSystemClass FileSystem; + +}; + +// We enclose File and FileSystem classes in namespace BridgeLib to avoid +// conflicts with legacy SD library. + +// This ensure compatibility with older sketches that uses only Bridge lib +// (the user can still use File instead of BridgeFile) +using namespace BridgeLib; + +// This allows sketches to use BridgeLib::File together with SD library +// (you must use BridgeFile instead of File when needed to disambiguate) +typedef BridgeLib::File BridgeFile; +typedef BridgeLib::FileSystemClass BridgeFileSystemClass; +#define BridgeFileSystem BridgeLib::FileSystem + +#endif diff --git a/libraries/Bridge/src/HttpClient.cpp b/libraries/Bridge/src/HttpClient.cpp new file mode 100644 index 000000000..ee1629cc3 --- /dev/null +++ b/libraries/Bridge/src/HttpClient.cpp @@ -0,0 +1,204 @@ +/* + Copyright (c) 2013-2014 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "HttpClient.h" + +HttpClient::HttpClient() : + insecure(false) { + // Empty +} + +unsigned int HttpClient::get(String &url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + return run(); +} + +unsigned int HttpClient::get(const char *url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::getAsynchronously(String &url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + runAsynchronously(); +} + +void HttpClient::getAsynchronously(const char *url) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::post(String &url, String &data) { + return post(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::post(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("POST"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::postAsynchronously(String &url, String &data) { + postAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::postAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("POST"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::patch(String &url, String &data) { + return patch(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::patch(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PATCH"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::patchAsynchronously(String &url, String &data) { + patchAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::patchAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PATCH"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +unsigned int HttpClient::put(String &url, String &data) { + return put(url.c_str(), data.c_str()); +} + +unsigned int HttpClient::put(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PUT"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + return run(); +} + +void HttpClient::putAsynchronously(String &url, String &data) { + putAsynchronously(url.c_str(), data.c_str()); +} + +void HttpClient::putAsynchronously(const char *url, const char *data) { + begin("curl"); + if (insecure) { + addParameter("-k"); + } + addParameter("--request"); + addParameter("PUT"); + addParameter("--data"); + addParameter(data); + addHeader(); + addParameter(url); + runAsynchronously(); +} + +boolean HttpClient::ready() { + return !running(); +} + +unsigned int HttpClient::getResult() { + return exitValue(); +} + +void HttpClient::noCheckSSL() { + insecure = true; +} + +void HttpClient::checkSSL() { + insecure = false; +} + +void HttpClient::setHeader(String &header) { + this->header = header; +} + +void HttpClient::setHeader(const char * header) { + this->header = String(header); +} + +void HttpClient::addHeader() { + if (header.length() > 0) { + addParameter("--header"); + addParameter(header); + } +} + diff --git a/libraries/Bridge/src/HttpClient.h b/libraries/Bridge/src/HttpClient.h new file mode 100644 index 000000000..a6e3c77aa --- /dev/null +++ b/libraries/Bridge/src/HttpClient.h @@ -0,0 +1,59 @@ +/* + Copyright (c) 2013-2014 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef HTTPCLIENT_H_ +#define HTTPCLIENT_H_ + +#include + +class HttpClient : public Process { + public: + HttpClient(); + + unsigned int get(String &url); + unsigned int get(const char * url); + void getAsynchronously(String &url); + void getAsynchronously(const char * url); + unsigned int post(String &url, String &data); + unsigned int post(const char * url, const char * data); + void postAsynchronously(String &url, String &data); + void postAsynchronously(const char * url, const char * data); + unsigned int patch(String &url, String &data); + unsigned int patch(const char * url, const char * data); + void patchAsynchronously(String &url, String &data); + void patchAsynchronously(const char * url, const char * data); + unsigned int put(String &url, String &data); + unsigned int put(const char * url, const char * data); + void putAsynchronously(String &url, String &data); + void putAsynchronously(const char * url, const char * data); + void setHeader(String &header); + void setHeader(const char * header); + boolean ready(); + unsigned int getResult(); + void noCheckSSL(); + void checkSSL(); + + private: + boolean insecure; + + private: + void addHeader(); + String header; +}; + +#endif /* HTTPCLIENT_H_ */ diff --git a/libraries/Bridge/src/Mailbox.cpp b/libraries/Bridge/src/Mailbox.cpp new file mode 100644 index 000000000..0c571f73a --- /dev/null +++ b/libraries/Bridge/src/Mailbox.cpp @@ -0,0 +1,56 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include + +unsigned int MailboxClass::readMessage(uint8_t *buff, unsigned int size) { + uint8_t tmp[] = { 'm' }; + return bridge.transfer(tmp, 1, buff, size); +} + +void MailboxClass::readMessage(String &str, unsigned int maxLength) { + uint8_t tmp[] = { 'm' }; + // XXX: Is there a better way to create the string? + uint8_t buff[maxLength + 1]; + int l = bridge.transfer(tmp, 1, buff, maxLength); + buff[l] = 0; + str = (const char *)buff; +} + +void MailboxClass::writeMessage(const uint8_t *buff, unsigned int size) { + uint8_t cmd[] = {'M'}; + bridge.transfer(cmd, 1, buff, size, NULL, 0); +} + +void MailboxClass::writeMessage(const String& str) { + writeMessage((uint8_t*) str.c_str(), str.length()); +} + +void MailboxClass::writeJSON(const String& str) { + uint8_t cmd[] = {'J'}; + bridge.transfer(cmd, 1, (uint8_t*) str.c_str(), str.length(), NULL, 0); +} + +unsigned int MailboxClass::messageAvailable() { + uint8_t tmp[] = {'n'}; + uint8_t res[2]; + bridge.transfer(tmp, 1, res, 2); + return (res[0] << 8) + res[1]; +} + +MailboxClass Mailbox(Bridge); diff --git a/libraries/Bridge/src/Mailbox.h b/libraries/Bridge/src/Mailbox.h new file mode 100644 index 000000000..b2e383308 --- /dev/null +++ b/libraries/Bridge/src/Mailbox.h @@ -0,0 +1,53 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _MAILBOX_CLASS_H_INCLUDED_ +#define _MAILBOX_CLASS_H_INCLUDED_ + +#include + +class MailboxClass { + public: + MailboxClass(BridgeClass &b = Bridge) : bridge(b) { } + + void begin() { } + void end() { } + + // Receive a message and store it inside a buffer + unsigned int readMessage(uint8_t *buffer, unsigned int size); + // Receive a message and store it inside a String + void readMessage(String &str, unsigned int maxLength = 128); + + // Send a message + void writeMessage(const uint8_t *buffer, unsigned int size); + // Send a message + void writeMessage(const String& str); + // Send a JSON message + void writeJSON(const String& str); + + // Return the size of the next available message, 0 if there are + // no messages in queue. + unsigned int messageAvailable(); + + private: + BridgeClass &bridge; +}; + +extern MailboxClass Mailbox; + +#endif // _MAILBOX_CLASS_H_INCLUDED_ diff --git a/libraries/Bridge/src/Process.cpp b/libraries/Bridge/src/Process.cpp new file mode 100644 index 000000000..987f0b8ac --- /dev/null +++ b/libraries/Bridge/src/Process.cpp @@ -0,0 +1,142 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include + +Process::~Process() { + close(); +} + +size_t Process::write(uint8_t c) { + uint8_t cmd[] = {'I', handle, c}; + bridge.transfer(cmd, 3); + return 1; +} + +void Process::flush() { +} + +int Process::available() { + // Look if there is new data available + doBuffer(); + return buffered; +} + +int Process::read() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else { + buffered--; + return buffer[readPos++]; + } +} + +int Process::peek() { + doBuffer(); + if (buffered == 0) + return -1; // no chars available + else + return buffer[readPos]; +} + +void Process::doBuffer() { + // If there are already char in buffer exit + if (buffered > 0) + return; + + // Try to buffer up to 32 characters + readPos = 0; + uint8_t cmd[] = {'O', handle, sizeof(buffer)}; + buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); +} + +void Process::begin(const String &command) { + close(); + cmdline = new String(command); +} + +void Process::addParameter(const String ¶m) { + *cmdline += "\xFE"; + *cmdline += param; +} + +void Process::runAsynchronously() { + uint8_t cmd[] = {'R'}; + uint8_t res[2]; + bridge.transfer(cmd, 1, (uint8_t*)cmdline->c_str(), cmdline->length(), res, 2); + handle = res[1]; + + delete cmdline; + cmdline = NULL; + + if (res[0] == 0) // res[0] contains error code + started = true; +} + +boolean Process::running() { + uint8_t cmd[] = {'r', handle}; + uint8_t res[1]; + bridge.transfer(cmd, 2, res, 1); + return (res[0] == 1); +} + +unsigned int Process::exitValue() { + uint8_t cmd[] = {'W', handle}; + uint8_t res[2]; + bridge.transfer(cmd, 2, res, 2); + return (res[0] << 8) + res[1]; +} + +unsigned int Process::run() { + runAsynchronously(); + while (running()) + delay(100); + return exitValue(); +} + +void Process::close() { + if (started) { + uint8_t cmd[] = {'w', handle}; + bridge.transfer(cmd, 2); + } + started = false; +} + +unsigned int Process::runShellCommand(const String &command) { + runShellCommandAsynchronously(command); + while (running()) + delay(100); + return exitValue(); +} + +void Process::runShellCommandAsynchronously(const String &command) { + begin("/bin/ash"); + addParameter("-c"); + addParameter(command); + runAsynchronously(); +} + +// This method is currently unused +//static unsigned int __commandOutputAvailable(uint8_t handle) { +// uint8_t cmd[] = {'o', handle}; +// uint8_t res[1]; +// Bridge.transfer(cmd, 2, res, 1); +// return res[0]; +//} + diff --git a/libraries/Bridge/src/Process.h b/libraries/Bridge/src/Process.h new file mode 100644 index 000000000..7002764a0 --- /dev/null +++ b/libraries/Bridge/src/Process.h @@ -0,0 +1,71 @@ +/* + Copyright (c) 2013 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef PROCESS_H_ +#define PROCESS_H_ + +#include + +class Process : public Stream { + public: + // Constructor with a user provided BridgeClass instance + Process(BridgeClass &_b = Bridge) : + bridge(_b), started(false), buffered(0), readPos(0) { } + ~Process(); + + void begin(const String &command); + void addParameter(const String ¶m); + unsigned int run(); + void runAsynchronously(); + boolean running(); + unsigned int exitValue(); + void close(); + + unsigned int runShellCommand(const String &command); + void runShellCommandAsynchronously(const String &command); + + operator bool () { + return started; + } + + // Stream methods + // (read from process stdout) + int available(); + int read(); + int peek(); + // (write to process stdin) + size_t write(uint8_t); + void flush(); + // TODO: add optimized function for block write + + private: + BridgeClass &bridge; + uint8_t handle; + String *cmdline; + boolean started; + + private: + void doBuffer(); + uint8_t buffered; + uint8_t readPos; + static const int BUFFER_SIZE = 64; + uint8_t buffer[BUFFER_SIZE]; + +}; + +#endif diff --git a/libraries/Bridge/src/YunClient.h b/libraries/Bridge/src/YunClient.h new file mode 100644 index 000000000..faff247c9 --- /dev/null +++ b/libraries/Bridge/src/YunClient.h @@ -0,0 +1,27 @@ +/* + Copyright (c) 2014 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _YUN_CLIENT_H_ +#define _YUN_CLIENT_H_ + +#include + +#warning "The use of YunClient is deprecated. Use BridgeClient instead!" +typedef BridgeClient YunClient; + +#endif // _YUN_CLIENT_H_ diff --git a/libraries/Bridge/src/YunServer.h b/libraries/Bridge/src/YunServer.h new file mode 100644 index 000000000..95d05cd71 --- /dev/null +++ b/libraries/Bridge/src/YunServer.h @@ -0,0 +1,27 @@ +/* + Copyright (c) 2014 Arduino LLC. All right reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef _YUN_SERVER_H_ +#define _YUN_SERVER_H_ + +#include + +#warning "The use of YunServer is deprecated. Use BridgeServer instead!" +typedef BridgeServer YunServer; + +#endif // _YUN_SERVER_H_ diff --git a/libraries/Firmata/Boards.h b/libraries/Firmata/Boards.h new file mode 100644 index 000000000..e084f9cf8 --- /dev/null +++ b/libraries/Firmata/Boards.h @@ -0,0 +1,764 @@ +/* + Boards.h - Hardware Abstraction Layer for Firmata library + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2015 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated December 19th, 2015 +*/ + +#ifndef Firmata_Boards_h +#define Firmata_Boards_h + +#include + +#if defined(ARDUINO) && ARDUINO >= 100 +#include "Arduino.h" // for digitalRead, digitalWrite, etc +#else +#include "WProgram.h" +#endif + +// Normally Servo.h must be included before Firmata.h (which then includes +// this file). If Servo.h wasn't included, this allows the code to still +// compile, but without support for any Servos. Hopefully that's what the +// user intended by not including Servo.h +#ifndef MAX_SERVOS +#define MAX_SERVOS 0 +#endif + +/* + Firmata Hardware Abstraction Layer + +Firmata is built on top of the hardware abstraction functions of Arduino, +specifically digitalWrite, digitalRead, analogWrite, analogRead, and +pinMode. While these functions offer simple integer pin numbers, Firmata +needs more information than is provided by Arduino. This file provides +all other hardware specific details. To make Firmata support a new board, +only this file should require editing. + +The key concept is every "pin" implemented by Firmata may be mapped to +any pin as implemented by Arduino. Usually a simple 1-to-1 mapping is +best, but such mapping should not be assumed. This hardware abstraction +layer allows Firmata to implement any number of pins which map onto the +Arduino implemented pins in almost any arbitrary way. + + +General Constants: + +These constants provide basic information Firmata requires. + +TOTAL_PINS: The total number of pins Firmata implemented by Firmata. + Usually this will match the number of pins the Arduino functions + implement, including any pins pins capable of analog or digital. + However, Firmata may implement any number of pins. For example, + on Arduino Mini with 8 analog inputs, 6 of these may be used + for digital functions, and 2 are analog only. On such boards, + Firmata can implement more pins than Arduino's pinMode() + function, in order to accommodate those special pins. The + Firmata protocol supports a maximum of 128 pins, so this + constant must not exceed 128. + +TOTAL_ANALOG_PINS: The total number of analog input pins implemented. + The Firmata protocol allows up to 16 analog inputs, accessed + using offsets 0 to 15. Because Firmata presents the analog + inputs using different offsets than the actual pin numbers + (a legacy of Arduino's analogRead function, and the way the + analog input capable pins are physically labeled on all + Arduino boards), the total number of analog input signals + must be specified. 16 is the maximum. + +VERSION_BLINK_PIN: When Firmata starts up, it will blink the version + number. This constant is the Arduino pin number where a + LED is connected. + + +Pin Mapping Macros: + +These macros provide the mapping between pins as implemented by +Firmata protocol and the actual pin numbers used by the Arduino +functions. Even though such mappings are often simple, pin +numbers received by Firmata protocol should always be used as +input to these macros, and the result of the macro should be +used with with any Arduino function. + +When Firmata is extended to support a new pin mode or feature, +a pair of macros should be added and used for all hardware +access. For simple 1:1 mapping, these macros add no actual +overhead, yet their consistent use allows source code which +uses them consistently to be easily adapted to all other boards +with different requirements. + +IS_PIN_XXXX(pin): The IS_PIN macros resolve to true or non-zero + if a pin as implemented by Firmata corresponds to a pin + that actually implements the named feature. + +PIN_TO_XXXX(pin): The PIN_TO macros translate pin numbers as + implemented by Firmata to the pin numbers needed as inputs + to the Arduino functions. The corresponding IS_PIN macro + should always be tested before using a PIN_TO macro, so + these macros only need to handle valid Firmata pin + numbers for the named feature. + + +Port Access Inline Funtions: + +For efficiency, Firmata protocol provides access to digital +input and output pins grouped by 8 bit ports. When these +groups of 8 correspond to actual 8 bit ports as implemented +by the hardware, these inline functions can provide high +speed direct port access. Otherwise, a default implementation +using 8 calls to digitalWrite or digitalRead is used. + +When porting Firmata to a new board, it is recommended to +use the default functions first and focus only on the constants +and macros above. When those are working, if optimized port +access is desired, these inline functions may be extended. +The recommended approach defines a symbol indicating which +optimization to use, and then conditional complication is +used within these functions. + +readPort(port, bitmask): Read an 8 bit port, returning the value. + port: The port number, Firmata pins port*8 to port*8+7 + bitmask: The actual pins to read, indicated by 1 bits. + +writePort(port, value, bitmask): Write an 8 bit port. + port: The port number, Firmata pins port*8 to port*8+7 + value: The 8 bit value to write + bitmask: The actual pins to write, indicated by 1 bits. +*/ + +/*============================================================================== + * Board Specific Configuration + *============================================================================*/ + +#ifndef digitalPinHasPWM +#define digitalPinHasPWM(p) IS_PIN_DIGITAL(p) +#endif + +// Arduino Duemilanove, Diecimila, and NG +#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) +#if defined(NUM_ANALOG_INPUTS) && NUM_ANALOG_INPUTS == 6 +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#else +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 22 // 14 digital + 8 analog +#endif +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) +#define ARDUINO_PINOUT_OPTIMIZE 1 + + +// Wiring (and board) +#elif defined(WIRING) +#define VERSION_BLINK_PIN WLED +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= FIRST_ANALOG_PIN && (p) < (FIRST_ANALOG_PIN+TOTAL_ANALOG_PINS)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - FIRST_ANALOG_PIN) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// old Arduinos +#elif defined(__AVR_ATmega8__) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) +#define ARDUINO_PINOUT_OPTIMIZE 1 + + +// Arduino Mega +#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) +#define TOTAL_ANALOG_PINS 16 +#define TOTAL_PINS 70 // 54 digital + 16 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 19 +#define PIN_SERIAL1_TX 18 +#define PIN_SERIAL2_RX 17 +#define PIN_SERIAL2_TX 16 +#define PIN_SERIAL3_RX 15 +#define PIN_SERIAL3_TX 14 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Arduino DUE +#elif defined(__SAM3X8E__) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 66 // 54 digital + 12 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 19 +#define PIN_SERIAL1_TX 18 +#define PIN_SERIAL2_RX 17 +#define PIN_SERIAL2_TX 16 +#define PIN_SERIAL3_RX 15 +#define PIN_SERIAL3_TX 14 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // 70 71 +#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Arduino/Genuino MKR1000 +#elif defined(ARDUINO_SAMD_MKR1000) +#define TOTAL_ANALOG_PINS 7 +#define TOTAL_PINS 22 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog +#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21) && !IS_PIN_SERIAL(p)) +#define IS_PIN_ANALOG(p) ((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 15) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Arduino Zero +// Note this will work with an Arduino Zero Pro, but not with an Arduino M0 Pro +// Arduino M0 Pro does not properly map pins to the board labeled pin numbers +#elif defined(_VARIANT_ARDUINO_ZERO_) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 25 // 14 digital + 6 analog + 2 i2c + 3 spi +#define TOTAL_PORTS 3 // set when TOTAL_PINS > num digitial I/O pins +#define VERSION_BLINK_PIN LED_BUILTIN +//#define PIN_SERIAL1_RX 0 // already defined in zero core variant.h +//#define PIN_SERIAL1_TX 1 // already defined in zero core variant.h +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // SDA = 20, SCL = 21 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) // SS = A2 +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Arduino 101 +#elif defined(_VARIANT_ARDUINO_101_X_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS +#define TOTAL_PINS NUM_DIGITAL_PINS // 15 digital (including ATN pin) + 6 analog +#define VERSION_BLINK_PIN LED_BUILTIN +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 20) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) // 3, 5, 6, 9 +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) // SDA = 18, SCL = 19 +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 + + +// Teensy 1.0 +#elif defined(__AVR_AT90USB162__) +#define TOTAL_ANALOG_PINS 0 +#define TOTAL_PINS 21 // 21 digital + no analog +#define VERSION_BLINK_PIN 6 +#define PIN_SERIAL1_RX 2 +#define PIN_SERIAL1_TX 3 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) (0) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) (0) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (0) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 2.0 +#elif defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 25 // 11 digital + 12 analog +#define VERSION_BLINK_PIN 11 +#define PIN_SERIAL1_RX 7 +#define PIN_SERIAL1_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 11 && (p) <= 22) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 5 || (p) == 6) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 7 || (p) == 8) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (((p) < 22) ? 21 - (p) : 11) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy 3.0, 3.1 and 3.2 +#elif defined(__MK20DX128__) || defined(__MK20DX256__) +#define TOTAL_ANALOG_PINS 14 +#define TOTAL_PINS 38 // 24 digital + 10 analog-digital + 4 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 33) +#define IS_PIN_ANALOG(p) (((p) >= 14 && (p) <= 23) || ((p) >= 34 && (p) <= 38)) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (((p) <= 23) ? (p) - 14 : (p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy-LC +#elif defined(__MKL26Z64__) +#define TOTAL_ANALOG_PINS 13 +#define TOTAL_PINS 27 // 27 digital + 13 analog-digital +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define PIN_SERIAL2_RX 9 +#define PIN_SERIAL2_TX 10 +#define PIN_SERIAL3_RX 7 +#define PIN_SERIAL3_TX 8 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 26) +#define IS_PIN_ANALOG(p) ((p) >= 14) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) +#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Teensy++ 1.0 and 2.0 +#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 46 // 38 digital + 8 analog +#define VERSION_BLINK_PIN 6 +#define PIN_SERIAL1_RX 2 +#define PIN_SERIAL1_TX 3 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 38 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 0 || (p) == 1) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 38) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Leonardo +#elif defined(__AVR_ATmega32U4__) +#define TOTAL_ANALOG_PINS 12 +#define TOTAL_PINS 30 // 14 digital + 12 analog + 4 SPI (D14-D17 on ISP header) +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 18 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) - 18 +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) (p) + + +// Intel Galileo Board (gen 1 and 2) and Intel Edison +#elif defined(ARDUINO_LINUX) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 20 // 14 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define PIN_SERIAL1_RX 0 +#define PIN_SERIAL1_TX 1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Sanguino +#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS 32 // 24 digital + 8 analog +#define VERSION_BLINK_PIN 0 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Illuminato +#elif defined(__AVR_ATmega645__) +#define TOTAL_ANALOG_PINS 6 +#define TOTAL_PINS 42 // 36 digital + 6 analog +#define VERSION_BLINK_PIN 13 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) +#define IS_PIN_ANALOG(p) ((p) >= 36 && (p) < TOTAL_PINS) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) +#define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 36) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + + +// Pic32 chipKIT FubarinoSD +#elif defined(_BOARD_FUBARINO_SD_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 15 +#define TOTAL_PINS NUM_DIGITAL_PINS // 45, All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) 1 +#define IS_PIN_ANALOG(p) ((p) >= 30 && (p) <= 44) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 1 || (p) == 2) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (14 - (p - 30)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT FubarinoMini +// Note, FubarinoMini analog pin 20 will not function in Firmata as analog input due to limitation in analog mapping +#elif defined(_BOARD_FUBARINO_MINI_) +#define TOTAL_ANALOG_PINS 14 // We have to fake this because of the poor analog pin mapping planning in FubarinoMini +#define TOTAL_PINS NUM_DIGITAL_PINS // 33 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) != 14 && (p) != 15 && (p) != 31 && (p) != 32) +#define IS_PIN_ANALOG(p) ((p) == 0 || ((p) >= 3 && (p) <= 13)) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 25 || (p) == 26) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT UNO32 +#elif defined(_BOARD_UNO_) && defined(__PIC32) // NOTE: no _BOARD_UNO32_ to use +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 +#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT DP32 +#elif defined(_BOARD_DP32_) +#define TOTAL_ANALOG_PINS 15 // Really only has 9, but have to override because of mistake in variant file +#define TOTAL_PINS NUM_DIGITAL_PINS // 19 +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) (((p) != 1) && ((p) != 4) && ((p) != 5) && ((p) != 15) && ((p) != 16)) +#define IS_PIN_ANALOG(p) ((p) >= 6 && (p) <= 14) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) (p) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT uC32 +#elif defined(_BOARD_UC32_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 +#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital +#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT WF32 +#elif defined(_BOARD_WF32_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS +#define TOTAL_PINS NUM_DIGITAL_PINS +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 49) // Accounts for SD and WiFi dedicated pins +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 14) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT WiFire +#elif defined(_BOARD_WIFIRE_) +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 14 +#define TOTAL_PINS NUM_DIGITAL_PINS // 71 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 47) // Accounts for SD and WiFi dedicated pins +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) <= 25 ? ((p) - 14) : (p) - 36) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT MAX32 +#elif defined(_BOARD_MEGA_) && defined(__PIC32) // NOTE: no _BOARD_MAX32_ to use +#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 16 +#define TOTAL_PINS NUM_DIGITAL_PINS // 87 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) ((p) >= 2) +#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) <= 69) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 54) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + + +// Pic32 chipKIT Pi +#elif defined(_BOARD_CHIPKIT_PI_) +#define TOTAL_ANALOG_PINS 16 +#define TOTAL_PINS NUM_DIGITAL_PINS // 19 +#define MAX_SERVOS NUM_DIGITAL_PINS +#define VERSION_BLINK_PIN PIN_LED1 +#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 3) || (((p) >= 8) && ((p) <= 13)) || (((p) >= 14) && ((p) <= 17))) +#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 17) +#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) <= 15 ? (p) - 14 : (p) - 12) +//#define PIN_TO_ANALOG(p) (((p) <= 16) ? ((p) - 14) : ((p) - 16)) +#define PIN_TO_PWM(p) (p) +#define PIN_TO_SERVO(p) (p) + +// Pinoccio Scout +// Note: digital pins 9-16 are usable but not labeled on the board numerically. +// SS=9, MOSI=10, MISO=11, SCK=12, RX1=13, TX1=14, SCL=15, SDA=16 +#elif defined(ARDUINO_PINOCCIO) +#define TOTAL_ANALOG_PINS 8 +#define TOTAL_PINS NUM_DIGITAL_PINS // 32 +#define VERSION_BLINK_PIN 23 +#define PIN_SERIAL1_RX 13 +#define PIN_SERIAL1_TX 14 +#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 16)) || (((p) >= 24) && ((p) <= 31)) +#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) <= 31) +#define IS_PIN_PWM(p) digitalPinHasPWM(p) +#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) +#define IS_PIN_I2C(p) ((p) == SCL || (p) == SDA) +#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) +#define IS_PIN_SERIAL(p) ((p) == 13 || (p) == 14) +#define PIN_TO_DIGITAL(p) (p) +#define PIN_TO_ANALOG(p) ((p) - 24) +#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) +#define PIN_TO_SERVO(p) ((p) - 2) + +// anything else +#else +#error "Please edit Boards.h with a hardware abstraction for this board" +#endif + +// as long this is not defined for all boards: +#ifndef IS_PIN_SPI +#define IS_PIN_SPI(p) 0 +#endif + +#ifndef IS_PIN_SERIAL +#define IS_PIN_SERIAL(p) 0 +#endif + + +/*============================================================================== + * readPort() - Read an 8 bit port + *============================================================================*/ + +static inline unsigned char readPort(byte, byte) __attribute__((always_inline, unused)); +static inline unsigned char readPort(byte port, byte bitmask) +{ +#if defined(ARDUINO_PINOUT_OPTIMIZE) + if (port == 0) return (PIND & 0xFC) & bitmask; // ignore Rx/Tx 0/1 + if (port == 1) return ((PINB & 0x3F) | ((PINC & 0x03) << 6)) & bitmask; + if (port == 2) return ((PINC & 0x3C) >> 2) & bitmask; + return 0; +#else + unsigned char out = 0, pin = port * 8; + if (IS_PIN_DIGITAL(pin + 0) && (bitmask & 0x01) && digitalRead(PIN_TO_DIGITAL(pin + 0))) out |= 0x01; + if (IS_PIN_DIGITAL(pin + 1) && (bitmask & 0x02) && digitalRead(PIN_TO_DIGITAL(pin + 1))) out |= 0x02; + if (IS_PIN_DIGITAL(pin + 2) && (bitmask & 0x04) && digitalRead(PIN_TO_DIGITAL(pin + 2))) out |= 0x04; + if (IS_PIN_DIGITAL(pin + 3) && (bitmask & 0x08) && digitalRead(PIN_TO_DIGITAL(pin + 3))) out |= 0x08; + if (IS_PIN_DIGITAL(pin + 4) && (bitmask & 0x10) && digitalRead(PIN_TO_DIGITAL(pin + 4))) out |= 0x10; + if (IS_PIN_DIGITAL(pin + 5) && (bitmask & 0x20) && digitalRead(PIN_TO_DIGITAL(pin + 5))) out |= 0x20; + if (IS_PIN_DIGITAL(pin + 6) && (bitmask & 0x40) && digitalRead(PIN_TO_DIGITAL(pin + 6))) out |= 0x40; + if (IS_PIN_DIGITAL(pin + 7) && (bitmask & 0x80) && digitalRead(PIN_TO_DIGITAL(pin + 7))) out |= 0x80; + return out; +#endif +} + +/*============================================================================== + * writePort() - Write an 8 bit port, only touch pins specified by a bitmask + *============================================================================*/ + +static inline unsigned char writePort(byte, byte, byte) __attribute__((always_inline, unused)); +static inline unsigned char writePort(byte port, byte value, byte bitmask) +{ +#if defined(ARDUINO_PINOUT_OPTIMIZE) + if (port == 0) { + bitmask = bitmask & 0xFC; // do not touch Tx & Rx pins + byte valD = value & bitmask; + byte maskD = ~bitmask; + cli(); + PORTD = (PORTD & maskD) | valD; + sei(); + } else if (port == 1) { + byte valB = (value & bitmask) & 0x3F; + byte valC = (value & bitmask) >> 6; + byte maskB = ~(bitmask & 0x3F); + byte maskC = ~((bitmask & 0xC0) >> 6); + cli(); + PORTB = (PORTB & maskB) | valB; + PORTC = (PORTC & maskC) | valC; + sei(); + } else if (port == 2) { + bitmask = bitmask & 0x0F; + byte valC = (value & bitmask) << 2; + byte maskC = ~(bitmask << 2); + cli(); + PORTC = (PORTC & maskC) | valC; + sei(); + } + return 1; +#else + byte pin = port * 8; + if ((bitmask & 0x01)) digitalWrite(PIN_TO_DIGITAL(pin + 0), (value & 0x01)); + if ((bitmask & 0x02)) digitalWrite(PIN_TO_DIGITAL(pin + 1), (value & 0x02)); + if ((bitmask & 0x04)) digitalWrite(PIN_TO_DIGITAL(pin + 2), (value & 0x04)); + if ((bitmask & 0x08)) digitalWrite(PIN_TO_DIGITAL(pin + 3), (value & 0x08)); + if ((bitmask & 0x10)) digitalWrite(PIN_TO_DIGITAL(pin + 4), (value & 0x10)); + if ((bitmask & 0x20)) digitalWrite(PIN_TO_DIGITAL(pin + 5), (value & 0x20)); + if ((bitmask & 0x40)) digitalWrite(PIN_TO_DIGITAL(pin + 6), (value & 0x40)); + if ((bitmask & 0x80)) digitalWrite(PIN_TO_DIGITAL(pin + 7), (value & 0x80)); + return 1; +#endif +} + + + + +#ifndef TOTAL_PORTS +#define TOTAL_PORTS ((TOTAL_PINS + 7) / 8) +#endif + + +#endif /* Firmata_Boards_h */ diff --git a/libraries/Firmata/Firmata.cpp b/libraries/Firmata/Firmata.cpp new file mode 100644 index 000000000..5e5d4b799 --- /dev/null +++ b/libraries/Firmata/Firmata.cpp @@ -0,0 +1,668 @@ +/* + Firmata.cpp - Firmata library v2.5.2 - 2016-2-15 + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +//****************************************************************************** +//* Includes +//****************************************************************************** + +#include "Firmata.h" +#include "HardwareSerial.h" + +extern "C" { +#include +#include +} + +//****************************************************************************** +//* Support Functions +//****************************************************************************** + +/** + * Split a 16-bit byte into two 7-bit values and write each value. + * @param value The 16-bit value to be split and written separately. + */ +void FirmataClass::sendValueAsTwo7bitBytes(int value) +{ + FirmataStream->write(value & B01111111); // LSB + FirmataStream->write(value >> 7 & B01111111); // MSB +} + +/** + * A helper method to write the beginning of a Sysex message transmission. + */ +void FirmataClass::startSysex(void) +{ + FirmataStream->write(START_SYSEX); +} + +/** + * A helper method to write the end of a Sysex message transmission. + */ +void FirmataClass::endSysex(void) +{ + FirmataStream->write(END_SYSEX); +} + +//****************************************************************************** +//* Constructors +//****************************************************************************** + +/** + * The Firmata class. + * An instance named "Firmata" is created automatically for the user. + */ +FirmataClass::FirmataClass() +{ + firmwareVersionCount = 0; + firmwareVersionVector = 0; + systemReset(); +} + +//****************************************************************************** +//* Public Methods +//****************************************************************************** + +/** + * Initialize the default Serial transport at the default baud of 57600. + */ +void FirmataClass::begin(void) +{ + begin(57600); +} + +/** + * Initialize the default Serial transport and override the default baud. + * Sends the protocol version to the host application followed by the firmware version and name. + * blinkVersion is also called. To skip the call to blinkVersion, call Firmata.disableBlinkVersion() + * before calling Firmata.begin(baud). + * @param speed The baud to use. 57600 baud is the default value. + */ +void FirmataClass::begin(long speed) +{ + Serial.begin(speed); + FirmataStream = &Serial; + blinkVersion(); + printVersion(); // send the protocol version + printFirmwareVersion(); // send the firmware name and version +} + +/** + * Reassign the Firmata stream transport. + * @param s A reference to the Stream transport object. This can be any type of + * transport that implements the Stream interface. Some examples include Ethernet, WiFi + * and other UARTs on the board (Serial1, Serial2, etc). + */ +void FirmataClass::begin(Stream &s) +{ + FirmataStream = &s; + // do not call blinkVersion() here because some hardware such as the + // Ethernet shield use pin 13 + printVersion(); + printFirmwareVersion(); +} + +/** + * Send the Firmata protocol version to the Firmata host application. + */ +void FirmataClass::printVersion(void) +{ + FirmataStream->write(REPORT_VERSION); + FirmataStream->write(FIRMATA_PROTOCOL_MAJOR_VERSION); + FirmataStream->write(FIRMATA_PROTOCOL_MINOR_VERSION); +} + +/** + * Blink the Firmata protocol version to the onboard LEDs (if the board has an onboard LED). + * If VERSION_BLINK_PIN is not defined in Boards.h for a particular board, then this method + * does nothing. + * The first series of flashes indicates the firmware major version (2 flashes = 2). + * The second series of flashes indicates the firmware minor version (5 flashes = 5). + */ +void FirmataClass::blinkVersion(void) +{ +#if defined(VERSION_BLINK_PIN) + if (blinkVersionDisabled) return; + // flash the pin with the protocol version + pinMode(VERSION_BLINK_PIN, OUTPUT); + strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MAJOR_VERSION, 40, 210); + delay(250); + strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MINOR_VERSION, 40, 210); + delay(125); +#endif +} + +/** + * Provides a means to disable the version blink sequence on the onboard LED, trimming startup + * time by a couple of seconds. + * Call this before Firmata.begin(). It only applies when using the default Serial transport. + */ +void FirmataClass::disableBlinkVersion() +{ + blinkVersionDisabled = true; +} + +/** + * Sends the firmware name and version to the Firmata host application. The major and minor version + * numbers are the first 2 bytes in the message. The following bytes are the characters of the + * firmware name. + */ +void FirmataClass::printFirmwareVersion(void) +{ + byte i; + + if (firmwareVersionCount) { // make sure that the name has been set before reporting + startSysex(); + FirmataStream->write(REPORT_FIRMWARE); + FirmataStream->write(firmwareVersionVector[0]); // major version number + FirmataStream->write(firmwareVersionVector[1]); // minor version number + for (i = 2; i < firmwareVersionCount; ++i) { + sendValueAsTwo7bitBytes(firmwareVersionVector[i]); + } + endSysex(); + } +} + +/** + * Sets the name and version of the firmware. This is not the same version as the Firmata protocol + * (although at times the firmware version and protocol version may be the same number). + * @param name A pointer to the name char array + * @param major The major version number + * @param minor The minor version number + */ +void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor) +{ + const char *firmwareName; + const char *extension; + + // parse out ".cpp" and "applet/" that comes from using __FILE__ + extension = strstr(name, ".cpp"); + firmwareName = strrchr(name, '/'); + + if (!firmwareName) { + // windows + firmwareName = strrchr(name, '\\'); + } + if (!firmwareName) { + // user passed firmware name + firmwareName = name; + } else { + firmwareName ++; + } + + if (!extension) { + firmwareVersionCount = strlen(firmwareName) + 2; + } else { + firmwareVersionCount = extension - firmwareName + 2; + } + + // in case anyone calls setFirmwareNameAndVersion more than once + free(firmwareVersionVector); + + firmwareVersionVector = (byte *) malloc(firmwareVersionCount + 1); + firmwareVersionVector[firmwareVersionCount] = 0; + firmwareVersionVector[0] = major; + firmwareVersionVector[1] = minor; + strncpy((char *)firmwareVersionVector + 2, firmwareName, firmwareVersionCount - 2); +} + +//------------------------------------------------------------------------------ +// Serial Receive Handling + +/** + * A wrapper for Stream::available() + * @return The number of bytes remaining in the input stream buffer. + */ +int FirmataClass::available(void) +{ + return FirmataStream->available(); +} + +/** + * Process incoming sysex messages. Handles REPORT_FIRMWARE and STRING_DATA internally. + * Calls callback function for STRING_DATA and all other sysex messages. + * @private + */ +void FirmataClass::processSysexMessage(void) +{ + switch (storedInputData[0]) { //first byte in buffer is command + case REPORT_FIRMWARE: + printFirmwareVersion(); + break; + case STRING_DATA: + if (currentStringCallback) { + byte bufferLength = (sysexBytesRead - 1) / 2; + byte i = 1; + byte j = 0; + while (j < bufferLength) { + // The string length will only be at most half the size of the + // stored input buffer so we can decode the string within the buffer. + storedInputData[j] = storedInputData[i]; + i++; + storedInputData[j] += (storedInputData[i] << 7); + i++; + j++; + } + // Make sure string is null terminated. This may be the case for data + // coming from client libraries in languages that don't null terminate + // strings. + if (storedInputData[j - 1] != '\0') { + storedInputData[j] = '\0'; + } + (*currentStringCallback)((char *)&storedInputData[0]); + } + break; + default: + if (currentSysexCallback) + (*currentSysexCallback)(storedInputData[0], sysexBytesRead - 1, storedInputData + 1); + } +} + +/** + * Read a single int from the input stream. If the value is not = -1, pass it on to parse(byte) + */ +void FirmataClass::processInput(void) +{ + int inputData = FirmataStream->read(); // this is 'int' to handle -1 when no data + if (inputData != -1) { + parse(inputData); + } +} + +/** + * Parse data from the input stream. + * @param inputData A single byte to be added to the parser. + */ +void FirmataClass::parse(byte inputData) +{ + int command; + + if (parsingSysex) { + if (inputData == END_SYSEX) { + //stop sysex byte + parsingSysex = false; + //fire off handler function + processSysexMessage(); + } else { + //normal data byte - add to buffer + storedInputData[sysexBytesRead] = inputData; + sysexBytesRead++; + } + } else if ( (waitForData > 0) && (inputData < 128) ) { + waitForData--; + storedInputData[waitForData] = inputData; + if ( (waitForData == 0) && executeMultiByteCommand ) { // got the whole message + switch (executeMultiByteCommand) { + case ANALOG_MESSAGE: + if (currentAnalogCallback) { + (*currentAnalogCallback)(multiByteChannel, + (storedInputData[0] << 7) + + storedInputData[1]); + } + break; + case DIGITAL_MESSAGE: + if (currentDigitalCallback) { + (*currentDigitalCallback)(multiByteChannel, + (storedInputData[0] << 7) + + storedInputData[1]); + } + break; + case SET_PIN_MODE: + if (currentPinModeCallback) + (*currentPinModeCallback)(storedInputData[1], storedInputData[0]); + break; + case SET_DIGITAL_PIN_VALUE: + if (currentPinValueCallback) + (*currentPinValueCallback)(storedInputData[1], storedInputData[0]); + break; + case REPORT_ANALOG: + if (currentReportAnalogCallback) + (*currentReportAnalogCallback)(multiByteChannel, storedInputData[0]); + break; + case REPORT_DIGITAL: + if (currentReportDigitalCallback) + (*currentReportDigitalCallback)(multiByteChannel, storedInputData[0]); + break; + } + executeMultiByteCommand = 0; + } + } else { + // remove channel info from command byte if less than 0xF0 + if (inputData < 0xF0) { + command = inputData & 0xF0; + multiByteChannel = inputData & 0x0F; + } else { + command = inputData; + // commands in the 0xF* range don't use channel data + } + switch (command) { + case ANALOG_MESSAGE: + case DIGITAL_MESSAGE: + case SET_PIN_MODE: + case SET_DIGITAL_PIN_VALUE: + waitForData = 2; // two data bytes needed + executeMultiByteCommand = command; + break; + case REPORT_ANALOG: + case REPORT_DIGITAL: + waitForData = 1; // one data byte needed + executeMultiByteCommand = command; + break; + case START_SYSEX: + parsingSysex = true; + sysexBytesRead = 0; + break; + case SYSTEM_RESET: + systemReset(); + break; + case REPORT_VERSION: + Firmata.printVersion(); + break; + } + } +} + +/** + * @return Returns true if the parser is actively parsing data. + */ +boolean FirmataClass::isParsingMessage(void) +{ + return (waitForData > 0 || parsingSysex); +} + +//------------------------------------------------------------------------------ +// Output Stream Handling + +/** + * Send an analog message to the Firmata host application. The range of pins is limited to [0..15] + * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits + * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG + * message. + * @param pin The analog pin to send the value of (limited to pins 0 - 15). + * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc). + * The maximum value is 14-bits (16384). + */ +void FirmataClass::sendAnalog(byte pin, int value) +{ + // pin can only be 0-15, so chop higher bits + FirmataStream->write(ANALOG_MESSAGE | (pin & 0xF)); + sendValueAsTwo7bitBytes(value); +} + +/* (intentionally left out asterix here) + * STUB - NOT IMPLEMENTED + * Send a single digital pin value to the Firmata host application. + * @param pin The digital pin to send the value of. + * @param value The value of the pin. + */ +void FirmataClass::sendDigital(byte pin, int value) +{ + /* TODO add single pin digital messages to the protocol, this needs to + * track the last digital data sent so that it can be sure to change just + * one bit in the packet. This is complicated by the fact that the + * numbering of the pins will probably differ on Arduino, Wiring, and + * other boards. + */ + + // TODO: the digital message should not be sent on the serial port every + // time sendDigital() is called. Instead, it should add it to an int + // which will be sent on a schedule. If a pin changes more than once + // before the digital message is sent on the serial port, it should send a + // digital message for each change. + + // if(value == 0) + // sendDigitalPortPair(); +} + + +/** + * Send an 8-bit port in a single digital message (protocol v2 and later). + * Send 14-bits in a single digital message (protocol v1). + * @param portNumber The port number to send. Note that this is not the same as a "port" on the + * physical microcontroller. Ports are defined in order per every 8 pins in ascending order + * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. + * @param portData The value of the port. The value of each pin in the port is represented by a bit. + */ +void FirmataClass::sendDigitalPort(byte portNumber, int portData) +{ + FirmataStream->write(DIGITAL_MESSAGE | (portNumber & 0xF)); + FirmataStream->write((byte)portData % 128); // Tx bits 0-6 (protocol v1 and higher) + FirmataStream->write(portData >> 7); // Tx bits 7-13 (bit 7 only for protocol v2 and higher) +} + +/** + * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes + * (this is not always the case so this function is not always used to send sysex messages). + * @param command The sysex command byte. + * @param bytec The number of data bytes in the message (excludes start, command and end bytes). + * @param bytev A pointer to the array of data bytes to send in the message. + */ +void FirmataClass::sendSysex(byte command, byte bytec, byte *bytev) +{ + byte i; + startSysex(); + FirmataStream->write(command); + for (i = 0; i < bytec; i++) { + sendValueAsTwo7bitBytes(bytev[i]); + } + endSysex(); +} + +/** + * Send a string to the Firmata host application. + * @param command Must be STRING_DATA + * @param string A pointer to the char string + */ +void FirmataClass::sendString(byte command, const char *string) +{ + if (command == STRING_DATA) { + sendSysex(command, strlen(string), (byte *)string); + } +} + +/** + * Send a string to the Firmata host application. + * @param string A pointer to the char string + */ +void FirmataClass::sendString(const char *string) +{ + sendString(STRING_DATA, string); +} + +/** + * A wrapper for Stream::available(). + * Write a single byte to the output stream. + * @param c The byte to be written. + */ +void FirmataClass::write(byte c) +{ + FirmataStream->write(c); +} + +/** + * Attach a generic sysex callback function to a command (options are: ANALOG_MESSAGE, + * DIGITAL_MESSAGE, REPORT_ANALOG, REPORT DIGITAL, SET_PIN_MODE and SET_DIGITAL_PIN_VALUE). + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the callback function to attach. + */ +void FirmataClass::attach(byte command, callbackFunction newFunction) +{ + switch (command) { + case ANALOG_MESSAGE: currentAnalogCallback = newFunction; break; + case DIGITAL_MESSAGE: currentDigitalCallback = newFunction; break; + case REPORT_ANALOG: currentReportAnalogCallback = newFunction; break; + case REPORT_DIGITAL: currentReportDigitalCallback = newFunction; break; + case SET_PIN_MODE: currentPinModeCallback = newFunction; break; + case SET_DIGITAL_PIN_VALUE: currentPinValueCallback = newFunction; break; + } +} + +/** + * Attach a callback function for the SYSTEM_RESET command. + * @param command Must be set to SYSTEM_RESET or it will be ignored. + * @param newFunction A reference to the system reset callback function to attach. + */ +void FirmataClass::attach(byte command, systemResetCallbackFunction newFunction) +{ + switch (command) { + case SYSTEM_RESET: currentSystemResetCallback = newFunction; break; + } +} + +/** + * Attach a callback function for the STRING_DATA command. + * @param command Must be set to STRING_DATA or it will be ignored. + * @param newFunction A reference to the string callback function to attach. + */ +void FirmataClass::attach(byte command, stringCallbackFunction newFunction) +{ + switch (command) { + case STRING_DATA: currentStringCallback = newFunction; break; + } +} + +/** + * Attach a generic sysex callback function to sysex command. + * @param command The ID of the command to attach a callback function to. + * @param newFunction A reference to the sysex callback function to attach. + */ +void FirmataClass::attach(byte command, sysexCallbackFunction newFunction) +{ + currentSysexCallback = newFunction; +} + +/** + * Detach a callback function for a specified command (such as SYSTEM_RESET, STRING_DATA, + * ANALOG_MESSAGE, DIGITAL_MESSAGE, etc). + * @param command The ID of the command to detatch the callback function from. + */ +void FirmataClass::detach(byte command) +{ + switch (command) { + case SYSTEM_RESET: currentSystemResetCallback = NULL; break; + case STRING_DATA: currentStringCallback = NULL; break; + case START_SYSEX: currentSysexCallback = NULL; break; + default: + attach(command, (callbackFunction)NULL); + } +} + +/** + * @param pin The pin to get the configuration of. + * @return The configuration of the specified pin. + */ +byte FirmataClass::getPinMode(byte pin) +{ + return pinConfig[pin]; +} + +/** + * Set the pin mode/configuration. The pin configuration (or mode) in Firmata represents the + * current function of the pin. Examples are digital input or output, analog input, pwm, i2c, + * serial (uart), etc. + * @param pin The pin to configure. + * @param config The configuration value for the specified pin. + */ +void FirmataClass::setPinMode(byte pin, byte config) +{ + if (pinConfig[pin] == PIN_MODE_IGNORE) + return; + + pinConfig[pin] = config; +} + +/** + * @param pin The pin to get the state of. + * @return The state of the specified pin. + */ +int FirmataClass::getPinState(byte pin) +{ + return pinState[pin]; +} + +/** + * Set the pin state. The pin state of an output pin is the pin value. The state of an + * input pin is 0, unless the pin has it's internal pull up resistor enabled, then the value is 1. + * @param pin The pin to set the state of + * @param state Set the state of the specified pin + */ +void FirmataClass::setPinState(byte pin, int state) +{ + pinState[pin] = state; +} + +// sysex callbacks +/* + * this is too complicated for analogReceive, but maybe for Sysex? + void FirmataClass::attachSysex(sysexFunction newFunction) + { + byte i; + byte tmpCount = analogReceiveFunctionCount; + analogReceiveFunction* tmpArray = analogReceiveFunctionArray; + analogReceiveFunctionCount++; + analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction)); + for(i = 0; i < tmpCount; i++) { + analogReceiveFunctionArray[i] = tmpArray[i]; + } + analogReceiveFunctionArray[tmpCount] = newFunction; + free(tmpArray); + } +*/ + +//****************************************************************************** +//* Private Methods +//****************************************************************************** + +/** + * Resets the system state upon a SYSTEM_RESET message from the host software. + * @private + */ +void FirmataClass::systemReset(void) +{ + byte i; + + waitForData = 0; // this flag says the next serial input will be data + executeMultiByteCommand = 0; // execute this after getting multi-byte data + multiByteChannel = 0; // channel data for multiByteCommands + + for (i = 0; i < MAX_DATA_BYTES; i++) { + storedInputData[i] = 0; + } + + parsingSysex = false; + sysexBytesRead = 0; + + if (currentSystemResetCallback) + (*currentSystemResetCallback)(); +} + +/** + * Flashing the pin for the version number + * @private + * @param pin The pin the LED is attached to. + * @param count The number of times to flash the LED. + * @param onInterval The number of milliseconds for the LED to be ON during each interval. + * @param offInterval The number of milliseconds for the LED to be OFF during each interval. + */ +void FirmataClass::strobeBlinkPin(byte pin, int count, int onInterval, int offInterval) +{ + byte i; + for (i = 0; i < count; i++) { + delay(offInterval); + digitalWrite(pin, HIGH); + delay(onInterval); + digitalWrite(pin, LOW); + } +} + +// make one instance for the user to use +FirmataClass Firmata; diff --git a/libraries/Firmata/Firmata.h b/libraries/Firmata/Firmata.h new file mode 100644 index 000000000..569bdf7e4 --- /dev/null +++ b/libraries/Firmata/Firmata.h @@ -0,0 +1,224 @@ +/* + Firmata.h - Firmata library v2.5.2 - 2016-2-15 + Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2009-2015 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef Firmata_h +#define Firmata_h + +#include "Boards.h" /* Hardware Abstraction Layer + Wiring/Arduino */ + +/* Version numbers for the protocol. The protocol is still changing, so these + * version numbers are important. + * Query using the REPORT_VERSION message. + */ +#define FIRMATA_PROTOCOL_MAJOR_VERSION 2 // for non-compatible changes +#define FIRMATA_PROTOCOL_MINOR_VERSION 5 // for backwards compatible changes +#define FIRMATA_PROTOCOL_BUGFIX_VERSION 1 // for bugfix releases + +/* Version numbers for the Firmata library. + * The firmware version will not always equal the protocol version going forward. + * Query using the REPORT_FIRMWARE message. + */ +#define FIRMATA_FIRMWARE_MAJOR_VERSION 2 +#define FIRMATA_FIRMWARE_MINOR_VERSION 5 +#define FIRMATA_FIRMWARE_BUGFIX_VERSION 2 + +/* DEPRECATED as of Firmata v2.5.1. As of 2.5.1 there are separate version numbers for + * the protocol version and the firmware version. + */ +#define FIRMATA_MAJOR_VERSION 2 // same as FIRMATA_PROTOCOL_MAJOR_VERSION +#define FIRMATA_MINOR_VERSION 5 // same as FIRMATA_PROTOCOL_MINOR_VERSION +#define FIRMATA_BUGFIX_VERSION 1 // same as FIRMATA_PROTOCOL_BUGFIX_VERSION + +#define MAX_DATA_BYTES 64 // max number of data bytes in incoming messages + +// Arduino 101 also defines SET_PIN_MODE as a macro in scss_registers.h +#ifdef SET_PIN_MODE +#undef SET_PIN_MODE +#endif + +// message command bytes (128-255/0x80-0xFF) +#define DIGITAL_MESSAGE 0x90 // send data for a digital port (collection of 8 pins) +#define ANALOG_MESSAGE 0xE0 // send data for an analog pin (or PWM) +#define REPORT_ANALOG 0xC0 // enable analog input by pin # +#define REPORT_DIGITAL 0xD0 // enable digital input by port pair +// +#define SET_PIN_MODE 0xF4 // set a pin to INPUT/OUTPUT/PWM/etc +#define SET_DIGITAL_PIN_VALUE 0xF5 // set value of an individual digital pin +// +#define REPORT_VERSION 0xF9 // report protocol version +#define SYSTEM_RESET 0xFF // reset from MIDI +// +#define START_SYSEX 0xF0 // start a MIDI Sysex message +#define END_SYSEX 0xF7 // end a MIDI Sysex message + +// extended command set using sysex (0-127/0x00-0x7F) +/* 0x00-0x0F reserved for user-defined commands */ +#define SERIAL_MESSAGE 0x60 // communicate with serial devices, including other boards +#define ENCODER_DATA 0x61 // reply with encoders current positions +#define SERVO_CONFIG 0x70 // set max angle, minPulse, maxPulse, freq +#define STRING_DATA 0x71 // a string message with 14-bits per char +#define STEPPER_DATA 0x72 // control a stepper motor +#define ONEWIRE_DATA 0x73 // send an OneWire read/write/reset/select/skip/search request +#define SHIFT_DATA 0x75 // a bitstream to/from a shift register +#define I2C_REQUEST 0x76 // send an I2C read/write request +#define I2C_REPLY 0x77 // a reply to an I2C read request +#define I2C_CONFIG 0x78 // config I2C settings such as delay times and power pins +#define EXTENDED_ANALOG 0x6F // analog write (PWM, Servo, etc) to any pin +#define PIN_STATE_QUERY 0x6D // ask for a pin's current mode and value +#define PIN_STATE_RESPONSE 0x6E // reply with pin's current mode and value +#define CAPABILITY_QUERY 0x6B // ask for supported modes and resolution of all pins +#define CAPABILITY_RESPONSE 0x6C // reply with supported modes and resolution +#define ANALOG_MAPPING_QUERY 0x69 // ask for mapping of analog to pin numbers +#define ANALOG_MAPPING_RESPONSE 0x6A // reply with mapping info +#define REPORT_FIRMWARE 0x79 // report name and version of the firmware +#define SAMPLING_INTERVAL 0x7A // set the poll rate of the main loop +#define SCHEDULER_DATA 0x7B // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler +#define SYSEX_NON_REALTIME 0x7E // MIDI Reserved for non-realtime messages +#define SYSEX_REALTIME 0x7F // MIDI Reserved for realtime messages +// these are DEPRECATED to make the naming more consistent +#define FIRMATA_STRING 0x71 // same as STRING_DATA +#define SYSEX_I2C_REQUEST 0x76 // same as I2C_REQUEST +#define SYSEX_I2C_REPLY 0x77 // same as I2C_REPLY +#define SYSEX_SAMPLING_INTERVAL 0x7A // same as SAMPLING_INTERVAL + +// pin modes +//#define INPUT 0x00 // defined in Arduino.h +//#define OUTPUT 0x01 // defined in Arduino.h +#define PIN_MODE_ANALOG 0x02 // analog pin in analogInput mode +#define PIN_MODE_PWM 0x03 // digital pin in PWM output mode +#define PIN_MODE_SERVO 0x04 // digital pin in Servo output mode +#define PIN_MODE_SHIFT 0x05 // shiftIn/shiftOut mode +#define PIN_MODE_I2C 0x06 // pin included in I2C setup +#define PIN_MODE_ONEWIRE 0x07 // pin configured for 1-wire +#define PIN_MODE_STEPPER 0x08 // pin configured for stepper motor +#define PIN_MODE_ENCODER 0x09 // pin configured for rotary encoders +#define PIN_MODE_SERIAL 0x0A // pin configured for serial communication +#define PIN_MODE_PULLUP 0x0B // enable internal pull-up resistor for pin +#define PIN_MODE_IGNORE 0x7F // pin configured to be ignored by digitalWrite and capabilityResponse +#define TOTAL_PIN_MODES 13 +// DEPRECATED as of Firmata v2.5 +#define ANALOG 0x02 // same as PIN_MODE_ANALOG +#define PWM 0x03 // same as PIN_MODE_PWM +#define SERVO 0x04 // same as PIN_MODE_SERVO +#define SHIFT 0x05 // same as PIN_MODE_SHIFT +#define I2C 0x06 // same as PIN_MODE_I2C +#define ONEWIRE 0x07 // same as PIN_MODE_ONEWIRE +#define STEPPER 0x08 // same as PIN_MODE_STEPPER +#define ENCODER 0x09 // same as PIN_MODE_ENCODER +#define IGNORE 0x7F // same as PIN_MODE_IGNORE + +extern "C" { + // callback function types + typedef void (*callbackFunction)(byte, int); + typedef void (*systemResetCallbackFunction)(void); + typedef void (*stringCallbackFunction)(char *); + typedef void (*sysexCallbackFunction)(byte command, byte argc, byte *argv); +} + +// TODO make it a subclass of a generic Serial/Stream base class +class FirmataClass +{ + public: + FirmataClass(); + /* Arduino constructors */ + void begin(); + void begin(long); + void begin(Stream &s); + /* querying functions */ + void printVersion(void); + void blinkVersion(void); + void printFirmwareVersion(void); + //void setFirmwareVersion(byte major, byte minor); // see macro below + void setFirmwareNameAndVersion(const char *name, byte major, byte minor); + void disableBlinkVersion(); + /* serial receive handling */ + int available(void); + void processInput(void); + void parse(unsigned char value); + boolean isParsingMessage(void); + /* serial send handling */ + void sendAnalog(byte pin, int value); + void sendDigital(byte pin, int value); // TODO implement this + void sendDigitalPort(byte portNumber, int portData); + void sendString(const char *string); + void sendString(byte command, const char *string); + void sendSysex(byte command, byte bytec, byte *bytev); + void write(byte c); + /* attach & detach callback functions to messages */ + void attach(byte command, callbackFunction newFunction); + void attach(byte command, systemResetCallbackFunction newFunction); + void attach(byte command, stringCallbackFunction newFunction); + void attach(byte command, sysexCallbackFunction newFunction); + void detach(byte command); + + /* access pin state and config */ + byte getPinMode(byte pin); + void setPinMode(byte pin, byte config); + /* access pin state */ + int getPinState(byte pin); + void setPinState(byte pin, int state); + + /* utility methods */ + void sendValueAsTwo7bitBytes(int value); + void startSysex(void); + void endSysex(void); + + private: + Stream *FirmataStream; + /* firmware name and version */ + byte firmwareVersionCount; + byte *firmwareVersionVector; + /* input message handling */ + byte waitForData; // this flag says the next serial input will be data + byte executeMultiByteCommand; // execute this after getting multi-byte data + byte multiByteChannel; // channel data for multiByteCommands + byte storedInputData[MAX_DATA_BYTES]; // multi-byte data + /* sysex */ + boolean parsingSysex; + int sysexBytesRead; + /* pin configuration */ + byte pinConfig[TOTAL_PINS]; + int pinState[TOTAL_PINS]; + + /* callback functions */ + callbackFunction currentAnalogCallback; + callbackFunction currentDigitalCallback; + callbackFunction currentReportAnalogCallback; + callbackFunction currentReportDigitalCallback; + callbackFunction currentPinModeCallback; + callbackFunction currentPinValueCallback; + systemResetCallbackFunction currentSystemResetCallback; + stringCallbackFunction currentStringCallback; + sysexCallbackFunction currentSysexCallback; + + boolean blinkVersionDisabled = false; + + /* private methods ------------------------------ */ + void processSysexMessage(void); + void systemReset(void); + void strobeBlinkPin(byte pin, int count, int onInterval, int offInterval); +}; + +extern FirmataClass Firmata; + +/*============================================================================== + * MACROS + *============================================================================*/ + +/* shortcut for setFirmwareNameAndVersion() that uses __FILE__ to set the + * firmware name. It needs to be a macro so that __FILE__ is included in the + * firmware source file rather than the library source file. + */ +#define setFirmwareVersion(x, y) setFirmwareNameAndVersion(__FILE__, x, y) + +#endif /* Firmata_h */ diff --git a/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino b/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino new file mode 100644 index 000000000..7cfcd60c3 --- /dev/null +++ b/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino @@ -0,0 +1,90 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please clink on the following link + * to open the download page in your default browser. + * + * http://firmata.org/wiki/Download + */ + +/* + * This firmware reads all inputs and sends them as fast as it can. It was + * inspired by the ease-of-use of the Arduino2Max program. + * + * This example code is in the public domain. + */ +#include + +byte pin; + +int analogValue; +int previousAnalogValues[TOTAL_ANALOG_PINS]; + +byte portStatus[TOTAL_PORTS]; // each bit: 1=pin is digital input, 0=other/ignore +byte previousPINs[TOTAL_PORTS]; + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +/* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you + get long, random delays. So only read analogs every 20ms or so */ +int samplingInterval = 19; // how often to run the main loop (in ms) + +void sendPort(byte portNumber, byte portValue) +{ + portValue = portValue & portStatus[portNumber]; + if (previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +void setup() +{ + byte i, port, status; + + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + for (pin = 0; pin < TOTAL_PINS; pin++) { + if IS_PIN_DIGITAL(pin) pinMode(PIN_TO_DIGITAL(pin), INPUT); + } + + for (port = 0; port < TOTAL_PORTS; port++) { + status = 0; + for (i = 0; i < 8; i++) { + if (IS_PIN_DIGITAL(port * 8 + i)) status |= (1 << i); + } + portStatus[port] = status; + } + + Firmata.begin(57600); +} + +void loop() +{ + byte i; + + for (i = 0; i < TOTAL_PORTS; i++) { + sendPort(i, readPort(i, 0xff)); + } + /* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you + get long, random delays. So only read analogs every 20ms or so */ + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + while (Firmata.available()) { + Firmata.processInput(); + } + for (pin = 0; pin < TOTAL_ANALOG_PINS; pin++) { + analogValue = analogRead(pin); + if (analogValue != previousAnalogValues[pin]) { + Firmata.sendAnalog(pin, analogValue); + previousAnalogValues[pin] = analogValue; + } + } + } +} + + diff --git a/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino b/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino new file mode 100644 index 000000000..8373f88dd --- /dev/null +++ b/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino @@ -0,0 +1,94 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please clink on the following link + * to open the download page in your default browser. + * + * http://firmata.org/wiki/Download + */ + +/* This firmware supports as many analog ports as possible, all analog inputs, + * four PWM outputs, and two with servo support. + * + * This example code is in the public domain. + */ +#include +#include + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +/* servos */ +Servo servo9, servo10; // one instance per pin +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting +int analogPin = 0; // counter for reading analog pins +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis + + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void analogWriteCallback(byte pin, int value) +{ + switch (pin) { + case 9: servo9.write(value); break; + case 10: servo10.write(value); break; + case 3: + case 5: + case 6: + case 11: // PWM pins + analogWrite(pin, value); + break; + } +} +// ----------------------------------------------------------------------------- +// sets bits in a bit array (int) to toggle the reporting of the analogIns +void reportAnalogCallback(byte pin, int value) +{ + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << pin); + } + else { // everything but 0 enables reporting of that pin + analogInputsToReport = analogInputsToReport | (1 << pin); + } + // TODO: save status to EEPROM here, if changed +} + +/*============================================================================== + * SETUP() + *============================================================================*/ +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + + servo9.attach(9); + servo10.attach(10); + Firmata.begin(57600); +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + while (Firmata.available()) + Firmata.processInput(); + currentMillis = millis(); + if (currentMillis - previousMillis > 20) { + previousMillis += 20; // run this every 20ms + for (analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) { + if ( analogInputsToReport & (1 << analogPin) ) + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } +} + diff --git a/libraries/Firmata/examples/EchoString/EchoString.ino b/libraries/Firmata/examples/EchoString/EchoString.ino new file mode 100644 index 000000000..9849806a3 --- /dev/null +++ b/libraries/Firmata/examples/EchoString/EchoString.ino @@ -0,0 +1,44 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please clink on the following link + * to open the download page in your default browser. + * + * http://firmata.org/wiki/Download + */ + +/* This sketch accepts strings and raw sysex messages and echos them back. + * + * This example code is in the public domain. + */ +#include + +void stringCallback(char *myString) +{ + Firmata.sendString(myString); +} + + +void sysexCallback(byte command, byte argc, byte *argv) +{ + Firmata.sendSysex(command, argc, argv); +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(STRING_DATA, stringCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.begin(57600); +} + +void loop() +{ + while (Firmata.available()) { + Firmata.processInput(); + } +} + + diff --git a/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt b/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino b/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino new file mode 100644 index 000000000..62dd54ea3 --- /dev/null +++ b/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino @@ -0,0 +1,239 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please clink on the following link + * to open the download page in your default browser. + * + * http://firmata.org/wiki/Download + */ + +/* + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + */ + +/* + * This is an old version of StandardFirmata (v2.0). It is kept here because + * its the last version that works on an ATMEGA8 chip. Also, it can be used + * for host software that has not been updated to a newer version of the + * protocol. It also uses the old baud rate of 115200 rather than 57600. + */ + +#include +#include + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting +int analogPin = 0; // counter for reading analog pins + +/* digital pins */ +byte reportPINs[TOTAL_PORTS]; // PIN == input port +byte previousPINs[TOTAL_PORTS]; // PIN == input port +byte pinStatus[TOTAL_PINS]; // store pin status, default OUTPUT +byte portStatus[TOTAL_PORTS]; + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis + + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void outputPort(byte portNumber, byte portValue) +{ + portValue = portValue & ~ portStatus[portNumber]; + if (previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + Firmata.sendDigitalPort(portNumber, portValue); + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + byte i, tmp; + for (i = 0; i < TOTAL_PORTS; i++) { + if (reportPINs[i]) { + switch (i) { + case 0: outputPort(0, PIND & ~ B00000011); break; // ignore Rx/Tx 0/1 + case 1: outputPort(1, PINB); break; + case 2: outputPort(2, PINC); break; + } + } + } +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) { + byte port = 0; + byte offset = 0; + + if (pin < 8) { + port = 0; + offset = 0; + } else if (pin < 14) { + port = 1; + offset = 8; + } else if (pin < 22) { + port = 2; + offset = 14; + } + + if (pin > 1) { // ignore RxTx (pins 0 and 1) + pinStatus[pin] = mode; + switch (mode) { + case INPUT: + pinMode(pin, INPUT); + portStatus[port] = portStatus[port] & ~ (1 << (pin - offset)); + break; + case OUTPUT: + digitalWrite(pin, LOW); // disable PWM + case PWM: + pinMode(pin, OUTPUT); + portStatus[port] = portStatus[port] | (1 << (pin - offset)); + break; + //case ANALOG: // TODO figure this out + default: + Firmata.sendString(""); + } + // TODO: save status to EEPROM here, if changed + } +} + +void analogWriteCallback(byte pin, int value) +{ + setPinModeCallback(pin, PIN_MODE_PWM); + analogWrite(pin, value); +} + +void digitalWriteCallback(byte port, int value) +{ + switch (port) { + case 0: // pins 2-7 (don't change Rx/Tx, pins 0 and 1) + // 0xFF03 == B1111111100000011 0x03 == B00000011 + PORTD = (value & ~ 0xFF03) | (PORTD & 0x03); + break; + case 1: // pins 8-13 (14,15 are disabled for the crystal) + PORTB = (byte)value; + break; + case 2: // analog pins used as digital + PORTC = (byte)value; + break; + } +} + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte pin, int value) +{ + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << pin); + } + else { // everything but 0 enables reporting of that pin + analogInputsToReport = analogInputsToReport | (1 << pin); + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + reportPINs[port] = (byte)value; + if (port == 2) // turn off analog reporting when used as digital + analogInputsToReport = 0; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ +void setup() +{ + byte i; + + Firmata.setFirmwareVersion(2, 0); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + + portStatus[0] = B00000011; // ignore Tx/RX pins + portStatus[1] = B11000000; // ignore 14/15 pins + portStatus[2] = B00000000; + + // for(i=0; i 20) { + previousMillis += 20; // run this every 20ms + /* SERIALREAD - Serial.read() uses a 128 byte circular buffer, so handle + * all serialReads at once, i.e. empty the buffer */ + while (Firmata.available()) + Firmata.processInput(); + /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over + * 60 bytes. use a timer to sending an event character every 4 ms to + * trigger the buffer to dump. */ + + /* ANALOGREAD - right after the event character, do all of the + * analogReads(). These only need to be done every 4ms. */ + for (analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) { + if ( analogInputsToReport & (1 << analogPin) ) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } +} diff --git a/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino b/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino new file mode 100644 index 000000000..1ccc411d4 --- /dev/null +++ b/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino @@ -0,0 +1,65 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please clink on the following link + * to open the download page in your default browser. + * + * http://firmata.org/wiki/Download + */ + +/* This firmware supports as many servos as possible using the Servo library + * included in Arduino 0017 + * + * This example code is in the public domain. + */ + +#include +#include + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte servoCount = 0; + +void analogWriteCallback(byte pin, int value) +{ + if (IS_PIN_DIGITAL(pin)) { + servos[servoPinMap[pin]].write(value); + } +} + +void systemResetCallback() +{ + servoCount = 0; +} + +void setup() +{ + byte pin; + + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + Firmata.begin(57600); + systemResetCallback(); + + // attach servos from first digital pin up to max number of + // servos supported for the board + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + if (servoCount < MAX_SERVOS) { + servoPinMap[pin] = servoCount; + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + servoCount++; + } + } + } +} + +void loop() +{ + while (Firmata.available()) + Firmata.processInput(); +} diff --git a/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino b/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino new file mode 100644 index 000000000..f4a3eaabe --- /dev/null +++ b/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino @@ -0,0 +1,46 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please clink on the following link + * to open the download page in your default browser. + * + * http://firmata.org/wiki/Download + */ + +/* Supports as many analog inputs and analog PWM outputs as possible. + * + * This example code is in the public domain. + */ +#include + +byte analogPin = 0; + +void analogWriteCallback(byte pin, int value) +{ + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), value); + } +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.begin(57600); +} + +void loop() +{ + while (Firmata.available()) { + Firmata.processInput(); + } + // do one analogRead per loop, so if PC is sending a lot of + // analog write messages, we will only delay 1 analogRead + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + analogPin = analogPin + 1; + if (analogPin >= TOTAL_ANALOG_PINS) analogPin = 0; +} + diff --git a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino new file mode 100644 index 000000000..56d388e92 --- /dev/null +++ b/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino @@ -0,0 +1,72 @@ +/* + * Firmata is a generic protocol for communicating with microcontrollers + * from software on a host computer. It is intended to work with + * any host computer software package. + * + * To download a host software package, please clink on the following link + * to open the download page in your default browser. + * + * http://firmata.org/wiki/Download + */ + +/* Supports as many digital inputs and outputs as possible. + * + * This example code is in the public domain. + */ +#include + +byte previousPIN[TOTAL_PORTS]; // PIN means PORT for input +byte previousPORT[TOTAL_PORTS]; + +void outputPort(byte portNumber, byte portValue) +{ + // only send the data when it changes, otherwise you get too many messages! + if (previousPIN[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPIN[portNumber] = portValue; + } +} + +void setPinModeCallback(byte pin, int mode) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), mode); + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte i; + byte currentPinValue, previousPinValue; + + if (port < TOTAL_PORTS && value != previousPORT[port]) { + for (i = 0; i < 8; i++) { + currentPinValue = (byte) value & (1 << i); + previousPinValue = previousPORT[port] & (1 << i); + if (currentPinValue != previousPinValue) { + digitalWrite(i + (port * 8), currentPinValue); + } + } + previousPORT[port] = value; + } +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.begin(57600); +} + +void loop() +{ + byte i; + + for (i = 0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, 0xff)); + } + + while (Firmata.available()) { + Firmata.processInput(); + } +} diff --git a/libraries/Firmata/examples/StandardFirmata/LICENSE.txt b/libraries/Firmata/examples/StandardFirmata/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmata/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino b/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino new file mode 100644 index 000000000..e969e5a8c --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino @@ -0,0 +1,815 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please clink on the following link + to open the list of Firmata client libraries your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +#include +#include +#include + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to run the main loop (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous more */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[32]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(8); // 8 = 8-bit resolution + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega, + // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this: + // Serial1.begin(57600); + // Firmata.begin(Serial1); + // However do not do this if you are using SERIAL_MESSAGE + + Firmata.begin(57600); + while (!Serial) { + ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101 + } + + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * FTDI buffer using Serial.print() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif +} diff --git a/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino b/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino new file mode 100644 index 000000000..11437a65a --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino @@ -0,0 +1,793 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please clink on the following link + to open the list of Firmata client libraries your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + Copyright (C) 2015 Brian Schmalz. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +#include // Gives us PWM and Servo on every pin +#include +#include + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to run the main loop (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous more */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[32]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +SoftServo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* Sets a pin that is in Servo mode to a particular output value + * (i.e. pulse width). Different boards may have different ways of + * setting servo values, so putting it in a function keeps things cleaner. + */ +void servoWrite(byte pin, int value) +{ + SoftPWMServoPWMWrite(PIN_TO_PWM(pin), value); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + servoWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + servoWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(8); // 8 = 8-bit resolution + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + } +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + /* For chipKIT Pi board, we need to use Serial1. All others just use Serial. */ +#if defined(_BOARD_CHIPKIT_PI_) + Serial1.begin(57600); + Firmata.begin(Serial1); +#else + Firmata.begin(57600); +#endif + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * FTDI buffer using Serial.print() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } +} diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino b/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino new file mode 100644 index 000000000..d0f1e585a --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino @@ -0,0 +1,910 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please clink on the following link + to open the list of Firmata client libraries your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +/* + README + + StandardFirmataEthernet is a client implementation. You will need a Firmata client library with + a network transport that can act as a server in order to establish a connection between + StandardFirmataEthernet and the Firmata client application. + + To use StandardFirmataEthernet you will need to have one of the following + boards or shields: + + - Arduino Ethernet shield (or clone) + - Arduino Ethernet board (or clone) + - Arduino Yun + + Follow the instructions in the ethernetConfig.h file (ethernetConfig.h tab in Arduino IDE) to + configure your particular hardware. + + NOTE: If you are using an Arduino Ethernet shield you cannot use the following pins on + the following boards. Firmata will ignore any requests to use these pins: + + - Arduino Uno or other ATMega328 boards: (D4, D10, D11, D12, D13) + - Arduino Mega: (D4, D10, D50, D51, D52, D53) + - Arduino Leonardo: (D4, D10) + - Arduino Due: (D4, D10) + - Arduino Zero: (D4, D10) + + If you are using an ArduinoEthernet board, the following pins cannot be used (same as Uno): + - D4, D10, D11, D12, D13 +*/ + +#include +#include +#include + +/* + * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your connection + * that may help in the event of connection issues. If defined, some boards may not begin executing this sketch + * until the Serial console is opened. + */ +//#define SERIAL_DEBUG +#include "utility/firmataDebug.h" + +// follow the instructions in ethernetConfig.h to configure your particular hardware +#include "ethernetConfig.h" +#include "utility/EthernetClientStream.h" + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +/* network */ +#if defined remote_ip && !defined remote_host +#ifdef local_ip +EthernetClientStream stream(client, local_ip, remote_ip, NULL, remote_port); +#else +EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), remote_ip, NULL, remote_port); +#endif +#endif + +#if !defined remote_ip && defined remote_host +#ifdef local_ip +EthernetClientStream stream(client, local_ip, IPAddress(0, 0, 0, 0), remote_host, remote_port); +#else +EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), IPAddress(0, 0, 0, 0), remote_host, remote_port); +#endif +#endif + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous mode */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[32]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Stream output queue using Stream.write() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(8); // 8 = 8-bit resolution + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + DEBUG_BEGIN(9600); + +#ifdef YUN_ETHERNET + Bridge.begin(); +#else +#ifdef local_ip + Ethernet.begin((uint8_t *)mac, local_ip); //start ethernet +#else + Ethernet.begin((uint8_t *)mac); //start ethernet using dhcp +#endif +#endif + + DEBUG_PRINTLN("connecting..."); + + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + +#ifdef WIZ5100_ETHERNET + // StandardFirmataEthernet communicates with Ethernet shields over SPI. Therefore all + // SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. + // add Pin 10 and configure pin 53 as output if using a MEGA with an Ethernet shield. + + for (byte i = 0; i < TOTAL_PINS; i++) { + if (IS_IGNORE_ETHERNET_SHIELD(i) + #if defined(__AVR_ATmega32U4__) + || 24 == i // On Leonardo, pin 24 maps to D4 and pin 28 maps to D10 + || 28 == i + #endif + ) { + Firmata.setPinMode(i, PIN_MODE_IGNORE); + } + } + + // Arduino Ethernet and Arduino EthernetShield have SD SS wired to D4 + pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata + digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; +#endif // WIZ5100_ETHERNET + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA +#endif + + // start up Network Firmata: + Firmata.begin(stream); + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * Stream buffer using Stream.write() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif + +#if !defined local_ip && !defined YUN_ETHERNET + // only necessary when using DHCP, ensures local IP is updated appropriately if it changes + if (Ethernet.maintain()) { + stream.maintain(Ethernet.localIP()); + } +#endif + +} diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h b/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h new file mode 100644 index 000000000..4cccaa00a --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h @@ -0,0 +1,85 @@ +/*============================================================================== + * NETWORK CONFIGURATION + * + * You must configure your particular hardware. Follow the steps below. + * + * Currently StandardFirmataEthernet is configured as a client. An option to + * configure as a server may be added in the future. + *============================================================================*/ + +// STEP 1 [REQUIRED] +// Uncomment / comment the appropriate set of includes for your hardware (OPTION A or B) +// Option A is enabled by default. + +/* + * OPTION A: Configure for Arduino Ethernet board or Arduino Ethernet shield (or clone) + * + * To configure StandardFirmataEthernet to use the original WIZ5100-based + * ethernet shield or Arduino Ethernet uncomment the WIZ5100_ETHERNET define below + */ +#define WIZ5100_ETHERNET + +#ifdef WIZ5100_ETHERNET +#include +#include +EthernetClient client; +#endif + +/* + * OPTION B: Configure for Arduin Yun + * + * The Ethernet port on the Arduino Yun board can be used with Firmata in this configuration. + * + * To execute StandardFirmataEthernet on Yun uncomment the YUN_ETHERNET define below and make + * sure the WIZ5100_ETHERNET define (above) is commented out. + * + * On Yun there's no need to configure local_ip and mac address as this is automatically + * configured on the linux-side of Yun. + */ +//#define YUN_ETHERNET + +#ifdef YUN_ETHERNET +#include +#include +YunClient client; +#endif + + +// STEP 2 [REQUIRED for all boards and shields] +// replace with IP of the server you want to connect to, comment out if using 'remote_host' +#define remote_ip IPAddress(10, 0, 0, 3) +// *** REMOTE HOST IS NOT YET WORKING *** +// replace with hostname of server you want to connect to, comment out if using 'remote_ip' +// #define remote_host "server.local" + +// STEP 3 [REQUIRED unless using Arduin Yun] +// Replace with the port that your server is listening on +#define remote_port 3030 + +// STEP 4 [REQUIRED unless using Arduino Yun OR if not using DHCP] +// Replace with your board or ethernet shield's IP address +// Comment out if you want to use DHCP +#define local_ip IPAddress(10, 0, 0, 15) + +// STEP 5 [REQUIRED unless using Arduino Yun] +// replace with ethernet shield mac. Must be unique for your network +const byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x53, 0xE5}; + +/*============================================================================== + * CONFIGURATION ERROR CHECK (don't change anything here) + *============================================================================*/ + +#if !defined WIZ5100_ETHERNET && !defined YUN_ETHERNET +#error "you must define either WIZ5100_ETHERNET or YUN_ETHERNET in ethernetConfig.h" +#endif + +#if defined remote_ip && defined remote_host +#error "cannot define both remote_ip and remote_host at the same time in ethernetConfig.h" +#endif + +/*============================================================================== + * PIN IGNORE MACROS (don't change anything here) + *============================================================================*/ + +// ignore SPI pins, pin 10 (Ethernet SS) and pin 4 (SS for SD-Card on Ethernet shield) +#define IS_IGNORE_ETHERNET_SHIELD(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 10) diff --git a/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino b/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino new file mode 100644 index 000000000..a1d13aba0 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino @@ -0,0 +1,909 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please clink on the following link + to open the list of Firmata client libraries your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +/* + README + + StandardFirmataEthernetPlus is a client implementation. You will need a Firmata client library + with a network transport that can act as a server in order to establish a connection between + StandardFirmataEthernetPlus and the Firmata client application. + + StandardFirmataEthernetPlus adds additional features that may exceed the Flash and + RAM sizes of Arduino boards such as ATMega328p (Uno) and ATMega32u4 + (Leonardo, Micro, Yun, etc). It is best to use StandardFirmataPlus with a board that + has > 32k Flash and > 3k RAM such as: Arduino Mega, Arduino Due, Teensy 3.0/3.1/3.2, etc. + + This sketch consumes too much Flash and RAM to run reliably on an + Arduino Leonardo, Yun, ATMega32u4-based board. Use StandardFirmataEthernet.ino instead + for those boards and other boards that do not meet the Flash and RAM requirements. + + To use StandardFirmataEthernet you will need to have one of the following + boards or shields: + + - Arduino Ethernet shield (or clone) + - Arduino Ethernet board (or clone) + + Follow the instructions in the ethernetConfig.h file (ethernetConfig.h tab in Arduino IDE) to + configure your particular hardware. + + NOTE: If you are using an Arduino Ethernet shield you cannot use the following pins on + the following boards. Firmata will ignore any requests to use these pins: + + - Arduino Mega: (D4, D10, D50, D51, D52, D53) + - Arduino Due: (D4, D10) + - Arduino Zero: (D4, D10) + - Arduino Uno or other ATMega328p boards: (D4, D10, D11, D12, D13) + + If you are using an ArduinoEthernet board, the following pins cannot be used (same as Uno): + - D4, D10, D11, D12, D13 +*/ + +#include +#include +#include + +/* + * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your connection + * that may help in the event of connection issues. If defined, some boards may not begin executing this sketch + * until the Serial console is opened. + */ +//#define SERIAL_DEBUG +#include "utility/firmataDebug.h" + +// follow the instructions in ethernetConfig.h to configure your particular hardware +#include "ethernetConfig.h" +#include "utility/EthernetClientStream.h" + +#include "utility/SerialFirmata.h" + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#if defined remote_ip && !defined remote_host +#ifdef local_ip +EthernetClientStream stream(client, local_ip, remote_ip, NULL, remote_port); +#else +EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), remote_ip, NULL, remote_port); +#endif +#endif + +#if !defined remote_ip && defined remote_host +#ifdef local_ip +EthernetClientStream stream(client, local_ip, IPAddress(0, 0, 0, 0), remote_host, remote_port); +#else +EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), IPAddress(0, 0, 0, 0), remote_host, remote_port); +#endif +#endif + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous mode */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[32]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Stream output queue using Stream.write() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(8); // 8 = 8-bit resolution + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + DEBUG_BEGIN(9600); + +#ifdef local_ip + Ethernet.begin((uint8_t *)mac, local_ip); //start ethernet +#else + Ethernet.begin((uint8_t *)mac); //start ethernet using dhcp +#endif + + DEBUG_PRINTLN("connecting..."); + + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + +#ifdef WIZ5100_ETHERNET + // StandardFirmataEthernetPlus communicates with Ethernet shields over SPI. Therefore all + // SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. + // add Pin 10 and configure pin 53 as output if using a MEGA with an Ethernet shield. + + for (byte i = 0; i < TOTAL_PINS; i++) { + if (IS_IGNORE_ETHERNET_SHIELD(i)) { + Firmata.setPinMode(i, PIN_MODE_IGNORE); + } + } + + // Arduino Ethernet and Arduino EthernetShield have SD SS wired to D4 + pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata + digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; +#endif // WIZ5100_ETHERNET + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA +#endif + + // start up Network Firmata: + Firmata.begin(stream); + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * Stream buffer using Stream.write() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif + +#if !defined local_ip + // only necessary when using DHCP, ensures local IP is updated appropriately if it changes + if (Ethernet.maintain()) { + stream.maintain(Ethernet.localIP()); + } +#endif + +} diff --git a/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h b/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h new file mode 100644 index 000000000..105a87923 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h @@ -0,0 +1,55 @@ +/*============================================================================== + * NETWORK CONFIGURATION + * + * You must configure your particular hardware. Follow the steps below. + * + * Currently StandardFirmataEthernetPlus is configured as a client. An option to + * configure as a server may be added in the future. + *============================================================================*/ + +/* + * Only WIZ5100-based shields and boards are currently supported for + * StandardFirmataEthernetPlus. + */ +#define WIZ5100_ETHERNET + +#ifdef WIZ5100_ETHERNET +#include +#include +EthernetClient client; +#endif + +// STEP 1 [REQUIRED for all boards and shields] +// replace with IP of the server you want to connect to, comment out if using 'remote_host' +#define remote_ip IPAddress(10, 0, 0, 3) +// *** REMOTE HOST IS NOT YET WORKING *** +// replace with hostname of server you want to connect to, comment out if using 'remote_ip' +// #define remote_host "server.local" + +// STEP 2 [REQUIRED] +// Replace with the port that your server is listening on +#define remote_port 3030 + +// STEP 3 [REQUIRED unless using DHCP] +// Replace with your board or ethernet shield's IP address +// Comment out if you want to use DHCP +#define local_ip IPAddress(10, 0, 0, 15) + +// STEP 4 [REQUIRED] +// replace with ethernet shield mac. Must be unique for your network +const byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x53, 0xE5}; + +/*============================================================================== + * CONFIGURATION ERROR CHECK (don't change anything here) + *============================================================================*/ + +#if defined remote_ip && defined remote_host +#error "cannot define both remote_ip and remote_host at the same time in ethernetConfig.h" +#endif + +/*============================================================================== + * PIN IGNORE MACROS (don't change anything here) + *============================================================================*/ + +// ignore SPI pins, pin 10 (Ethernet SS) and pin 4 (SS for SD-Card on Ethernet shield) +#define IS_IGNORE_ETHERNET_SHIELD(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 10) diff --git a/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino b/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino new file mode 100644 index 000000000..657a9da1f --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino @@ -0,0 +1,838 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please clink on the following link + to open the list of Firmata client libraries your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +/* + README + + StandardFirmataPlus adds additional features that may exceed the Flash and + RAM sizes of Arduino boards such as ATMega328p (Uno) and ATMega32u4 + (Leonardo, Micro, Yun, etc). It is best to use StandardFirmataPlus with higher + memory boards such as the Arduino Mega, Arduino Due, Teensy 3.0/3.1/3.2. + + All Firmata examples that are appended with "Plus" add the following features: + + - Ability to interface with serial devices using UART, USART, or SoftwareSerial + depending on the capatilities of the board. + + At the time of this writing, StandardFirmataPlus will still compile and run + on ATMega328p and ATMega32u4-based boards, but future versions of this sketch + may not as new features are added. +*/ + +#include +#include +#include + +#include "utility/SerialFirmata.h" + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to run the main loop (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous more */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[32]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Serial output queue using Serial.print() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(8); // 8 = 8-bit resolution + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void setup() +{ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + // Save a couple of seconds by disabling the startup blink sequence. + Firmata.disableBlinkVersion(); + + // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega, + // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this: + // Serial1.begin(57600); + // Firmata.begin(Serial1); + // However do not do this if you are using SERIAL_MESSAGE + + Firmata.begin(57600); + while (!Serial) { + ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101 + } + + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * FTDI buffer using Serial.print() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) + Firmata.processInput(); + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif +} diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt b/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino b/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino new file mode 100644 index 000000000..bc616fec8 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino @@ -0,0 +1,1023 @@ +/* + Firmata is a generic protocol for communicating with microcontrollers + from software on a host computer. It is intended to work with + any host computer software package. + + To download a host software package, please clink on the following link + to open the list of Firmata client libraries your default browser. + + https://github.com/firmata/arduino#firmata-client-libraries + + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + Copyright (C) 2015-2016 Jesse Frush. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +/* + README + + StandardFirmataWiFi is a WiFi server application. You will need a Firmata client library with + a network transport in order to establish a connection with StandardFirmataWiFi. + + To use StandardFirmataWiFi you will need to have one of the following + boards or shields: + + - Arduino WiFi Shield (or clone) + - Arduino WiFi Shield 101 + - Arduino MKR1000 board (built-in WiFi 101) + - Adafruit HUZZAH CC3000 WiFi Shield (support coming soon) + + Follow the instructions in the wifiConfig.h file (wifiConfig.h tab in Arduino IDE) to + configure your particular hardware. + + Dependencies: + - WiFi Shield 101 requires version 0.7.0 or higher of the WiFi101 library (available in Arduino + 1.6.8 or higher, or update the library via the Arduino Library Manager or clone from source: + https://github.com/arduino-libraries/WiFi101) + + In order to use the WiFi Shield 101 with Firmata you will need a board with at least + 35k of Flash memory. This means you cannot use the WiFi Shield 101 with an Arduino Uno + or any other ATmega328p-based microcontroller or with an Arduino Leonardo or other + ATmega32u4-based microcontroller. Some boards that will work are: + + - Arduino Zero + - Arduino Due + - Arduino 101 + - Arduino Mega + + NOTE: If you are using an Arduino WiFi (legacy) shield you cannot use the following pins on + the following boards. Firmata will ignore any requests to use these pins: + + - Arduino Uno or other ATMega328 boards: (D4, D7, D10, D11, D12, D13) + - Arduino Mega: (D4, D7, D10, D50, D51, D52, D53) + - Arduino Due, Zero or Leonardo: (D4, D7, D10) + + If you are using an Arduino WiFi 101 shield you cannot use the following pins on the following + boards: + + - Arduino Due or Zero: (D5, D7, D10) + - Arduino Mega: (D5, D7, D10, D50, D52, D53) +*/ + +#include +#include +#include + +/* + * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your + * connection that may help in the event of connection issues. If defined, some boards may not begin + * executing this sketch until the Serial console is opened. + */ +//#define SERIAL_DEBUG +#include "utility/firmataDebug.h" + +/* + * Uncomment the following include to enable interfacing with Serial devices via hardware or + * software serial. Note that if enabled, this sketch will likely consume too much memory to run on + * an Arduino Uno or Leonardo or other ATmega328p-based or ATmega32u4-based boards. + */ +//#include "utility/SerialFirmata.h" + +// follow the instructions in wifiConfig.h to configure your particular hardware +#include "wifiConfig.h" + +#define I2C_WRITE B00000000 +#define I2C_READ B00001000 +#define I2C_READ_CONTINUOUSLY B00010000 +#define I2C_STOP_READING B00011000 +#define I2C_READ_WRITE_MODE_MASK B00011000 +#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 +#define I2C_END_TX_MASK B01000000 +#define I2C_STOP_TX 1 +#define I2C_RESTART_TX 0 +#define I2C_MAX_QUERIES 8 +#define I2C_REGISTER_NOT_SPECIFIED -1 + +// the minimum interval for sampling analog input +#define MINIMUM_SAMPLING_INTERVAL 1 + +#define WIFI_MAX_CONN_ATTEMPTS 3 + +/*============================================================================== + * GLOBAL VARIABLES + *============================================================================*/ + +#ifdef FIRMATA_SERIAL_FEATURE +SerialFirmata serialFeature; +#endif + +#ifdef STATIC_IP_ADDRESS +IPAddress local_ip(STATIC_IP_ADDRESS); +#endif + +int wifiConnectionAttemptCounter = 0; +int wifiStatus = WL_IDLE_STATUS; + +/* analog inputs */ +int analogInputsToReport = 0; // bitwise array to store pin reporting + +/* digital input ports */ +byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence +byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent + +/* pins configuration */ +byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else + +/* timer variables */ +unsigned long currentMillis; // store the current value from millis() +unsigned long previousMillis; // for comparison with currentMillis +unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) + +/* i2c data */ +struct i2c_device_info { + byte addr; + int reg; + byte bytes; + byte stopTX; +}; + +/* for i2c read continuous mode */ +i2c_device_info query[I2C_MAX_QUERIES]; + +byte i2cRxData[32]; +boolean isI2CEnabled = false; +signed char queryIndex = -1; +// default delay time between i2c read request and Wire.requestFrom() +unsigned int i2cReadDelayTime = 0; + +Servo servos[MAX_SERVOS]; +byte servoPinMap[TOTAL_PINS]; +byte detachedServos[MAX_SERVOS]; +byte detachedServoCount = 0; +byte servoCount = 0; + +boolean isResetting = false; + +/* utility functions */ +void wireWrite(byte data) +{ +#if ARDUINO >= 100 + Wire.write((byte)data); +#else + Wire.send(data); +#endif +} + +byte wireRead(void) +{ +#if ARDUINO >= 100 + return Wire.read(); +#else + return Wire.receive(); +#endif +} + +/*============================================================================== + * FUNCTIONS + *============================================================================*/ + +void attachServo(byte pin, int minPulse, int maxPulse) +{ + if (servoCount < MAX_SERVOS) { + // reuse indexes of detached servos until all have been reallocated + if (detachedServoCount > 0) { + servoPinMap[pin] = detachedServos[detachedServoCount - 1]; + if (detachedServoCount > 0) detachedServoCount--; + } else { + servoPinMap[pin] = servoCount; + servoCount++; + } + if (minPulse > 0 && maxPulse > 0) { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); + } else { + servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); + } + } else { + Firmata.sendString("Max servos attached"); + } +} + +void detachServo(byte pin) +{ + servos[servoPinMap[pin]].detach(); + // if we're detaching the last servo, decrement the count + // otherwise store the index of the detached servo + if (servoPinMap[pin] == servoCount && servoCount > 0) { + servoCount--; + } else if (servoCount > 0) { + // keep track of detached servos because we want to reuse their indexes + // before incrementing the count of attached servos + detachedServoCount++; + detachedServos[detachedServoCount - 1] = servoPinMap[pin]; + } + + servoPinMap[pin] = 255; +} + +void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { + // allow I2C requests that don't require a register read + // for example, some devices using an interrupt pin to signify new data available + // do not always require the register read so upon interrupt you call Wire.requestFrom() + if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { + Wire.beginTransmission(address); + wireWrite((byte)theRegister); + Wire.endTransmission(stopTX); // default = true + // do not set a value of 0 + if (i2cReadDelayTime > 0) { + // delay is necessary for some devices such as WiiNunchuck + delayMicroseconds(i2cReadDelayTime); + } + } else { + theRegister = 0; // fill the register with a dummy value + } + + Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom + + // check to be sure correct number of bytes were returned by slave + if (numBytes < Wire.available()) { + Firmata.sendString("I2C: Too many bytes received"); + } else if (numBytes > Wire.available()) { + Firmata.sendString("I2C: Too few bytes received"); + } + + i2cRxData[0] = address; + i2cRxData[1] = theRegister; + + for (int i = 0; i < numBytes && Wire.available(); i++) { + i2cRxData[2 + i] = wireRead(); + } + + // send slave address, register and received bytes + Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); +} + +void outputPort(byte portNumber, byte portValue, byte forceSend) +{ + // pins not configured as INPUT are cleared to zeros + portValue = portValue & portConfigInputs[portNumber]; + // only send if the value is different than previously sent + if (forceSend || previousPINs[portNumber] != portValue) { + Firmata.sendDigitalPort(portNumber, portValue); + previousPINs[portNumber] = portValue; + } +} + +/* ----------------------------------------------------------------------------- + * check all the active digital inputs for change of state, then add any events + * to the Stream output queue using Stream.write() */ +void checkDigitalInputs(void) +{ + /* Using non-looping code allows constants to be given to readPort(). + * The compiler will apply substantial optimizations if the inputs + * to readPort() are compile-time constants. */ + if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); + if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); + if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); + if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); + if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); + if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); + if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); + if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); + if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); + if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); + if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); + if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); + if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); + if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); + if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); + if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); +} + +// ----------------------------------------------------------------------------- +/* sets the pin mode to the correct state and sets the relevant bits in the + * two bit-arrays that track Digital I/O and PWM status + */ +void setPinModeCallback(byte pin, int mode) +{ + if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) + return; + + if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { + // disable i2c so pins can be used for other functions + // the following if statements should reconfigure the pins properly + disableI2CPins(); + } + if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + } + if (IS_PIN_ANALOG(pin)) { + reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting + } + if (IS_PIN_DIGITAL(pin)) { + if (mode == INPUT || mode == PIN_MODE_PULLUP) { + portConfigInputs[pin / 8] |= (1 << (pin & 7)); + } else { + portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); + } + } + Firmata.setPinState(pin, 0); + switch (mode) { + case PIN_MODE_ANALOG: + if (IS_PIN_ANALOG(pin)) { + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + } + Firmata.setPinMode(pin, PIN_MODE_ANALOG); + } + break; + case INPUT: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver +#if ARDUINO <= 100 + // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups +#endif + Firmata.setPinMode(pin, INPUT); + } + break; + case PIN_MODE_PULLUP: + if (IS_PIN_DIGITAL(pin)) { + pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); + Firmata.setPinMode(pin, PIN_MODE_PULLUP); + Firmata.setPinState(pin, 1); + } + break; + case OUTPUT: + if (IS_PIN_DIGITAL(pin)) { + digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM + pinMode(PIN_TO_DIGITAL(pin), OUTPUT); + Firmata.setPinMode(pin, OUTPUT); + } + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) { + pinMode(PIN_TO_PWM(pin), OUTPUT); + analogWrite(PIN_TO_PWM(pin), 0); + Firmata.setPinMode(pin, PIN_MODE_PWM); + } + break; + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) { + Firmata.setPinMode(pin, PIN_MODE_SERVO); + if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { + // pass -1 for min and max pulse values to use default values set + // by Servo library + attachServo(pin, -1, -1); + } + } + break; + case PIN_MODE_I2C: + if (IS_PIN_I2C(pin)) { + // mark the pin as i2c + // the user must call I2C_CONFIG to enable I2C for a device + Firmata.setPinMode(pin, PIN_MODE_I2C); + } + break; + case PIN_MODE_SERIAL: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); +#endif + break; + default: + Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM + } + // TODO: save status to EEPROM here, if changed +} + +/* + * Sets the value of an individual pin. Useful if you want to set a pin value but + * are not tracking the digital port state. + * Can only be used on pins configured as OUTPUT. + * Cannot be used to enable pull-ups on Digital INPUT pins. + */ +void setPinValueCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { + if (Firmata.getPinMode(pin) == OUTPUT) { + Firmata.setPinState(pin, value); + digitalWrite(PIN_TO_DIGITAL(pin), value); + } + } +} + +void analogWriteCallback(byte pin, int value) +{ + if (pin < TOTAL_PINS) { + switch (Firmata.getPinMode(pin)) { + case PIN_MODE_SERVO: + if (IS_PIN_DIGITAL(pin)) + servos[servoPinMap[pin]].write(value); + Firmata.setPinState(pin, value); + break; + case PIN_MODE_PWM: + if (IS_PIN_PWM(pin)) + analogWrite(PIN_TO_PWM(pin), value); + Firmata.setPinState(pin, value); + break; + } + } +} + +void digitalWriteCallback(byte port, int value) +{ + byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; + + if (port < TOTAL_PORTS) { + // create a mask of the pins on this port that are writable. + lastPin = port * 8 + 8; + if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; + for (pin = port * 8; pin < lastPin; pin++) { + // do not disturb non-digital pins (eg, Rx & Tx) + if (IS_PIN_DIGITAL(pin)) { + // do not touch pins in PWM, ANALOG, SERVO or other modes + if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { + pinValue = ((byte)value & mask) ? 1 : 0; + if (Firmata.getPinMode(pin) == OUTPUT) { + pinWriteMask |= mask; + } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { + // only handle INPUT here for backwards compatibility +#if ARDUINO > 100 + pinMode(pin, INPUT_PULLUP); +#else + // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier + pinWriteMask |= mask; +#endif + } + Firmata.setPinState(pin, pinValue); + } + } + mask = mask << 1; + } + writePort(port, (byte)value, pinWriteMask); + } +} + + +// ----------------------------------------------------------------------------- +/* sets bits in a bit array (int) to toggle the reporting of the analogIns + */ +//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { +//} +void reportAnalogCallback(byte analogPin, int value) +{ + if (analogPin < TOTAL_ANALOG_PINS) { + if (value == 0) { + analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); + } else { + analogInputsToReport = analogInputsToReport | (1 << analogPin); + // prevent during system reset or all analog pin values will be reported + // which may report noise for unconnected analog pins + if (!isResetting) { + // Send pin value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // TODO: save status to EEPROM here, if changed +} + +void reportDigitalCallback(byte port, int value) +{ + if (port < TOTAL_PORTS) { + reportPINs[port] = (byte)value; + // Send port value immediately. This is helpful when connected via + // ethernet, wi-fi or bluetooth so pin states can be known upon + // reconnecting. + if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); + } + // do not disable analog reporting on these 8 pins, to allow some + // pins used for digital, others analog. Instead, allow both types + // of reporting to be enabled, but check if the pin is configured + // as analog when sampling the analog inputs. Likewise, while + // scanning digital pins, portConfigInputs will mask off values from any + // pins configured as analog +} + +/*============================================================================== + * SYSEX-BASED commands + *============================================================================*/ + +void sysexCallback(byte command, byte argc, byte *argv) +{ + byte mode; + byte stopTX; + byte slaveAddress; + byte data; + int slaveRegister; + unsigned int delayTime; + + switch (command) { + case I2C_REQUEST: + mode = argv[1] & I2C_READ_WRITE_MODE_MASK; + if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { + Firmata.sendString("10-bit addressing not supported"); + return; + } + else { + slaveAddress = argv[0]; + } + + // need to invert the logic here since 0 will be default for client + // libraries that have not updated to add support for restart tx + if (argv[1] & I2C_END_TX_MASK) { + stopTX = I2C_RESTART_TX; + } + else { + stopTX = I2C_STOP_TX; // default + } + + switch (mode) { + case I2C_WRITE: + Wire.beginTransmission(slaveAddress); + for (byte i = 2; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + wireWrite(data); + } + Wire.endTransmission(); + delayMicroseconds(70); + break; + case I2C_READ: + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); + break; + case I2C_READ_CONTINUOUSLY: + if ((queryIndex + 1) >= I2C_MAX_QUERIES) { + // too many queries, just ignore + Firmata.sendString("too many queries"); + break; + } + if (argc == 6) { + // a slave register is specified + slaveRegister = argv[2] + (argv[3] << 7); + data = argv[4] + (argv[5] << 7); // bytes to read + } + else { + // a slave register is NOT specified + slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; + data = argv[2] + (argv[3] << 7); // bytes to read + } + queryIndex++; + query[queryIndex].addr = slaveAddress; + query[queryIndex].reg = slaveRegister; + query[queryIndex].bytes = data; + query[queryIndex].stopTX = stopTX; + break; + case I2C_STOP_READING: + byte queryIndexToSkip; + // if read continuous mode is enabled for only 1 i2c device, disable + // read continuous reporting for that device + if (queryIndex <= 0) { + queryIndex = -1; + } else { + queryIndexToSkip = 0; + // if read continuous mode is enabled for multiple devices, + // determine which device to stop reading and remove it's data from + // the array, shifiting other array data to fill the space + for (byte i = 0; i < queryIndex + 1; i++) { + if (query[i].addr == slaveAddress) { + queryIndexToSkip = i; + break; + } + } + + for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { + if (i < I2C_MAX_QUERIES) { + query[i].addr = query[i + 1].addr; + query[i].reg = query[i + 1].reg; + query[i].bytes = query[i + 1].bytes; + query[i].stopTX = query[i + 1].stopTX; + } + } + queryIndex--; + } + break; + default: + break; + } + break; + case I2C_CONFIG: + delayTime = (argv[0] + (argv[1] << 7)); + + if (delayTime > 0) { + i2cReadDelayTime = delayTime; + } + + if (!isI2CEnabled) { + enableI2CPins(); + } + + break; + case SERVO_CONFIG: + if (argc > 4) { + // these vars are here for clarity, they'll optimized away by the compiler + byte pin = argv[0]; + int minPulse = argv[1] + (argv[2] << 7); + int maxPulse = argv[3] + (argv[4] << 7); + + if (IS_PIN_DIGITAL(pin)) { + if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { + detachServo(pin); + } + attachServo(pin, minPulse, maxPulse); + setPinModeCallback(pin, PIN_MODE_SERVO); + } + } + break; + case SAMPLING_INTERVAL: + if (argc > 1) { + samplingInterval = argv[0] + (argv[1] << 7); + if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { + samplingInterval = MINIMUM_SAMPLING_INTERVAL; + } + } else { + //Firmata.sendString("Not enough data"); + } + break; + case EXTENDED_ANALOG: + if (argc > 1) { + int val = argv[1]; + if (argc > 2) val |= (argv[2] << 7); + if (argc > 3) val |= (argv[3] << 14); + analogWriteCallback(argv[0], val); + } + break; + case CAPABILITY_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(CAPABILITY_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_DIGITAL(pin)) { + Firmata.write((byte)INPUT); + Firmata.write(1); + Firmata.write((byte)PIN_MODE_PULLUP); + Firmata.write(1); + Firmata.write((byte)OUTPUT); + Firmata.write(1); + } + if (IS_PIN_ANALOG(pin)) { + Firmata.write(PIN_MODE_ANALOG); + Firmata.write(10); // 10 = 10-bit resolution + } + if (IS_PIN_PWM(pin)) { + Firmata.write(PIN_MODE_PWM); + Firmata.write(8); // 8 = 8-bit resolution + } + if (IS_PIN_DIGITAL(pin)) { + Firmata.write(PIN_MODE_SERVO); + Firmata.write(14); + } + if (IS_PIN_I2C(pin)) { + Firmata.write(PIN_MODE_I2C); + Firmata.write(1); // TODO: could assign a number to map to SCL or SDA + } +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleCapability(pin); +#endif + Firmata.write(127); + } + Firmata.write(END_SYSEX); + break; + case PIN_STATE_QUERY: + if (argc > 0) { + byte pin = argv[0]; + Firmata.write(START_SYSEX); + Firmata.write(PIN_STATE_RESPONSE); + Firmata.write(pin); + if (pin < TOTAL_PINS) { + Firmata.write(Firmata.getPinMode(pin)); + Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); + if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); + if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); + } + Firmata.write(END_SYSEX); + } + break; + case ANALOG_MAPPING_QUERY: + Firmata.write(START_SYSEX); + Firmata.write(ANALOG_MAPPING_RESPONSE); + for (byte pin = 0; pin < TOTAL_PINS; pin++) { + Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); + } + Firmata.write(END_SYSEX); + break; + + case SERIAL_MESSAGE: +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.handleSysex(command, argc, argv); +#endif + break; + } +} + +void enableI2CPins() +{ + byte i; + // is there a faster way to do this? would probaby require importing + // Arduino.h to get SCL and SDA pins + for (i = 0; i < TOTAL_PINS; i++) { + if (IS_PIN_I2C(i)) { + // mark pins as i2c so they are ignore in non i2c data requests + setPinModeCallback(i, PIN_MODE_I2C); + } + } + + isI2CEnabled = true; + + Wire.begin(); +} + +/* disable the i2c pins so they can be used for other functions */ +void disableI2CPins() { + isI2CEnabled = false; + // disable read continuous mode for all devices + queryIndex = -1; +} + +/*============================================================================== + * SETUP() + *============================================================================*/ + +void systemResetCallback() +{ + isResetting = true; + + // initialize a defalt state + // TODO: option to load config from EEPROM instead of default + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.reset(); +#endif + + if (isI2CEnabled) { + disableI2CPins(); + } + + for (byte i = 0; i < TOTAL_PORTS; i++) { + reportPINs[i] = false; // by default, reporting off + portConfigInputs[i] = 0; // until activated + previousPINs[i] = 0; + } + + for (byte i = 0; i < TOTAL_PINS; i++) { + // pins with analog capability default to analog input + // otherwise, pins default to digital output + if (IS_PIN_ANALOG(i)) { + // turns off pullup, configures everything + setPinModeCallback(i, PIN_MODE_ANALOG); + } else if (IS_PIN_DIGITAL(i)) { + // sets the output to 0, configures portConfigInputs + setPinModeCallback(i, OUTPUT); + } + + servoPinMap[i] = 255; + } + // by default, do not report any analog inputs + analogInputsToReport = 0; + + detachedServoCount = 0; + servoCount = 0; + + /* send digital inputs to set the initial state on the host computer, + * since once in the loop(), this firmware will only send on change */ + /* + TODO: this can never execute, since no pins default to digital input + but it will be needed when/if we support EEPROM stored config + for (byte i=0; i < TOTAL_PORTS; i++) { + outputPort(i, readPort(i, portConfigInputs[i]), true); + } + */ + isResetting = false; +} + +void printWifiStatus() { +#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + if ( WiFi.status() != WL_CONNECTED ) + { + DEBUG_PRINT( "WiFi connection failed. Status value: " ); + DEBUG_PRINTLN( WiFi.status() ); + } + else +#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + { + // print the SSID of the network you're attached to: + DEBUG_PRINT( "SSID: " ); + +#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + DEBUG_PRINTLN( WiFi.SSID() ); +#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + + // print your WiFi shield's IP address: + DEBUG_PRINT( "IP Address: " ); + +#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + IPAddress ip = WiFi.localIP(); + DEBUG_PRINTLN( ip ); +#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + + // print the received signal strength: + DEBUG_PRINT( "signal strength (RSSI): " ); + +#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + long rssi = WiFi.RSSI(); + DEBUG_PRINT( rssi ); +#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) + + DEBUG_PRINTLN( " dBm" ); + } +} + +void setup() +{ + /* + * WIFI SETUP + */ + DEBUG_BEGIN(9600); + + /* + * This statement will clarify how a connection is being made + */ + DEBUG_PRINT( "StandardFirmataWiFi will attempt a WiFi connection " ); +#if defined(WIFI_101) + DEBUG_PRINTLN( "using the WiFi 101 library." ); +#elif defined(ARDUINO_WIFI_SHIELD) + DEBUG_PRINTLN( "using the legacy WiFi library." ); +#elif defined(HUZZAH_WIFI) + DEBUG_PRINTLN( "using the HUZZAH WiFi library." ); + //else should never happen here as error-checking in wifiConfig.h will catch this +#endif //defined(WIFI_101) + + /* + * Configure WiFi IP Address + */ +#ifdef STATIC_IP_ADDRESS + DEBUG_PRINT( "Using static IP: " ); + DEBUG_PRINTLN( local_ip ); + //you can also provide a static IP in the begin() functions, but this simplifies + //ifdef logic in this sketch due to support for all different encryption types. + stream.config( local_ip ); +#else + DEBUG_PRINTLN( "IP will be requested from DHCP ..." ); +#endif + + /* + * Configure WiFi security + */ +#if defined(WIFI_WEP_SECURITY) + while (wifiStatus != WL_CONNECTED) { + DEBUG_PRINT( "Attempting to connect to WEP SSID: " ); + DEBUG_PRINTLN(ssid); + wifiStatus = stream.begin( ssid, wep_index, wep_key, SERVER_PORT ); + delay(5000); // TODO - determine minimum delay + if (++wifiConnectionAttemptCounter > WIFI_MAX_CONN_ATTEMPTS) break; + } + +#elif defined(WIFI_WPA_SECURITY) + while (wifiStatus != WL_CONNECTED) { + DEBUG_PRINT( "Attempting to connect to WPA SSID: " ); + DEBUG_PRINTLN(ssid); + wifiStatus = stream.begin(ssid, wpa_passphrase, SERVER_PORT); + delay(5000); // TODO - determine minimum delay + if (++wifiConnectionAttemptCounter > WIFI_MAX_CONN_ATTEMPTS) break; + } + +#else //OPEN network + while (wifiStatus != WL_CONNECTED) { + DEBUG_PRINTLN( "Attempting to connect to open SSID: " ); + DEBUG_PRINTLN(ssid); + wifiStatus = stream.begin(ssid, SERVER_PORT); + delay(5000); // TODO - determine minimum delay + if (++wifiConnectionAttemptCounter > WIFI_MAX_CONN_ATTEMPTS) break; + } +#endif //defined(WIFI_WEP_SECURITY) + + DEBUG_PRINTLN( "WiFi setup done" ); + printWifiStatus(); + + /* + * FIRMATA SETUP + */ + Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); + + Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); + Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); + Firmata.attach(REPORT_ANALOG, reportAnalogCallback); + Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); + Firmata.attach(SET_PIN_MODE, setPinModeCallback); + Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); + Firmata.attach(START_SYSEX, sysexCallback); + Firmata.attach(SYSTEM_RESET, systemResetCallback); + + // StandardFirmataWiFi communicates with WiFi shields over SPI. Therefore all + // SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. + // Additional pins may also need to be ignored depending on the particular board or + // shield in use. + + for (byte i = 0; i < TOTAL_PINS; i++) { +#if defined(ARDUINO_WIFI_SHIELD) + if (IS_IGNORE_WIFI_SHIELD(i) + #if defined(__AVR_ATmega32U4__) + || 24 == i // On Leonardo, pin 24 maps to D4 and pin 28 maps to D10 + || 28 == i + #endif //defined(__AVR_ATmega32U4__) + ) { +#elif defined (WIFI_101) + if (IS_IGNORE_WIFI101_SHIELD(i)) { +#elif defined (HUZZAH_WIFI) + // TODO + if (false) { +#else + if (false) { +#endif + Firmata.setPinMode(i, PIN_MODE_IGNORE); + } + } + + //Set up controls for the Arduino WiFi Shield SS for the SD Card +#ifdef ARDUINO_WIFI_SHIELD + // Arduino WiFi, Arduino WiFi Shield and Arduino Yun all have SD SS wired to D4 + pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata + digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; + +#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA +#endif //defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + +#endif //ARDUINO_WIFI_SHIELD + + // start up Network Firmata: + Firmata.begin(stream); + systemResetCallback(); // reset to default config +} + +/*============================================================================== + * LOOP() + *============================================================================*/ +void loop() +{ + byte pin, analogPin; + + /* DIGITALREAD - as fast as possible, check for changes and output them to the + * Stream buffer using Stream.write() */ + checkDigitalInputs(); + + /* STREAMREAD - processing incoming messagse as soon as possible, while still + * checking digital inputs. */ + while (Firmata.available()) { + Firmata.processInput(); + } + + // TODO - ensure that Stream buffer doesn't go over 60 bytes + + currentMillis = millis(); + if (currentMillis - previousMillis > samplingInterval) { + previousMillis += samplingInterval; + /* ANALOGREAD - do all analogReads() at the configured sampling interval */ + for (pin = 0; pin < TOTAL_PINS; pin++) { + if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { + analogPin = PIN_TO_ANALOG(pin); + if (analogInputsToReport & (1 << analogPin)) { + Firmata.sendAnalog(analogPin, analogRead(analogPin)); + } + } + } + // report i2c data for all device with read continuous mode enabled + if (queryIndex > -1) { + for (byte i = 0; i < queryIndex + 1; i++) { + readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); + } + } + } + +#ifdef FIRMATA_SERIAL_FEATURE + serialFeature.update(); +#endif + + stream.maintain(); +} diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h b/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h new file mode 100644 index 000000000..3cd4b5cd9 --- /dev/null +++ b/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h @@ -0,0 +1,155 @@ +/*============================================================================== + * WIFI CONFIGURATION + * + * You must configure your particular hardware. Follow the steps below. + * + * Currently StandardFirmataWiFi is configured as a server. An option to + * configure as a client may be added in the future. + *============================================================================*/ + +// STEP 1 [REQUIRED] +// Uncomment / comment the appropriate set of includes for your hardware (OPTION A, B or C) +// Option A is enabled by default. + +/* + * OPTION A: Configure for Arduino WiFi shield + * + * This will configure StandardFirmataWiFi to use the original WiFi library (deprecated) provided + * with the Arduino IDE. It is supported by the Arduino WiFi shield (a discontinued product) and + * is compatible with 802.11 B/G networks. + * + * To configure StandardFirmataWiFi to use the Arduino WiFi shield + * leave the #define below uncommented. + */ +#define ARDUINO_WIFI_SHIELD + +//do not modify these next 4 lines +#ifdef ARDUINO_WIFI_SHIELD +#include "utility/WiFiStream.h" +WiFiStream stream; +#endif + +/* + * OPTION B: Configure for WiFi 101 + * + * This will configure StandardFirmataWiFi to use the WiFi101 library, which works with the Arduino WiFi101 + * shield and devices that have the WiFi101 chip built in (such as the MKR1000). It is compatible + * with 802.11 B/G/N networks. + * + * To enable, uncomment the #define WIFI_101 below and verify the #define values under + * options A and C are commented out. + * + * IMPORTANT: You must have the WiFI 101 library installed. To easily install this library, opent the library manager via: + * Arduino IDE Menus: Sketch > Include Library > Manage Libraries > filter search for "WiFi101" > Select the result and click 'install' + */ +//#define WIFI_101 + +//do not modify these next 4 lines +#ifdef WIFI_101 +#include "utility/WiFi101Stream.h" +WiFi101Stream stream; +#endif + +/* + * OPTION C: Configure for HUZZAH + * + * HUZZAH is not yet supported, this will be added in a later revision to StandardFirmataWiFi + */ + +//------------------------------ +// TODO +//------------------------------ +//#define HUZZAH_WIFI + + +// STEP 2 [REQUIRED for all boards and shields] +// replace this with your wireless network SSID +char ssid[] = "your_network_name"; + +// STEP 3 [OPTIONAL for all boards and shields] +// if you want to use a static IP (v4) address, uncomment the line below. You can also change the IP. +// if this line is commented out, the WiFi shield will attempt to get an IP from the DHCP server +// #define STATIC_IP_ADDRESS 192,168,1,113 + +// STEP 4 [REQUIRED for all boards and shields] +// define your port number here, you will need this to open a TCP connection to your Arduino +#define SERVER_PORT 3030 + +// STEP 5 [REQUIRED for all boards and shields] +// determine your network security type (OPTION A, B, or C). Option A is the most common, and the default. + + +/* + * OPTION A: WPA / WPA2 + * + * WPA is the most common network security type. A passphrase is required to connect to this type. + * + * To enable, leave #define WIFI_WPA_SECURITY uncommented below, set your wpa_passphrase value appropriately, + * and do not uncomment the #define values under options B and C + */ +#define WIFI_WPA_SECURITY + +#ifdef WIFI_WPA_SECURITY +char wpa_passphrase[] = "your_wpa_passphrase"; +#endif //WIFI_WPA_SECURITY + +/* + * OPTION B: WEP + * + * WEP is a less common (and regarded as less safe) security type. A WEP key and its associated index are required + * to connect to this type. + * + * To enable, Uncomment the #define below, set your wep_index and wep_key values appropriately, and verify + * the #define values under options A and C are commented out. + */ +//#define WIFI_WEP_SECURITY + +#ifdef WIFI_WEP_SECURITY +//The wep_index below is a zero-indexed value. +//Valid indices are [0-3], even if your router/gateway numbers your keys [1-4]. +byte wep_index = 0; +char wep_key[] = "your_wep_key"; +#endif //WIFI_WEP_SECURITY + + +/* + * OPTION C: Open network (no security) + * + * Open networks have no security, can be connected to by any device that knows the ssid, and are unsafe. + * + * To enable, uncomment #define WIFI_NO_SECURITY below and verify the #define values + * under options A and B are commented out. + */ +//#define WIFI_NO_SECURITY + +/*============================================================================== + * CONFIGURATION ERROR CHECK (don't change anything here) + *============================================================================*/ + +#if ((defined(ARDUINO_WIFI_SHIELD) && (defined(WIFI_101) || defined(HUZZAH_WIFI))) || (defined(WIFI_101) && defined(HUZZAH_WIFI))) +#error "you may not define more than one wifi device type in wifiConfig.h." +#endif //WIFI device type check + +#if !(defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) || defined(HUZZAH_WIFI)) +#error "you must define a wifi device type in wifiConfig.h." +#endif + +#if ((defined(WIFI_NO_SECURITY) && (defined(WIFI_WEP_SECURITY) || defined(WIFI_WPA_SECURITY))) || (defined(WIFI_WEP_SECURITY) && defined(WIFI_WPA_SECURITY))) +#error "you may not define more than one security type at the same time in wifiConfig.h." +#endif //WIFI_* security define check + +#if !(defined(WIFI_NO_SECURITY) || defined(WIFI_WEP_SECURITY) || defined(WIFI_WPA_SECURITY)) +#error "you must define a wifi security type in wifiConfig.h." +#endif //WIFI_* security define check + +/*============================================================================== + * PIN IGNORE MACROS (don't change anything here) + *============================================================================*/ + +// ignore SPI pins, pin 5 (reset WiFi101 shield), pin 7 (WiFi handshake) and pin 10 (WiFi SS) +// also don't ignore SS pin if it's not pin 10 +// TODO - need to differentiate between Arduino WiFi1 101 Shield and Arduino MKR1000 +#define IS_IGNORE_WIFI101_SHIELD(p) ((p) == 10 || (IS_PIN_SPI(p) && (p) != SS) || (p) == 5 || (p) == 7) + +// ignore SPI pins, pin 4 (SS for SD-Card on WiFi-shield), pin 7 (WiFi handshake) and pin 10 (WiFi SS) +#define IS_IGNORE_WIFI_SHIELD(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 7 || (p) == 10) diff --git a/libraries/Firmata/extras/LICENSE.txt b/libraries/Firmata/extras/LICENSE.txt new file mode 100644 index 000000000..77cec6dd1 --- /dev/null +++ b/libraries/Firmata/extras/LICENSE.txt @@ -0,0 +1,458 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + diff --git a/libraries/Firmata/extras/revisions.txt b/libraries/Firmata/extras/revisions.txt new file mode 100644 index 000000000..7d129327c --- /dev/null +++ b/libraries/Firmata/extras/revisions.txt @@ -0,0 +1,202 @@ +FIRMATA 2.5.2 - Feb 15, 2016 + +[core library] +* Added Wi-Fi transport (Jesse Frush) +* Added support for Arduino MKR1000 (Jesse Frush) +* Moved Serial feature to own class SerialFimata +* Moved pin config and pin state handling to Firmata.cpp +* Added new method disableBlinkVersion to provide a way to optionally bypass startup blink sequence + +[StandardFirmata & variants] +* Added StandardFirmataWiFi (Jesse Frush) +* Added ethernetConfig.h for StandardFirmataEthernet and StandardFirmtaEthernetPlus +* Removed serialUtils.h and using SerialFirmata class instead for Serial feature + +FIRMATA 2.5.1 - Dec 26, 2015 + +[core library] +* Added support for Arduino 101 +* Make VERSION_BLINK_PIN optional +* Separate protocol version from firmware version. + Use FIRMATA_PROTOCOL_VERSION_[MAJOR/MINOR/BUGFIX] for protocol and use + FIRMATA_FIRMWARE_VERSION_[MAJOR/MINOR/BUGFIX] for firmware (library version). + +[StandardFirmata & variants] +* Added ability to auto-restart I2C transmission by setting bit 6 of byte 3 + of the I2C_REQUEST message. + +FIRMATA 2.5.0 - Nov 7, 2015 + +[core library] +* Added Serial feature for interfacing with serial devices via hardware + or software serial. See github.com/firmata/protocol/serial.md for details +* Added ability to set the value of a pin by sending a single value instead + of a port value. See 'set digital pin value' in github.com/firmata/protocol/protocol.md + for details +* Added support for Arduino Zero board +* Added support for Teensy LC board (copied from Teensy Firmata lib) +* Added support for Pinoccio Scout board (Pawel Szymczykowski) +* Lowered minimun sampling interval from 10 to 1 millisecond +* Added new pin mode (PIN_MODE_PULLUP) for setting the INPUT_PULLUP pin mode +* Changed pin mode defines to safer names (old names still included but + deprecated) - see Firmata.h + +[StandardFirmata & variants] +* Created new StandardFirmataPlus that implements the Serial feature + Note: The new Serial features is only implemented in the "Plus" versions of + StandardFirmata. +* Created new StandardFirmataEthernetPlus that implements the Serial feature +* Fixed issue where StandardFirmata was not compiling for Intel Galileo boards +* Moved StandardFirmataYun to its own repo (github.com/firmata/StandardFirmataYun) + +FIRMATA 2.4.4 - Aug 9, 2015 + +[core library] +* Added support for chipKIT boards (Brian Schmalz, Rick Anderson and Keith Vogel) +* Added support for ATmega328 boards (previously only ATmega328p was supported) + +[StandardFirmata] +* Added StandardFirmataChipKIT for ChipKIT boards (Brian Schmalz, Rick Anderson and Keith Vogel) +* Ensure Serial is ready on Leonardo and other ATMega32u4-based boards + +FIRMATA 2.4.3 - Apr 11, 2015 + +[core library] +* Added debug macros (utility/firmataDebug.h) +* Added Norbert Truchsess' EthernetClientStream lib from the configurable branch + +[examples] +* Added StandardFirmataEthernet to enable Firmata over Ethernet +* Minor updates to StandardFirmata and StandardFirmataYun + +FIRMATA 2.4.2 - Mar 16, 2015 + +[core library] +* Add support for Teesy 3.1 (Olivier Louvignes) + +FIRMATA 2.4.1 - Feb 7, 2015 + +[core library] +* Fixed off-by-one bug in setFirmwareNameAndVersion (Brian Schmalz) + +[StandardFirmata] +* Prevent analog values from being reported during system reset + +FIRMATA 2.4.0 - Dec 21, 2014 + +Changes from 2.3.6 to 2.4 that may impact existing Firmata client implementations: + +* When sending a string from the client application to the board (STRING_DATA) a +static buffer is now used for the incoming string in place of a dynamically allocated +block of memory (see Firmata.cpp lines 181 - 205). In Firmata 2.3.6 and older, +the dynamically allocated block was never freed, causing a memory leak. If your +client library had freed this memory in the string callback method, that code +will break in Firmata 2.4. If the string data needs to persist beyond the string +callback, it should be copied within the string callback. + +* As of Firmata 2.4, when digital port reporting or analog pin reporting is enabled, +the value of the port (digital) or pin (analog) is immediately sent back to the client +application. This will likely not have a negative impact on existing client +implementations, but may be unexpected. This feature was added to better support +non-serial streams (such as Ethernet, Wi-Fi, Bluetooth, etc) that may lose +connectivity and need a quick way to get the current state of the pins upon +reestablishing a connection. + +[core library] +* Changed sendValueAsTwo7bitBytes, startSysex and endSysex from private to + public methods. +* Added Intel Galileo to Boards.h +* Renamed FirmataSerial to FirmataStream +* Updated to latest Arduino library format +* writePort function in Boards.h now returns 1 (to suppress compiler warning) +* Updated syntax highlighting (keywords.txt) +* Fixed IS_PIN_SPI ifndef condition in boards.h +* Added constants to Firmata.h to reserve configurable firmata features +* Fixed issue where firmwareName was not reported correctly in Windows +* Ensure incoming String via STRING_DATA command is null-terminated +* Fixed memory leak when receiving String via STRING_DATA command + (note this change may break existing code if you were manually deallocating + the incoming string in your string callback function. See code for details) +* Added ability for user to specify a filename when calling setFirmwareNameAndVersion +* Increased input data buffer size from 32 to 64 bytes + +[StandardFirmata] +* Updated I2C_READ_CONTINUOUSLY to work with or without slaveRegister (Rick Waldron) +* Added Yun variant of StandardFirmata +* When a digital port is enabled, its value is now immediately sent to the client +* When an analog pin is enabled, its value is now immediately sent to the client +* Changed the way servo pins are mapped to enable use of servos on + a wider range of pins, including analog pins. +* Fixed management of unexpected sized I2C replies (Nahuel Greco) +* Fixed a bug when removing a monitored device with I2C_STOP_Reading (Nahuel Greco) +* Fixed conditional expression in I2C_STOP_READING case +* Changed samplingInterval from type int to type unsigned int +* Shortened error message strings to save a few bytes + +[examples] +* Updated FirmataServo example to use new pin mapping technique +* Removed makefiles from examples (because they were not being updated) +* Updated all examples to set current firmware version + +FIRMATA 2.3.6 - Jun 18, 2013 (Version included with Arduino core libraries) + +[core library] +* Fixed bug introduced in 2.3.5 that broke ability to use Ethernet. + +FIRMATA 2.3.5 - May 21, 2013 + +[core library] +* Added Arduino Due to Boards.h +* Added Teensy 3.0 to Boards.h +* Updated unit tests to use ArduinoUnit v2.0 +* Renamed pin13strobe to strobeBlinkPin +* Removed blinkVersion method from begin method for non-serial streams +* Fixed memory leak in setting firmware version (Matthew Murdoch) +* Added unit tests for a few core functions (Matthew Murdoch) +* Added IS_PIN_SPI macro to all board definitions in Board.h (Norbert Truchsess) + +FIRMATA 2.3.4 - Feb 11, 2013 + +[core library] +* Fixed Stream implementation so Firmata can be used with Streams other than + Serial (Norbert Truchsess) + +FIRMATA 2.3.3 - Oct 6, 2012 + +[core library] +* Added write method to expose FirmataSerial.write +* Added Arduino Leonardo to Boards.h + +[StandardFirmata] +* Changed all instances of Serial.write to Firmata.write +* Fixed delayMicroseconds(0) bug in readAndReportData + +FIRMATA 2.3.0 - 2.3.2 + +* Removed angle from servo config +* Changed file extensions from .pde to .ino +* Added MEGA2560 to Boards.h +* Added I2C pins to Boards.h +* Modified examples to be compatible with Arduino 0022 and 1.0 or greater +* Removed I2CFirmata example +* Changes to StandardFirmata + * Added I2C support + * Added system reset message to reset all pins to default config on sysex reset + +FIRMATA 2.2 (changes prior to Firmata 2.3.0 were not well documented) + +* changes undocumented + +FIRMATA 2.1 + +* added support for changing the sampling interval +* added Servo support + +FIRMATA 2.0 + +* changed to 8-bit port-based digital messages to mirror ports from previous 14-bit ports modeled after the standard Arduino board. +* switched order of version message so major version is reported first + +FIRMATA 1.0 + +* switched to MIDI-compatible packet format (though the message interpretation differs) diff --git a/libraries/Firmata/keywords.txt b/libraries/Firmata/keywords.txt new file mode 100644 index 000000000..5ab13d05d --- /dev/null +++ b/libraries/Firmata/keywords.txt @@ -0,0 +1,90 @@ +####################################### +# Syntax Coloring Map For Firmata +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Firmata KEYWORD1 Firmata +callbackFunction KEYWORD1 callbackFunction +systemResetCallbackFunction KEYWORD1 systemResetCallbackFunction +stringCallbackFunction KEYWORD1 stringCallbackFunction +sysexCallbackFunction KEYWORD1 sysexCallbackFunction + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +printVersion KEYWORD2 +blinkVersion KEYWORD2 +printFirmwareVersion KEYWORD2 +setFirmwareVersion KEYWORD2 +setFirmwareNameAndVersion KEYWORD2 +available KEYWORD2 +processInput KEYWORD2 +isParsingMessage KEYWORD2 +parse KEYWORD2 +sendAnalog KEYWORD2 +sendDigital KEYWORD2 +sendDigitalPort KEYWORD2 +sendString KEYWORD2 +sendSysex KEYWORD2 +getPinMode KEYWORD2 +setPinMode KEYWORD2 +getPinState KEYWORD2 +setPinState KEYWORD2 +attach KEYWORD2 +detach KEYWORD2 +write KEYWORD2 +sendValueAsTwo7bitBytes KEYWORD2 +startSysex KEYWORD2 +endSysex KEYWORD2 +writePort KEYWORD2 +readPort KEYWORD2 +disableBlinkVersion KEYWORD2 + + +####################################### +# Constants (LITERAL1) +####################################### + +FIRMATA_MAJOR_VERSION LITERAL1 +FIRMATA_MINOR_VERSION LITERAL1 +FIRMATA_BUGFIX_VERSION LITERAL1 + +MAX_DATA_BYTES LITERAL1 + +DIGITAL_MESSAGE LITERAL1 +ANALOG_MESSAGE LITERAL1 +REPORT_ANALOG LITERAL1 +REPORT_DIGITAL LITERAL1 +REPORT_VERSION LITERAL1 +SET_PIN_MODE LITERAL1 +SET_DIGITAL_PIN_VALUE LITERAL1 +SYSTEM_RESET LITERAL1 +START_SYSEX LITERAL1 +END_SYSEX LITERAL1 +REPORT_FIRMWARE LITERAL1 +STRING_DATA LITERAL1 + +PIN_MODE_ANALOG LITERAL1 +PIN_MODE_PWM LITERAL1 +PIN_MODE_SERVO LITERAL1 +PIN_MODE_SHIFT LITERAL1 +PIN_MODE_I2C LITERAL1 +PIN_MODE_ONEWIRE LITERAL1 +PIN_MODE_STEPPER LITERAL1 +PIN_MODE_ENCODER LITERAL1 +PIN_MODE_SERIAL LITERAL1 +PIN_MODE_PULLUP LITERAL1 +PIN_MODE_IGNORE LITERAL1 + +TOTAL_PINS LITERAL1 +TOTAL_ANALOG_PINS LITERAL1 +TOTAL_DIGITAL_PINS LITERAL1 +TOTAL_PIN_MODES LITERAL1 +TOTAL_PORTS LITERAL1 +ANALOG_PORT LITERAL1 +MAX_SERVOS LITERAL1 diff --git a/libraries/Firmata/library.properties b/libraries/Firmata/library.properties new file mode 100644 index 000000000..53f26f187 --- /dev/null +++ b/libraries/Firmata/library.properties @@ -0,0 +1,9 @@ +name=Firmata +version=2.5.2 +author=Firmata Developers +maintainer=https://github.com/firmata/arduino +sentence=Enables the communication with computer apps using a standard serial protocol. For all Arduino boards. +paragraph=The Firmata library implements the Firmata protocol for communicating with software on the host computer. This allows you to write custom firmware without having to create your own protocol and objects for the programming environment that you are using. +category=Device Control +url=https://github.com/firmata/arduino +architectures=* diff --git a/libraries/Firmata/readme.md b/libraries/Firmata/readme.md new file mode 100644 index 000000000..b1ecaf181 --- /dev/null +++ b/libraries/Firmata/readme.md @@ -0,0 +1,177 @@ +#Firmata + +[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/firmata/arduino?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) + +Firmata is a protocol for communicating with microcontrollers from software on a host computer. The [protocol](https://github.com/firmata/protocol) can be implemented in firmware on any microcontroller architecture as well as software on any host computer software package. The Arduino repository described here is a Firmata library for Arduino and Arduino-compatible devices. If you would like to contribute to Firmata, please see the [Contributing](#contributing) section below. + +##Usage + +There are two main models of usage of Firmata. In one model, the author of the Arduino sketch uses the various methods provided by the Firmata library to selectively send and receive data between the Arduino device and the software running on the host computer. For example, a user can send analog data to the host using ``` Firmata.sendAnalog(analogPin, analogRead(analogPin)) ``` or send data packed in a string using ``` Firmata.sendString(stringToSend) ```. See File -> Examples -> Firmata -> AnalogFirmata & EchoString respectively for examples. + +The second and more common model is to load a general purpose sketch called StandardFirmata (or one of the variants such as StandardFirmataPlus or StandardFirmataEthernet depending on your needs) on the Arduino board and then use the host computer exclusively to interact with the Arduino board. StandardFirmata is located in the Arduino IDE in File -> Examples -> Firmata. + +##Firmata Client Libraries +Most of the time you will be interacting with Arduino with a client library on the host computers. Several Firmata client libraries have been implemented in a variety of popular programming languages: + +* processing + * [https://github.com/firmata/processing] + * [http://funnel.cc] +* python + * [https://github.com/MrYsLab/pymata-aio] + * [https://github.com/MrYsLab/PyMata] + * [https://github.com/tino/pyFirmata] + * [https://github.com/lupeke/python-firmata] + * [https://github.com/firmata/pyduino] +* perl + * [https://github.com/ntruchsess/perl-firmata] + * [https://github.com/rcaputo/rx-firmata] +* ruby + * [https://github.com/hardbap/firmata] + * [https://github.com/PlasticLizard/rufinol] + * [http://funnel.cc] +* clojure + * [https://github.com/nakkaya/clodiuno] + * [https://github.com/peterschwarz/clj-firmata] +* javascript + * [https://github.com/jgautier/firmata] + * [https://github.com/rwldrn/johnny-five] + * [http://breakoutjs.com] +* java + * [https://github.com/kurbatov/firmata4j] + * [https://github.com/4ntoine/Firmata] + * [https://github.com/reapzor/FiloFirmata] +* .NET + * [https://github.com/SolidSoils/Arduino] + * [http://www.imagitronics.org/projects/firmatanet/] +* Flash/AS3 + * [http://funnel.cc] + * [http://code.google.com/p/as3glue/] +* PHP + * [https://bitbucket.org/ThomasWeinert/carica-firmata] + * [https://github.com/oasynnoum/phpmake_firmata] +* Haskell + * [http://hackage.haskell.org/package/hArduino] +* iOS + * [https://github.com/jacobrosenthal/iosfirmata] +* Dart + * [https://github.com/nfrancois/firmata] +* Max/MSP + * [http://www.maxuino.org/] +* Elixir + * [https://github.com/kfatehi/firmata] +* Modelica + * [https://www.wolfram.com/system-modeler/libraries/model-plug/] +* golang + * [https://github.com/kraman/go-firmata] + +Note: The above libraries may support various versions of the Firmata protocol and therefore may not support all features of the latest Firmata spec nor all Arduino and Arduino-compatible boards. Refer to the respective projects for details. + +##Updating Firmata in the Arduino IDE - Arduino 1.6.4 and higher + +If you want to update to the latest stable version: + +1. Open the Arduino IDE and navigate to: `Sketch > Include Library > Manage Libraries` +2. Filter by "Firmata" and click on the "Firmata by Firmata Developers" item in the list of results. +3. Click the `Select version` dropdown and select the most recent version (note you can also install previous versions) +4. Click `Install`. + +###Cloning Firmata + +If you are contributing to Firmata or otherwise need a version newer than the latest tagged release, you can clone Firmata directly to your Arduino/libraries/ directory (where 3rd party libraries are installed). This only works for Arduino 1.6.4 and higher, for older versions you need to clone into the Arduino application directory (see section below titled "Using the Source code rather than release archive"). Be sure to change the name to Firmata as follows: + +```bash +$ git clone git@github.com:firmata/arduino.git ~/Documents/Arduino/libraries/Firmata +``` + +*Update path above if you're using Windows or Linux or changed the default Arduino directory on OS X* + + +##Updating Firmata in the Arduino IDE - older versions (<= 1.6.3 or 1.0.x) + +Download the latest [release](https://github.com/firmata/arduino/releases/tag/2.5.2) (for Arduino 1.0.x or Arduino 1.5.6 or higher) and replace the existing Firmata folder in your Arduino application. See the instructions below for your platform. + +*Note that Arduino 1.5.0 - 1.5.5 are not supported. Please use Arduino 1.5.6 or higher (or Arduino 1.0.5 or 1.0.6).* + +###Mac OSX: + +The Firmata library is contained within the Arduino package. + +1. Navigate to the Arduino application +2. Right click on the application icon and select `Show Package Contents` +3. Navigate to: `/Contents/Resources/Java/libraries/` and replace the existing +`Firmata` folder with latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.2) (note there is a different download +for Arduino 1.0.x vs 1.6.x) +4. Restart the Arduino application and the latest version of Firmata will be available. + +*If you are using the Java 7 version of Arduino 1.5.7 or higher, the file path +will differ slightly: `Contents/Java/libraries/Firmata` (no Resources directory).* + +###Windows: + +1. Navigate to `c:/Program\ Files/arduino-1.x/libraries/` and replace the existing +`Firmata` folder with the latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.2) (note there is a different download +for Arduino 1.0.x vs 1.6.x). +2. Restart the Arduino application and the latest version of Firmata will be available. + +*Update the path and Arduino version as necessary* + +###Linux: + +1. Navigate to `~/arduino-1.x/libraries/` and replace the existing +`Firmata` folder with the latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.2) (note there is a different download +for Arduino 1.0.x vs 1.6.x). +2. Restart the Arduino application and the latest version of Firmata will be available. + +*Update the path and Arduino version as necessary* + +###Using the Source code rather than release archive (only for versions older than Arduino 1.6.3) + +*It is recommended you update to Arduino 1.6.4 or higher if possible, that way you can clone directly into the external Arduino/libraries/ directory which persists between Arduino application updates. Otherwise you will need to move your clone each time you update to a newer version of the Arduino IDE.* + +If you're stuck with an older version of the IDE, then follow these keep reading otherwise jump up to the "Cloning Firmata section above". + +Clone this repo directly into the core Arduino application libraries directory. If you are using +Arduino 1.5.x or <= 1.6.3, the repo directory structure will not match the Arduino +library format, however it should still compile as long as you are using Arduino 1.5.7 +or higher. + +You will first need to remove the existing Firmata library, then clone firmata/arduino +into an empty Firmata directory: + +```bash +$ rm -r /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata +$ git clone git@github.com:firmata/arduino.git /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata +``` + +*Update paths if you're using Windows or Linux* + +To generate properly formatted versions of Firmata (for Arduino 1.0.x and Arduino 1.6.x), run the +`release.sh` script. + + + +##Contributing + +If you discover a bug or would like to propose a new feature, please open a new [issue](https://github.com/firmata/arduino/issues?sort=created&state=open). Due to the limited memory of standard Arduino boards we cannot add every requested feature to StandardFirmata. Requests to add new features to StandardFirmata will be evaluated by the Firmata developers. However it is still possible to add new features to other Firmata implementations (Firmata is a protocol whereas StandardFirmata is just one of many possible implementations). + +To contribute, fork this repository and create a new topic branch for the bug, feature or other existing issue you are addressing. Submit the pull request against the *master* branch. + +If you would like to contribute but don't have a specific bugfix or new feature to contribute, you can take on an existing issue, see issues labeled "pull-request-encouraged". Add a comment to the issue to express your intent to begin work and/or to get any additional information about the issue. + +You must thoroughly test your contributed code. In your pull request, describe tests performed to ensure that no existing code is broken and that any changes maintain backwards compatibility with the existing api. Test on multiple Arduino board variants if possible. We hope to enable some form of automated (or at least semi-automated) testing in the future, but for now any tests will need to be executed manually by the contributor and reviewers. + +Use [Artistic Style](http://astyle.sourceforge.net/) (astyle) to format your code. Set the following rules for the astyle formatter: + +``` +style = "" +indent-spaces = 2 +indent-classes = true +indent-switches = true +indent-cases = true +indent-col1-comments = true +pad-oper = true +pad-header = true +keep-one-line-statements = true +``` + +If you happen to use Sublime Text, [this astyle plugin](https://github.com/timonwong/SublimeAStyleFormatter) is helpful. Set the above rules in the user settings file. diff --git a/libraries/Firmata/release.sh b/libraries/Firmata/release.sh new file mode 100644 index 000000000..9c3f32992 --- /dev/null +++ b/libraries/Firmata/release.sh @@ -0,0 +1,35 @@ +#!/bin/sh + +# use this script to package Firmata for distribution + +# package for Arduino 1.0.x +mkdir -p temp/Firmata +cp -r examples temp/Firmata +cp -r extras temp/Firmata +cp -r utility temp/Firmata +cp Boards.h temp/Firmata +cp Firmata.cpp temp/Firmata +cp Firmata.h temp/Firmata +cp keywords.txt temp/Firmata +cp readme.md temp/Firmata +cd temp +find . -name "*.DS_Store" -type f -delete +zip -r Firmata.zip ./Firmata/ +cd .. +mv ./temp/Firmata.zip Firmata-2.5.2.zip + +#package for Arduino 1.6.x +cp library.properties temp/Firmata +cd temp/Firmata +mv readme.md ./extras/ +mkdir src +mv Boards.h ./src/ +mv Firmata.cpp ./src/ +mv Firmata.h ./src/ +mv utility ./src/ +cd .. +find . -name "*.DS_Store" -type f -delete +zip -r Firmata.zip ./Firmata/ +cd .. +mv ./temp/Firmata.zip Arduino-1.6.x-Firmata-2.5.2.zip +rm -r ./temp diff --git a/libraries/Firmata/test/firmata_test/firmata_test.ino b/libraries/Firmata/test/firmata_test/firmata_test.ino new file mode 100644 index 000000000..ce40afa57 --- /dev/null +++ b/libraries/Firmata/test/firmata_test/firmata_test.ino @@ -0,0 +1,136 @@ +/* + * To run this test suite, you must first install the ArduinoUnit library + * to your Arduino/libraries/ directory. + * You can get ArduinoUnit here: https://github.com/mmurdoch/arduinounit + * Download version 2.0 or greater or install it via the Arduino library manager. + */ + +#include +#include + +void setup() +{ + Serial.begin(9600); +} + +void loop() +{ + Test::run(); +} + +test(beginPrintsVersion) +{ + FakeStream stream; + + Firmata.begin(stream); + + char expected[] = { + REPORT_VERSION, + FIRMATA_PROTOCOL_MAJOR_VERSION, + FIRMATA_PROTOCOL_MINOR_VERSION, + 0 + }; + assertEqual(expected, stream.bytesWritten()); +} + +void processMessage(const byte *message, size_t length) +{ + FakeStream stream; + Firmata.begin(stream); + + for (size_t i = 0; i < length; i++) { + stream.nextByte(message[i]); + Firmata.processInput(); + } +} + +byte _digitalPort; +int _digitalPortValue; +void writeToDigitalPort(byte port, int value) +{ + _digitalPort = port; + _digitalPortValue = value; +} + +void setupDigitalPort() +{ + _digitalPort = 0; + _digitalPortValue = 0; +} + +test(processWriteDigital_0) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0, 0 }; + processMessage(message, 3); + + assertEqual(0, _digitalPortValue); +} + +test(processWriteDigital_127) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 127, 0 }; + processMessage(message, 3); + + assertEqual(127, _digitalPortValue); +} + +test(processWriteDigital_128) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0, 1 }; + processMessage(message, 3); + + assertEqual(128, _digitalPortValue); +} + +test(processWriteLargestDigitalValue) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0x7F, 0x7F }; + processMessage(message, 3); + + // Maximum of 14 bits can be set (B0011111111111111) + assertEqual(0x3FFF, _digitalPortValue); +} + +test(defaultDigitalWritePortIsZero) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE, 0, 0 }; + processMessage(message, 3); + + assertEqual(0, _digitalPort); +} + +test(specifiedDigitalWritePort) +{ + setupDigitalPort(); + Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); + + byte message[] = { DIGITAL_MESSAGE + 1, 0, 0 }; + processMessage(message, 3); + + assertEqual(1, _digitalPort); +} + +test(setFirmwareVersionDoesNotLeakMemory) +{ + Firmata.setFirmwareVersion(1, 0); + int initialMemory = freeMemory(); + + Firmata.setFirmwareVersion(1, 0); + + assertEqual(0, initialMemory - freeMemory()); +} diff --git a/libraries/Firmata/test/readme.md b/libraries/Firmata/test/readme.md new file mode 100644 index 000000000..726cbcba7 --- /dev/null +++ b/libraries/Firmata/test/readme.md @@ -0,0 +1,13 @@ +#Testing Firmata + +Tests tests are written using the [ArduinoUnit](https://github.com/mmurdoch/arduinounit) library (version 2.0). + +Follow the instructions in the [ArduinoUnit readme](https://github.com/mmurdoch/arduinounit/blob/master/readme.md) to install the library. + +Compile and upload the test sketch as you would any other sketch. Then open the +Serial Monitor to view the test results. + +If you make changes to Firmata.cpp, run the tests in /test/ to ensure +that your changes have not produced any unexpected errors. + +You should also perform manual tests against actual hardware. diff --git a/libraries/Firmata/utility/EthernetClientStream.cpp b/libraries/Firmata/utility/EthernetClientStream.cpp new file mode 100644 index 000000000..34078e312 --- /dev/null +++ b/libraries/Firmata/utility/EthernetClientStream.cpp @@ -0,0 +1,114 @@ +/* + EthernetClientStream.cpp + An Arduino-Stream that wraps an instance of Client reconnecting to + the remote-ip in a transparent way. A disconnected client may be + recognized by the returnvalues -1 from calls to peek or read and + a 0 from calls to write. + + Copyright (C) 2013 Norbert Truchsess. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + formatted using the GNU C formatting and indenting + */ + +#include "EthernetClientStream.h" +#include + +//#define SERIAL_DEBUG +#include "firmataDebug.h" + +#define MILLIS_RECONNECT 5000 + +EthernetClientStream::EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port) +: client(client), + localip(localip), + ip(ip), + host(host), + port(port), + connected(false) +{ +} + +int +EthernetClientStream::available() +{ + return maintain() ? client.available() : 0; +} + +int +EthernetClientStream::read() +{ + return maintain() ? client.read() : -1; +} + +int +EthernetClientStream::peek() +{ + return maintain() ? client.peek() : -1; +} + +void EthernetClientStream::flush() +{ + if (maintain()) + client.flush(); +} + +size_t +EthernetClientStream::write(uint8_t c) +{ + return maintain() ? client.write(c) : 0; +} + +void +EthernetClientStream::maintain(IPAddress localip) +{ +// temporary hack to Firmata to compile for Intel Galileo +// the issue is documented here: https://github.com/firmata/arduino/issues/218 +#if !defined(ARDUINO_LINUX) + // ensure the local IP is updated in the case that it is changed by the DHCP server + if (this->localip != localip) + { + this->localip = localip; + if (connected) + stop(); + } +#endif +} + +void +EthernetClientStream::stop() +{ + client.stop(); + connected = false; + time_connect = millis(); +} + +bool +EthernetClientStream::maintain() +{ + if (client && client.connected()) + return true; + + if (connected) + { + stop(); + } + // if the client is disconnected, attempt to reconnect every 5 seconds + else if (millis()-time_connect >= MILLIS_RECONNECT) + { + connected = host ? client.connect(host, port) : client.connect(ip, port); + if (!connected) { + time_connect = millis(); + DEBUG_PRINTLN("connection failed. attempting to reconnect..."); + } else { + DEBUG_PRINTLN("connected"); + } + } + return connected; +} diff --git a/libraries/Firmata/utility/EthernetClientStream.h b/libraries/Firmata/utility/EthernetClientStream.h new file mode 100644 index 000000000..bae34ce9f --- /dev/null +++ b/libraries/Firmata/utility/EthernetClientStream.h @@ -0,0 +1,52 @@ +/* + EthernetClientStream.h + An Arduino-Stream that wraps an instance of Client reconnecting to + the remote-ip in a transparent way. A disconnected client may be + recognized by the returnvalues -1 from calls to peek or read and + a 0 from calls to write. + + Copyright (C) 2013 Norbert Truchsess. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + formatted using the GNU C formatting and indenting + */ + +#ifndef ETHERNETCLIENTSTREAM_H +#define ETHERNETCLIENTSTREAM_H + +#include +#include +#include +#include +#include + +class EthernetClientStream : public Stream +{ +public: + EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port); + int available(); + int read(); + int peek(); + void flush(); + size_t write(uint8_t); + void maintain(IPAddress localip); + +private: + Client &client; + IPAddress localip; + IPAddress ip; + const char* host; + uint16_t port; + bool connected; + uint32_t time_connect; + bool maintain(); + void stop(); +}; + +#endif diff --git a/libraries/Firmata/utility/FirmataFeature.h b/libraries/Firmata/utility/FirmataFeature.h new file mode 100644 index 000000000..d5e229d0d --- /dev/null +++ b/libraries/Firmata/utility/FirmataFeature.h @@ -0,0 +1,38 @@ +/* + FirmataFeature.h + Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. + Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. + Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. + Copyright (C) 2013 Norbert Truchsess. All rights reserved. + Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + Interface for Firmata feature classes. + + This version of FirmataFeature.h differs from the ConfigurableFirmata + version in the following ways: + + - Imports Firmata.h rather than ConfigurableFirmata.h + + See file LICENSE.txt for further informations on licensing terms. +*/ + +#ifndef FirmataFeature_h +#define FirmataFeature_h + +#include + +class FirmataFeature +{ + public: + virtual void handleCapability(byte pin) = 0; + virtual boolean handlePinMode(byte pin, int mode) = 0; + virtual boolean handleSysex(byte command, byte argc, byte* argv) = 0; + virtual void reset() = 0; +}; + +#endif diff --git a/libraries/Firmata/utility/SerialFirmata.cpp b/libraries/Firmata/utility/SerialFirmata.cpp new file mode 100644 index 000000000..9dba3f2ba --- /dev/null +++ b/libraries/Firmata/utility/SerialFirmata.cpp @@ -0,0 +1,328 @@ +/* + SerialFirmata.cpp + Copyright (C) 2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + This version of SerialFirmata.cpp differs from the ConfigurableFirmata + version in the following ways: + + - handlePinMode calls Firmata::setPinMode + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +#include "SerialFirmata.h" + +SerialFirmata::SerialFirmata() +{ + swSerial0 = NULL; + swSerial1 = NULL; + swSerial2 = NULL; + swSerial3 = NULL; + + serialIndex = -1; +} + +boolean SerialFirmata::handlePinMode(byte pin, int mode) +{ + // used for both HW and SW serial + if (mode == PIN_MODE_SERIAL) { + Firmata.setPinMode(pin, PIN_MODE_SERIAL); + return true; + } + return false; +} + +void SerialFirmata::handleCapability(byte pin) +{ + if (IS_PIN_SERIAL(pin)) { + Firmata.write(PIN_MODE_SERIAL); + Firmata.write(getSerialPinType(pin)); + } +} + +boolean SerialFirmata::handleSysex(byte command, byte argc, byte *argv) +{ + if (command == SERIAL_MESSAGE) { + + Stream *serialPort; + byte mode = argv[0] & SERIAL_MODE_MASK; + byte portId = argv[0] & SERIAL_PORT_ID_MASK; + + switch (mode) { + case SERIAL_CONFIG: + { + long baud = (long)argv[1] | ((long)argv[2] << 7) | ((long)argv[3] << 14); + serial_pins pins; + + if (portId < 8) { + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + pins = getSerialPinNumbers(portId); + if (pins.rx != 0 && pins.tx != 0) { + Firmata.setPinMode(pins.rx, PIN_MODE_SERIAL); + Firmata.setPinMode(pins.tx, PIN_MODE_SERIAL); + // Fixes an issue where some serial devices would not work properly with Arduino Due + // because all Arduino pins are set to OUTPUT by default in StandardFirmata. + pinMode(pins.rx, INPUT); + } + ((HardwareSerial*)serialPort)->begin(baud); + } + } else { +#if defined(SoftwareSerial_h) + byte swTxPin, swRxPin; + if (argc > 4) { + swRxPin = argv[4]; + swTxPin = argv[5]; + } else { + // RX and TX pins must be specified when using SW serial + Firmata.sendString("Specify serial RX and TX pins"); + return false; + } + switch (portId) { + case SW_SERIAL0: + if (swSerial0 == NULL) { + swSerial0 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + case SW_SERIAL1: + if (swSerial1 == NULL) { + swSerial1 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + case SW_SERIAL2: + if (swSerial2 == NULL) { + swSerial2 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + case SW_SERIAL3: + if (swSerial3 == NULL) { + swSerial3 = new SoftwareSerial(swRxPin, swTxPin); + } + break; + } + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + Firmata.setPinMode(swRxPin, PIN_MODE_SERIAL); + Firmata.setPinMode(swTxPin, PIN_MODE_SERIAL); + ((SoftwareSerial*)serialPort)->begin(baud); + } +#endif + } + break; // SERIAL_CONFIG + } + case SERIAL_WRITE: + { + byte data; + serialPort = getPortFromId(portId); + if (serialPort == NULL) { + break; + } + for (byte i = 1; i < argc; i += 2) { + data = argv[i] + (argv[i + 1] << 7); + serialPort->write(data); + } + break; // SERIAL_WRITE + } + case SERIAL_READ: + if (argv[1] == SERIAL_READ_CONTINUOUSLY) { + if (serialIndex + 1 >= MAX_SERIAL_PORTS) { + break; + } + + if (argc > 2) { + // maximum number of bytes to read from buffer per iteration of loop() + serialBytesToRead[portId] = (int)argv[2] | ((int)argv[3] << 7); + } else { + // read all available bytes per iteration of loop() + serialBytesToRead[portId] = 0; + } + serialIndex++; + reportSerial[serialIndex] = portId; + } else if (argv[1] == SERIAL_STOP_READING) { + byte serialIndexToSkip = 0; + if (serialIndex <= 0) { + serialIndex = -1; + } else { + for (byte i = 0; i < serialIndex + 1; i++) { + if (reportSerial[i] == portId) { + serialIndexToSkip = i; + break; + } + } + // shift elements over to fill space left by removed element + for (byte i = serialIndexToSkip; i < serialIndex + 1; i++) { + if (i < MAX_SERIAL_PORTS) { + reportSerial[i] = reportSerial[i + 1]; + } + } + serialIndex--; + } + } + break; // SERIAL_READ + case SERIAL_CLOSE: + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + if (portId < 8) { + ((HardwareSerial*)serialPort)->end(); + } else { +#if defined(SoftwareSerial_h) + ((SoftwareSerial*)serialPort)->end(); + if (serialPort != NULL) { + free(serialPort); + serialPort = NULL; + } +#endif + } + } + break; // SERIAL_CLOSE + case SERIAL_FLUSH: + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + getPortFromId(portId)->flush(); + } + break; // SERIAL_FLUSH +#if defined(SoftwareSerial_h) + case SERIAL_LISTEN: + // can only call listen() on software serial ports + if (portId > 7) { + serialPort = getPortFromId(portId); + if (serialPort != NULL) { + ((SoftwareSerial*)serialPort)->listen(); + } + } + break; // SERIAL_LISTEN +#endif + } // end switch + return true; + } + return false; +} + +void SerialFirmata::update() +{ + checkSerial(); +} + +void SerialFirmata::reset() +{ +#if defined(SoftwareSerial_h) + Stream *serialPort; + // free memory allocated for SoftwareSerial ports + for (byte i = SW_SERIAL0; i < SW_SERIAL3 + 1; i++) { + serialPort = getPortFromId(i); + if (serialPort != NULL) { + free(serialPort); + serialPort = NULL; + } + } +#endif + + serialIndex = -1; + for (byte i = 0; i < SERIAL_READ_ARR_LEN; i++) { + serialBytesToRead[i] = 0; + } +} + +// get a pointer to the serial port associated with the specified port id +Stream* SerialFirmata::getPortFromId(byte portId) +{ + switch (portId) { + case HW_SERIAL0: + // block use of Serial (typically pins 0 and 1) until ability to reclaim Serial is implemented + //return &Serial; + return NULL; +#if defined(PIN_SERIAL1_RX) + case HW_SERIAL1: + return &Serial1; +#endif +#if defined(PIN_SERIAL2_RX) + case HW_SERIAL2: + return &Serial2; +#endif +#if defined(PIN_SERIAL3_RX) + case HW_SERIAL3: + return &Serial3; +#endif +#if defined(SoftwareSerial_h) + case SW_SERIAL0: + if (swSerial0 != NULL) { + // instances of SoftwareSerial are already pointers so simply return the instance + return swSerial0; + } + break; + case SW_SERIAL1: + if (swSerial1 != NULL) { + return swSerial1; + } + break; + case SW_SERIAL2: + if (swSerial2 != NULL) { + return swSerial2; + } + break; + case SW_SERIAL3: + if (swSerial3 != NULL) { + return swSerial3; + } + break; +#endif + } + return NULL; +} + +// Check serial ports that have READ_CONTINUOUS mode set and relay any data +// for each port to the device attached to that port. +void SerialFirmata::checkSerial() +{ + byte portId, serialData; + int bytesToRead = 0; + int numBytesToRead = 0; + Stream* serialPort; + + if (serialIndex > -1) { + + // loop through all reporting (READ_CONTINUOUS) serial ports + for (byte i = 0; i < serialIndex + 1; i++) { + portId = reportSerial[i]; + bytesToRead = serialBytesToRead[portId]; + serialPort = getPortFromId(portId); + if (serialPort == NULL) { + continue; + } +#if defined(SoftwareSerial_h) + // only the SoftwareSerial port that is "listening" can read data + if (portId > 7 && !((SoftwareSerial*)serialPort)->isListening()) { + continue; + } +#endif + if (serialPort->available() > 0) { + Firmata.write(START_SYSEX); + Firmata.write(SERIAL_MESSAGE); + Firmata.write(SERIAL_REPLY | portId); + + if (bytesToRead == 0 || (serialPort->available() <= bytesToRead)) { + numBytesToRead = serialPort->available(); + } else { + numBytesToRead = bytesToRead; + } + + // relay serial data to the serial device + while (numBytesToRead > 0) { + serialData = serialPort->read(); + Firmata.write(serialData & 0x7F); + Firmata.write((serialData >> 7) & 0x7F); + numBytesToRead--; + } + Firmata.write(END_SYSEX); + } + + } + } +} diff --git a/libraries/Firmata/utility/SerialFirmata.h b/libraries/Firmata/utility/SerialFirmata.h new file mode 100644 index 000000000..b3357f44b --- /dev/null +++ b/libraries/Firmata/utility/SerialFirmata.h @@ -0,0 +1,167 @@ +/* + SerialFirmata.h + Copyright (C) 2016 Jeff Hoefs. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + + This version of SerialFirmata.h differs from the ConfigurableFirmata + version in the following ways: + + - Defines FIRMATA_SERIAL_FEATURE (could add to Configurable version as well) + - Imports Firmata.h rather than ConfigurableFirmata.h + + Last updated by Jeff Hoefs: January 10th, 2016 +*/ + +#ifndef SerialFirmata_h +#define SerialFirmata_h + +#include +#include "FirmataFeature.h" +// SoftwareSerial is currently only supported for AVR-based boards and the Arduino 101 +// The third condition checks if the IDE is in the 1.0.x series, if so, include SoftwareSerial +// since it should be available to all boards in that IDE. +#if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ARC32) || (ARDUINO >= 100 && ARDUINO < 10500) +#include +#endif + +#define FIRMATA_SERIAL_FEATURE + +// Serial port Ids +#define HW_SERIAL0 0x00 +#define HW_SERIAL1 0x01 +#define HW_SERIAL2 0x02 +#define HW_SERIAL3 0x03 +// extensible up to 0x07 + +#define SW_SERIAL0 0x08 +#define SW_SERIAL1 0x09 +#define SW_SERIAL2 0x0A +#define SW_SERIAL3 0x0B +// extensible up to 0x0F + +#define SERIAL_PORT_ID_MASK 0x0F +#define MAX_SERIAL_PORTS 8 +#define SERIAL_READ_ARR_LEN 12 + +// map configuration query response resolution value to serial pin type +#define RES_RX1 0x02 +#define RES_TX1 0x03 +#define RES_RX2 0x04 +#define RES_TX2 0x05 +#define RES_RX3 0x06 +#define RES_TX3 0x07 + +// Serial command bytes +#define SERIAL_CONFIG 0x10 +#define SERIAL_WRITE 0x20 +#define SERIAL_READ 0x30 +#define SERIAL_REPLY 0x40 +#define SERIAL_CLOSE 0x50 +#define SERIAL_FLUSH 0x60 +#define SERIAL_LISTEN 0x70 + +// Serial read modes +#define SERIAL_READ_CONTINUOUSLY 0x00 +#define SERIAL_STOP_READING 0x01 +#define SERIAL_MODE_MASK 0xF0 + +namespace { + + struct serial_pins { + uint8_t rx; + uint8_t tx; + }; + + /* + * Get the serial serial pin type (RX1, TX1, RX2, TX2, etc) for the specified pin. + */ + inline uint8_t getSerialPinType(uint8_t pin) { + #if defined(PIN_SERIAL_RX) + // TODO when use of HW_SERIAL0 is enabled + #endif + #if defined(PIN_SERIAL1_RX) + if (pin == PIN_SERIAL1_RX) return RES_RX1; + if (pin == PIN_SERIAL1_TX) return RES_TX1; + #endif + #if defined(PIN_SERIAL2_RX) + if (pin == PIN_SERIAL2_RX) return RES_RX2; + if (pin == PIN_SERIAL2_TX) return RES_TX2; + #endif + #if defined(PIN_SERIAL3_RX) + if (pin == PIN_SERIAL3_RX) return RES_RX3; + if (pin == PIN_SERIAL3_TX) return RES_TX3; + #endif + return 0; + } + + /* + * Get the RX and TX pins numbers for the specified HW serial port. + */ + inline serial_pins getSerialPinNumbers(uint8_t portId) { + serial_pins pins; + switch (portId) { + #if defined(PIN_SERIAL_RX) + // case HW_SERIAL0: + // // TODO when use of HW_SERIAL0 is enabled + // break; + #endif + #if defined(PIN_SERIAL1_RX) + case HW_SERIAL1: + pins.rx = PIN_SERIAL1_RX; + pins.tx = PIN_SERIAL1_TX; + break; + #endif + #if defined(PIN_SERIAL2_RX) + case HW_SERIAL2: + pins.rx = PIN_SERIAL2_RX; + pins.tx = PIN_SERIAL2_TX; + break; + #endif + #if defined(PIN_SERIAL3_RX) + case HW_SERIAL3: + pins.rx = PIN_SERIAL3_RX; + pins.tx = PIN_SERIAL3_TX; + break; + #endif + default: + pins.rx = 0; + pins.tx = 0; + } + return pins; + } + +} // end namespace + + +class SerialFirmata: public FirmataFeature +{ + public: + SerialFirmata(); + boolean handlePinMode(byte pin, int mode); + void handleCapability(byte pin); + boolean handleSysex(byte command, byte argc, byte* argv); + void update(); + void reset(); + void checkSerial(); + + private: + byte reportSerial[MAX_SERIAL_PORTS]; + int serialBytesToRead[SERIAL_READ_ARR_LEN]; + signed char serialIndex; + + Stream *swSerial0; + Stream *swSerial1; + Stream *swSerial2; + Stream *swSerial3; + + Stream* getPortFromId(byte portId); + +}; + +#endif /* SerialFirmata_h */ diff --git a/libraries/Firmata/utility/WiFi101Stream.cpp b/libraries/Firmata/utility/WiFi101Stream.cpp new file mode 100644 index 000000000..3beaf40e7 --- /dev/null +++ b/libraries/Firmata/utility/WiFi101Stream.cpp @@ -0,0 +1,4 @@ +/* + * Implementation is in WiFi101Stream.h to avoid linker issues. Legacy WiFi and modern WiFi101 both define WiFiClass which + * will cause linker errors whenever Firmata.h is included. + */ diff --git a/libraries/Firmata/utility/WiFi101Stream.h b/libraries/Firmata/utility/WiFi101Stream.h new file mode 100644 index 000000000..eb95cf51d --- /dev/null +++ b/libraries/Firmata/utility/WiFi101Stream.h @@ -0,0 +1,259 @@ +/* + WiFi101Stream.h + An Arduino Stream that wraps an instance of a WiFi101 server. For use + with Arduino WiFi 101 shield, Arduino MKR1000 and other boards and + shields that are compatible with the Arduino WiFi101 library. + + Copyright (C) 2015-2016 Jesse Frush. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + */ + +#ifndef WIFI101_STREAM_H +#define WIFI101_STREAM_H + +#include +#include +#include + + +class WiFi101Stream : public Stream +{ +private: + WiFiServer _server = WiFiServer(23); + WiFiClient _client; + + //configuration members + IPAddress _local_ip; + uint16_t _port = 0; + uint8_t _key_idx = 0; //WEP + const char *_key = nullptr; //WEP + const char *_passphrase = nullptr; //WPA + char *_ssid = nullptr; + + inline int connect_client() + { + if( !( _client && _client.connected() ) ) + { + WiFiClient newClient = _server.available(); + if( !newClient ) + { + return 0; + } + + _client = newClient; + } + return 1; + } + + inline bool is_ready() + { + uint8_t status = WiFi.status(); + return !( status == WL_NO_SHIELD || status == WL_CONNECTED ); + } + +public: + WiFi101Stream() {}; + + // allows another way to configure a static IP before begin is called + inline void config(IPAddress local_ip) + { + _local_ip = local_ip; + WiFi.config( local_ip ); + } + + // get DCHP IP + inline IPAddress localIP() + { + return WiFi.localIP(); + } + + inline bool maintain() + { + if( connect_client() ) return true; + + stop(); + int result = 0; + if( WiFi.status() != WL_CONNECTED ) + { + if( _local_ip ) + { + WiFi.config( _local_ip ); + } + + if( _passphrase ) + { + result = WiFi.begin( _ssid, _passphrase); + } + else if( _key_idx && _key ) + { + result = WiFi.begin( _ssid, _key_idx, _key ); + } + else + { + result = WiFi.begin( _ssid ); + } + } + if( result == 0 ) return false; + + _server = WiFiServer( _port ); + _server.begin(); + return result; + } + +/****************************************************************************** + * Connection functions with DHCP + ******************************************************************************/ + + //OPEN networks + inline int begin(char *ssid, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + int result = WiFi.begin( ssid ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WEP-encrypted networks + inline int begin(char *ssid, uint8_t key_idx, const char *key, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _key_idx = key_idx; + _key = key; + + int result = WiFi.begin( ssid, key_idx, key ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WPA-encrypted networks + inline int begin(char *ssid, const char *passphrase, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _passphrase = passphrase; + + int result = WiFi.begin( ssid, passphrase); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + +/****************************************************************************** + * Connection functions without DHCP + ******************************************************************************/ + + //OPEN networks with static IP + inline int begin(char *ssid, IPAddress local_ip, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _local_ip = local_ip; + + WiFi.config( local_ip ); + int result = WiFi.begin( ssid ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WEP-encrypted networks with static IP + inline int begin(char *ssid, IPAddress local_ip, uint8_t key_idx, const char *key, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _local_ip = local_ip; + _key_idx = key_idx; + _key = key; + + WiFi.config( local_ip ); + int result = WiFi.begin( ssid, key_idx, key ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WPA-encrypted networks with static IP + inline int begin(char *ssid, IPAddress local_ip, const char *passphrase, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _local_ip = local_ip; + _passphrase = passphrase; + + WiFi.config( local_ip ); + int result = WiFi.begin( ssid, passphrase); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + +/****************************************************************************** + * Stream implementations + ******************************************************************************/ + + inline int available() + { + return connect_client() ? _client.available() : 0; + } + + inline void flush() + { + if( _client ) _client.flush(); + } + + inline int peek() + { + return connect_client() ? _client.peek(): 0; + } + + inline int read() + { + return connect_client() ? _client.read() : -1; + } + + inline void stop() + { + _client.stop(); + } + + inline size_t write(uint8_t byte) + { + if( connect_client() ) _client.write( byte ); + } +}; + +#endif //WIFI101_STREAM_H diff --git a/libraries/Firmata/utility/WiFiStream.cpp b/libraries/Firmata/utility/WiFiStream.cpp new file mode 100644 index 000000000..9b54a5ace --- /dev/null +++ b/libraries/Firmata/utility/WiFiStream.cpp @@ -0,0 +1,4 @@ +/* + * Implementation is in WiFiStream.h to avoid linker issues. Legacy WiFi and modern WiFi101 both define WiFiClass which + * will cause linker errors whenever Firmata.h is included. + */ diff --git a/libraries/Firmata/utility/WiFiStream.h b/libraries/Firmata/utility/WiFiStream.h new file mode 100644 index 000000000..fdcb483a3 --- /dev/null +++ b/libraries/Firmata/utility/WiFiStream.h @@ -0,0 +1,258 @@ +/* + WiFiStream.h + An Arduino Stream that wraps an instance of a WiFi server. For use + with legacy Arduino WiFi shield and other boards and sheilds that + are compatible with the Arduino WiFi library. + + Copyright (C) 2015-2016 Jesse Frush. All rights reserved. + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + See file LICENSE.txt for further informations on licensing terms. + */ + +#ifndef WIFI_STREAM_H +#define WIFI_STREAM_H + +#include +#include +#include + +class WiFiStream : public Stream +{ +private: + WiFiServer _server = WiFiServer(23); + WiFiClient _client; + + //configuration members + IPAddress _local_ip; + uint16_t _port = 0; + uint8_t _key_idx = 0; //WEP + const char *_key = nullptr; //WEP + const char *_passphrase = nullptr; //WPA + char *_ssid = nullptr; + + inline int connect_client() + { + if( !( _client && _client.connected() ) ) + { + WiFiClient newClient = _server.available(); + if( !newClient ) + { + return 0; + } + + _client = newClient; + } + return 1; + } + + inline bool is_ready() + { + uint8_t status = WiFi.status(); + return !( status == WL_NO_SHIELD || status == WL_CONNECTED ); + } + +public: + WiFiStream() {}; + + // allows another way to configure a static IP before begin is called + inline void config(IPAddress local_ip) + { + _local_ip = local_ip; + WiFi.config( local_ip ); + } + + // get DCHP IP + inline IPAddress localIP() + { + return WiFi.localIP(); + } + + inline bool maintain() + { + if( connect_client() ) return true; + + stop(); + int result = 0; + if( WiFi.status() != WL_CONNECTED ) + { + if( _local_ip ) + { + WiFi.config( _local_ip ); + } + + if( _passphrase ) + { + result = WiFi.begin( _ssid, _passphrase); + } + else if( _key_idx && _key ) + { + result = WiFi.begin( _ssid, _key_idx, _key ); + } + else + { + result = WiFi.begin( _ssid ); + } + } + if( result == 0 ) return false; + + _server = WiFiServer( _port ); + _server.begin(); + return result; + } + +/****************************************************************************** + * Connection functions with DHCP + ******************************************************************************/ + + //OPEN networks + inline int begin(char *ssid, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + int result = WiFi.begin( ssid ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WEP-encrypted networks + inline int begin(char *ssid, uint8_t key_idx, const char *key, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _key_idx = key_idx; + _key = key; + + int result = WiFi.begin( ssid, key_idx, key ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WPA-encrypted networks + inline int begin(char *ssid, const char *passphrase, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _passphrase = passphrase; + + int result = WiFi.begin( ssid, passphrase); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + +/****************************************************************************** + * Connection functions without DHCP + ******************************************************************************/ + + //OPEN networks with static IP + inline int begin(char *ssid, IPAddress local_ip, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _local_ip = local_ip; + + WiFi.config( local_ip ); + int result = WiFi.begin( ssid ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WEP-encrypted networks with static IP + inline int begin(char *ssid, IPAddress local_ip, uint8_t key_idx, const char *key, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _local_ip = local_ip; + _key_idx = key_idx; + _key = key; + + WiFi.config( local_ip ); + int result = WiFi.begin( ssid, key_idx, key ); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + + //WPA-encrypted networks with static IP + inline int begin(char *ssid, IPAddress local_ip, const char *passphrase, uint16_t port) + { + if( !is_ready() ) return 0; + + _ssid = ssid; + _port = port; + _local_ip = local_ip; + _passphrase = passphrase; + + WiFi.config( local_ip ); + int result = WiFi.begin( ssid, passphrase); + if( result == 0 ) return 0; + + _server = WiFiServer( port ); + _server.begin(); + return result; + } + +/****************************************************************************** + * Stream implementations + ******************************************************************************/ + + inline int available() + { + return connect_client() ? _client.available() : 0; + } + + inline void flush() + { + if( _client ) _client.flush(); + } + + inline int peek() + { + return connect_client() ? _client.peek(): 0; + } + + inline int read() + { + return connect_client() ? _client.read() : -1; + } + + inline void stop() + { + _client.stop(); + } + + inline size_t write(uint8_t byte) + { + if( connect_client() ) _client.write( byte ); + } +}; + +#endif //WIFI_STREAM_H diff --git a/libraries/Firmata/utility/firmataDebug.h b/libraries/Firmata/utility/firmataDebug.h new file mode 100644 index 000000000..6e364b0c7 --- /dev/null +++ b/libraries/Firmata/utility/firmataDebug.h @@ -0,0 +1,14 @@ +#ifndef FIRMATA_DEBUG_H +#define FIRMATA_DEBUG_H + +#ifdef SERIAL_DEBUG + #define DEBUG_BEGIN(baud) Serial.begin(baud); while(!Serial) {;} + #define DEBUG_PRINTLN(x) Serial.println (x) + #define DEBUG_PRINT(x) Serial.print (x) +#else + #define DEBUG_BEGIN(baud) + #define DEBUG_PRINTLN(x) + #define DEBUG_PRINT(x) +#endif + +#endif /* FIRMATA_DEBUG_H */ diff --git a/libraries/Keyboard/README.adoc b/libraries/Keyboard/README.adoc new file mode 100644 index 000000000..0d77d9a83 --- /dev/null +++ b/libraries/Keyboard/README.adoc @@ -0,0 +1,25 @@ += Keyboard Library for Arduino = + +This library allows an Arduino board with USB capabilites to act as a Keyboard. +Being based on HID library you need to include "HID.h" in your sketch. + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/Keyboard + +== License == + +Copyright (c) Arduino LLC. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/Keyboard/keywords.txt b/libraries/Keyboard/keywords.txt new file mode 100644 index 000000000..2078f0329 --- /dev/null +++ b/libraries/Keyboard/keywords.txt @@ -0,0 +1,24 @@ +####################################### +# Syntax Coloring Map For Keyboard +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Keyboard KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +write KEYWORD2 +press KEYWORD2 +release KEYWORD2 +releaseAll KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### + diff --git a/libraries/Keyboard/library.properties b/libraries/Keyboard/library.properties new file mode 100644 index 000000000..4fa367a08 --- /dev/null +++ b/libraries/Keyboard/library.properties @@ -0,0 +1,9 @@ +name=Keyboard +version=1.0.1 +author=Arduino +maintainer=Arduino +sentence=Allows an Arduino/Genuino board with USB capabilites to act as a Keyboard. +paragraph=This library plugs on the HID library. It can be used with or without other HID-based libraries (Mouse, Gamepad etc) +category=Device Control +url=http://www.arduino.cc/en/Reference/Keyboard +architectures=* diff --git a/libraries/Keyboard/src/Keyboard.cpp b/libraries/Keyboard/src/Keyboard.cpp new file mode 100644 index 000000000..48f085219 --- /dev/null +++ b/libraries/Keyboard/src/Keyboard.cpp @@ -0,0 +1,322 @@ +/* + Keyboard.cpp + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "Keyboard.h" + +#if defined(_USING_HID) + +//================================================================================ +//================================================================================ +// Keyboard + +static const uint8_t _hidReportDescriptor[] PROGMEM = { + + // Keyboard + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47 + 0x09, 0x06, // USAGE (Keyboard) + 0xa1, 0x01, // COLLECTION (Application) + 0x85, 0x02, // REPORT_ID (2) + 0x05, 0x07, // USAGE_PAGE (Keyboard) + + 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) + 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x01, // LOGICAL_MAXIMUM (1) + 0x75, 0x01, // REPORT_SIZE (1) + + 0x95, 0x08, // REPORT_COUNT (8) + 0x81, 0x02, // INPUT (Data,Var,Abs) + 0x95, 0x01, // REPORT_COUNT (1) + 0x75, 0x08, // REPORT_SIZE (8) + 0x81, 0x03, // INPUT (Cnst,Var,Abs) + + 0x95, 0x06, // REPORT_COUNT (6) + 0x75, 0x08, // REPORT_SIZE (8) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x65, // LOGICAL_MAXIMUM (101) + 0x05, 0x07, // USAGE_PAGE (Keyboard) + + 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) + 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application) + 0x81, 0x00, // INPUT (Data,Ary,Abs) + 0xc0, // END_COLLECTION +}; + +Keyboard_::Keyboard_(void) +{ + static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); + HID().AppendDescriptor(&node); +} + +void Keyboard_::begin(void) +{ +} + +void Keyboard_::end(void) +{ +} + +void Keyboard_::sendReport(KeyReport* keys) +{ + HID().SendReport(2,keys,sizeof(KeyReport)); +} + +extern +const uint8_t _asciimap[128] PROGMEM; + +#define SHIFT 0x80 +const uint8_t _asciimap[128] = +{ + 0x00, // NUL + 0x00, // SOH + 0x00, // STX + 0x00, // ETX + 0x00, // EOT + 0x00, // ENQ + 0x00, // ACK + 0x00, // BEL + 0x2a, // BS Backspace + 0x2b, // TAB Tab + 0x28, // LF Enter + 0x00, // VT + 0x00, // FF + 0x00, // CR + 0x00, // SO + 0x00, // SI + 0x00, // DEL + 0x00, // DC1 + 0x00, // DC2 + 0x00, // DC3 + 0x00, // DC4 + 0x00, // NAK + 0x00, // SYN + 0x00, // ETB + 0x00, // CAN + 0x00, // EM + 0x00, // SUB + 0x00, // ESC + 0x00, // FS + 0x00, // GS + 0x00, // RS + 0x00, // US + + 0x2c, // ' ' + 0x1e|SHIFT, // ! + 0x34|SHIFT, // " + 0x20|SHIFT, // # + 0x21|SHIFT, // $ + 0x22|SHIFT, // % + 0x24|SHIFT, // & + 0x34, // ' + 0x26|SHIFT, // ( + 0x27|SHIFT, // ) + 0x25|SHIFT, // * + 0x2e|SHIFT, // + + 0x36, // , + 0x2d, // - + 0x37, // . + 0x38, // / + 0x27, // 0 + 0x1e, // 1 + 0x1f, // 2 + 0x20, // 3 + 0x21, // 4 + 0x22, // 5 + 0x23, // 6 + 0x24, // 7 + 0x25, // 8 + 0x26, // 9 + 0x33|SHIFT, // : + 0x33, // ; + 0x36|SHIFT, // < + 0x2e, // = + 0x37|SHIFT, // > + 0x38|SHIFT, // ? + 0x1f|SHIFT, // @ + 0x04|SHIFT, // A + 0x05|SHIFT, // B + 0x06|SHIFT, // C + 0x07|SHIFT, // D + 0x08|SHIFT, // E + 0x09|SHIFT, // F + 0x0a|SHIFT, // G + 0x0b|SHIFT, // H + 0x0c|SHIFT, // I + 0x0d|SHIFT, // J + 0x0e|SHIFT, // K + 0x0f|SHIFT, // L + 0x10|SHIFT, // M + 0x11|SHIFT, // N + 0x12|SHIFT, // O + 0x13|SHIFT, // P + 0x14|SHIFT, // Q + 0x15|SHIFT, // R + 0x16|SHIFT, // S + 0x17|SHIFT, // T + 0x18|SHIFT, // U + 0x19|SHIFT, // V + 0x1a|SHIFT, // W + 0x1b|SHIFT, // X + 0x1c|SHIFT, // Y + 0x1d|SHIFT, // Z + 0x2f, // [ + 0x31, // bslash + 0x30, // ] + 0x23|SHIFT, // ^ + 0x2d|SHIFT, // _ + 0x35, // ` + 0x04, // a + 0x05, // b + 0x06, // c + 0x07, // d + 0x08, // e + 0x09, // f + 0x0a, // g + 0x0b, // h + 0x0c, // i + 0x0d, // j + 0x0e, // k + 0x0f, // l + 0x10, // m + 0x11, // n + 0x12, // o + 0x13, // p + 0x14, // q + 0x15, // r + 0x16, // s + 0x17, // t + 0x18, // u + 0x19, // v + 0x1a, // w + 0x1b, // x + 0x1c, // y + 0x1d, // z + 0x2f|SHIFT, // { + 0x31|SHIFT, // | + 0x30|SHIFT, // } + 0x35|SHIFT, // ~ + 0 // DEL +}; + + +uint8_t USBPutChar(uint8_t c); + +// press() adds the specified key (printing, non-printing, or modifier) +// to the persistent key report and sends the report. Because of the way +// USB HID works, the host acts like the key remains pressed until we +// call release(), releaseAll(), or otherwise clear the report and resend. +size_t Keyboard_::press(uint8_t k) +{ + uint8_t i; + if (k >= 136) { // it's a non-printing key (not a modifier) + k = k - 136; + } else if (k >= 128) { // it's a modifier key + _keyReport.modifiers |= (1<<(k-128)); + k = 0; + } else { // it's a printing key + k = pgm_read_byte(_asciimap + k); + if (!k) { + setWriteError(); + return 0; + } + if (k & 0x80) { // it's a capital letter or other character reached with shift + _keyReport.modifiers |= 0x02; // the left shift modifier + k &= 0x7F; + } + } + + // Add k to the key report only if it's not already present + // and if there is an empty slot. + if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && + _keyReport.keys[2] != k && _keyReport.keys[3] != k && + _keyReport.keys[4] != k && _keyReport.keys[5] != k) { + + for (i=0; i<6; i++) { + if (_keyReport.keys[i] == 0x00) { + _keyReport.keys[i] = k; + break; + } + } + if (i == 6) { + setWriteError(); + return 0; + } + } + sendReport(&_keyReport); + return 1; +} + +// release() takes the specified key out of the persistent key report and +// sends the report. This tells the OS the key is no longer pressed and that +// it shouldn't be repeated any more. +size_t Keyboard_::release(uint8_t k) +{ + uint8_t i; + if (k >= 136) { // it's a non-printing key (not a modifier) + k = k - 136; + } else if (k >= 128) { // it's a modifier key + _keyReport.modifiers &= ~(1<<(k-128)); + k = 0; + } else { // it's a printing key + k = pgm_read_byte(_asciimap + k); + if (!k) { + return 0; + } + if (k & 0x80) { // it's a capital letter or other character reached with shift + _keyReport.modifiers &= ~(0x02); // the left shift modifier + k &= 0x7F; + } + } + + // Test the key report to see if k is present. Clear it if it exists. + // Check all positions in case the key is present more than once (which it shouldn't be) + for (i=0; i<6; i++) { + if (0 != k && _keyReport.keys[i] == k) { + _keyReport.keys[i] = 0x00; + } + } + + sendReport(&_keyReport); + return 1; +} + +void Keyboard_::releaseAll(void) +{ + _keyReport.keys[0] = 0; + _keyReport.keys[1] = 0; + _keyReport.keys[2] = 0; + _keyReport.keys[3] = 0; + _keyReport.keys[4] = 0; + _keyReport.keys[5] = 0; + _keyReport.modifiers = 0; + sendReport(&_keyReport); +} + +size_t Keyboard_::write(uint8_t c) +{ + uint8_t p = press(c); // Keydown + release(c); // Keyup + return p; // just return the result of press() since release() almost always returns 1 +} + +Keyboard_ Keyboard; + +#endif diff --git a/libraries/Keyboard/src/Keyboard.h b/libraries/Keyboard/src/Keyboard.h new file mode 100644 index 000000000..8f173f31c --- /dev/null +++ b/libraries/Keyboard/src/Keyboard.h @@ -0,0 +1,99 @@ +/* + Keyboard.h + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef KEYBOARD_h +#define KEYBOARD_h + +#include "HID.h" + +#if !defined(_USING_HID) + +#warning "Using legacy HID core (non pluggable)" + +#else + +//================================================================================ +//================================================================================ +// Keyboard + +#define KEY_LEFT_CTRL 0x80 +#define KEY_LEFT_SHIFT 0x81 +#define KEY_LEFT_ALT 0x82 +#define KEY_LEFT_GUI 0x83 +#define KEY_RIGHT_CTRL 0x84 +#define KEY_RIGHT_SHIFT 0x85 +#define KEY_RIGHT_ALT 0x86 +#define KEY_RIGHT_GUI 0x87 + +#define KEY_UP_ARROW 0xDA +#define KEY_DOWN_ARROW 0xD9 +#define KEY_LEFT_ARROW 0xD8 +#define KEY_RIGHT_ARROW 0xD7 +#define KEY_BACKSPACE 0xB2 +#define KEY_TAB 0xB3 +#define KEY_RETURN 0xB0 +#define KEY_ESC 0xB1 +#define KEY_INSERT 0xD1 +#define KEY_DELETE 0xD4 +#define KEY_PAGE_UP 0xD3 +#define KEY_PAGE_DOWN 0xD6 +#define KEY_HOME 0xD2 +#define KEY_END 0xD5 +#define KEY_CAPS_LOCK 0xC1 +#define KEY_F1 0xC2 +#define KEY_F2 0xC3 +#define KEY_F3 0xC4 +#define KEY_F4 0xC5 +#define KEY_F5 0xC6 +#define KEY_F6 0xC7 +#define KEY_F7 0xC8 +#define KEY_F8 0xC9 +#define KEY_F9 0xCA +#define KEY_F10 0xCB +#define KEY_F11 0xCC +#define KEY_F12 0xCD + +// Low level key report: up to 6 keys and shift, ctrl etc at once +typedef struct +{ + uint8_t modifiers; + uint8_t reserved; + uint8_t keys[6]; +} KeyReport; + +class Keyboard_ : public Print +{ +private: + KeyReport _keyReport; + void sendReport(KeyReport* keys); +public: + Keyboard_(void); + void begin(void); + void end(void); + size_t write(uint8_t k); + size_t press(uint8_t k); + size_t release(uint8_t k); + void releaseAll(void); +}; +extern Keyboard_ Keyboard; + +#endif +#endif diff --git a/libraries/Mouse/README.adoc b/libraries/Mouse/README.adoc new file mode 100644 index 000000000..3e61306c6 --- /dev/null +++ b/libraries/Mouse/README.adoc @@ -0,0 +1,25 @@ += Mouse Library for Arduino = + +This library allows an Arduino board with USB capabilites to act as a Mouse. +Being based on HID library you need to include "HID.h" in your sketch + +For more information about this library please visit us at +http://www.arduino.cc/en/Reference/Mouse + +== License == + +Copyright (c) Arduino LLC. All right reserved. + +This library is free software; you can redistribute it and/or +modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation; either +version 2.1 of the License, or (at your option) any later version. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/libraries/Mouse/keywords.txt b/libraries/Mouse/keywords.txt new file mode 100644 index 000000000..258c48eeb --- /dev/null +++ b/libraries/Mouse/keywords.txt @@ -0,0 +1,24 @@ +####################################### +# Syntax Coloring Map For Keyboard +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### + +Mouse KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### + +begin KEYWORD2 +click KEYWORD2 +move KEYWORD2 +press KEYWORD2 +release KEYWORD2 +isPressed KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### diff --git a/libraries/Mouse/library.properties b/libraries/Mouse/library.properties new file mode 100644 index 000000000..6e60f0125 --- /dev/null +++ b/libraries/Mouse/library.properties @@ -0,0 +1,9 @@ +name=Mouse +version=1.0.1 +author=Arduino +maintainer=Arduino +sentence=Allows an Arduino/Genuino board with USB capabilites to act as a Mouse. +paragraph=This library plugs on the HID library. Can be used with or without other HID-based libraries (Keyboard, Gamepad etc) +category=Device Control +url=http://www.arduino.cc/en/Reference/Mouse +architectures=* diff --git a/libraries/Mouse/src/Mouse.cpp b/libraries/Mouse/src/Mouse.cpp new file mode 100644 index 000000000..b2a2cd7b8 --- /dev/null +++ b/libraries/Mouse/src/Mouse.cpp @@ -0,0 +1,123 @@ +/* + Mouse.cpp + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include "Mouse.h" + +#if defined(_USING_HID) + +static const uint8_t _hidReportDescriptor[] PROGMEM = { + + // Mouse + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54 + 0x09, 0x02, // USAGE (Mouse) + 0xa1, 0x01, // COLLECTION (Application) + 0x09, 0x01, // USAGE (Pointer) + 0xa1, 0x00, // COLLECTION (Physical) + 0x85, 0x01, // REPORT_ID (1) + 0x05, 0x09, // USAGE_PAGE (Button) + 0x19, 0x01, // USAGE_MINIMUM (Button 1) + 0x29, 0x03, // USAGE_MAXIMUM (Button 3) + 0x15, 0x00, // LOGICAL_MINIMUM (0) + 0x25, 0x01, // LOGICAL_MAXIMUM (1) + 0x95, 0x03, // REPORT_COUNT (3) + 0x75, 0x01, // REPORT_SIZE (1) + 0x81, 0x02, // INPUT (Data,Var,Abs) + 0x95, 0x01, // REPORT_COUNT (1) + 0x75, 0x05, // REPORT_SIZE (5) + 0x81, 0x03, // INPUT (Cnst,Var,Abs) + 0x05, 0x01, // USAGE_PAGE (Generic Desktop) + 0x09, 0x30, // USAGE (X) + 0x09, 0x31, // USAGE (Y) + 0x09, 0x38, // USAGE (Wheel) + 0x15, 0x81, // LOGICAL_MINIMUM (-127) + 0x25, 0x7f, // LOGICAL_MAXIMUM (127) + 0x75, 0x08, // REPORT_SIZE (8) + 0x95, 0x03, // REPORT_COUNT (3) + 0x81, 0x06, // INPUT (Data,Var,Rel) + 0xc0, // END_COLLECTION + 0xc0, // END_COLLECTION +}; + +//================================================================================ +//================================================================================ +// Mouse + +Mouse_::Mouse_(void) : _buttons(0) +{ + static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); + HID().AppendDescriptor(&node); +} + +void Mouse_::begin(void) +{ +} + +void Mouse_::end(void) +{ +} + +void Mouse_::click(uint8_t b) +{ + _buttons = b; + move(0,0,0); + _buttons = 0; + move(0,0,0); +} + +void Mouse_::move(signed char x, signed char y, signed char wheel) +{ + uint8_t m[4]; + m[0] = _buttons; + m[1] = x; + m[2] = y; + m[3] = wheel; + HID().SendReport(1,m,4); +} + +void Mouse_::buttons(uint8_t b) +{ + if (b != _buttons) + { + _buttons = b; + move(0,0,0); + } +} + +void Mouse_::press(uint8_t b) +{ + buttons(_buttons | b); +} + +void Mouse_::release(uint8_t b) +{ + buttons(_buttons & ~b); +} + +bool Mouse_::isPressed(uint8_t b) +{ + if ((b & _buttons) > 0) + return true; + return false; +} + +Mouse_ Mouse; + +#endif diff --git a/libraries/Mouse/src/Mouse.h b/libraries/Mouse/src/Mouse.h new file mode 100644 index 000000000..2672b5c93 --- /dev/null +++ b/libraries/Mouse/src/Mouse.h @@ -0,0 +1,60 @@ +/* + Mouse.h + + Copyright (c) 2015, Arduino LLC + Original code (pre-library): Copyright (c) 2011, Peter Barrett + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#ifndef MOUSE_h +#define MOUSE_h + +#include "HID.h" + +#if !defined(_USING_HID) + +#warning "Using legacy HID core (non pluggable)" + +#else + +//================================================================================ +//================================================================================ +// Mouse + +#define MOUSE_LEFT 1 +#define MOUSE_RIGHT 2 +#define MOUSE_MIDDLE 4 +#define MOUSE_ALL (MOUSE_LEFT | MOUSE_RIGHT | MOUSE_MIDDLE) + +class Mouse_ +{ +private: + uint8_t _buttons; + void buttons(uint8_t b); +public: + Mouse_(void); + void begin(void); + void end(void); + void click(uint8_t b = MOUSE_LEFT); + void move(signed char x, signed char y, signed char wheel = 0); + void press(uint8_t b = MOUSE_LEFT); // press LEFT by default + void release(uint8_t b = MOUSE_LEFT); // release LEFT by default + bool isPressed(uint8_t b = MOUSE_LEFT); // check LEFT by default +}; +extern Mouse_ Mouse; + +#endif +#endif \ No newline at end of file diff --git a/libraries/OneWire/OneWire.cpp b/libraries/OneWire/OneWire.cpp index 631813f8e..cf349338e 100644 --- a/libraries/OneWire/OneWire.cpp +++ b/libraries/OneWire/OneWire.cpp @@ -12,6 +12,11 @@ works on OneWire every 6 to 12 months. Patches usually wait that long. If anyone is interested in more actively maintaining OneWire, please contact Paul. +Version 2.3: + Unknonw chip fallback mode, Roger Clark + Teensy-LC compatibility, Paul Stoffregen + Search bug fix, Love Nystrom + Version 2.2: Teensy 3.0 compatibility, Paul Stoffregen, paul@pjrc.com Arduino Due compatibility, http://arduino.cc/forum/index.php?topic=141030 @@ -339,7 +344,7 @@ void OneWire::target_search(uint8_t family_code) // Return TRUE : device found, ROM number in ROM_NO buffer // FALSE : device not found, end of search // -uint8_t OneWire::search(uint8_t *newAddr) +uint8_t OneWire::search(uint8_t *newAddr, bool search_mode /* = true */) { uint8_t id_bit_number; uint8_t last_zero, rom_byte_number, search_result; @@ -368,7 +373,11 @@ uint8_t OneWire::search(uint8_t *newAddr) } // issue the search command - write(0xF0); + if (search_mode == true) { + write(0xF0); // NORMAL SEARCH + } else { + write(0xEC); // CONDITIONAL SEARCH + } // loop to do the search do @@ -452,8 +461,9 @@ uint8_t OneWire::search(uint8_t *newAddr) LastDeviceFlag = FALSE; LastFamilyDiscrepancy = 0; search_result = FALSE; + } else { + for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; } - for (int i = 0; i < 8; i++) newAddr[i] = ROM_NO[i]; return search_result; } diff --git a/libraries/OneWire/OneWire.h b/libraries/OneWire/OneWire.h index 916c52907..8753e912f 100644 --- a/libraries/OneWire/OneWire.h +++ b/libraries/OneWire/OneWire.h @@ -45,8 +45,12 @@ #define ONEWIRE_CRC16 1 #endif +#ifndef FALSE #define FALSE 0 +#endif +#ifndef TRUE #define TRUE 1 +#endif // Platform specific I/O definitions @@ -61,7 +65,7 @@ #define DIRECT_WRITE_LOW(base, mask) ((*((base)+2)) &= ~(mask)) #define DIRECT_WRITE_HIGH(base, mask) ((*((base)+2)) |= (mask)) -#elif defined(__MK20DX128__) +#elif defined(__MK20DX128__) || defined(__MK20DX256__) || defined(__MK66FX1M0__) || defined(__MK64FX512__) #define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) #define PIN_TO_BITMASK(pin) (1) #define IO_REG_TYPE uint8_t @@ -72,6 +76,17 @@ #define DIRECT_WRITE_LOW(base, mask) (*((base)+256) = 1) #define DIRECT_WRITE_HIGH(base, mask) (*((base)+128) = 1) +#elif defined(__MKL26Z64__) +#define PIN_TO_BASEREG(pin) (portOutputRegister(pin)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint8_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) ((*((base)+16) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) (*((base)+20) &= ~(mask)) +#define DIRECT_MODE_OUTPUT(base, mask) (*((base)+20) |= (mask)) +#define DIRECT_WRITE_LOW(base, mask) (*((base)+8) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) (*((base)+4) = (mask)) + #elif defined(__SAM3X8E__) // Arduino 1.5.1 may have a bug in delayMicroseconds() on Arduino Due. // http://arduino.cc/forum/index.php/topic,141030.msg1076268.html#msg1076268 @@ -104,8 +119,131 @@ #define DIRECT_WRITE_LOW(base, mask) ((*(base+8+1)) = (mask)) //LATXCLR + 0x24 #define DIRECT_WRITE_HIGH(base, mask) ((*(base+8+2)) = (mask)) //LATXSET + 0x28 +#elif defined(ARDUINO_ARCH_ESP8266) +#define PIN_TO_BASEREG(pin) ((volatile uint32_t*) GPO) +#define PIN_TO_BITMASK(pin) (1 << pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) ((GPI & (mask)) ? 1 : 0) //GPIO_IN_ADDRESS +#define DIRECT_MODE_INPUT(base, mask) (GPE &= ~(mask)) //GPIO_ENABLE_W1TC_ADDRESS +#define DIRECT_MODE_OUTPUT(base, mask) (GPE |= (mask)) //GPIO_ENABLE_W1TS_ADDRESS +#define DIRECT_WRITE_LOW(base, mask) (GPOC = (mask)) //GPIO_OUT_W1TC_ADDRESS +#define DIRECT_WRITE_HIGH(base, mask) (GPOS = (mask)) //GPIO_OUT_W1TS_ADDRESS + +#elif defined(__SAMD21G18A__) +#define PIN_TO_BASEREG(pin) portModeRegister(digitalPinToPort(pin)) +#define PIN_TO_BITMASK(pin) (digitalPinToBitMask(pin)) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, mask) (((*((base)+8)) & (mask)) ? 1 : 0) +#define DIRECT_MODE_INPUT(base, mask) ((*((base)+1)) = (mask)) +#define DIRECT_MODE_OUTPUT(base, mask) ((*((base)+2)) = (mask)) +#define DIRECT_WRITE_LOW(base, mask) ((*((base)+5)) = (mask)) +#define DIRECT_WRITE_HIGH(base, mask) ((*((base)+6)) = (mask)) + +#elif defined(RBL_NRF51822) +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) (pin) +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM +#define DIRECT_READ(base, pin) nrf_gpio_pin_read(pin) +#define DIRECT_WRITE_LOW(base, pin) nrf_gpio_pin_clear(pin) +#define DIRECT_WRITE_HIGH(base, pin) nrf_gpio_pin_set(pin) +#define DIRECT_MODE_INPUT(base, pin) nrf_gpio_cfg_input(pin, NRF_GPIO_PIN_NOPULL) +#define DIRECT_MODE_OUTPUT(base, pin) nrf_gpio_cfg_output(pin) + +#elif defined(__arc__) /* Arduino101/Genuino101 specifics */ + +#include "scss_registers.h" +#include "portable.h" +#include "avr/pgmspace.h" + +#define GPIO_ID(pin) (g_APinDescription[pin].ulGPIOId) +#define GPIO_TYPE(pin) (g_APinDescription[pin].ulGPIOType) +#define GPIO_BASE(pin) (g_APinDescription[pin].ulGPIOBase) +#define DIR_OFFSET_SS 0x01 +#define DIR_OFFSET_SOC 0x04 +#define EXT_PORT_OFFSET_SS 0x0A +#define EXT_PORT_OFFSET_SOC 0x50 + +/* GPIO registers base address */ +#define PIN_TO_BASEREG(pin) ((volatile uint32_t *)g_APinDescription[pin].ulGPIOBase) +#define PIN_TO_BITMASK(pin) pin +#define IO_REG_TYPE uint32_t +#define IO_REG_ASM + +static inline __attribute__((always_inline)) +IO_REG_TYPE directRead(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + IO_REG_TYPE ret; + if (SS_GPIO == GPIO_TYPE(pin)) { + ret = READ_ARC_REG(((IO_REG_TYPE)base + EXT_PORT_OFFSET_SS)); + } else { + ret = MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, EXT_PORT_OFFSET_SOC); + } + return ((ret >> GPIO_ID(pin)) & 0x01); +} + +static inline __attribute__((always_inline)) +void directModeInput(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG((((IO_REG_TYPE)base) + DIR_OFFSET_SS)) & ~(0x01 << GPIO_ID(pin)), + ((IO_REG_TYPE)(base) + DIR_OFFSET_SS)); + } else { + MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, DIR_OFFSET_SOC) &= ~(0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directModeOutput(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(((IO_REG_TYPE)(base) + DIR_OFFSET_SS)) | (0x01 << GPIO_ID(pin)), + ((IO_REG_TYPE)(base) + DIR_OFFSET_SS)); + } else { + MMIO_REG_VAL_FROM_BASE((IO_REG_TYPE)base, DIR_OFFSET_SOC) |= (0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directWriteLow(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(base) & ~(0x01 << GPIO_ID(pin)), base); + } else { + MMIO_REG_VAL(base) &= ~(0x01 << GPIO_ID(pin)); + } +} + +static inline __attribute__((always_inline)) +void directWriteHigh(volatile IO_REG_TYPE *base, IO_REG_TYPE pin) +{ + if (SS_GPIO == GPIO_TYPE(pin)) { + WRITE_ARC_REG(READ_ARC_REG(base) | (0x01 << GPIO_ID(pin)), base); + } else { + MMIO_REG_VAL(base) |= (0x01 << GPIO_ID(pin)); + } +} + +#define DIRECT_READ(base, pin) directRead(base, pin) +#define DIRECT_MODE_INPUT(base, pin) directModeInput(base, pin) +#define DIRECT_MODE_OUTPUT(base, pin) directModeOutput(base, pin) +#define DIRECT_WRITE_LOW(base, pin) directWriteLow(base, pin) +#define DIRECT_WRITE_HIGH(base, pin) directWriteHigh(base, pin) + #else -#error "Please define I/O register types here" +#define PIN_TO_BASEREG(pin) (0) +#define PIN_TO_BITMASK(pin) (pin) +#define IO_REG_TYPE unsigned int +#define IO_REG_ASM +#define DIRECT_READ(base, pin) digitalRead(pin) +#define DIRECT_WRITE_LOW(base, pin) digitalWrite(pin, LOW) +#define DIRECT_WRITE_HIGH(base, pin) digitalWrite(pin, HIGH) +#define DIRECT_MODE_INPUT(base, pin) pinMode(pin,INPUT) +#define DIRECT_MODE_OUTPUT(base, pin) pinMode(pin,OUTPUT) +#warning "OneWire. Fallback mode. Using API calls for pinMode,digitalRead and digitalWrite. Operation of this library is not guaranteed on this architecture." + #endif @@ -178,7 +316,7 @@ class OneWire // might be a good idea to check the CRC to make sure you didn't // get garbage. The order is deterministic. You will always get // the same devices in the same order. - uint8_t search(uint8_t *newAddr); + uint8_t search(uint8_t *newAddr, bool search_mode = true); #endif #if ONEWIRE_CRC diff --git a/libraries/OneWire/library.json b/libraries/OneWire/library.json new file mode 100644 index 000000000..ed232503e --- /dev/null +++ b/libraries/OneWire/library.json @@ -0,0 +1,58 @@ +{ +"name": "OneWire", +"frameworks": "Arduino", +"keywords": "onewire, 1-wire, bus, sensor, temperature, ibutton", +"description": "Control 1-Wire protocol (DS18S20, DS18B20, DS2408 and etc)", +"authors": +[ + { + "name": "Paul Stoffregen", + "email": "paul@pjrc.com", + "url": "http://www.pjrc.com", + "maintainer": true + }, + { + "name": "Jim Studt" + }, + { + "name": "Tom Pollard", + "email": "pollard@alum.mit.edu" + }, + { + "name": "Derek Yerger" + }, + { + "name": "Josh Larios" + }, + { + "name": "Robin James" + }, + { + "name": "Glenn Trewitt" + }, + { + "name": "Jason Dangel", + "email": "dangel.jason AT gmail.com" + }, + { + "name": "Guillermo Lovato" + }, + { + "name": "Ken Butcher" + }, + { + "name": "Mark Tillotson" + }, + { + "name": "Bertrik Sikken" + }, + { + "name": "Scott Roberts" + } +], +"repository": +{ + "type": "git", + "url": "https://github.com/PaulStoffregen/OneWire" +} +} diff --git a/libraries/OneWire/library.properties b/libraries/OneWire/library.properties new file mode 100644 index 000000000..0946c9aa9 --- /dev/null +++ b/libraries/OneWire/library.properties @@ -0,0 +1,10 @@ +name=OneWire +version=2.3.2 +author=Jim Studt, Tom Pollard, Robin James, Glenn Trewitt, Jason Dangel, Guillermo Lovato, Paul Stoffregen, Scott Roberts, Bertrik Sikken, Mark Tillotson, Ken Butcher, Roger Clark, Love Nystrom +maintainer=Paul Stoffregen +sentence=Access 1-wire temperature sensors, memory and other chips. +paragraph= +category=Communication +url=http://www.pjrc.com/teensy/td_libs_OneWire.html +architectures=* + From eae75a8f54b885acf8f2d4d0209964df1b078e5f Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 9 Mar 2016 11:56:48 -1000 Subject: [PATCH 50/79] Adding reste --- camera_box/camera_box.ino | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index c75ca7312..11f7ea6b9 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -1,3 +1,4 @@ + #include #include #include @@ -10,6 +11,8 @@ const int CAM_01_PIN = 5; const int CAM_02_PIN = 6; +const int RESET_PIN = 12; + int led_value = LOW; Adafruit_MMA8451 accelerometer = Adafruit_MMA8451(); @@ -28,9 +31,11 @@ void setup(void) { pinMode(CAM_01_PIN, OUTPUT); pinMode(CAM_02_PIN, OUTPUT); + pinMode(RESET_PIN, OUTPUT); + // Turn on Camera relays - turn_camera_on(CAM_01_PIN); - turn_camera_on(CAM_02_PIN); + turn_pin_on(CAM_01_PIN); + turn_pin_on(CAM_02_PIN); if (! accelerometer.begin()) { while (1); @@ -45,7 +50,7 @@ void setup(void) { } void loop() { - + // Read any serial input // - Input will be two comma separated integers, the // first specifying the pin and the second the status @@ -61,16 +66,21 @@ void loop() { switch (pin_num) { case CAM_01_PIN: if (pin_status == 1) { - turn_camera_on(CAM_01_PIN); + turn_pin_on(CAM_01_PIN); } else { - turn_camera_off(CAM_01_PIN); + turn_pin_off(CAM_01_PIN); } break; case CAM_02_PIN: if (pin_status == 1) { - turn_camera_on(CAM_02_PIN); + turn_pin_on(CAM_02_PIN); } else { - turn_camera_off(CAM_02_PIN); + turn_pin_off(CAM_02_PIN); + } + break; + case RESET_PIN: + if (pin_status == 1) { + turn_pin_off(RESET_PIN); } break; case LED_BUILTIN: @@ -91,6 +101,10 @@ void loop() { Serial.println("}"); delay(1000); + + while (1){ + Serial.println("Waiting on reset"); // Lock-up so that watchdog trips reset + } } /* ACCELEROMETER */ @@ -127,10 +141,10 @@ void toggle_led() { digitalWrite(LED_BUILTIN, led_value); } -void turn_camera_on(int camera_pin) { +void turn_pin_on(int camera_pin) { digitalWrite(camera_pin, HIGH); } -void turn_camera_off(int camera_pin) { +void turn_pin_off(int camera_pin) { digitalWrite(camera_pin, LOW); } From e22c2bd8ed5a9ed87d4f57911c30acb977b13025 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 10 Mar 2016 06:44:08 -1000 Subject: [PATCH 51/79] Delete Test_DSLR.py Removing cruft --- Test_DSLR.py | 73 ---------------------------------------------------- 1 file changed, 73 deletions(-) delete mode 100755 Test_DSLR.py diff --git a/Test_DSLR.py b/Test_DSLR.py deleted file mode 100755 index 78ac1f383..000000000 --- a/Test_DSLR.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/env/python - -# from __future__ import division, print_function - -## Import General Tools -import sys -import os -import argparse -import logging - -import serial - -##------------------------------------------------------------------------- -## Main Program -##------------------------------------------------------------------------- -def main(): - - ##------------------------------------------------------------------------- - ## Parse Command Line Arguments - ##------------------------------------------------------------------------- - ## create a parser object for understanding command-line arguments - parser = argparse.ArgumentParser( - description="Program description.") - ## add flags - parser.add_argument("-v", "--verbose", - action="store_true", dest="verbose", - default=False, help="Be verbose! (default = False)") - ## add arguments - parser.add_argument("--command", "-c", - type=str, dest="command", - help="Command string to send to Arduino.") - args = parser.parse_args() - - ##------------------------------------------------------------------------- - ## Create logger object - ##------------------------------------------------------------------------- - logger = logging.getLogger('MyLogger') - logger.setLevel(logging.DEBUG) - ## Set up console output - LogConsoleHandler = logging.StreamHandler() - if args.verbose: - LogConsoleHandler.setLevel(logging.DEBUG) - else: - LogConsoleHandler.setLevel(logging.INFO) - LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s') - LogConsoleHandler.setFormatter(LogFormat) - logger.addHandler(LogConsoleHandler) - ## Set up file output -# LogFileName = None -# LogFileHandler = logging.FileHandler(LogFileName) -# LogFileHandler.setLevel(logging.DEBUG) -# LogFileHandler.setFormatter(LogFormat) -# logger.addHandler(LogFileHandler) - - - ##------------------------------------------------------------------------- - ## Send command over serial - ##------------------------------------------------------------------------- - connection = serial.Serial('/dev/tty.usbmodemfd1251', 9600, timeout=3.5) - send_string = str(args.command + '/n') - connection.write(send_string) - response = connection.readline() - if response != '': - print(response) - else: - print("No response from Arduino.") - connection.close() - - - - -if __name__ == '__main__': - main() From d2571b167dfcf9e2c04736ed8c8bf4a851095817 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 10 Mar 2016 06:45:40 -1000 Subject: [PATCH 52/79] Removing cruft --- DSLR_Controller/DSLR_Controller.ino | 204 --------------------------- WeatherStation/WeatherStation.ino | 207 ---------------------------- WeatherStation/stino.settings | 7 - 3 files changed, 418 deletions(-) delete mode 100644 DSLR_Controller/DSLR_Controller.ino delete mode 100644 WeatherStation/WeatherStation.ino delete mode 100644 WeatherStation/stino.settings diff --git a/DSLR_Controller/DSLR_Controller.ino b/DSLR_Controller/DSLR_Controller.ino deleted file mode 100644 index 98da95cae..000000000 --- a/DSLR_Controller/DSLR_Controller.ino +++ /dev/null @@ -1,204 +0,0 @@ -/* -Canon DSLR Camera Control - -To activate cameras send a serial tring to the board. The string should -consist of three integers. The first and second indicate which cameras -should be activated. Any non-zero, positive integer in the first field -will activate the first camera and any non-zero integer in the second -field will activate the second camera. The third value is the exposure -time in milliseconds. - -Serial Commands to Board: -Enn,mmmmmm -- Expose camera for mmmmmm milliseconds. -C -- Cancel exposure. Cancels exposure on both cameras. -Q -- Query which cameras are exposing. -T -- Query temperature and humidity from DHT22 (only works if camera not exposing) -O -- Query orientation (only works if camera not exposing) -*/ - -char Command[3]; -char Data[7]; -const int bSize = 20; -char Buffer[bSize]; // Serial buffer -int ByteCount; - -int camera1_pin = 2; -int camera2_pin = 4; - -//Analog read pins -const int xPin = 0; -const int yPin = 1; -const int zPin = 2; - -//The minimum and maximum values that came from -//the accelerometer while standing still -//You very well may need to change these -int minVal = 265; -int maxVal = 402; - -//to hold the caculated values -double x; -double y; -double z; - -//----------------------------------------------------------------------------- -// SerialParser -//----------------------------------------------------------------------------- -void SerialParser(void) { - ByteCount = -1; - ByteCount = Serial.readBytesUntil('\n',Buffer,bSize); - if (ByteCount > 0) { - strcpy(Command,strtok(Buffer,",")); - strcpy(Data,strtok(NULL,",")); - } - memset(Buffer, 0, sizeof(Buffer)); // Clear contents of Buffer - Serial.flush(); -} - - -//----------------------------------------------------------------------------- -// SETUP -//----------------------------------------------------------------------------- -void setup() { - // Open serial communications and wait for port to open: - Serial.begin(9600); - while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } - Serial.print("Setup Camera Relay Pins ... "); - pinMode(camera1_pin, OUTPUT); - pinMode(camera2_pin, OUTPUT); - digitalWrite(camera1_pin, LOW); - digitalWrite(camera2_pin, LOW); - Serial.println("done!"); -} - - -//----------------------------------------------------------------------------- -// MAIN LOOP -//----------------------------------------------------------------------------- -void loop() { - boolean cam1 = false; - boolean cam2 = false; - SerialParser(); - if (Command[0] == 'E') { - if (Command[1] == '1') {cam1 = true;} - if (Command[1] == '2') {cam2 = true;} - if (Command[2] == '1') {cam1 = true;} - if (Command[2] == '2') {cam2 = true;} - String exptime_ms_string = String(Data); - unsigned long exptime_ms = exptime_ms_string.toInt(); - float exptime_sec = exptime_ms/1000.0; - Serial.print("EXP"); - if (cam1 == true) {Serial.print("1");} - if (cam2 == true) {Serial.print("2");} - Serial.print(","); - Serial.print(exptime_ms); - Serial.println('#'); - if (cam1 == true) {digitalWrite(camera1_pin, HIGH);} - if (cam2 == true) {digitalWrite(camera2_pin, HIGH);} - // Now go in to loop waiting for exposure time to finish - // If a cancel command is received, cancel exposure. - unsigned long total_exptime = 0; - unsigned long remainder = exptime_ms % 100; - unsigned long startTime = millis(); - while (total_exptime < exptime_ms - remainder) { - delay(100); - total_exptime = total_exptime + 100; - Serial.println(total_exptime); - // Look for cancel or query status commands - SerialParser(); - if (ByteCount > 0) { - if (Command[0] == 'Q') { - Serial.print("EXP"); - if (cam1 == true) {Serial.print("1");} - if (cam2 == true) {Serial.print("2");} - Serial.println('#'); - } else if (Command[0] == 'X') { - cam1 = false; - cam2 = false; - digitalWrite(camera1_pin, LOW); - digitalWrite(camera2_pin, LOW); - Serial.print("EXP"); - if (cam1 == true) {Serial.print("1");} - if (cam2 == true) {Serial.print("2");} - Serial.println('X#'); - total_exptime = exptime_ms; - } else { - Serial.println('?#'); - } - } - } - delay(remainder); - total_exptime = total_exptime + remainder; - // Set pins low (stop exposure) - cam1 = false; - cam2 = false; - digitalWrite(camera1_pin, LOW); - digitalWrite(camera2_pin, LOW); - unsigned long elapsed = millis() - startTime; - Serial.println(elapsed); - } else if (Command[0] == 'Q') { - Serial.print("EXP"); - Serial.println('#'); - } else if (Command[0] == 'X') { - Serial.print("EXP"); - Serial.println('#'); - } else if (Command[0] == 'T') { - // - } else if (Command[0] == 'O') { - queryOrientation(); - } else if (Command[0] != ' ') { - Serial.println('#'); - } - Command[0] = ' '; - Command[1] = '0'; - Command[2] = '0'; - Data[0] = '0'; - Data[1] = '0'; - Data[2] = '0'; - Data[3] = '0'; - Data[4] = '0'; - Data[5] = '0'; - Data[6] = '0'; - delay(100); -} - - -//----------------------------------------------------------------------------- -// Query Temperature -//----------------------------------------------------------------------------- -float queryTemperature(void) { - -} - - -//----------------------------------------------------------------------------- -// Query Orientation -//----------------------------------------------------------------------------- -float queryOrientation(void) { - //read the analog values from the accelerometer - int xRead = analogRead(xPin); - int yRead = analogRead(yPin); - int zRead = analogRead(zPin); - - //convert read values to degrees -90 to 90 - Needed for atan2 - int xAng = map(xRead, minVal, maxVal, -90, 90); - int yAng = map(yRead, minVal, maxVal, -90, 90); - int zAng = map(zRead, minVal, maxVal, -90, 90); - - //Caculate 360deg values like so: atan2(-yAng, -zAng) - //atan2 outputs the value of -π to π (radians) - //We are then converting the radians to degrees - x = RAD_TO_DEG * (atan2(-yAng, -zAng) + PI); - y = RAD_TO_DEG * (atan2(-xAng, -zAng) + PI); - z = RAD_TO_DEG * (atan2(-yAng, -xAng) + PI); - - //Output the caculations - Serial.print("x: "); - Serial.print(x); - Serial.print(" | y: "); - Serial.print(y); - Serial.print(" | z: "); - Serial.println(z); -} diff --git a/WeatherStation/WeatherStation.ino b/WeatherStation/WeatherStation.ino deleted file mode 100644 index 00cb953b0..000000000 --- a/WeatherStation/WeatherStation.ino +++ /dev/null @@ -1,207 +0,0 @@ -// This script is for a Weather Station that contains two RG-11 Rain Gauges, -// a DHT22 Humidity and Temperature Sensor, two TMP36 Temperature Sensors, -// a TSL235R Light to Frequency Sensor, and an MLX90614 Infrared Thermometer. -// -// Program will read sensors and periodically print out a line of text via -// serial with the readings. - - -#include -#include - - -// Pin Constants -const int WarningLEDpin = 13; // This LED turns on when the weather conditions are not good for observing. -const int RainSensor1 = 7; // The Rain Gauges can be connected to any of the digital pins. -const int RainSensor2 = 8; -const int TMP36pin1 = 2; // The TMP36 sensors must be connected to analogue pins. -const int TMP36pin2 = 3; -#define DHTPIN 5 // The DHT22 is connected to a digital pin. -#define DHTTYPE DHT22 -DHT dht(DHTPIN, DHTTYPE); - - -// Thresholds for Warnings -// --> These need to be modified after experience in the field -const float Threshold_VeryCloudy = -20.0; -const float Threshold_Cloudy = -40.0; -const float Threshold_Humidity = 80.0; - - -// Constants for TSL235R -volatile unsigned long cnt = 0; -unsigned long oldcnt = 0; -unsigned long t = 0; -unsigned long last; - -void irq1() -{ - cnt++; -} - - -void setup() { - Serial.begin(9600); - - Serial.print("Setup LED Pin..."); - pinMode(WarningLEDpin, OUTPUT); - Serial.println("done!"); - - Serial.print("Setup DHT22..."); - dht.begin(); - Serial.println("done!"); - - Serial.print("Setup I2C..."); - i2c_init(); // Initialise the i2c bus - PORTC = (1 << PORTC4) | (1 << PORTC5); // Enable pullups - Serial.println("done!"); - - Serial.print("Setup TSL235R..."); - pinMode(2, INPUT); // TSL235R must use digital pin 2. - digitalWrite(2, HIGH); - attachInterrupt(0, irq1, RISING); - Serial.println("done!"); - - Serial.print("Setup first RG-11..."); - pinMode(RainSensor1, INPUT); - Serial.println("done!"); - - Serial.print("Setup second RG-11..."); - pinMode(RainSensor2, INPUT); - Serial.println("done!"); - - - // print header to Serial - Serial.print("Light "); - Serial.print("SkyTemp "); - Serial.print("AmbTemp "); - Serial.print("Humidity "); - Serial.print("HW "); - Serial.print("TempDiff "); - Serial.print("CW "); - Serial.print("CaseTemp 1 "); - Serial.print("CaseTemp 2 "); - Serial.print("Rain1? "); - Serial.print("Rain2? "); - Serial.print("Safe? "); - Serial.println(""); -} - -void loop() { - - // Read light level TSL235R in mW/m2 - last = millis(); - t = cnt; - unsigned long hz = t - oldcnt; - oldcnt = t; - float Light = (hz+50)/100; // +50 == rounding last digit - // print output to Serial - Serial.print(Light); - Serial.print(" mW/m2 "); - - // Read sky temperature MLX90614 in Celsius - float SkyTemp_C = readMLX90614() - 273.15; // Converting from Kelvin to Celsius - // print output to Serial - Serial.print(SkyTemp_C); - Serial.print(" C "); - - // Read ambient temperature and humidity DHT22 - float Humidity = dht.readHumidity(); - float AmbTemp_C = dht.readTemperature(); - // check if returns are valid, if they are NaN (not a number) then something went wrong! - if (isnan(AmbTemp_C) || isnan(Humidity)) { - Serial.println("Failed to read from DHT"); - } - int HumidityWarning = 0; - if (Humidity > Threshold_Humidity) { HumidityWarning = 1; } - // print output to Serial - Serial.print(AmbTemp_C); - Serial.print(" C "); - Serial.print(Humidity); - Serial.print(" % "); - Serial.print(HumidityWarning); - Serial.print(" "); - - // Determine Sky / Ambient Temperature Difference - float TempDiff = SkyTemp_C - AmbTemp_C; - int Cloudiness; - // print output to Serial - Serial.print(TempDiff); - Serial.print(" C "); - if (TempDiff >= Threshold_VeryCloudy) { Cloudiness = 2; } - if (TempDiff >= Threshold_Cloudy && TempDiff < Threshold_VeryCloudy) { Cloudiness = 1; } - if (TempDiff < Threshold_Cloudy) { Cloudiness = 0; } - // print output to Serial - Serial.print(Cloudiness); - Serial.print(" "); - - // Read case temperature from TMP36 primary - int TMP36reading1 = analogRead(TMP36pin1); - float TMP36voltage1 = (TMP36reading1 / 1024.0) * 5000; - float CaseTemp_C1 = (TMP36voltage1 -500) / 10.0; - // print output to Serial - Serial.print(CaseTemp_C1); - Serial.print(" C "); - - // Read case temperature from TMP36 secondary - int TMP36reading2 = analogRead(TMP36pin2); - float TMP36voltage2 = (TMP36reading2 / 1024.0) * 5000; - float CaseTemp_C2 = (TMP36voltage2 -500) / 10.0; - // print output to Serial - Serial.print(CaseTemp_C2); - Serial.print(" C "); - - // Are the RG-11 Rain Gauges on? - int rain1; - rain1 = digitalRead(RainSensor1); // read the input pin - // print output to Serial - Serial.print(rain1); - Serial.print(" "); - - int rain2; - rain2 = digitalRead(RainSensor2); // read the input pin - // print output to Serial - Serial.print(rain2); - Serial.print(" "); - - // Are conditions safe? - bool Safe = false; - if (HumidityWarning == 0 && Cloudiness <= 1) { Safe = true; } - if (Safe) { digitalWrite(WarningLEDpin, LOW); } - else { digitalWrite(WarningLEDpin, HIGH); } - // print output to Serial - Serial.print(Safe); - Serial.print(" "); - - Serial.println(""); -} - -// Read MLX90614 IR thermometer and return temperature in Kelvin -float readMLX90614(void){ - int dev = 0x5A<<1; - int data_low = 0; - int data_high = 0; - int pec = 0; - - i2c_start_wait(dev+I2C_WRITE); - i2c_write(0x07); - - i2c_rep_start(dev+I2C_READ); - data_low = i2c_readAck(); // Read 1 byte and then send ack - data_high = i2c_readAck(); // Read 1 byte and then send ack - pec = i2c_readNak(); - i2c_stop(); - - // This converts high and low bytes together and processes temperature, MSB is an error bit and is ignored for temps - double tempFactor = 0.02; // 0.02 degrees per LSB (measurement resolution of the MLX90614) - double tempData = 0x0000; // Zero out the data - int frac; // Data past the decimal point - - // This masks off the error bit of the high byte, then moves it left 8 bits and adds the low byte. - tempData = (double)(((data_high & 0x007F) << 8) + data_low); - tempData = (tempData * tempFactor) - 0.01; - - float kelvin = tempData; - - return kelvin; -} diff --git a/WeatherStation/stino.settings b/WeatherStation/stino.settings deleted file mode 100644 index 014af2ffd..000000000 --- a/WeatherStation/stino.settings +++ /dev/null @@ -1,7 +0,0 @@ -{ - "arduino_folder": "/home/wtgee/arduino-1.5.8", - "full_compilation": true, - "platform": 1, - "platform_name": "Arduino AVR Boards", - "serial_port": 0 -} \ No newline at end of file From dbdaeff57127ca106b83fb903ee1522184b874cb Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 13 Jul 2016 13:38:47 +1000 Subject: [PATCH 53/79] Create LICENSE Name & Date change on license --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..d36a2d274 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 PANOPTES Foundation + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From fc8c09640137975ccab7b5795758c4bc513dcfcd Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 14 Jul 2016 06:21:14 +1000 Subject: [PATCH 54/79] Update LICENSE Name change --- LICENSE | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/LICENSE b/LICENSE index d36a2d274..b2eadfab8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2016 PANOPTES Foundation +Copyright (c) 2016 PANOPTES Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal From 507faf0a936e6b9adf2e633855fa5632f88a22c8 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Thu, 21 Jul 2016 12:08:52 +1000 Subject: [PATCH 55/79] Create CONTRIBUTING.md panoptes/POCS#34 --- CONTRIBUTING.md | 1 + 1 file changed, 1 insertion(+) create mode 100644 CONTRIBUTING.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..5fd24977e --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1 @@ +Please see the [POCS CONTRIBUTING](https://github.com/panoptes/POCS/blob/develop/CONTRIBUTING.md) file. From 221bd388a3bb6c4c6c43c544af543dcd581ec131 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sat, 20 Aug 2016 14:07:01 +1000 Subject: [PATCH 56/79] Flush the output fully --- camera_box/camera_box.ino | 1 + 1 file changed, 1 insertion(+) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index 11f7ea6b9..9fb0e465e 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -100,6 +100,7 @@ void loop() { Serial.println("}"); + Serial.flush(); delay(1000); while (1){ From d5b894f0165a874e4c3d21c888114a60aee5a42b Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Fri, 3 Mar 2017 08:57:46 +1100 Subject: [PATCH 57/79] * Telemetry Board (former computer box) * Add current sensing * Clean up * Updates to the Camera sketch * Update DHT22 pin based on schematic * Consistent style with telemetry board sketch --- camera_box/camera_box.ino | 35 ++--- .../{computer_box.ino => telemetry_board.ino} | 137 ++++++++++++------ 2 files changed, 111 insertions(+), 61 deletions(-) rename computer_box/{computer_box.ino => telemetry_board.ino} (54%) diff --git a/camera_box/camera_box.ino b/camera_box/camera_box.ino index 9fb0e465e..b377f62bb 100644 --- a/camera_box/camera_box.ino +++ b/camera_box/camera_box.ino @@ -5,20 +5,23 @@ #include #include -#define DHT_PIN 4 // DHT Temp & Humidity Pin #define DHT_TYPE DHT22 // DHT 22 (AM2302) -const int CAM_01_PIN = 5; -const int CAM_02_PIN = 6; - +/* DECLARE PINS */ +const int DHT_PIN 9; // DHT Temp & Humidity Pin +const int CAM_01_RELAY = 5; +const int CAM_02_RELAY = 6; const int RESET_PIN = 12; -int led_value = LOW; +/* CONSTANTS */ Adafruit_MMA8451 accelerometer = Adafruit_MMA8451(); +// Setup DHT22 DHT dht(DHT_PIN, DHT_TYPE); +int led_value = LOW; + void setup(void) { Serial.begin(9600); Serial.flush(); @@ -28,14 +31,14 @@ void setup(void) { digitalWrite(LED_BUILTIN, LOW); // Setup Camera relays - pinMode(CAM_01_PIN, OUTPUT); - pinMode(CAM_02_PIN, OUTPUT); + pinMode(CAM_01_RELAY, OUTPUT); + pinMode(CAM_02_RELAY, OUTPUT); pinMode(RESET_PIN, OUTPUT); // Turn on Camera relays - turn_pin_on(CAM_01_PIN); - turn_pin_on(CAM_02_PIN); + turn_pin_on(CAM_01_RELAY); + turn_pin_on(CAM_02_RELAY); if (! accelerometer.begin()) { while (1); @@ -64,18 +67,12 @@ void loop() { int pin_status = Serial.parseInt(); switch (pin_num) { - case CAM_01_PIN: - if (pin_status == 1) { - turn_pin_on(CAM_01_PIN); - } else { - turn_pin_off(CAM_01_PIN); - } - break; - case CAM_02_PIN: + case CAM_01_RELAY: + case CAM_02_RELAY: if (pin_status == 1) { - turn_pin_on(CAM_02_PIN); + turn_pin_on(pin_num); } else { - turn_pin_off(CAM_02_PIN); + turn_pin_off(pin_num); } break; case RESET_PIN: diff --git a/computer_box/computer_box.ino b/computer_box/telemetry_board.ino similarity index 54% rename from computer_box/computer_box.ino rename to computer_box/telemetry_board.ino index 609b919bf..d2e187064 100644 --- a/computer_box/computer_box.ino +++ b/computer_box/telemetry_board.ino @@ -5,16 +5,37 @@ #define DHTTYPE DHT22 // DHT 22 (AM2302) -const int AC_PROBE = 2; -const int DC_PROBE = 1; +/* DECLARE PINS */ + +// Analog Pins +const int I_MAIN = A1; +const int I_FAN = A2; +const int I_MOUNT = A3; +const int I_CAMERAS = A4; + +// Digital Pins +const int AC_IN = 11; +const int DS18_IN = 10; // DS18B20 Temperature (OneWire) +const int DHT_IN = 9; // DHT Temp & Humidity Pin + +const int COMP_RELAY = 8; // Computer Relay +const int CAMERAS_RELAY = 7; // Cameras Relay +const int FAN_RELAY = 6; // Fan Relay +const int WEATHER_RELAY = 5; // Weather Relay +const int MOUNT_RELAY = 4; // Mount Relay -const int FAN_PIN = 4; -const int DHT_PIN = 3; // DHT Temp & Humidity Pin -const int DS18_PIN = 2; const int NUM_DS18 = 3; // Number of DS18B20 Sensors -//const int LED_BUILTIN = 13; -int led_value = LOW; + +/* CONSTANTS */ +/* +For info on the current sensing, see: + http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/the-acs712-current-sensor-with-an-arduino/ + http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-current-sensor-user-manual/ +*/ +const int mV_per_amp = 185; +const int ACS_offset = 2500; + uint8_t sensors_address[NUM_DS18][8]; @@ -25,18 +46,24 @@ float get_ds18b20_temp (uint8_t *address); // Setup DHT22 DHT dht(DHT_PIN, DHTTYPE); +int led_value = LOW; + + void setup() { Serial.begin(9600); Serial.flush(); pinMode(LED_BUILTIN, OUTPUT); + pinMode(DS18_PIN, OUTPUT); - pinMode(FAN_PIN, OUTPUT); - dht.begin(); + pinMode(COMP_RELAY, OUTPUT); + pinMode(CAMERAS_RELAY, OUTPUT); + pinMode(FAN_RELAY, OUTPUT); + pinMode(WEATHER_RELAY, OUTPUT); + pinMode(MOUNT_RELAY, OUTPUT); - // Turn on the fan - turn_fan_on(); + dht.begin(); // Search for attached DS18B20 sensors int x, c = 0; @@ -61,11 +88,22 @@ void loop() { int pin_status = Serial.parseInt(); switch (pin_num) { - case FAN_PIN: - case LED_BUILTIN: - digitalWrite(pin_num, pin_status); - break; - } + case COMP_RELAY: + case CAMERAS_RELAY: + case FAN_RELAY: + case WEATHER_RELAY: + case MOUNT_RELAY: + if (pin_status == 1) { + turn_pin_on(pin_num); + } else { + turn_pin_off(pin_num); + } + break; + case FAN_PIN: + case LED_BUILTIN: + digitalWrite(pin_num, pin_status); + break; + } } Serial.print("{"); @@ -76,8 +114,6 @@ void loop() { read_ds18b20_temp(); Serial.print(","); - read_fan_status(); Serial.print(","); - Serial.print("\"count\":"); Serial.print(millis()); Serial.println("}"); @@ -87,18 +123,50 @@ void loop() { delay(1000); } +/* Toggle Pin */ +void turn_pin_on(int camera_pin) { + digitalWrite(camera_pin, HIGH); +} -/* DC Probe: ~730 = 11.53 */ -void read_voltages() { - int ac_reading = analogRead(AC_PROBE); - float ac_voltage = ac_reading / 1023 * 5; +void turn_pin_off(int camera_pin) { + digitalWrite(camera_pin, LOW); +} + + +/* Read Voltages + +Gets the AC probe as well as the values of the current on the AC I_ pins - int dc_reading = analogRead(DC_PROBE); - float dc_voltage = dc_reading * 0.0158; +https://www.arduino.cc/en/Reference/AnalogRead + + */ +void read_voltages() { + int ac_reading = analogRead(AC_IN); + float ac_voltage = (ac_reading / 1023.) * 5000; + ac_amps = ((ac_voltage - ACS_offset) / mV_per_amp); + + int main_reading = analogRead(I_MAIN); + float main_voltage = (main_reading / 1023.) * 5000; + main_amps = ((main_voltage - ACS_offset) / mV_per_amp); + + int fan_reading = analogRead(I_FAN); + float fan_voltage = (fan_reading / 1023.) * 5000; + fan_amps = ((fan_voltage - ACS_offset) / mV_per_amp); + + int mount_reading = analogRead(I_MOUNT); + float mount_voltage = (mount_reading / 1023.) * 5000; + mount_amps = ((mount_voltage - ACS_offset) / mV_per_amp); + + int camera_reading = analogRead(I_CAMERAS); + float camera_voltage = (camera_reading / 1023.) * 5000; + camera_amps = ((camera_voltage - ACS_offset) / mV_per_amp); Serial.print("\"voltages\":{"); Serial.print("\"ac\":"); Serial.print(ac_voltage); Serial.print(','); - Serial.print("\"dc\":"); Serial.print(dc_voltage); + Serial.print("\"main\":"); Serial.print(main_amps); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(fan_amps); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(mount_amps); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(cameras_amps); Serial.print('}'); } @@ -133,12 +201,6 @@ void read_ds18b20_temp() { } } -void read_fan_status() { - int fan_status = digitalRead(FAN_PIN); - - Serial.print("\"fan\":"); Serial.print(fan_status); -} - float get_ds18b20_temp(uint8_t *addr) { byte data[12]; @@ -164,6 +226,7 @@ float get_ds18b20_temp(uint8_t *addr) { return TemperatureSum; } + /************************************ * Utitlity Methods *************************************/ @@ -171,14 +234,4 @@ float get_ds18b20_temp(uint8_t *addr) { void toggle_led() { led_value = ! led_value; digitalWrite(LED_BUILTIN, led_value); -} - -void turn_fan_on() { - digitalWrite(FAN_PIN, HIGH); - Serial.println("Fan turned on"); -} - -void turn_fan_off() { - digitalWrite(FAN_PIN, LOW); - Serial.println("Fan turned off"); -} +} \ No newline at end of file From f9522ba6d5887aa36e5421d10363b05b5d71027c Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sat, 4 Mar 2017 09:31:49 +1100 Subject: [PATCH 58/79] Rename camera_box.ino to camera_board.ino Updating name --- camera_box/{camera_box.ino => camera_board.ino} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename camera_box/{camera_box.ino => camera_board.ino} (100%) diff --git a/camera_box/camera_box.ino b/camera_box/camera_board.ino similarity index 100% rename from camera_box/camera_box.ino rename to camera_box/camera_board.ino From c4b6b15f238243b03d096d6ec32800e9055a32d3 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 13 Mar 2017 09:06:40 +1100 Subject: [PATCH 59/79] Making directory names consistent with files --- {camera_box => camera_board}/camera_board.ino | 0 {camera_box => camera_board}/stino.settings | 0 {computer_box => telemetry_board}/telemetry_board.ino | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename {camera_box => camera_board}/camera_board.ino (100%) rename {camera_box => camera_board}/stino.settings (100%) rename {computer_box => telemetry_board}/telemetry_board.ino (100%) diff --git a/camera_box/camera_board.ino b/camera_board/camera_board.ino similarity index 100% rename from camera_box/camera_board.ino rename to camera_board/camera_board.ino diff --git a/camera_box/stino.settings b/camera_board/stino.settings similarity index 100% rename from camera_box/stino.settings rename to camera_board/stino.settings diff --git a/computer_box/telemetry_board.ino b/telemetry_board/telemetry_board.ino similarity index 100% rename from computer_box/telemetry_board.ino rename to telemetry_board/telemetry_board.ino From d4caea2631d15122b8e3c324801216f1952f8904 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 13 Mar 2017 11:25:58 +1100 Subject: [PATCH 60/79] * Consistent pins names with each other * Small typo fixes --- camera_board/camera_board.ino | 2 +- telemetry_board/telemetry_board.ino | 23 +++++++++++------------ 2 files changed, 12 insertions(+), 13 deletions(-) diff --git a/camera_board/camera_board.ino b/camera_board/camera_board.ino index b377f62bb..25e4963d8 100644 --- a/camera_board/camera_board.ino +++ b/camera_board/camera_board.ino @@ -8,7 +8,7 @@ #define DHT_TYPE DHT22 // DHT 22 (AM2302) /* DECLARE PINS */ -const int DHT_PIN 9; // DHT Temp & Humidity Pin +const int DHT_PIN = 9; // DHT Temp & Humidity Pin const int CAM_01_RELAY = 5; const int CAM_02_RELAY = 6; const int RESET_PIN = 12; diff --git a/telemetry_board/telemetry_board.ino b/telemetry_board/telemetry_board.ino index d2e187064..bfde1b916 100644 --- a/telemetry_board/telemetry_board.ino +++ b/telemetry_board/telemetry_board.ino @@ -14,9 +14,9 @@ const int I_MOUNT = A3; const int I_CAMERAS = A4; // Digital Pins -const int AC_IN = 11; -const int DS18_IN = 10; // DS18B20 Temperature (OneWire) -const int DHT_IN = 9; // DHT Temp & Humidity Pin +const int AC_PIN = 11; +const int DS18_PIN = 10; // DS18B20 Temperature (OneWire) +const int DHT_PIN = 9; // DHT Temp & Humidity Pin const int COMP_RELAY = 8; // Computer Relay const int CAMERAS_RELAY = 7; // Cameras Relay @@ -99,7 +99,6 @@ void loop() { turn_pin_off(pin_num); } break; - case FAN_PIN: case LED_BUILTIN: digitalWrite(pin_num, pin_status); break; @@ -141,32 +140,32 @@ https://www.arduino.cc/en/Reference/AnalogRead */ void read_voltages() { - int ac_reading = analogRead(AC_IN); + int ac_reading = analogRead(AC_PIN); float ac_voltage = (ac_reading / 1023.) * 5000; - ac_amps = ((ac_voltage - ACS_offset) / mV_per_amp); + float ac_amps = ((ac_voltage - ACS_offset) / mV_per_amp); int main_reading = analogRead(I_MAIN); float main_voltage = (main_reading / 1023.) * 5000; - main_amps = ((main_voltage - ACS_offset) / mV_per_amp); + float main_amps = ((main_voltage - ACS_offset) / mV_per_amp); int fan_reading = analogRead(I_FAN); float fan_voltage = (fan_reading / 1023.) * 5000; - fan_amps = ((fan_voltage - ACS_offset) / mV_per_amp); + float fan_amps = ((fan_voltage - ACS_offset) / mV_per_amp); int mount_reading = analogRead(I_MOUNT); float mount_voltage = (mount_reading / 1023.) * 5000; - mount_amps = ((mount_voltage - ACS_offset) / mV_per_amp); + float mount_amps = ((mount_voltage - ACS_offset) / mV_per_amp); int camera_reading = analogRead(I_CAMERAS); float camera_voltage = (camera_reading / 1023.) * 5000; - camera_amps = ((camera_voltage - ACS_offset) / mV_per_amp); + float camera_amps = ((camera_voltage - ACS_offset) / mV_per_amp); Serial.print("\"voltages\":{"); Serial.print("\"ac\":"); Serial.print(ac_voltage); Serial.print(','); Serial.print("\"main\":"); Serial.print(main_amps); Serial.print(','); Serial.print("\"fan\":"); Serial.print(fan_amps); Serial.print(','); Serial.print("\"mount\":"); Serial.print(mount_amps); Serial.print(','); - Serial.print("\"cameras\":"); Serial.print(cameras_amps); + Serial.print("\"cameras\":"); Serial.print(camera_amps); Serial.print('}'); } @@ -234,4 +233,4 @@ float get_ds18b20_temp(uint8_t *addr) { void toggle_led() { led_value = ! led_value; digitalWrite(LED_BUILTIN, led_value); -} \ No newline at end of file +} From 7d925faad4ed3ce7ef124817f0d551f9017aeb52 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 26 Mar 2017 22:38:11 -1000 Subject: [PATCH 61/79] Updates to camera board and telemetry board for new electroncs * Better reporting/switching --- camera_board/camera_board.ino | 25 +++-- telemetry_board/telemetry_board.ino | 158 ++++++++++++++++------------ 2 files changed, 108 insertions(+), 75 deletions(-) diff --git a/camera_board/camera_board.ino b/camera_board/camera_board.ino index 25e4963d8..1377b6438 100644 --- a/camera_board/camera_board.ino +++ b/camera_board/camera_board.ino @@ -1,4 +1,3 @@ - #include #include #include @@ -89,9 +88,11 @@ void loop() { // Begin reading values and outputting as JSON string Serial.print("{"); - read_accelerometer(); Serial.print(','); + read_status(); + + read_accelerometer(); - read_dht_temp(); Serial.print(","); + read_dht_temp(); Serial.print("\"count\":"); Serial.print(millis()); @@ -99,10 +100,14 @@ void loop() { Serial.flush(); delay(1000); +} - while (1){ - Serial.println("Waiting on reset"); // Lock-up so that watchdog trips reset - } +void read_status() { + + Serial.print("\"power\":{"); + Serial.print("\"camera_00\":"); Serial.print(is_pin_on(CAM_01_RELAY)); Serial.print(','); + Serial.print("\"camera_01\":"); Serial.print(is_pin_on(CAM_02_RELAY)); Serial.print(','); + Serial.print("},"); } /* ACCELEROMETER */ @@ -117,7 +122,7 @@ void read_accelerometer() { Serial.print("\"y\":"); Serial.print(event.acceleration.y); Serial.print(','); Serial.print("\"z\":"); Serial.print(event.acceleration.z); Serial.print(','); Serial.print("\"o\": "); Serial.print(o); - Serial.print('}'); + Serial.print("},"); } //// Reading temperature or humidity takes about 250 milliseconds! @@ -127,7 +132,7 @@ void read_dht_temp() { float c = dht.readTemperature(); // Celsius Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); - Serial.print("\"temp_01\":"); Serial.print(c); + Serial.print("\"temp_00\":"); Serial.print(c); Serial.print(","); } /************************************ @@ -146,3 +151,7 @@ void turn_pin_on(int camera_pin) { void turn_pin_off(int camera_pin) { digitalWrite(camera_pin, LOW); } + +int is_pin_on(int camera_pin) { + return digitalRead(camera_pin); +} diff --git a/telemetry_board/telemetry_board.ino b/telemetry_board/telemetry_board.ino index bfde1b916..ae5650f53 100644 --- a/telemetry_board/telemetry_board.ino +++ b/telemetry_board/telemetry_board.ino @@ -1,5 +1,7 @@ #include #include +#include + #include @@ -19,9 +21,9 @@ const int DS18_PIN = 10; // DS18B20 Temperature (OneWire) const int DHT_PIN = 9; // DHT Temp & Humidity Pin const int COMP_RELAY = 8; // Computer Relay -const int CAMERAS_RELAY = 7; // Cameras Relay -const int FAN_RELAY = 6; // Fan Relay -const int WEATHER_RELAY = 5; // Weather Relay +const int CAMERAS_RELAY = 7; // Cameras Relay Off: 70s Both On: 800s One On: 350 +const int FAN_RELAY = 6; // Fan Relay Off: 0 On: 80s +const int WEATHER_RELAY = 5; // Weather Relay 250mA upon init and 250mA to read const int MOUNT_RELAY = 4; // Mount Relay const int NUM_DS18 = 3; // Number of DS18B20 Sensors @@ -33,15 +35,15 @@ For info on the current sensing, see: http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/the-acs712-current-sensor-with-an-arduino/ http://henrysbench.capnfatz.com/henrys-bench/arduino-current-measurements/acs712-current-sensor-user-manual/ */ -const int mV_per_amp = 185; -const int ACS_offset = 2500; +const float mV_per_amp = 0.185; +const float ACS_offset = 0.; uint8_t sensors_address[NUM_DS18][8]; // Temperature chip I/O -OneWire sensor_bus(DS18_PIN); -float get_ds18b20_temp (uint8_t *address); +OneWire ds(DS18_PIN); +DallasTemperature sensors(&ds); // Setup DHT22 DHT dht(DHT_PIN, DHTTYPE); @@ -55,7 +57,9 @@ void setup() { pinMode(LED_BUILTIN, OUTPUT); - pinMode(DS18_PIN, OUTPUT); + sensors.begin(); + + pinMode(AC_PIN, INPUT); pinMode(COMP_RELAY, OUTPUT); pinMode(CAMERAS_RELAY, OUTPUT); @@ -63,14 +67,15 @@ void setup() { pinMode(WEATHER_RELAY, OUTPUT); pinMode(MOUNT_RELAY, OUTPUT); + // Turn relays on to start + digitalWrite(COMP_RELAY, HIGH); + digitalWrite(CAMERAS_RELAY, HIGH); + digitalWrite(FAN_RELAY, HIGH); + digitalWrite(WEATHER_RELAY, HIGH); + digitalWrite(MOUNT_RELAY, HIGH); + dht.begin(); - // Search for attached DS18B20 sensors - int x, c = 0; - for (x = 0; x < NUM_DS18; x++) { - if (sensor_bus.search(sensors_address[x])) - c++; - } } void loop() { @@ -88,7 +93,32 @@ void loop() { int pin_status = Serial.parseInt(); switch (pin_num) { + case 0: // All off + turn_pin_off(COMP_RELAY); + turn_pin_off(CAMERAS_RELAY); + turn_pin_off(FAN_RELAY); + turn_pin_off(WEATHER_RELAY); + turn_pin_off(MOUNT_RELAY); + break; + case 1: // All on + turn_pin_on(COMP_RELAY); + turn_pin_on(CAMERAS_RELAY); + turn_pin_on(FAN_RELAY); + turn_pin_on(WEATHER_RELAY); + turn_pin_on(MOUNT_RELAY); + break; case COMP_RELAY: + /* The computer shutting itself off: + * - Power down + * - Wait 30 seconds + * - Power up + */ + if (pin_status == 0){ + turn_pin_off(COMP_RELAY); + delay(1000 * 30); + turn_pin_on(COMP_RELAY); + } + break; case CAMERAS_RELAY: case FAN_RELAY: case WEATHER_RELAY: @@ -107,18 +137,18 @@ void loop() { Serial.print("{"); - read_voltages(); Serial.print(","); + read_voltages(); - read_dht_temp(); Serial.print(","); + read_dht_temp(); - read_ds18b20_temp(); Serial.print(","); + read_ds18b20_temp(); Serial.print("\"count\":"); Serial.print(millis()); Serial.println("}"); // Simple heartbeat - toggle_led(); + // toggle_led(); delay(1000); } @@ -131,6 +161,9 @@ void turn_pin_off(int camera_pin) { digitalWrite(camera_pin, LOW); } +int is_pin_on(int camera_pin) { + return digitalRead(camera_pin); +} /* Read Voltages @@ -140,33 +173,52 @@ https://www.arduino.cc/en/Reference/AnalogRead */ void read_voltages() { - int ac_reading = analogRead(AC_PIN); - float ac_voltage = (ac_reading / 1023.) * 5000; - float ac_amps = ((ac_voltage - ACS_offset) / mV_per_amp); + int ac_reading = digitalRead(AC_PIN); int main_reading = analogRead(I_MAIN); - float main_voltage = (main_reading / 1023.) * 5000; + float main_voltage = (main_reading / 1023.) * 5.; float main_amps = ((main_voltage - ACS_offset) / mV_per_amp); int fan_reading = analogRead(I_FAN); - float fan_voltage = (fan_reading / 1023.) * 5000; + float fan_voltage = (fan_reading / 1023.) * 5.; float fan_amps = ((fan_voltage - ACS_offset) / mV_per_amp); int mount_reading = analogRead(I_MOUNT); - float mount_voltage = (mount_reading / 1023.) * 5000; + float mount_voltage = (mount_reading / 1023.) * 5.; float mount_amps = ((mount_voltage - ACS_offset) / mV_per_amp); int camera_reading = analogRead(I_CAMERAS); - float camera_voltage = (camera_reading / 1023.) * 5000; + float camera_voltage = (camera_reading / 1023.) * 5.; float camera_amps = ((camera_voltage - ACS_offset) / mV_per_amp); - Serial.print("\"voltages\":{"); - Serial.print("\"ac\":"); Serial.print(ac_voltage); Serial.print(','); - Serial.print("\"main\":"); Serial.print(main_amps); Serial.print(','); - Serial.print("\"fan\":"); Serial.print(fan_amps); Serial.print(','); - Serial.print("\"mount\":"); Serial.print(mount_amps); Serial.print(','); - Serial.print("\"cameras\":"); Serial.print(camera_amps); - Serial.print('}'); + Serial.print("\"power\":{"); + Serial.print("\"computer\":"); Serial.print(is_pin_on(COMP_RELAY)); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(is_pin_on(FAN_RELAY)); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(is_pin_on(MOUNT_RELAY)); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(is_pin_on(CAMERAS_RELAY)); Serial.print(','); + Serial.print("\"weather\":"); Serial.print(is_pin_on(WEATHER_RELAY)); Serial.print(','); + Serial.print("},"); + + Serial.print("\"current\":{"); + Serial.print("\"main\":"); Serial.print(main_reading); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(fan_reading); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(mount_reading); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(camera_reading); + Serial.print("},"); + +// Serial.print("\"volts\":{"); +// Serial.print("\"main\":"); Serial.print(main_voltage); Serial.print(','); +// Serial.print("\"fan\":"); Serial.print(fan_voltage); Serial.print(','); +// Serial.print("\"mount\":"); Serial.print(mount_voltage); Serial.print(','); +// Serial.print("\"cameras\":"); Serial.print(camera_voltage); +// Serial.print("},"); +// +// Serial.print("\"amps\":{"); +// Serial.print("\"main\":"); Serial.print(main_amps); Serial.print(','); +// Serial.print("\"fan\":"); Serial.print(fan_amps); Serial.print(','); +// Serial.print("\"mount\":"); Serial.print(mount_amps); Serial.print(','); +// Serial.print("\"cameras\":"); Serial.print(camera_amps); +// Serial.print("},"); } //// Reading temperature or humidity takes about 250 milliseconds! @@ -182,50 +234,22 @@ void read_dht_temp() { // } Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); - Serial.print("\"temp_00\":"); Serial.print(c); + Serial.print("\"temp_00\":"); Serial.print(c); Serial.print(','); } void read_ds18b20_temp() { - for (int x = 0; x < NUM_DS18; x++) { - Serial.print("\"temp_0"); - Serial.print(x + 1); - Serial.print("\":"); - Serial.print(get_ds18b20_temp(sensors_address[x])); - - // Append a comma to all but last - if (x < NUM_DS18 - 1) { - Serial.print(","); - } - } -} - -float get_ds18b20_temp(uint8_t *addr) { - byte data[12]; + sensors.requestTemperatures(); - sensor_bus.reset(); - sensor_bus.select(addr); - sensor_bus.write(0x44, 1); // start conversion, with parasite power on at the end + Serial.print("\"temperature\":["); - byte present = sensor_bus.reset(); - sensor_bus.select(addr); - sensor_bus.write(0xBE); // Read Scratchpad - - for (int i = 0; i < 9; i++) { // we need 9 bytes - data[i] = sensor_bus.read(); + for (int x = 0; x < NUM_DS18; x++) { + Serial.print(sensors.getTempCByIndex(x)); Serial.print(","); } - - sensor_bus.reset_search(); - - byte MSB = data[1]; - byte LSB = data[0]; - - float tempRead = ((MSB << 8) | LSB); //using two's compliment - float TemperatureSum = tempRead / 16; - - return TemperatureSum; + Serial.print("],"); } + /************************************ * Utitlity Methods *************************************/ From 5004f4e35ea92f7bbdaeb2215f3adc4a79bc5a18 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 27 Mar 2017 01:27:13 -1000 Subject: [PATCH 62/79] Adding toggle method --- camera_board/camera_board.ino | 8 +++++++- telemetry_board/telemetry_board.ino | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/camera_board/camera_board.ino b/camera_board/camera_board.ino index 1377b6438..a0c1b6c19 100644 --- a/camera_board/camera_board.ino +++ b/camera_board/camera_board.ino @@ -70,8 +70,10 @@ void loop() { case CAM_02_RELAY: if (pin_status == 1) { turn_pin_on(pin_num); - } else { + } else if (pin_status == 0) { turn_pin_off(pin_num); + } else if (pin_status == 9) { + toggle_pin(pin_num); } break; case RESET_PIN: @@ -144,6 +146,10 @@ void toggle_led() { digitalWrite(LED_BUILTIN, led_value); } +void toggle_pin(int pin_num) { + digitalWrite(pin_num, !digitalRead(pin_num)); +} + void turn_pin_on(int camera_pin) { digitalWrite(camera_pin, HIGH); } diff --git a/telemetry_board/telemetry_board.ino b/telemetry_board/telemetry_board.ino index ae5650f53..856e86a35 100644 --- a/telemetry_board/telemetry_board.ino +++ b/telemetry_board/telemetry_board.ino @@ -125,8 +125,10 @@ void loop() { case MOUNT_RELAY: if (pin_status == 1) { turn_pin_on(pin_num); - } else { + } else if (pin_status == 0) { turn_pin_off(pin_num); + } else if (pin_status == 9) { + toggle_pin(pin_num); } break; case LED_BUILTIN: @@ -161,6 +163,10 @@ void turn_pin_off(int camera_pin) { digitalWrite(camera_pin, LOW); } +void toggle_pin(int pin_num) { + digitalWrite(pin_num, !digitalRead(pin_num)); +} + int is_pin_on(int camera_pin) { return digitalRead(camera_pin); } From 5a2e20bbaa058854400ed906963ef8e284bf01d2 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 27 Mar 2017 09:31:31 -1000 Subject: [PATCH 63/79] * Adding names to electronic board output * Adding multipliers to get amps --- camera_board/camera_board.ino | 2 ++ telemetry_board/telemetry_board.ino | 49 ++++++++++++++++------------- 2 files changed, 30 insertions(+), 21 deletions(-) diff --git a/camera_board/camera_board.ino b/camera_board/camera_board.ino index a0c1b6c19..0e6b4529c 100644 --- a/camera_board/camera_board.ino +++ b/camera_board/camera_board.ino @@ -96,6 +96,8 @@ void loop() { read_dht_temp(); + Serial.print("\"name\":\"camera_board\""); Serial.print(","); + Serial.print("\"count\":"); Serial.print(millis()); Serial.println("}"); diff --git a/telemetry_board/telemetry_board.ino b/telemetry_board/telemetry_board.ino index 856e86a35..0c7935f48 100644 --- a/telemetry_board/telemetry_board.ino +++ b/telemetry_board/telemetry_board.ino @@ -26,6 +26,11 @@ const int FAN_RELAY = 6; // Fan Relay Off: 0 On: 80s const int WEATHER_RELAY = 5; // Weather Relay 250mA upon init and 250mA to read const int MOUNT_RELAY = 4; // Mount Relay +const float main_amps_mult = 2.8; +const float fan_amps_mult = 1.8; +const float mount_amps_mult = 1.8; +const float camera_amps_mult = 1.0; + const int NUM_DS18 = 3; // Number of DS18B20 Sensors @@ -145,6 +150,8 @@ void loop() { read_ds18b20_temp(); + Serial.print("\"name\":\"telemetry_board\""); Serial.print(","); + Serial.print("\"count\":"); Serial.print(millis()); Serial.println("}"); @@ -182,20 +189,20 @@ void read_voltages() { int ac_reading = digitalRead(AC_PIN); int main_reading = analogRead(I_MAIN); - float main_voltage = (main_reading / 1023.) * 5.; - float main_amps = ((main_voltage - ACS_offset) / mV_per_amp); + float main_amps = (main_reading / 1023.) * main_amps_mult; +// float main_amps = ((main_voltage - ACS_offset) / mV_per_amp); int fan_reading = analogRead(I_FAN); - float fan_voltage = (fan_reading / 1023.) * 5.; - float fan_amps = ((fan_voltage - ACS_offset) / mV_per_amp); + float fan_amps = (fan_reading / 1023.) * fan_amps_mult; +// float fan_amps = ((fan_voltage - ACS_offset) / mV_per_amp); int mount_reading = analogRead(I_MOUNT); - float mount_voltage = (mount_reading / 1023.) * 5.; - float mount_amps = ((mount_voltage - ACS_offset) / mV_per_amp); + float mount_amps = (mount_reading / 1023.) * mount_amps_mult; +// float mount_amps = ((mount_voltage - ACS_offset) / mV_per_amp); int camera_reading = analogRead(I_CAMERAS); - float camera_voltage = (camera_reading / 1023.) * 5.; - float camera_amps = ((camera_voltage - ACS_offset) / mV_per_amp); + float camera_amps = (camera_reading / 1023.) * 1; +// float camera_amps = ((camera_voltage - ACS_offset) / mV_per_amp); Serial.print("\"power\":{"); Serial.print("\"computer\":"); Serial.print(is_pin_on(COMP_RELAY)); Serial.print(','); @@ -205,12 +212,12 @@ void read_voltages() { Serial.print("\"weather\":"); Serial.print(is_pin_on(WEATHER_RELAY)); Serial.print(','); Serial.print("},"); - Serial.print("\"current\":{"); - Serial.print("\"main\":"); Serial.print(main_reading); Serial.print(','); - Serial.print("\"fan\":"); Serial.print(fan_reading); Serial.print(','); - Serial.print("\"mount\":"); Serial.print(mount_reading); Serial.print(','); - Serial.print("\"cameras\":"); Serial.print(camera_reading); - Serial.print("},"); +// Serial.print("\"current\":{"); +// Serial.print("\"main\":"); Serial.print(main_reading); Serial.print(','); +// Serial.print("\"fan\":"); Serial.print(fan_reading); Serial.print(','); +// Serial.print("\"mount\":"); Serial.print(mount_reading); Serial.print(','); +// Serial.print("\"cameras\":"); Serial.print(camera_reading); +// Serial.print("},"); // Serial.print("\"volts\":{"); // Serial.print("\"main\":"); Serial.print(main_voltage); Serial.print(','); @@ -218,13 +225,13 @@ void read_voltages() { // Serial.print("\"mount\":"); Serial.print(mount_voltage); Serial.print(','); // Serial.print("\"cameras\":"); Serial.print(camera_voltage); // Serial.print("},"); -// -// Serial.print("\"amps\":{"); -// Serial.print("\"main\":"); Serial.print(main_amps); Serial.print(','); -// Serial.print("\"fan\":"); Serial.print(fan_amps); Serial.print(','); -// Serial.print("\"mount\":"); Serial.print(mount_amps); Serial.print(','); -// Serial.print("\"cameras\":"); Serial.print(camera_amps); -// Serial.print("},"); + + Serial.print("\"amps\":{"); + Serial.print("\"main\":"); Serial.print(main_amps); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(fan_amps); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(mount_amps); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(camera_amps); + Serial.print("},"); } //// Reading temperature or humidity takes about 250 milliseconds! From 8f31925724be9d1eece9a17b2f835b988d683df7 Mon Sep 17 00:00:00 2001 From: blackflip14 Date: Thu, 20 Jul 2017 12:45:06 -1000 Subject: [PATCH 64/79] Add files via upload Infineon Shield current sensing --- .../Profet_2_Current_Sensing.ino | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino diff --git a/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino b/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino new file mode 100644 index 000000000..6c1b603b8 --- /dev/null +++ b/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino @@ -0,0 +1,23 @@ +int analogValue = A2; +//IS-2 Current sense of PROFET 2 +void setup() { +pinMode(9, OUTPUT); +//DEN_1 DIAGNOSIS enable +pinMode(A2, INPUT); + +pinMode(8, OUTPUT); +//OUT2_0 +Serial.begin(9600); +} + +void loop() { + // put your main code here, to run repeatedly: +digitalWrite(9, HIGH); +digitalWrite(8, HIGH); + +analogValue = analogRead(A2); +float voltage = analogValue * (21/ 1023.0); +//for 8 volts use 35 +Serial.println(voltage); +delay(750); +} From 1c4a1e6e71c8bd85e1b6a6c58affe5a61927cb36 Mon Sep 17 00:00:00 2001 From: blackflip14 Date: Thu, 27 Jul 2017 11:52:43 -1000 Subject: [PATCH 65/79] Add files via upload --- telemetry_board/mount_Current_Sensing.ino | 35 +++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 telemetry_board/mount_Current_Sensing.ino diff --git a/telemetry_board/mount_Current_Sensing.ino b/telemetry_board/mount_Current_Sensing.ino new file mode 100644 index 000000000..ab301b52c --- /dev/null +++ b/telemetry_board/mount_Current_Sensing.ino @@ -0,0 +1,35 @@ + +const int numReadings = 30; // sample size of readings +int readings[numReadings]; // the readings from the analog input +int readIndex = 0; // the index of the current reading +int total = 0; // the running total +int average = 0; // the average +int analogValue = A2; //IS-2 Current sense of PROFET 2 + +void setup() { +pinMode(9, OUTPUT); //DEN_1 DIAGNOSIS enable +pinMode(A2, INPUT); //IS-2 Current sense of PROFET 2 +pinMode(8, OUTPUT); //OUT2_0 +Serial.begin(9600); + for (int thisReading = 0; thisReading < numReadings; thisReading++) { + readings[thisReading] = 0; // initialize all the readings to 0: + } +} + +void loop() { +digitalWrite(9, HIGH); //DEN_1 DIAGNOSIS enable +digitalWrite(8, HIGH); //OUT2_0 +float voltage = analogRead(analogValue); //IS-2 Current sense of PROFET 2 +total = total - readings[readIndex]; // subtract the last reading: +readings[readIndex] = voltage; // read from the sensor: +total = total + readings[readIndex]; // add the reading to the total: +readIndex = readIndex + 1; // advance to the next position in the array: + if (readIndex >= numReadings) { // if we're at the end of the array... + readIndex = 0; // ...wrap around to the beginning: + } + float average = total / numReadings; // calculate the average: + Serial.println(average * (17/ 1023.0)); // send it to the computer as ASCII digits + //(17/ 1023.0) converts the readings from 12 volts to current + delay(100); // delay in between reads for stability +} + From 8e41671c926f1a84c71e56dce2ddc9b9017d9cca Mon Sep 17 00:00:00 2001 From: blackflip14 Date: Thu, 27 Jul 2017 11:55:02 -1000 Subject: [PATCH 66/79] Update mount_Current_Sensing.ino Current testing with the mount hooked up to the 24v shield and the arduino uno --- telemetry_board/mount_Current_Sensing.ino | 67 +++++++++++------------ 1 file changed, 33 insertions(+), 34 deletions(-) diff --git a/telemetry_board/mount_Current_Sensing.ino b/telemetry_board/mount_Current_Sensing.ino index ab301b52c..4c21a80a1 100644 --- a/telemetry_board/mount_Current_Sensing.ino +++ b/telemetry_board/mount_Current_Sensing.ino @@ -1,35 +1,34 @@ - -const int numReadings = 30; // sample size of readings -int readings[numReadings]; // the readings from the analog input -int readIndex = 0; // the index of the current reading -int total = 0; // the running total -int average = 0; // the average -int analogValue = A2; //IS-2 Current sense of PROFET 2 - -void setup() { -pinMode(9, OUTPUT); //DEN_1 DIAGNOSIS enable -pinMode(A2, INPUT); //IS-2 Current sense of PROFET 2 -pinMode(8, OUTPUT); //OUT2_0 -Serial.begin(9600); - for (int thisReading = 0; thisReading < numReadings; thisReading++) { - readings[thisReading] = 0; // initialize all the readings to 0: - } -} - -void loop() { -digitalWrite(9, HIGH); //DEN_1 DIAGNOSIS enable -digitalWrite(8, HIGH); //OUT2_0 -float voltage = analogRead(analogValue); //IS-2 Current sense of PROFET 2 -total = total - readings[readIndex]; // subtract the last reading: -readings[readIndex] = voltage; // read from the sensor: -total = total + readings[readIndex]; // add the reading to the total: -readIndex = readIndex + 1; // advance to the next position in the array: - if (readIndex >= numReadings) { // if we're at the end of the array... - readIndex = 0; // ...wrap around to the beginning: - } - float average = total / numReadings; // calculate the average: - Serial.println(average * (17/ 1023.0)); // send it to the computer as ASCII digits - //(17/ 1023.0) converts the readings from 12 volts to current - delay(100); // delay in between reads for stability -} +const int numReadings = 30; // sample size of readings +int readings[numReadings]; // the readings from the analog input +int readIndex = 0; // the index of the current reading +int total = 0; // the running total +int average = 0; // the average +int analogValue = A2; //IS-2 Current sense of PROFET 2 + +void setup() { +pinMode(9, OUTPUT); //DEN_1 DIAGNOSIS enable +pinMode(A2, INPUT); //IS-2 Current sense of PROFET 2 +pinMode(8, OUTPUT); //OUT2_0 +Serial.begin(9600); + for (int thisReading = 0; thisReading < numReadings; thisReading++) { + readings[thisReading] = 0; // initialize all the readings to 0: + } +} + +void loop() { +digitalWrite(9, HIGH); //DEN_1 DIAGNOSIS enable +digitalWrite(8, HIGH); //OUT2_0 +float voltage = analogRead(analogValue); //IS-2 Current sense of PROFET 2 +total = total - readings[readIndex]; // subtract the last reading: +readings[readIndex] = voltage; // read from the sensor: +total = total + readings[readIndex]; // add the reading to the total: +readIndex = readIndex + 1; // advance to the next position in the array: + if (readIndex >= numReadings) { // if we're at the end of the array... + readIndex = 0; // ...wrap around to the beginning: + } + float average = total / numReadings; // calculate the average: + Serial.println(average * (17/ 1023.0)); // send it to the computer as ASCII digits + //(17/ 1023.0) converts the readings from 12 volts to current + delay(100); // delay in between reads for stability +} From cae00de167ce547e5149e2e63cc5c3e697631fe6 Mon Sep 17 00:00:00 2001 From: blackflip14 Date: Thu, 27 Jul 2017 11:55:37 -1000 Subject: [PATCH 67/79] Update mount_Current_Sensing.ino --- telemetry_board/mount_Current_Sensing.ino | 1 - 1 file changed, 1 deletion(-) diff --git a/telemetry_board/mount_Current_Sensing.ino b/telemetry_board/mount_Current_Sensing.ino index 4c21a80a1..870351fc4 100644 --- a/telemetry_board/mount_Current_Sensing.ino +++ b/telemetry_board/mount_Current_Sensing.ino @@ -31,4 +31,3 @@ readIndex = readIndex + 1; // advance to the next position in the //(17/ 1023.0) converts the readings from 12 volts to current delay(100); // delay in between reads for stability } - From dffc1702c91fcf5660ffb011fb92269e376d71bf Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 7 Aug 2017 08:42:53 +1000 Subject: [PATCH 68/79] Remove the convenience method to shut down everything (#1) --- telemetry_board/telemetry_board.ino | 27 +++++++-------------------- 1 file changed, 7 insertions(+), 20 deletions(-) diff --git a/telemetry_board/telemetry_board.ino b/telemetry_board/telemetry_board.ino index 0c7935f48..f4dc91910 100644 --- a/telemetry_board/telemetry_board.ino +++ b/telemetry_board/telemetry_board.ino @@ -98,20 +98,6 @@ void loop() { int pin_status = Serial.parseInt(); switch (pin_num) { - case 0: // All off - turn_pin_off(COMP_RELAY); - turn_pin_off(CAMERAS_RELAY); - turn_pin_off(FAN_RELAY); - turn_pin_off(WEATHER_RELAY); - turn_pin_off(MOUNT_RELAY); - break; - case 1: // All on - turn_pin_on(COMP_RELAY); - turn_pin_on(CAMERAS_RELAY); - turn_pin_on(FAN_RELAY); - turn_pin_on(WEATHER_RELAY); - turn_pin_on(MOUNT_RELAY); - break; case COMP_RELAY: /* The computer shutting itself off: * - Power down @@ -210,14 +196,15 @@ void read_voltages() { Serial.print("\"mount\":"); Serial.print(is_pin_on(MOUNT_RELAY)); Serial.print(','); Serial.print("\"cameras\":"); Serial.print(is_pin_on(CAMERAS_RELAY)); Serial.print(','); Serial.print("\"weather\":"); Serial.print(is_pin_on(WEATHER_RELAY)); Serial.print(','); + Serial.print("\"main\":"); Serial.print(ac_reading); Serial.print(','); Serial.print("},"); -// Serial.print("\"current\":{"); -// Serial.print("\"main\":"); Serial.print(main_reading); Serial.print(','); -// Serial.print("\"fan\":"); Serial.print(fan_reading); Serial.print(','); -// Serial.print("\"mount\":"); Serial.print(mount_reading); Serial.print(','); -// Serial.print("\"cameras\":"); Serial.print(camera_reading); -// Serial.print("},"); + Serial.print("\"current\":{"); + Serial.print("\"main\":"); Serial.print(main_reading); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(fan_reading); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(mount_reading); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(camera_reading); + Serial.print("},"); // Serial.print("\"volts\":{"); // Serial.print("\"main\":"); Serial.print(main_voltage); Serial.print(','); From 7d47a86c3bb42282bf54529c131c855e0fab555c Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 6 Nov 2017 12:00:37 +1100 Subject: [PATCH 69/79] Moving files into resources dir for merge --- .../camera_board}/camera_board.ino | 0 .../camera_board}/stino.settings | 0 .../arduino_files/power_board/power_board.ino | 239 ++++++++++++++++++ .../Profet_2_Current_Sensing.ino | 0 .../mount_Current_Sensing.ino | 0 .../telemetry_board}/telemetry_board.ino | 0 6 files changed, 239 insertions(+) rename {camera_board => resources/arduino_files/camera_board}/camera_board.ino (100%) rename {camera_board => resources/arduino_files/camera_board}/stino.settings (100%) create mode 100644 resources/arduino_files/power_board/power_board.ino rename {telemetry_board => resources/arduino_files/telemetry_board}/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino (100%) rename {telemetry_board => resources/arduino_files/telemetry_board}/mount_Current_Sensing.ino (100%) rename {telemetry_board => resources/arduino_files/telemetry_board}/telemetry_board.ino (100%) diff --git a/camera_board/camera_board.ino b/resources/arduino_files/camera_board/camera_board.ino similarity index 100% rename from camera_board/camera_board.ino rename to resources/arduino_files/camera_board/camera_board.ino diff --git a/camera_board/stino.settings b/resources/arduino_files/camera_board/stino.settings similarity index 100% rename from camera_board/stino.settings rename to resources/arduino_files/camera_board/stino.settings diff --git a/resources/arduino_files/power_board/power_board.ino b/resources/arduino_files/power_board/power_board.ino new file mode 100644 index 000000000..dc8c79b85 --- /dev/null +++ b/resources/arduino_files/power_board/power_board.ino @@ -0,0 +1,239 @@ +#include + +#include +#include +#include + +#define DHTTYPE DHT22 // DHT 22 (AM2302) + +/* DECLARE PINS */ + +// Current Sense +const int IS_0 = A0; // PROFET-0 +const int IS_1 = A1; // PROFET-1 +const int IS_2 = A2; // PROFET-2 + +// Channel select +const int DSEL_0 = 2; // PROFET-0 +const int DSEL_1 = 6; // PROFET-1 + +const inst DEN_0 = A4; // PROFET-0 +const inst DEN_1 = 5; // PROFET-1 +const inst DEN_2 = 9; // PROFET-2 + +// Digital Pins +const int DS18_PIN = 10; // DS18B20 Temperature (OneWire) +const int DHT_PIN = 11; // DHT Temp & Humidity Pin + +// Relays +const int RELAY_1 = A3; // 0_0 PROFET-0 Channel 0 +const int RELAY_2 = 3; // 1_0 PROFET-0 Channel 1 +const int RELAY_3 = 4; // 0_1 PROFET-1 Channel 0 +const int RELAY_4 = 7; // 1_1 PROFET-1 Channel 1 +const int RELAY_5 = 8; // 0_2 PROFET-2 Channel 0 + +const int relayArray[] = {RELAY_1, RELAY_2, RELAY_3, RELAY_4, RELAY_5}; +const int numRelay = 5; + +const int NUM_DS18 = 3; // Number of DS18B20 Sensors + +uint8_t sensors_address[NUM_DS18][8]; + +// Temperature chip I/O +OneWire ds(DS18_PIN); +DallasTemperature sensors(&ds); + +// Setup DHT22 +DHT dht(DHT_PIN, DHTTYPE); + +int led_value = LOW; + +void setup() { + Serial.begin(9600); + Serial.flush(); + + pinMode(LED_BUILTIN, OUTPUT); + + sensors.begin(); + + pinMode(AC_PIN, INPUT); + + // Turn relays on to start + for (int i = 0; i < numRelay; i++) { + pinMode(relayArray[i], OUTPUT); + digitalWrite(relayArray[i], HIGH); + delay(250); + } + + dht.begin(); +} + +void loop() { + + // Read any serial input + // - Input will be two comma separated integers, the + // first specifying the pin and the second the status + // to change to (1/0). Only the fan and the debug led + // are currently supported. + // Example serial input: + // 4,1 # Turn relay 4 on + // 4,2 # Toggle relay 4 + // 4,3 # Toggle relay 4 w/ 30 sec delay + // 4,9 # Turn relay 4 off + while (Serial.available() > 0) { + int pin_num = Serial.parseInt(); + int pin_status = Serial.parseInt(); + + switch (pin_status) { + case 1: + turn_pin_on(pin_num); + break; + case 2: + toggle_pin(pin_num); + break; + case 3: + toggle_pin_delay(pin_num); + case 9: + turn_pin_off(pin_num); + break; + } + } + + get_readings(); + + // Simple heartbeat + toggle_led(); + delay(500); +} + +void get_readings() { + Serial.print("{"); + + read_voltages(); + + read_dht_temp(); + + read_ds18b20_temp(); + + Serial.print("\"name\":\"telemetry_board\""); Serial.print(","); + + Serial.print("\"count\":"); Serial.print(millis()); + + Serial.println("}"); +} + +/* Read Voltages + +Gets the AC probe as well as the values of the current on the AC I_ pins + +https://www.arduino.cc/en/Reference/AnalogRead + + */ +void read_voltages() { + int ac_reading = digitalRead(AC_PIN); + + int main_reading = analogRead(I_MAIN); + float main_amps = (main_reading / 1023.) * main_amps_mult; +// float main_amps = ((main_voltage - ACS_offset) / mV_per_amp); + + int fan_reading = analogRead(I_FAN); + float fan_amps = (fan_reading / 1023.) * fan_amps_mult; +// float fan_amps = ((fan_voltage - ACS_offset) / mV_per_amp); + + int mount_reading = analogRead(I_MOUNT); + float mount_amps = (mount_reading / 1023.) * mount_amps_mult; +// float mount_amps = ((mount_voltage - ACS_offset) / mV_per_amp); + + int camera_reading = analogRead(I_CAMERAS); + float camera_amps = (camera_reading / 1023.) * 1; +// float camera_amps = ((camera_voltage - ACS_offset) / mV_per_amp); + + Serial.print("\"power\":{"); + Serial.print("\"computer\":"); Serial.print(is_pin_on(COMP_RELAY)); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(is_pin_on(FAN_RELAY)); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(is_pin_on(MOUNT_RELAY)); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(is_pin_on(CAMERAS_RELAY)); Serial.print(','); + Serial.print("\"weather\":"); Serial.print(is_pin_on(WEATHER_RELAY)); Serial.print(','); + Serial.print("\"main\":"); Serial.print(ac_reading); Serial.print(','); + Serial.print("},"); + + Serial.print("\"current\":{"); + Serial.print("\"main\":"); Serial.print(main_reading); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(fan_reading); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(mount_reading); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(camera_reading); + Serial.print("},"); + +// Serial.print("\"volts\":{"); +// Serial.print("\"main\":"); Serial.print(main_voltage); Serial.print(','); +// Serial.print("\"fan\":"); Serial.print(fan_voltage); Serial.print(','); +// Serial.print("\"mount\":"); Serial.print(mount_voltage); Serial.print(','); +// Serial.print("\"cameras\":"); Serial.print(camera_voltage); +// Serial.print("},"); + + Serial.print("\"amps\":{"); + Serial.print("\"main\":"); Serial.print(main_amps); Serial.print(','); + Serial.print("\"fan\":"); Serial.print(fan_amps); Serial.print(','); + Serial.print("\"mount\":"); Serial.print(mount_amps); Serial.print(','); + Serial.print("\"cameras\":"); Serial.print(camera_amps); + Serial.print("},"); +} + +// Reading temperature or humidity takes about 250 milliseconds! +// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) +void read_dht_temp() { + float h = dht.readHumidity(); + float c = dht.readTemperature(); // Celsius + + // Check if any reads failed and exit early (to try again). + // if (isnan(h) || isnan(t)) { + // Serial.println("Failed to read from DHT sensor!"); + // return; + // } + + Serial.print("\"humidity\":"); Serial.print(h); Serial.print(','); + Serial.print("\"temp_00\":"); Serial.print(c); Serial.print(','); +} + +void read_ds18b20_temp() { + + sensors.requestTemperatures(); + + Serial.print("\"temperature\":["); + + for (int x = 0; x < NUM_DS18; x++) { + Serial.print(sensors.getTempCByIndex(x)); Serial.print(","); + } + Serial.print("],"); +} + + +/************************************ +* Utitlity Methods +*************************************/ + +int is_pin_on(int pin_num) { + return digitalRead(pin_num); +} + +void turn_pin_on(int pin_num) { + digitalWrite(pin_num, HIGH); +} + +void turn_pin_off(int pin_num) { + digitalWrite(pin_num, LOW); +} + +void toggle_pin(int pin_num) { + digitalWrite(pin_num, !digitalRead(pin_num)); +} + +void toggle_pin_delay(int pin_num, int delay = 30) { + turn_pin_off(pin_num); + delay(1000 * delay); + turn_pin_on(pin_num); +} + +void toggle_led() { + toggle_pin(LED_BUILTIN); +} diff --git a/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino b/resources/arduino_files/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino similarity index 100% rename from telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino rename to resources/arduino_files/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino diff --git a/telemetry_board/mount_Current_Sensing.ino b/resources/arduino_files/telemetry_board/mount_Current_Sensing.ino similarity index 100% rename from telemetry_board/mount_Current_Sensing.ino rename to resources/arduino_files/telemetry_board/mount_Current_Sensing.ino diff --git a/telemetry_board/telemetry_board.ino b/resources/arduino_files/telemetry_board/telemetry_board.ino similarity index 100% rename from telemetry_board/telemetry_board.ino rename to resources/arduino_files/telemetry_board/telemetry_board.ino From f694c037a23f939e15bb48346a46a273ac5ec10d Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 6 Nov 2017 12:00:55 +1100 Subject: [PATCH 70/79] Removing unncessary files --- resources/arduino_files/camera_board/stino.settings | 8 -------- 1 file changed, 8 deletions(-) delete mode 100644 resources/arduino_files/camera_board/stino.settings diff --git a/resources/arduino_files/camera_board/stino.settings b/resources/arduino_files/camera_board/stino.settings deleted file mode 100644 index bc199434d..000000000 --- a/resources/arduino_files/camera_board/stino.settings +++ /dev/null @@ -1,8 +0,0 @@ -{ - "arduino_folder": "/home/wtgee/arduino-1.5.8", - "board": 7, - "full_compilation": true, - "platform": 1, - "platform_name": "Arduino AVR Boards", - "serial_port": 0 -} \ No newline at end of file From 86658fb3c58f98ae3f40d8dc7349f5555562dc09 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 6 Nov 2017 12:03:22 +1100 Subject: [PATCH 71/79] MOving libraries for arudino files into resources dir --- .../libraries}/Adafruit_MMA8451/Adafruit_MMA8451.cpp | 0 .../arduino_files/libraries}/Adafruit_MMA8451/Adafruit_MMA8451.h | 0 .../arduino_files/libraries}/Adafruit_MMA8451/README.md | 0 .../Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino | 0 .../arduino_files/libraries}/Adafruit_MMA8451/license.txt | 0 .../arduino_files/libraries}/Adafruit_Sensor/Adafruit_Sensor.cpp | 0 .../arduino_files/libraries}/Adafruit_Sensor/Adafruit_Sensor.h | 0 .../arduino_files/libraries}/Adafruit_Sensor/README.md | 0 .../arduino_files/libraries}/Bridge/README.adoc | 0 .../arduino_files/libraries}/Bridge/examples/Bridge/Bridge.ino | 0 .../Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino | 0 .../libraries}/Bridge/examples/ConsolePixel/ConsolePixel.ino | 0 .../libraries}/Bridge/examples/ConsoleRead/ConsoleRead.ino | 0 .../libraries}/Bridge/examples/Datalogger/Datalogger.ino | 0 .../Bridge/examples/FileWriteScript/FileWriteScript.ino | 0 .../libraries}/Bridge/examples/HttpClient/HttpClient.ino | 0 .../Bridge/examples/HttpClientConsole/HttpClientConsole.ino | 0 .../Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino | 0 .../arduino_files/libraries}/Bridge/examples/Process/Process.ino | 0 .../libraries}/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino | 0 .../libraries}/Bridge/examples/ShellCommands/ShellCommands.ino | 0 .../Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino | 0 .../examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino | 0 .../examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino | 0 .../examples/SpacebrewYun/spacebrewString/spacebrewString.ino | 0 .../Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino | 0 .../libraries}/Bridge/examples/TemperatureWebPanel/www/index.html | 0 .../Bridge/examples/TemperatureWebPanel/www/zepto.min.js | 0 .../libraries}/Bridge/examples/TimeCheck/TimeCheck.ino | 0 .../libraries}/Bridge/examples/WiFiStatus/WiFiStatus.ino | 0 .../Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino | 0 .../arduino_files/libraries}/Bridge/keywords.txt | 0 .../arduino_files/libraries}/Bridge/library.properties | 0 .../arduino_files/libraries}/Bridge/src/Bridge.cpp | 0 .../arduino_files/libraries}/Bridge/src/Bridge.h | 0 .../arduino_files/libraries}/Bridge/src/BridgeClient.cpp | 0 .../arduino_files/libraries}/Bridge/src/BridgeClient.h | 0 .../arduino_files/libraries}/Bridge/src/BridgeServer.cpp | 0 .../arduino_files/libraries}/Bridge/src/BridgeServer.h | 0 .../arduino_files/libraries}/Bridge/src/BridgeUdp.cpp | 0 .../arduino_files/libraries}/Bridge/src/BridgeUdp.h | 0 .../arduino_files/libraries}/Bridge/src/Console.cpp | 0 .../arduino_files/libraries}/Bridge/src/Console.h | 0 .../arduino_files/libraries}/Bridge/src/FileIO.cpp | 0 .../arduino_files/libraries}/Bridge/src/FileIO.h | 0 .../arduino_files/libraries}/Bridge/src/HttpClient.cpp | 0 .../arduino_files/libraries}/Bridge/src/HttpClient.h | 0 .../arduino_files/libraries}/Bridge/src/Mailbox.cpp | 0 .../arduino_files/libraries}/Bridge/src/Mailbox.h | 0 .../arduino_files/libraries}/Bridge/src/Process.cpp | 0 .../arduino_files/libraries}/Bridge/src/Process.h | 0 .../arduino_files/libraries}/Bridge/src/YunClient.h | 0 .../arduino_files/libraries}/Bridge/src/YunServer.h | 0 {libraries => resources/arduino_files/libraries}/DHT/DHT.cpp | 0 {libraries => resources/arduino_files/libraries}/DHT/DHT.h | 0 {libraries => resources/arduino_files/libraries}/DHT/README.txt | 0 .../arduino_files/libraries}/DHT/examples/DHTtester/DHTtester.ino | 0 {libraries => resources/arduino_files/libraries}/Firmata/Boards.h | 0 .../arduino_files/libraries}/Firmata/Firmata.cpp | 0 .../arduino_files/libraries}/Firmata/Firmata.h | 0 .../Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino | 0 .../libraries}/Firmata/examples/AnalogFirmata/AnalogFirmata.ino | 0 .../libraries}/Firmata/examples/EchoString/EchoString.ino | 0 .../libraries}/Firmata/examples/OldStandardFirmata/LICENSE.txt | 0 .../Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino | 0 .../libraries}/Firmata/examples/ServoFirmata/ServoFirmata.ino | 0 .../Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino | 0 .../examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino | 0 .../libraries}/Firmata/examples/StandardFirmata/LICENSE.txt | 0 .../Firmata/examples/StandardFirmata/StandardFirmata.ino | 0 .../Firmata/examples/StandardFirmataChipKIT/LICENSE.txt | 0 .../examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino | 0 .../Firmata/examples/StandardFirmataEthernet/LICENSE.txt | 0 .../examples/StandardFirmataEthernet/StandardFirmataEthernet.ino | 0 .../Firmata/examples/StandardFirmataEthernet/ethernetConfig.h | 0 .../Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt | 0 .../StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino | 0 .../Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h | 0 .../libraries}/Firmata/examples/StandardFirmataPlus/LICENSE.txt | 0 .../Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino | 0 .../libraries}/Firmata/examples/StandardFirmataWiFi/LICENSE.txt | 0 .../Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino | 0 .../libraries}/Firmata/examples/StandardFirmataWiFi/wifiConfig.h | 0 .../arduino_files/libraries}/Firmata/extras/LICENSE.txt | 0 .../arduino_files/libraries}/Firmata/extras/revisions.txt | 0 .../arduino_files/libraries}/Firmata/keywords.txt | 0 .../arduino_files/libraries}/Firmata/library.properties | 0 .../arduino_files/libraries}/Firmata/readme.md | 0 .../arduino_files/libraries}/Firmata/release.sh | 0 .../libraries}/Firmata/test/firmata_test/firmata_test.ino | 0 .../arduino_files/libraries}/Firmata/test/readme.md | 0 .../libraries}/Firmata/utility/EthernetClientStream.cpp | 0 .../libraries}/Firmata/utility/EthernetClientStream.h | 0 .../arduino_files/libraries}/Firmata/utility/FirmataFeature.h | 0 .../arduino_files/libraries}/Firmata/utility/SerialFirmata.cpp | 0 .../arduino_files/libraries}/Firmata/utility/SerialFirmata.h | 0 .../arduino_files/libraries}/Firmata/utility/WiFi101Stream.cpp | 0 .../arduino_files/libraries}/Firmata/utility/WiFi101Stream.h | 0 .../arduino_files/libraries}/Firmata/utility/WiFiStream.cpp | 0 .../arduino_files/libraries}/Firmata/utility/WiFiStream.h | 0 .../arduino_files/libraries}/Firmata/utility/firmataDebug.h | 0 .../arduino_files/libraries}/Keyboard/README.adoc | 0 .../arduino_files/libraries}/Keyboard/keywords.txt | 0 .../arduino_files/libraries}/Keyboard/library.properties | 0 .../arduino_files/libraries}/Keyboard/src/Keyboard.cpp | 0 .../arduino_files/libraries}/Keyboard/src/Keyboard.h | 0 .../arduino_files/libraries}/Mouse/README.adoc | 0 .../arduino_files/libraries}/Mouse/keywords.txt | 0 .../arduino_files/libraries}/Mouse/library.properties | 0 .../arduino_files/libraries}/Mouse/src/Mouse.cpp | 0 .../arduino_files/libraries}/Mouse/src/Mouse.h | 0 .../arduino_files/libraries}/OneWire/OneWire.cpp | 0 .../arduino_files/libraries}/OneWire/OneWire.h | 0 .../OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde | 0 .../libraries}/OneWire/examples/DS2408_Switch/DS2408_Switch.pde | 0 .../libraries}/OneWire/examples/DS250x_PROM/DS250x_PROM.pde | 0 .../arduino_files/libraries}/OneWire/keywords.txt | 0 .../arduino_files/libraries}/OneWire/library.json | 0 .../arduino_files/libraries}/OneWire/library.properties | 0 119 files changed, 0 insertions(+), 0 deletions(-) rename {libraries => resources/arduino_files/libraries}/Adafruit_MMA8451/Adafruit_MMA8451.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Adafruit_MMA8451/Adafruit_MMA8451.h (100%) rename {libraries => resources/arduino_files/libraries}/Adafruit_MMA8451/README.md (100%) rename {libraries => resources/arduino_files/libraries}/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino (100%) rename {libraries => resources/arduino_files/libraries}/Adafruit_MMA8451/license.txt (100%) rename {libraries => resources/arduino_files/libraries}/Adafruit_Sensor/Adafruit_Sensor.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Adafruit_Sensor/Adafruit_Sensor.h (100%) rename {libraries => resources/arduino_files/libraries}/Adafruit_Sensor/README.md (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/README.adoc (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/Bridge/Bridge.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/ConsolePixel/ConsolePixel.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/ConsoleRead/ConsoleRead.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/Datalogger/Datalogger.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/FileWriteScript/FileWriteScript.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/HttpClient/HttpClient.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/HttpClientConsole/HttpClientConsole.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/Process/Process.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/ShellCommands/ShellCommands.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/TemperatureWebPanel/www/index.html (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/TemperatureWebPanel/www/zepto.min.js (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/TimeCheck/TimeCheck.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/WiFiStatus/WiFiStatus.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/keywords.txt (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/library.properties (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Bridge.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Bridge.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/BridgeClient.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/BridgeClient.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/BridgeServer.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/BridgeServer.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/BridgeUdp.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/BridgeUdp.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Console.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Console.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/FileIO.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/FileIO.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/HttpClient.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/HttpClient.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Mailbox.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Mailbox.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Process.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/Process.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/YunClient.h (100%) rename {libraries => resources/arduino_files/libraries}/Bridge/src/YunServer.h (100%) rename {libraries => resources/arduino_files/libraries}/DHT/DHT.cpp (100%) rename {libraries => resources/arduino_files/libraries}/DHT/DHT.h (100%) rename {libraries => resources/arduino_files/libraries}/DHT/README.txt (100%) rename {libraries => resources/arduino_files/libraries}/DHT/examples/DHTtester/DHTtester.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/Boards.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/Firmata.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/Firmata.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/AnalogFirmata/AnalogFirmata.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/EchoString/EchoString.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/OldStandardFirmata/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/ServoFirmata/ServoFirmata.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmata/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmata/StandardFirmata.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataEthernet/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataPlus/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataWiFi/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/examples/StandardFirmataWiFi/wifiConfig.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/extras/LICENSE.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/extras/revisions.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/keywords.txt (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/library.properties (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/readme.md (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/release.sh (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/test/firmata_test/firmata_test.ino (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/test/readme.md (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/EthernetClientStream.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/EthernetClientStream.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/FirmataFeature.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/SerialFirmata.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/SerialFirmata.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/WiFi101Stream.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/WiFi101Stream.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/WiFiStream.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/WiFiStream.h (100%) rename {libraries => resources/arduino_files/libraries}/Firmata/utility/firmataDebug.h (100%) rename {libraries => resources/arduino_files/libraries}/Keyboard/README.adoc (100%) rename {libraries => resources/arduino_files/libraries}/Keyboard/keywords.txt (100%) rename {libraries => resources/arduino_files/libraries}/Keyboard/library.properties (100%) rename {libraries => resources/arduino_files/libraries}/Keyboard/src/Keyboard.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Keyboard/src/Keyboard.h (100%) rename {libraries => resources/arduino_files/libraries}/Mouse/README.adoc (100%) rename {libraries => resources/arduino_files/libraries}/Mouse/keywords.txt (100%) rename {libraries => resources/arduino_files/libraries}/Mouse/library.properties (100%) rename {libraries => resources/arduino_files/libraries}/Mouse/src/Mouse.cpp (100%) rename {libraries => resources/arduino_files/libraries}/Mouse/src/Mouse.h (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/OneWire.cpp (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/OneWire.h (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/examples/DS2408_Switch/DS2408_Switch.pde (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/examples/DS250x_PROM/DS250x_PROM.pde (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/keywords.txt (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/library.json (100%) rename {libraries => resources/arduino_files/libraries}/OneWire/library.properties (100%) diff --git a/libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp b/resources/arduino_files/libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp similarity index 100% rename from libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp rename to resources/arduino_files/libraries/Adafruit_MMA8451/Adafruit_MMA8451.cpp diff --git a/libraries/Adafruit_MMA8451/Adafruit_MMA8451.h b/resources/arduino_files/libraries/Adafruit_MMA8451/Adafruit_MMA8451.h similarity index 100% rename from libraries/Adafruit_MMA8451/Adafruit_MMA8451.h rename to resources/arduino_files/libraries/Adafruit_MMA8451/Adafruit_MMA8451.h diff --git a/libraries/Adafruit_MMA8451/README.md b/resources/arduino_files/libraries/Adafruit_MMA8451/README.md similarity index 100% rename from libraries/Adafruit_MMA8451/README.md rename to resources/arduino_files/libraries/Adafruit_MMA8451/README.md diff --git a/libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino b/resources/arduino_files/libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino similarity index 100% rename from libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino rename to resources/arduino_files/libraries/Adafruit_MMA8451/examples/MMA8451demo/MMA8451demo.ino diff --git a/libraries/Adafruit_MMA8451/license.txt b/resources/arduino_files/libraries/Adafruit_MMA8451/license.txt similarity index 100% rename from libraries/Adafruit_MMA8451/license.txt rename to resources/arduino_files/libraries/Adafruit_MMA8451/license.txt diff --git a/libraries/Adafruit_Sensor/Adafruit_Sensor.cpp b/resources/arduino_files/libraries/Adafruit_Sensor/Adafruit_Sensor.cpp similarity index 100% rename from libraries/Adafruit_Sensor/Adafruit_Sensor.cpp rename to resources/arduino_files/libraries/Adafruit_Sensor/Adafruit_Sensor.cpp diff --git a/libraries/Adafruit_Sensor/Adafruit_Sensor.h b/resources/arduino_files/libraries/Adafruit_Sensor/Adafruit_Sensor.h similarity index 100% rename from libraries/Adafruit_Sensor/Adafruit_Sensor.h rename to resources/arduino_files/libraries/Adafruit_Sensor/Adafruit_Sensor.h diff --git a/libraries/Adafruit_Sensor/README.md b/resources/arduino_files/libraries/Adafruit_Sensor/README.md similarity index 100% rename from libraries/Adafruit_Sensor/README.md rename to resources/arduino_files/libraries/Adafruit_Sensor/README.md diff --git a/libraries/Bridge/README.adoc b/resources/arduino_files/libraries/Bridge/README.adoc similarity index 100% rename from libraries/Bridge/README.adoc rename to resources/arduino_files/libraries/Bridge/README.adoc diff --git a/libraries/Bridge/examples/Bridge/Bridge.ino b/resources/arduino_files/libraries/Bridge/examples/Bridge/Bridge.ino similarity index 100% rename from libraries/Bridge/examples/Bridge/Bridge.ino rename to resources/arduino_files/libraries/Bridge/examples/Bridge/Bridge.ino diff --git a/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino b/resources/arduino_files/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino similarity index 100% rename from libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino rename to resources/arduino_files/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino diff --git a/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino b/resources/arduino_files/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino similarity index 100% rename from libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino rename to resources/arduino_files/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino diff --git a/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino b/resources/arduino_files/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino similarity index 100% rename from libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino rename to resources/arduino_files/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino diff --git a/libraries/Bridge/examples/Datalogger/Datalogger.ino b/resources/arduino_files/libraries/Bridge/examples/Datalogger/Datalogger.ino similarity index 100% rename from libraries/Bridge/examples/Datalogger/Datalogger.ino rename to resources/arduino_files/libraries/Bridge/examples/Datalogger/Datalogger.ino diff --git a/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino b/resources/arduino_files/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino similarity index 100% rename from libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino rename to resources/arduino_files/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino diff --git a/libraries/Bridge/examples/HttpClient/HttpClient.ino b/resources/arduino_files/libraries/Bridge/examples/HttpClient/HttpClient.ino similarity index 100% rename from libraries/Bridge/examples/HttpClient/HttpClient.ino rename to resources/arduino_files/libraries/Bridge/examples/HttpClient/HttpClient.ino diff --git a/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino b/resources/arduino_files/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino similarity index 100% rename from libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino rename to resources/arduino_files/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino diff --git a/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino b/resources/arduino_files/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino similarity index 100% rename from libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino rename to resources/arduino_files/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino diff --git a/libraries/Bridge/examples/Process/Process.ino b/resources/arduino_files/libraries/Bridge/examples/Process/Process.ino similarity index 100% rename from libraries/Bridge/examples/Process/Process.ino rename to resources/arduino_files/libraries/Bridge/examples/Process/Process.ino diff --git a/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino b/resources/arduino_files/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino similarity index 100% rename from libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino rename to resources/arduino_files/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino diff --git a/libraries/Bridge/examples/ShellCommands/ShellCommands.ino b/resources/arduino_files/libraries/Bridge/examples/ShellCommands/ShellCommands.ino similarity index 100% rename from libraries/Bridge/examples/ShellCommands/ShellCommands.ino rename to resources/arduino_files/libraries/Bridge/examples/ShellCommands/ShellCommands.ino diff --git a/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino similarity index 100% rename from libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino rename to resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino diff --git a/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino similarity index 100% rename from libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino rename to resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino diff --git a/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino similarity index 100% rename from libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino rename to resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino diff --git a/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino similarity index 100% rename from libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino rename to resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino diff --git a/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino b/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino similarity index 100% rename from libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino rename to resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino diff --git a/libraries/Bridge/examples/TemperatureWebPanel/www/index.html b/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/index.html similarity index 100% rename from libraries/Bridge/examples/TemperatureWebPanel/www/index.html rename to resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/index.html diff --git a/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js b/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js similarity index 100% rename from libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js rename to resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js diff --git a/libraries/Bridge/examples/TimeCheck/TimeCheck.ino b/resources/arduino_files/libraries/Bridge/examples/TimeCheck/TimeCheck.ino similarity index 100% rename from libraries/Bridge/examples/TimeCheck/TimeCheck.ino rename to resources/arduino_files/libraries/Bridge/examples/TimeCheck/TimeCheck.ino diff --git a/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino b/resources/arduino_files/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino similarity index 100% rename from libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino rename to resources/arduino_files/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino diff --git a/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino b/resources/arduino_files/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino similarity index 100% rename from libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino rename to resources/arduino_files/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino diff --git a/libraries/Bridge/keywords.txt b/resources/arduino_files/libraries/Bridge/keywords.txt similarity index 100% rename from libraries/Bridge/keywords.txt rename to resources/arduino_files/libraries/Bridge/keywords.txt diff --git a/libraries/Bridge/library.properties b/resources/arduino_files/libraries/Bridge/library.properties similarity index 100% rename from libraries/Bridge/library.properties rename to resources/arduino_files/libraries/Bridge/library.properties diff --git a/libraries/Bridge/src/Bridge.cpp b/resources/arduino_files/libraries/Bridge/src/Bridge.cpp similarity index 100% rename from libraries/Bridge/src/Bridge.cpp rename to resources/arduino_files/libraries/Bridge/src/Bridge.cpp diff --git a/libraries/Bridge/src/Bridge.h b/resources/arduino_files/libraries/Bridge/src/Bridge.h similarity index 100% rename from libraries/Bridge/src/Bridge.h rename to resources/arduino_files/libraries/Bridge/src/Bridge.h diff --git a/libraries/Bridge/src/BridgeClient.cpp b/resources/arduino_files/libraries/Bridge/src/BridgeClient.cpp similarity index 100% rename from libraries/Bridge/src/BridgeClient.cpp rename to resources/arduino_files/libraries/Bridge/src/BridgeClient.cpp diff --git a/libraries/Bridge/src/BridgeClient.h b/resources/arduino_files/libraries/Bridge/src/BridgeClient.h similarity index 100% rename from libraries/Bridge/src/BridgeClient.h rename to resources/arduino_files/libraries/Bridge/src/BridgeClient.h diff --git a/libraries/Bridge/src/BridgeServer.cpp b/resources/arduino_files/libraries/Bridge/src/BridgeServer.cpp similarity index 100% rename from libraries/Bridge/src/BridgeServer.cpp rename to resources/arduino_files/libraries/Bridge/src/BridgeServer.cpp diff --git a/libraries/Bridge/src/BridgeServer.h b/resources/arduino_files/libraries/Bridge/src/BridgeServer.h similarity index 100% rename from libraries/Bridge/src/BridgeServer.h rename to resources/arduino_files/libraries/Bridge/src/BridgeServer.h diff --git a/libraries/Bridge/src/BridgeUdp.cpp b/resources/arduino_files/libraries/Bridge/src/BridgeUdp.cpp similarity index 100% rename from libraries/Bridge/src/BridgeUdp.cpp rename to resources/arduino_files/libraries/Bridge/src/BridgeUdp.cpp diff --git a/libraries/Bridge/src/BridgeUdp.h b/resources/arduino_files/libraries/Bridge/src/BridgeUdp.h similarity index 100% rename from libraries/Bridge/src/BridgeUdp.h rename to resources/arduino_files/libraries/Bridge/src/BridgeUdp.h diff --git a/libraries/Bridge/src/Console.cpp b/resources/arduino_files/libraries/Bridge/src/Console.cpp similarity index 100% rename from libraries/Bridge/src/Console.cpp rename to resources/arduino_files/libraries/Bridge/src/Console.cpp diff --git a/libraries/Bridge/src/Console.h b/resources/arduino_files/libraries/Bridge/src/Console.h similarity index 100% rename from libraries/Bridge/src/Console.h rename to resources/arduino_files/libraries/Bridge/src/Console.h diff --git a/libraries/Bridge/src/FileIO.cpp b/resources/arduino_files/libraries/Bridge/src/FileIO.cpp similarity index 100% rename from libraries/Bridge/src/FileIO.cpp rename to resources/arduino_files/libraries/Bridge/src/FileIO.cpp diff --git a/libraries/Bridge/src/FileIO.h b/resources/arduino_files/libraries/Bridge/src/FileIO.h similarity index 100% rename from libraries/Bridge/src/FileIO.h rename to resources/arduino_files/libraries/Bridge/src/FileIO.h diff --git a/libraries/Bridge/src/HttpClient.cpp b/resources/arduino_files/libraries/Bridge/src/HttpClient.cpp similarity index 100% rename from libraries/Bridge/src/HttpClient.cpp rename to resources/arduino_files/libraries/Bridge/src/HttpClient.cpp diff --git a/libraries/Bridge/src/HttpClient.h b/resources/arduino_files/libraries/Bridge/src/HttpClient.h similarity index 100% rename from libraries/Bridge/src/HttpClient.h rename to resources/arduino_files/libraries/Bridge/src/HttpClient.h diff --git a/libraries/Bridge/src/Mailbox.cpp b/resources/arduino_files/libraries/Bridge/src/Mailbox.cpp similarity index 100% rename from libraries/Bridge/src/Mailbox.cpp rename to resources/arduino_files/libraries/Bridge/src/Mailbox.cpp diff --git a/libraries/Bridge/src/Mailbox.h b/resources/arduino_files/libraries/Bridge/src/Mailbox.h similarity index 100% rename from libraries/Bridge/src/Mailbox.h rename to resources/arduino_files/libraries/Bridge/src/Mailbox.h diff --git a/libraries/Bridge/src/Process.cpp b/resources/arduino_files/libraries/Bridge/src/Process.cpp similarity index 100% rename from libraries/Bridge/src/Process.cpp rename to resources/arduino_files/libraries/Bridge/src/Process.cpp diff --git a/libraries/Bridge/src/Process.h b/resources/arduino_files/libraries/Bridge/src/Process.h similarity index 100% rename from libraries/Bridge/src/Process.h rename to resources/arduino_files/libraries/Bridge/src/Process.h diff --git a/libraries/Bridge/src/YunClient.h b/resources/arduino_files/libraries/Bridge/src/YunClient.h similarity index 100% rename from libraries/Bridge/src/YunClient.h rename to resources/arduino_files/libraries/Bridge/src/YunClient.h diff --git a/libraries/Bridge/src/YunServer.h b/resources/arduino_files/libraries/Bridge/src/YunServer.h similarity index 100% rename from libraries/Bridge/src/YunServer.h rename to resources/arduino_files/libraries/Bridge/src/YunServer.h diff --git a/libraries/DHT/DHT.cpp b/resources/arduino_files/libraries/DHT/DHT.cpp similarity index 100% rename from libraries/DHT/DHT.cpp rename to resources/arduino_files/libraries/DHT/DHT.cpp diff --git a/libraries/DHT/DHT.h b/resources/arduino_files/libraries/DHT/DHT.h similarity index 100% rename from libraries/DHT/DHT.h rename to resources/arduino_files/libraries/DHT/DHT.h diff --git a/libraries/DHT/README.txt b/resources/arduino_files/libraries/DHT/README.txt similarity index 100% rename from libraries/DHT/README.txt rename to resources/arduino_files/libraries/DHT/README.txt diff --git a/libraries/DHT/examples/DHTtester/DHTtester.ino b/resources/arduino_files/libraries/DHT/examples/DHTtester/DHTtester.ino similarity index 100% rename from libraries/DHT/examples/DHTtester/DHTtester.ino rename to resources/arduino_files/libraries/DHT/examples/DHTtester/DHTtester.ino diff --git a/libraries/Firmata/Boards.h b/resources/arduino_files/libraries/Firmata/Boards.h similarity index 100% rename from libraries/Firmata/Boards.h rename to resources/arduino_files/libraries/Firmata/Boards.h diff --git a/libraries/Firmata/Firmata.cpp b/resources/arduino_files/libraries/Firmata/Firmata.cpp similarity index 100% rename from libraries/Firmata/Firmata.cpp rename to resources/arduino_files/libraries/Firmata/Firmata.cpp diff --git a/libraries/Firmata/Firmata.h b/resources/arduino_files/libraries/Firmata/Firmata.h similarity index 100% rename from libraries/Firmata/Firmata.h rename to resources/arduino_files/libraries/Firmata/Firmata.h diff --git a/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino similarity index 100% rename from libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino rename to resources/arduino_files/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino diff --git a/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino similarity index 100% rename from libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino rename to resources/arduino_files/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino diff --git a/libraries/Firmata/examples/EchoString/EchoString.ino b/resources/arduino_files/libraries/Firmata/examples/EchoString/EchoString.ino similarity index 100% rename from libraries/Firmata/examples/EchoString/EchoString.ino rename to resources/arduino_files/libraries/Firmata/examples/EchoString/EchoString.ino diff --git a/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt similarity index 100% rename from libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt diff --git a/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino similarity index 100% rename from libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino rename to resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino diff --git a/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino similarity index 100% rename from libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino rename to resources/arduino_files/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino diff --git a/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino similarity index 100% rename from libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino rename to resources/arduino_files/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino diff --git a/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino similarity index 100% rename from libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino rename to resources/arduino_files/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino diff --git a/libraries/Firmata/examples/StandardFirmata/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/LICENSE.txt similarity index 100% rename from libraries/Firmata/examples/StandardFirmata/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmata/LICENSE.txt diff --git a/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino diff --git a/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt similarity index 100% rename from libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt diff --git a/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt similarity index 100% rename from libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino diff --git a/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h similarity index 100% rename from libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h diff --git a/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt similarity index 100% rename from libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt diff --git a/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino diff --git a/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h similarity index 100% rename from libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h diff --git a/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt similarity index 100% rename from libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt diff --git a/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt similarity index 100% rename from libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino similarity index 100% rename from libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino diff --git a/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h similarity index 100% rename from libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h rename to resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h diff --git a/libraries/Firmata/extras/LICENSE.txt b/resources/arduino_files/libraries/Firmata/extras/LICENSE.txt similarity index 100% rename from libraries/Firmata/extras/LICENSE.txt rename to resources/arduino_files/libraries/Firmata/extras/LICENSE.txt diff --git a/libraries/Firmata/extras/revisions.txt b/resources/arduino_files/libraries/Firmata/extras/revisions.txt similarity index 100% rename from libraries/Firmata/extras/revisions.txt rename to resources/arduino_files/libraries/Firmata/extras/revisions.txt diff --git a/libraries/Firmata/keywords.txt b/resources/arduino_files/libraries/Firmata/keywords.txt similarity index 100% rename from libraries/Firmata/keywords.txt rename to resources/arduino_files/libraries/Firmata/keywords.txt diff --git a/libraries/Firmata/library.properties b/resources/arduino_files/libraries/Firmata/library.properties similarity index 100% rename from libraries/Firmata/library.properties rename to resources/arduino_files/libraries/Firmata/library.properties diff --git a/libraries/Firmata/readme.md b/resources/arduino_files/libraries/Firmata/readme.md similarity index 100% rename from libraries/Firmata/readme.md rename to resources/arduino_files/libraries/Firmata/readme.md diff --git a/libraries/Firmata/release.sh b/resources/arduino_files/libraries/Firmata/release.sh similarity index 100% rename from libraries/Firmata/release.sh rename to resources/arduino_files/libraries/Firmata/release.sh diff --git a/libraries/Firmata/test/firmata_test/firmata_test.ino b/resources/arduino_files/libraries/Firmata/test/firmata_test/firmata_test.ino similarity index 100% rename from libraries/Firmata/test/firmata_test/firmata_test.ino rename to resources/arduino_files/libraries/Firmata/test/firmata_test/firmata_test.ino diff --git a/libraries/Firmata/test/readme.md b/resources/arduino_files/libraries/Firmata/test/readme.md similarity index 100% rename from libraries/Firmata/test/readme.md rename to resources/arduino_files/libraries/Firmata/test/readme.md diff --git a/libraries/Firmata/utility/EthernetClientStream.cpp b/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.cpp similarity index 100% rename from libraries/Firmata/utility/EthernetClientStream.cpp rename to resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.cpp diff --git a/libraries/Firmata/utility/EthernetClientStream.h b/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.h similarity index 100% rename from libraries/Firmata/utility/EthernetClientStream.h rename to resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.h diff --git a/libraries/Firmata/utility/FirmataFeature.h b/resources/arduino_files/libraries/Firmata/utility/FirmataFeature.h similarity index 100% rename from libraries/Firmata/utility/FirmataFeature.h rename to resources/arduino_files/libraries/Firmata/utility/FirmataFeature.h diff --git a/libraries/Firmata/utility/SerialFirmata.cpp b/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.cpp similarity index 100% rename from libraries/Firmata/utility/SerialFirmata.cpp rename to resources/arduino_files/libraries/Firmata/utility/SerialFirmata.cpp diff --git a/libraries/Firmata/utility/SerialFirmata.h b/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.h similarity index 100% rename from libraries/Firmata/utility/SerialFirmata.h rename to resources/arduino_files/libraries/Firmata/utility/SerialFirmata.h diff --git a/libraries/Firmata/utility/WiFi101Stream.cpp b/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.cpp similarity index 100% rename from libraries/Firmata/utility/WiFi101Stream.cpp rename to resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.cpp diff --git a/libraries/Firmata/utility/WiFi101Stream.h b/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.h similarity index 100% rename from libraries/Firmata/utility/WiFi101Stream.h rename to resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.h diff --git a/libraries/Firmata/utility/WiFiStream.cpp b/resources/arduino_files/libraries/Firmata/utility/WiFiStream.cpp similarity index 100% rename from libraries/Firmata/utility/WiFiStream.cpp rename to resources/arduino_files/libraries/Firmata/utility/WiFiStream.cpp diff --git a/libraries/Firmata/utility/WiFiStream.h b/resources/arduino_files/libraries/Firmata/utility/WiFiStream.h similarity index 100% rename from libraries/Firmata/utility/WiFiStream.h rename to resources/arduino_files/libraries/Firmata/utility/WiFiStream.h diff --git a/libraries/Firmata/utility/firmataDebug.h b/resources/arduino_files/libraries/Firmata/utility/firmataDebug.h similarity index 100% rename from libraries/Firmata/utility/firmataDebug.h rename to resources/arduino_files/libraries/Firmata/utility/firmataDebug.h diff --git a/libraries/Keyboard/README.adoc b/resources/arduino_files/libraries/Keyboard/README.adoc similarity index 100% rename from libraries/Keyboard/README.adoc rename to resources/arduino_files/libraries/Keyboard/README.adoc diff --git a/libraries/Keyboard/keywords.txt b/resources/arduino_files/libraries/Keyboard/keywords.txt similarity index 100% rename from libraries/Keyboard/keywords.txt rename to resources/arduino_files/libraries/Keyboard/keywords.txt diff --git a/libraries/Keyboard/library.properties b/resources/arduino_files/libraries/Keyboard/library.properties similarity index 100% rename from libraries/Keyboard/library.properties rename to resources/arduino_files/libraries/Keyboard/library.properties diff --git a/libraries/Keyboard/src/Keyboard.cpp b/resources/arduino_files/libraries/Keyboard/src/Keyboard.cpp similarity index 100% rename from libraries/Keyboard/src/Keyboard.cpp rename to resources/arduino_files/libraries/Keyboard/src/Keyboard.cpp diff --git a/libraries/Keyboard/src/Keyboard.h b/resources/arduino_files/libraries/Keyboard/src/Keyboard.h similarity index 100% rename from libraries/Keyboard/src/Keyboard.h rename to resources/arduino_files/libraries/Keyboard/src/Keyboard.h diff --git a/libraries/Mouse/README.adoc b/resources/arduino_files/libraries/Mouse/README.adoc similarity index 100% rename from libraries/Mouse/README.adoc rename to resources/arduino_files/libraries/Mouse/README.adoc diff --git a/libraries/Mouse/keywords.txt b/resources/arduino_files/libraries/Mouse/keywords.txt similarity index 100% rename from libraries/Mouse/keywords.txt rename to resources/arduino_files/libraries/Mouse/keywords.txt diff --git a/libraries/Mouse/library.properties b/resources/arduino_files/libraries/Mouse/library.properties similarity index 100% rename from libraries/Mouse/library.properties rename to resources/arduino_files/libraries/Mouse/library.properties diff --git a/libraries/Mouse/src/Mouse.cpp b/resources/arduino_files/libraries/Mouse/src/Mouse.cpp similarity index 100% rename from libraries/Mouse/src/Mouse.cpp rename to resources/arduino_files/libraries/Mouse/src/Mouse.cpp diff --git a/libraries/Mouse/src/Mouse.h b/resources/arduino_files/libraries/Mouse/src/Mouse.h similarity index 100% rename from libraries/Mouse/src/Mouse.h rename to resources/arduino_files/libraries/Mouse/src/Mouse.h diff --git a/libraries/OneWire/OneWire.cpp b/resources/arduino_files/libraries/OneWire/OneWire.cpp similarity index 100% rename from libraries/OneWire/OneWire.cpp rename to resources/arduino_files/libraries/OneWire/OneWire.cpp diff --git a/libraries/OneWire/OneWire.h b/resources/arduino_files/libraries/OneWire/OneWire.h similarity index 100% rename from libraries/OneWire/OneWire.h rename to resources/arduino_files/libraries/OneWire/OneWire.h diff --git a/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde b/resources/arduino_files/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde similarity index 100% rename from libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde rename to resources/arduino_files/libraries/OneWire/examples/DS18x20_Temperature/DS18x20_Temperature.pde diff --git a/libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde b/resources/arduino_files/libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde similarity index 100% rename from libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde rename to resources/arduino_files/libraries/OneWire/examples/DS2408_Switch/DS2408_Switch.pde diff --git a/libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde b/resources/arduino_files/libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde similarity index 100% rename from libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde rename to resources/arduino_files/libraries/OneWire/examples/DS250x_PROM/DS250x_PROM.pde diff --git a/libraries/OneWire/keywords.txt b/resources/arduino_files/libraries/OneWire/keywords.txt similarity index 100% rename from libraries/OneWire/keywords.txt rename to resources/arduino_files/libraries/OneWire/keywords.txt diff --git a/libraries/OneWire/library.json b/resources/arduino_files/libraries/OneWire/library.json similarity index 100% rename from libraries/OneWire/library.json rename to resources/arduino_files/libraries/OneWire/library.json diff --git a/libraries/OneWire/library.properties b/resources/arduino_files/libraries/OneWire/library.properties similarity index 100% rename from libraries/OneWire/library.properties rename to resources/arduino_files/libraries/OneWire/library.properties From 9b5d48094101f81d8f119f5c4b89a5ac08f26931 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 6 Nov 2017 12:05:38 +1100 Subject: [PATCH 72/79] Removing meta files - see #6 --- CONTRIBUTING.md | 1 - LICENSE | 21 --------------------- README.md | 4 ---- 3 files changed, 26 deletions(-) delete mode 100644 CONTRIBUTING.md delete mode 100644 LICENSE delete mode 100644 README.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md deleted file mode 100644 index 5fd24977e..000000000 --- a/CONTRIBUTING.md +++ /dev/null @@ -1 +0,0 @@ -Please see the [POCS CONTRIBUTING](https://github.com/panoptes/POCS/blob/develop/CONTRIBUTING.md) file. diff --git a/LICENSE b/LICENSE deleted file mode 100644 index b2eadfab8..000000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 PANOPTES - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 3c0f2669c..000000000 --- a/README.md +++ /dev/null @@ -1,4 +0,0 @@ -PACE -==== - -Panoptes Arduino Code for Electronics From 91fa0bc0dab4be84716984ee17df95b8d3fe6de0 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Wed, 8 Nov 2017 11:21:30 +1100 Subject: [PATCH 73/79] Removing unused libraries --- .../libraries/Bridge/README.adoc | 24 - .../Bridge/examples/Bridge/Bridge.ino | 185 --- .../ConsoleAsciiTable/ConsoleAsciiTable.ino | 95 -- .../examples/ConsolePixel/ConsolePixel.ino | 64 -- .../examples/ConsoleRead/ConsoleRead.ino | 60 - .../Bridge/examples/Datalogger/Datalogger.ino | 102 -- .../FileWriteScript/FileWriteScript.ino | 84 -- .../Bridge/examples/HttpClient/HttpClient.ino | 53 - .../HttpClientConsole/HttpClientConsole.ino | 55 - .../MailboxReadMessage/MailboxReadMessage.ino | 58 - .../Bridge/examples/Process/Process.ino | 72 -- .../RemoteDueBlink/RemoteDueBlink.ino | 33 - .../examples/ShellCommands/ShellCommands.ino | 55 - .../SpacebrewYun/inputOutput/inputOutput.ino | 134 --- .../spacebrewBoolean/spacebrewBoolean.ino | 94 -- .../spacebrewRange/spacebrewRange.ino | 88 -- .../spacebrewString/spacebrewString.ino | 86 -- .../TemperatureWebPanel.ino | 125 -- .../TemperatureWebPanel/www/index.html | 16 - .../TemperatureWebPanel/www/zepto.min.js | 2 - .../Bridge/examples/TimeCheck/TimeCheck.ino | 88 -- .../Bridge/examples/WiFiStatus/WiFiStatus.ino | 52 - .../YunSerialTerminal/YunSerialTerminal.ino | 82 -- .../libraries/Bridge/keywords.txt | 90 -- .../libraries/Bridge/library.properties | 10 - .../libraries/Bridge/src/Bridge.cpp | 281 ----- .../libraries/Bridge/src/Bridge.h | 125 -- .../libraries/Bridge/src/BridgeClient.cpp | 173 --- .../libraries/Bridge/src/BridgeClient.h | 70 -- .../libraries/Bridge/src/BridgeServer.cpp | 54 - .../libraries/Bridge/src/BridgeServer.h | 51 - .../libraries/Bridge/src/BridgeUdp.cpp | 198 ---- .../libraries/Bridge/src/BridgeUdp.h | 65 -- .../libraries/Bridge/src/Console.cpp | 150 --- .../libraries/Bridge/src/Console.h | 71 -- .../libraries/Bridge/src/FileIO.cpp | 283 ----- .../libraries/Bridge/src/FileIO.h | 120 -- .../libraries/Bridge/src/HttpClient.cpp | 204 ---- .../libraries/Bridge/src/HttpClient.h | 59 - .../libraries/Bridge/src/Mailbox.cpp | 56 - .../libraries/Bridge/src/Mailbox.h | 53 - .../libraries/Bridge/src/Process.cpp | 142 --- .../libraries/Bridge/src/Process.h | 71 -- .../libraries/Bridge/src/YunClient.h | 27 - .../libraries/Bridge/src/YunServer.h | 27 - .../arduino_files/libraries/Firmata/Boards.h | 764 ------------ .../libraries/Firmata/Firmata.cpp | 668 ----------- .../arduino_files/libraries/Firmata/Firmata.h | 224 ---- .../AllInputsFirmata/AllInputsFirmata.ino | 90 -- .../examples/AnalogFirmata/AnalogFirmata.ino | 94 -- .../examples/EchoString/EchoString.ino | 44 - .../examples/OldStandardFirmata/LICENSE.txt | 458 -------- .../OldStandardFirmata/OldStandardFirmata.ino | 239 ---- .../examples/ServoFirmata/ServoFirmata.ino | 65 -- .../SimpleAnalogFirmata.ino | 46 - .../SimpleDigitalFirmata.ino | 72 -- .../examples/StandardFirmata/LICENSE.txt | 458 -------- .../StandardFirmata/StandardFirmata.ino | 815 ------------- .../StandardFirmataChipKIT/LICENSE.txt | 458 -------- .../StandardFirmataChipKIT.ino | 793 ------------- .../StandardFirmataEthernet/LICENSE.txt | 458 -------- .../StandardFirmataEthernet.ino | 910 --------------- .../StandardFirmataEthernet/ethernetConfig.h | 85 -- .../StandardFirmataEthernetPlus/LICENSE.txt | 458 -------- .../StandardFirmataEthernetPlus.ino | 909 --------------- .../ethernetConfig.h | 55 - .../examples/StandardFirmataPlus/LICENSE.txt | 458 -------- .../StandardFirmataPlus.ino | 838 -------------- .../examples/StandardFirmataWiFi/LICENSE.txt | 458 -------- .../StandardFirmataWiFi.ino | 1023 ----------------- .../examples/StandardFirmataWiFi/wifiConfig.h | 155 --- .../libraries/Firmata/extras/LICENSE.txt | 458 -------- .../libraries/Firmata/extras/revisions.txt | 202 ---- .../libraries/Firmata/keywords.txt | 90 -- .../libraries/Firmata/library.properties | 9 - .../arduino_files/libraries/Firmata/readme.md | 177 --- .../libraries/Firmata/release.sh | 35 - .../test/firmata_test/firmata_test.ino | 136 --- .../libraries/Firmata/test/readme.md | 13 - .../Firmata/utility/EthernetClientStream.cpp | 114 -- .../Firmata/utility/EthernetClientStream.h | 52 - .../Firmata/utility/FirmataFeature.h | 38 - .../Firmata/utility/SerialFirmata.cpp | 328 ------ .../libraries/Firmata/utility/SerialFirmata.h | 167 --- .../Firmata/utility/WiFi101Stream.cpp | 4 - .../libraries/Firmata/utility/WiFi101Stream.h | 259 ----- .../libraries/Firmata/utility/WiFiStream.cpp | 4 - .../libraries/Firmata/utility/WiFiStream.h | 258 ----- .../libraries/Firmata/utility/firmataDebug.h | 14 - .../libraries/Keyboard/README.adoc | 25 - .../libraries/Keyboard/keywords.txt | 24 - .../libraries/Keyboard/library.properties | 9 - .../libraries/Keyboard/src/Keyboard.cpp | 322 ------ .../libraries/Keyboard/src/Keyboard.h | 99 -- .../arduino_files/libraries/Mouse/README.adoc | 25 - .../libraries/Mouse/keywords.txt | 24 - .../libraries/Mouse/library.properties | 9 - .../libraries/Mouse/src/Mouse.cpp | 123 -- .../arduino_files/libraries/Mouse/src/Mouse.h | 60 - 99 files changed, 18260 deletions(-) delete mode 100644 resources/arduino_files/libraries/Bridge/README.adoc delete mode 100644 resources/arduino_files/libraries/Bridge/examples/Bridge/Bridge.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/Datalogger/Datalogger.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/HttpClient/HttpClient.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/Process/Process.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/ShellCommands/ShellCommands.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/index.html delete mode 100644 resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js delete mode 100644 resources/arduino_files/libraries/Bridge/examples/TimeCheck/TimeCheck.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino delete mode 100644 resources/arduino_files/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino delete mode 100644 resources/arduino_files/libraries/Bridge/keywords.txt delete mode 100644 resources/arduino_files/libraries/Bridge/library.properties delete mode 100644 resources/arduino_files/libraries/Bridge/src/Bridge.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/Bridge.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/BridgeClient.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/BridgeClient.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/BridgeServer.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/BridgeServer.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/BridgeUdp.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/BridgeUdp.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/Console.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/Console.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/FileIO.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/FileIO.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/HttpClient.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/HttpClient.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/Mailbox.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/Mailbox.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/Process.cpp delete mode 100644 resources/arduino_files/libraries/Bridge/src/Process.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/YunClient.h delete mode 100644 resources/arduino_files/libraries/Bridge/src/YunServer.h delete mode 100644 resources/arduino_files/libraries/Firmata/Boards.h delete mode 100644 resources/arduino_files/libraries/Firmata/Firmata.cpp delete mode 100644 resources/arduino_files/libraries/Firmata/Firmata.h delete mode 100644 resources/arduino_files/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/EchoString/EchoString.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmata/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino delete mode 100644 resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h delete mode 100644 resources/arduino_files/libraries/Firmata/extras/LICENSE.txt delete mode 100644 resources/arduino_files/libraries/Firmata/extras/revisions.txt delete mode 100644 resources/arduino_files/libraries/Firmata/keywords.txt delete mode 100644 resources/arduino_files/libraries/Firmata/library.properties delete mode 100644 resources/arduino_files/libraries/Firmata/readme.md delete mode 100644 resources/arduino_files/libraries/Firmata/release.sh delete mode 100644 resources/arduino_files/libraries/Firmata/test/firmata_test/firmata_test.ino delete mode 100644 resources/arduino_files/libraries/Firmata/test/readme.md delete mode 100644 resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.cpp delete mode 100644 resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.h delete mode 100644 resources/arduino_files/libraries/Firmata/utility/FirmataFeature.h delete mode 100644 resources/arduino_files/libraries/Firmata/utility/SerialFirmata.cpp delete mode 100644 resources/arduino_files/libraries/Firmata/utility/SerialFirmata.h delete mode 100644 resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.cpp delete mode 100644 resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.h delete mode 100644 resources/arduino_files/libraries/Firmata/utility/WiFiStream.cpp delete mode 100644 resources/arduino_files/libraries/Firmata/utility/WiFiStream.h delete mode 100644 resources/arduino_files/libraries/Firmata/utility/firmataDebug.h delete mode 100644 resources/arduino_files/libraries/Keyboard/README.adoc delete mode 100644 resources/arduino_files/libraries/Keyboard/keywords.txt delete mode 100644 resources/arduino_files/libraries/Keyboard/library.properties delete mode 100644 resources/arduino_files/libraries/Keyboard/src/Keyboard.cpp delete mode 100644 resources/arduino_files/libraries/Keyboard/src/Keyboard.h delete mode 100644 resources/arduino_files/libraries/Mouse/README.adoc delete mode 100644 resources/arduino_files/libraries/Mouse/keywords.txt delete mode 100644 resources/arduino_files/libraries/Mouse/library.properties delete mode 100644 resources/arduino_files/libraries/Mouse/src/Mouse.cpp delete mode 100644 resources/arduino_files/libraries/Mouse/src/Mouse.h diff --git a/resources/arduino_files/libraries/Bridge/README.adoc b/resources/arduino_files/libraries/Bridge/README.adoc deleted file mode 100644 index c660f86ee..000000000 --- a/resources/arduino_files/libraries/Bridge/README.adoc +++ /dev/null @@ -1,24 +0,0 @@ -= Bridge Library for Arduino = - -The Bridge library simplifies communication between the ATmega32U4 and the AR9331. - -For more information about this library please visit us at -http://www.arduino.cc/en/Reference/YunBridgeLibrary - -== License == - -Copyright (c) 2014 Arduino LLC. All right reserved. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/resources/arduino_files/libraries/Bridge/examples/Bridge/Bridge.ino b/resources/arduino_files/libraries/Bridge/examples/Bridge/Bridge.ino deleted file mode 100644 index c6c7be3af..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/Bridge/Bridge.ino +++ /dev/null @@ -1,185 +0,0 @@ -/* - Arduino Yún Bridge example - - This example for the Arduino Yún shows how to use the - Bridge library to access the digital and analog pins - on the board through REST calls. It demonstrates how - you can create your own API when using REST style - calls through the browser. - - Possible commands created in this shetch: - - "/arduino/digital/13" -> digitalRead(13) - "/arduino/digital/13/1" -> digitalWrite(13, HIGH) - "/arduino/analog/2/123" -> analogWrite(2, 123) - "/arduino/analog/2" -> analogRead(2) - "/arduino/mode/13/input" -> pinMode(13, INPUT) - "/arduino/mode/13/output" -> pinMode(13, OUTPUT) - - This example code is part of the public domain - - http://www.arduino.cc/en/Tutorial/Bridge - -*/ - -#include -#include -#include - -// Listen to the default port 5555, the Yún webserver -// will forward there all the HTTP requests you send -BridgeServer server; - -void setup() { - // Bridge startup - pinMode(13, OUTPUT); - digitalWrite(13, LOW); - Bridge.begin(); - digitalWrite(13, HIGH); - - // Listen for incoming connection only from localhost - // (no one from the external network could connect) - server.listenOnLocalhost(); - server.begin(); -} - -void loop() { - // Get clients coming from server - BridgeClient client = server.accept(); - - // There is a new client? - if (client) { - // Process request - process(client); - - // Close connection and free resources. - client.stop(); - } - - delay(50); // Poll every 50ms -} - -void process(BridgeClient client) { - // read the command - String command = client.readStringUntil('/'); - - // is "digital" command? - if (command == "digital") { - digitalCommand(client); - } - - // is "analog" command? - if (command == "analog") { - analogCommand(client); - } - - // is "mode" command? - if (command == "mode") { - modeCommand(client); - } -} - -void digitalCommand(BridgeClient client) { - int pin, value; - - // Read pin number - pin = client.parseInt(); - - // If the next character is a '/' it means we have an URL - // with a value like: "/digital/13/1" - if (client.read() == '/') { - value = client.parseInt(); - digitalWrite(pin, value); - } else { - value = digitalRead(pin); - } - - // Send feedback to client - client.print(F("Pin D")); - client.print(pin); - client.print(F(" set to ")); - client.println(value); - - // Update datastore key with the current pin value - String key = "D"; - key += pin; - Bridge.put(key, String(value)); -} - -void analogCommand(BridgeClient client) { - int pin, value; - - // Read pin number - pin = client.parseInt(); - - // If the next character is a '/' it means we have an URL - // with a value like: "/analog/5/120" - if (client.read() == '/') { - // Read value and execute command - value = client.parseInt(); - analogWrite(pin, value); - - // Send feedback to client - client.print(F("Pin D")); - client.print(pin); - client.print(F(" set to analog ")); - client.println(value); - - // Update datastore key with the current pin value - String key = "D"; - key += pin; - Bridge.put(key, String(value)); - } else { - // Read analog pin - value = analogRead(pin); - - // Send feedback to client - client.print(F("Pin A")); - client.print(pin); - client.print(F(" reads analog ")); - client.println(value); - - // Update datastore key with the current pin value - String key = "A"; - key += pin; - Bridge.put(key, String(value)); - } -} - -void modeCommand(BridgeClient client) { - int pin; - - // Read pin number - pin = client.parseInt(); - - // If the next character is not a '/' we have a malformed URL - if (client.read() != '/') { - client.println(F("error")); - return; - } - - String mode = client.readStringUntil('\r'); - - if (mode == "input") { - pinMode(pin, INPUT); - // Send feedback to client - client.print(F("Pin D")); - client.print(pin); - client.print(F(" configured as INPUT!")); - return; - } - - if (mode == "output") { - pinMode(pin, OUTPUT); - // Send feedback to client - client.print(F("Pin D")); - client.print(pin); - client.print(F(" configured as OUTPUT!")); - return; - } - - client.print(F("error: invalid mode ")); - client.print(mode); -} - - diff --git a/resources/arduino_files/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino b/resources/arduino_files/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino deleted file mode 100644 index 79d5aff7e..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/ConsoleAsciiTable/ConsoleAsciiTable.ino +++ /dev/null @@ -1,95 +0,0 @@ -/* - ASCII table - - Prints out byte values in all possible formats: - * as raw binary values - * as ASCII-encoded decimal, hex, octal, and binary values - - For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII - - The circuit: No external hardware needed. - - created 2006 - by Nicholas Zambetti - http://www.zambetti.com - modified 9 Apr 2012 - by Tom Igoe - modified 22 May 2013 - by Cristian Maglie - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/ConsoleAsciiTable - - */ - -#include - -void setup() { - //Initialize Console and wait for port to open: - Bridge.begin(); - Console.begin(); - - // Uncomment the following line to enable buffering: - // - better transmission speed and efficiency - // - needs to call Console.flush() to ensure that all - // transmitted data is sent - - //Console.buffer(64); - - while (!Console) { - ; // wait for Console port to connect. - } - - // prints title with ending line break - Console.println("ASCII Table ~ Character Map"); -} - -// first visible ASCIIcharacter '!' is number 33: -int thisByte = 33; -// you can also write ASCII characters in single quotes. -// for example. '!' is the same as 33, so you could also use this: -//int thisByte = '!'; - -void loop() { - // prints value unaltered, i.e. the raw binary version of the - // byte. The Console monitor interprets all bytes as - // ASCII, so 33, the first number, will show up as '!' - Console.write(thisByte); - - Console.print(", dec: "); - // prints value as string as an ASCII-encoded decimal (base 10). - // Decimal is the default format for Console.print() and Console.println(), - // so no modifier is needed: - Console.print(thisByte); - // But you can declare the modifier for decimal if you want to. - //this also works if you uncomment it: - - // Console.print(thisByte, DEC); - - Console.print(", hex: "); - // prints value as string in hexadecimal (base 16): - Console.print(thisByte, HEX); - - Console.print(", oct: "); - // prints value as string in octal (base 8); - Console.print(thisByte, OCT); - - Console.print(", bin: "); - // prints value as string in binary (base 2) - // also prints ending line break: - Console.println(thisByte, BIN); - - // if printed last visible character '~' or 126, stop: - if (thisByte == 126) { // you could also use if (thisByte == '~') { - // ensure the latest bit of data is sent - Console.flush(); - - // This loop loops forever and does nothing - while (true) { - continue; - } - } - // go on to the next character - thisByte++; -} diff --git a/resources/arduino_files/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino b/resources/arduino_files/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino deleted file mode 100644 index ee78f4c61..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/ConsolePixel/ConsolePixel.ino +++ /dev/null @@ -1,64 +0,0 @@ -/* - Console Pixel - - An example of using the Arduino board to receive data from the - Console on the Arduino Yún. In this case, the Arduino boards turns on an LED when - it receives the character 'H', and turns off the LED when it - receives the character 'L'. - - To see the Console, pick your Yún's name and IP address in the Port menu - then open the Port Monitor. You can also see it by opening a terminal window - and typing - ssh root@ yourYunsName.local 'telnet localhost 6571' - then pressing enter. When prompted for the password, enter it. - - - The circuit: - * LED connected from digital pin 13 to ground - - created 2006 - by David A. Mellis - modified 25 Jun 2013 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/ConsolePixel - - */ - -#include - -const int ledPin = 13; // the pin that the LED is attached to -char incomingByte; // a variable to read incoming Console data into - -void setup() { - Bridge.begin(); // Initialize Bridge - Console.begin(); // Initialize Console - - // Wait for the Console port to connect - while (!Console); - - Console.println("type H or L to turn pin 13 on or off"); - - // initialize the LED pin as an output: - pinMode(ledPin, OUTPUT); -} - -void loop() { - // see if there's incoming Console data: - if (Console.available() > 0) { - // read the oldest byte in the Console buffer: - incomingByte = Console.read(); - Console.println(incomingByte); - // if it's a capital H (ASCII 72), turn on the LED: - if (incomingByte == 'H') { - digitalWrite(ledPin, HIGH); - } - // if it's an L (ASCII 76) turn off the LED: - if (incomingByte == 'L') { - digitalWrite(ledPin, LOW); - } - } -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino b/resources/arduino_files/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino deleted file mode 100644 index 8fc37fbe6..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/ConsoleRead/ConsoleRead.ino +++ /dev/null @@ -1,60 +0,0 @@ -/* - Console Read example - - Read data coming from bridge using the Console.read() function - and store it in a string. - - To see the Console, pick your Yún's name and IP address in the Port menu - then open the Port Monitor. You can also see it by opening a terminal window - and typing: - ssh root@ yourYunsName.local 'telnet localhost 6571' - then pressing enter. When prompted for the password, enter it. - - created 13 Jun 2013 - by Angelo Scialabba - modified 16 June 2013 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/ConsoleRead - - */ - -#include - -String name; - -void setup() { - // Initialize Console and wait for port to open: - Bridge.begin(); - Console.begin(); - - // Wait for Console port to connect - while (!Console); - - Console.println("Hi, what's your name?"); -} - -void loop() { - if (Console.available() > 0) { - char c = Console.read(); // read the next char received - // look for the newline character, this is the last character in the string - if (c == '\n') { - //print text with the name received - Console.print("Hi "); - Console.print(name); - Console.println("! Nice to meet you!"); - Console.println(); - // Ask again for name and clear the old name - Console.println("Hi, what's your name?"); - name = ""; // clear the name string - } else { // if the buffer is empty Cosole.read() returns -1 - name += c; // append the read char from Console to the name string - } - } else { - delay(100); - } -} - - diff --git a/resources/arduino_files/libraries/Bridge/examples/Datalogger/Datalogger.ino b/resources/arduino_files/libraries/Bridge/examples/Datalogger/Datalogger.ino deleted file mode 100644 index 367cd7226..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/Datalogger/Datalogger.ino +++ /dev/null @@ -1,102 +0,0 @@ -/* - SD card datalogger - - This example shows how to log data from three analog sensors - to an SD card mounted on the Arduino Yún using the Bridge library. - - The circuit: - * analog sensors on analog pins 0, 1 and 2 - * SD card attached to SD card slot of the Arduino Yún - - Prepare your SD card creating an empty folder in the SD root - named "arduino". This will ensure that the Yún will create a link - to the SD to the "/mnt/sd" path. - - You can remove the SD card while the Linux and the - sketch are running but be careful not to remove it while - the system is writing to it. - - created 24 Nov 2010 - modified 9 Apr 2012 - by Tom Igoe - adapted to the Yún Bridge library 20 Jun 2013 - by Federico Vanzati - modified 21 Jun 2013 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/YunDatalogger - - */ - -#include - -void setup() { - // Initialize the Bridge and the Serial - Bridge.begin(); - Serial.begin(9600); - FileSystem.begin(); - - while (!SerialUSB); // wait for Serial port to connect. - SerialUSB.println("Filesystem datalogger\n"); -} - - -void loop() { - // make a string that start with a timestamp for assembling the data to log: - String dataString; - dataString += getTimeStamp(); - dataString += " = "; - - // read three sensors and append to the string: - for (int analogPin = 0; analogPin < 3; analogPin++) { - int sensor = analogRead(analogPin); - dataString += String(sensor); - if (analogPin < 2) { - dataString += ","; // separate the values with a comma - } - } - - // open the file. note that only one file can be open at a time, - // so you have to close this one before opening another. - // The FileSystem card is mounted at the following "/mnt/FileSystema1" - File dataFile = FileSystem.open("/mnt/sd/datalog.txt", FILE_APPEND); - - // if the file is available, write to it: - if (dataFile) { - dataFile.println(dataString); - dataFile.close(); - // print to the serial port too: - SerialUSB.println(dataString); - } - // if the file isn't open, pop up an error: - else { - SerialUSB.println("error opening datalog.txt"); - } - - delay(15000); - -} - -// This function return a string with the time stamp -String getTimeStamp() { - String result; - Process time; - // date is a command line utility to get the date and the time - // in different formats depending on the additional parameter - time.begin("date"); - time.addParameter("+%D-%T"); // parameters: D for the complete date mm/dd/yy - // T for the time hh:mm:ss - time.run(); // run the command - - // read the output of the command - while (time.available() > 0) { - char c = time.read(); - if (c != '\n') { - result += c; - } - } - - return result; -} diff --git a/resources/arduino_files/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino b/resources/arduino_files/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino deleted file mode 100644 index 99899c080..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/FileWriteScript/FileWriteScript.ino +++ /dev/null @@ -1,84 +0,0 @@ -/* - Write to file using FileIO classes. - - This sketch demonstrate how to write file into the Yún filesystem. - A shell script file is created in /tmp, and it is executed afterwards. - - created 7 June 2010 - by Cristian Maglie - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/FileWriteScript - - */ - -#include - -void setup() { - // Setup Bridge (needed every time we communicate with the Arduino Yún) - Bridge.begin(); - // Initialize the Serial - SerialUSB.begin(9600); - - while (!SerialUSB); // wait for Serial port to connect. - SerialUSB.println("File Write Script example\n\n"); - - // Setup File IO - FileSystem.begin(); - - // Upload script used to gain network statistics - uploadScript(); -} - -void loop() { - // Run stats script every 5 secs. - runScript(); - delay(5000); -} - -// this function creates a file into the linux processor that contains a shell script -// to check the network traffic of the WiFi interface -void uploadScript() { - // Write our shell script in /tmp - // Using /tmp stores the script in RAM this way we can preserve - // the limited amount of FLASH erase/write cycles - File script = FileSystem.open("/tmp/wlan-stats.sh", FILE_WRITE); - // Shell script header - script.print("#!/bin/sh\n"); - // shell commands: - // ifconfig: is a command line utility for controlling the network interfaces. - // wlan0 is the interface we want to query - // grep: search inside the output of the ifconfig command the "RX bytes" keyword - // and extract the line that contains it - script.print("ifconfig wlan0 | grep 'RX bytes'\n"); - script.close(); // close the file - - // Make the script executable - Process chmod; - chmod.begin("chmod"); // chmod: change mode - chmod.addParameter("+x"); // x stays for executable - chmod.addParameter("/tmp/wlan-stats.sh"); // path to the file to make it executable - chmod.run(); -} - - -// this function run the script and read the output data -void runScript() { - // Run the script and show results on the Serial - Process myscript; - myscript.begin("/tmp/wlan-stats.sh"); - myscript.run(); - - String output = ""; - - // read the output of the script - while (myscript.available()) { - output += (char)myscript.read(); - } - // remove the blank spaces at the beginning and the ending of the string - output.trim(); - SerialUSB.println(output); - SerialUSB.flush(); -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/HttpClient/HttpClient.ino b/resources/arduino_files/libraries/Bridge/examples/HttpClient/HttpClient.ino deleted file mode 100644 index a3a5429af..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/HttpClient/HttpClient.ino +++ /dev/null @@ -1,53 +0,0 @@ -/* - Yún HTTP Client - - This example for the Arduino Yún shows how create a basic - HTTP client that connects to the internet and downloads - content. In this case, you'll connect to the Arduino - website and download a version of the logo as ASCII text. - - created by Tom igoe - May 2013 - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/HttpClient - - */ - -#include -#include - -void setup() { - // Bridge takes about two seconds to start up - // it can be helpful to use the on-board LED - // as an indicator for when it has initialized - pinMode(13, OUTPUT); - digitalWrite(13, LOW); - Bridge.begin(); - digitalWrite(13, HIGH); - - SerialUSB.begin(9600); - - while (!SerialUSB); // wait for a serial connection -} - -void loop() { - // Initialize the client library - HttpClient client; - - // Make a HTTP request: - client.get("http://www.arduino.cc/asciilogo.txt"); - - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - SerialUSB.print(c); - } - SerialUSB.flush(); - - delay(5000); -} - - diff --git a/resources/arduino_files/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino b/resources/arduino_files/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino deleted file mode 100644 index 6d8c0eeb8..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/HttpClientConsole/HttpClientConsole.ino +++ /dev/null @@ -1,55 +0,0 @@ -/* - Yún HTTP Client Console version for Arduino Uno and Mega using Yún Shield - - This example for the Arduino Yún shows how create a basic - HTTP client that connects to the internet and downloads - content. In this case, you'll connect to the Arduino - website and download a version of the logo as ASCII text. - - created by Tom igoe - May 2013 - modified by Marco Brianza to use Console - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/HttpClient - - */ - -#include -#include -#include - -void setup() { - // Bridge takes about two seconds to start up - // it can be helpful to use the on-board LED - // as an indicator for when it has initialized - pinMode(13, OUTPUT); - digitalWrite(13, LOW); - Bridge.begin(); - digitalWrite(13, HIGH); - - Console.begin(); - - while (!Console); // wait for a serial connection -} - -void loop() { - // Initialize the client library - HttpClient client; - - // Make a HTTP request: - client.get("http://www.arduino.cc/asciilogo.txt"); - - // if there are incoming bytes available - // from the server, read them and print them: - while (client.available()) { - char c = client.read(); - Console.print(c); - } - Console.flush(); - - delay(5000); -} - - diff --git a/resources/arduino_files/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino b/resources/arduino_files/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino deleted file mode 100644 index b7cbe8ad8..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino +++ /dev/null @@ -1,58 +0,0 @@ -/* - Read Messages from the Mailbox - - This example for the Arduino Yún shows how to - read the messages queue, called Mailbox, using the - Bridge library. - The messages can be sent to the queue through REST calls. - Appen the message in the URL after the keyword "/mailbox". - Example - - "/mailbox/hello" - - created 3 Feb 2014 - by Federico Vanzati & Federico Fissore - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/MailboxReadMessage - - */ - -#include - -void setup() { - pinMode(13, OUTPUT); - digitalWrite(13, LOW); - // Initialize Bridge and Mailbox - Bridge.begin(); - Mailbox.begin(); - digitalWrite(13, HIGH); - - // Initialize Serial - SerialUSB.begin(9600); - - // Wait until a Serial Monitor is connected. - while (!SerialUSB); - - SerialUSB.println("Mailbox Read Message\n"); - SerialUSB.println("The Mailbox is checked every 10 seconds. The incoming messages will be shown below.\n"); -} - -void loop() { - String message; - - // if there is a message in the Mailbox - if (Mailbox.messageAvailable()) { - // read all the messages present in the queue - while (Mailbox.messageAvailable()) { - Mailbox.readMessage(message); - SerialUSB.println(message); - } - - SerialUSB.println("Waiting 10 seconds before checking the Mailbox again"); - } - - // wait 10 seconds - delay(10000); -} diff --git a/resources/arduino_files/libraries/Bridge/examples/Process/Process.ino b/resources/arduino_files/libraries/Bridge/examples/Process/Process.ino deleted file mode 100644 index ad5b86944..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/Process/Process.ino +++ /dev/null @@ -1,72 +0,0 @@ -/* - Running process using Process class. - - This sketch demonstrate how to run linux processes - using an Arduino Yún. - - created 5 Jun 2013 - by Cristian Maglie - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/Process - - */ - -#include - -void setup() { - // Initialize Bridge - Bridge.begin(); - - // Initialize Serial - SerialUSB.begin(9600); - - // Wait until a Serial Monitor is connected. - while (!SerialUSB); - - // run various example processes - runCurl(); - runCpuInfo(); -} - -void loop() { - // Do nothing here. -} - -void runCurl() { - // Launch "curl" command and get Arduino ascii art logo from the network - // curl is command line program for transferring data using different internet protocols - Process p; // Create a process and call it "p" - p.begin("curl"); // Process that launch the "curl" command - p.addParameter("http://www.arduino.cc/asciilogo.txt"); // Add the URL parameter to "curl" - p.run(); // Run the process and wait for its termination - - // Print arduino logo over the Serial - // A process output can be read with the stream methods - while (p.available() > 0) { - char c = p.read(); - SerialUSB.print(c); - } - // Ensure the last bit of data is sent. - SerialUSB.flush(); -} - -void runCpuInfo() { - // Launch "cat /proc/cpuinfo" command (shows info on Atheros CPU) - // cat is a command line utility that shows the content of a file - Process p; // Create a process and call it "p" - p.begin("cat"); // Process that launch the "cat" command - p.addParameter("/proc/cpuinfo"); // Add the cpuifo file path as parameter to cut - p.run(); // Run the process and wait for its termination - - // Print command output on the SerialUSB. - // A process output can be read with the stream methods - while (p.available() > 0) { - char c = p.read(); - SerialUSB.print(c); - } - // Ensure the last bit of data is sent. - SerialUSB.flush(); -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino b/resources/arduino_files/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino deleted file mode 100644 index 4b5d2713c..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/RemoteDueBlink/RemoteDueBlink.ino +++ /dev/null @@ -1,33 +0,0 @@ -/* - Blink - Turns on an LED on for one second, then off for one second, repeatedly. - - Most Arduinos have an on-board LED you can control. On the Uno and - Leonardo, it is attached to digital pin 13. If you're unsure what - pin the on-board LED is connected to on your Arduino model, check - the documentation at http://www.arduino.cc - - This example code is in the public domain. - - modified 8 May 2014 - by Scott Fitzgerald - - modified by Marco Brianza to show the remote sketch update feature on Arduino Due using Yún Shield - */ - -#include - -// the setup function runs once when you press reset or power the board -void setup() { - checkForRemoteSketchUpdate(); - // initialize digital pin 13 as an output. - pinMode(13, OUTPUT); -} - -// the loop function runs over and over again forever -void loop() { - digitalWrite(13, HIGH); // turn the LED on (HIGH is the voltage level) - delay(100); // wait for a second - digitalWrite(13, LOW); // turn the LED off by making the voltage LOW - delay(100); // wait for a second -} diff --git a/resources/arduino_files/libraries/Bridge/examples/ShellCommands/ShellCommands.ino b/resources/arduino_files/libraries/Bridge/examples/ShellCommands/ShellCommands.ino deleted file mode 100644 index a90c6974f..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/ShellCommands/ShellCommands.ino +++ /dev/null @@ -1,55 +0,0 @@ -/* - Running shell commands using Process class. - - This sketch demonstrate how to run linux shell commands - using an Arduino Yún. It runs the wifiCheck script on the Linux side - of the Yún, then uses grep to get just the signal strength line. - Then it uses parseInt() to read the wifi signal strength as an integer, - and finally uses that number to fade an LED using analogWrite(). - - The circuit: - * Arduino Yún with LED connected to pin 9 - - created 12 Jun 2013 - by Cristian Maglie - modified 25 June 2013 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/ShellCommands - - */ - -#include - -void setup() { - Bridge.begin(); // Initialize the Bridge - SerialUSB.begin(9600); // Initialize the Serial - - // Wait until a Serial Monitor is connected. - while (!SerialUSB); -} - -void loop() { - Process p; - // This command line runs the WifiStatus script, (/usr/bin/pretty-wifi-info.lua), then - // sends the result to the grep command to look for a line containing the word - // "Signal:" the result is passed to this sketch: - p.runShellCommand("/usr/bin/pretty-wifi-info.lua | grep Signal"); - - // do nothing until the process finishes, so you get the whole output: - while (p.running()); - - // Read command output. runShellCommand() should have passed "Signal: xx&": - while (p.available()) { - int result = p.parseInt(); // look for an integer - int signal = map(result, 0, 100, 0, 255); // map result from 0-100 range to 0-255 - analogWrite(9, signal); // set the brightness of LED on pin 9 - SerialUSB.println(result); // print the number as well - } - delay(5000); // wait 5 seconds before you do it again -} - - - diff --git a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino deleted file mode 100644 index 0f259ede6..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/inputOutput/inputOutput.ino +++ /dev/null @@ -1,134 +0,0 @@ -/* - Input Output - - Demonstrates how to create a sketch that sends and receives all standard - spacebrew data types, and a custom data type. Every time data is - received it is output to the Serial monitor. - - Make sure that your Yún is connected to the internet for this example - to function properly. - - The circuit: - - No circuit required - - created 2013 - by Julio Terra - - This example code is in the public domain. - - More information about Spacebrew is available at: - http://spacebrew.cc/ - - */ - -#include -#include - -// create a variable of type SpacebrewYun and initialize it with the constructor -SpacebrewYun sb = SpacebrewYun("aYun", "Arduino Yun spacebrew test"); - -// create variables to manage interval between each time we send a string -long last = 0; -int interval = 2000; - -int counter = 0; - -void setup() { - - // start the serial port - SerialUSB.begin(57600); - - // for debugging, wait until a serial console is connected - delay(4000); - while (!SerialUSB) { - ; - } - - // start-up the bridge - Bridge.begin(); - - // configure the spacebrew object to print status messages to serial - sb.verbose(true); - - // configure the spacebrew publisher and subscriber - sb.addPublish("string test", "string"); - sb.addPublish("range test", "range"); - sb.addPublish("boolean test", "boolean"); - sb.addPublish("custom test", "crazy"); - sb.addSubscribe("string test", "string"); - sb.addSubscribe("range test", "range"); - sb.addSubscribe("boolean test", "boolean"); - sb.addSubscribe("custom test", "crazy"); - - // register the string message handler method - sb.onRangeMessage(handleRange); - sb.onStringMessage(handleString); - sb.onBooleanMessage(handleBoolean); - sb.onCustomMessage(handleCustom); - - // connect to cloud spacebrew server at "sandbox.spacebrew.cc" - sb.connect("sandbox.spacebrew.cc"); - // we give some time to arduino to connect to sandbox, otherwise the first sb.monitor(); call will give an error - delay(1000); -} - - -void loop() { - // monitor spacebrew connection for new data - sb.monitor(); - - // connected to spacebrew then send a string every 2 seconds - if (sb.connected()) { - - // check if it is time to send a new message - if ((millis() - last) > interval) { - String test_str_msg = "testing, testing, "; - test_str_msg += counter; - counter ++; - - sb.send("string test", test_str_msg); - sb.send("range test", 500); - sb.send("boolean test", true); - sb.send("custom test", "youre loco"); - - last = millis(); - - } - } - delay(1000); -} - -// define handler methods, all standard data type handlers take two appropriate arguments - -void handleRange(String route, int value) { - SerialUSB.print("Range msg "); - SerialUSB.print(route); - SerialUSB.print(", value "); - SerialUSB.println(value); -} - -void handleString(String route, String value) { - SerialUSB.print("String msg "); - SerialUSB.print(route); - SerialUSB.print(", value "); - SerialUSB.println(value); -} - -void handleBoolean(String route, boolean value) { - SerialUSB.print("Boolen msg "); - SerialUSB.print(route); - SerialUSB.print(", value "); - SerialUSB.println(value ? "true" : "false"); -} - -// custom data type handlers takes three String arguments - -void handleCustom(String route, String value, String type) { - SerialUSB.print("Custom msg "); - SerialUSB.print(route); - SerialUSB.print(" of type "); - SerialUSB.print(type); - SerialUSB.print(", value "); - SerialUSB.println(value); -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino deleted file mode 100644 index c63314d7c..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewBoolean/spacebrewBoolean.ino +++ /dev/null @@ -1,94 +0,0 @@ -/* - Spacebrew Boolean - - Demonstrates how to create a sketch that sends and receives a - boolean value to and from Spacebrew. Every time the buttton is - pressed (or other digital input component) a spacebrew message - is sent. The sketch also accepts analog range messages from - other Spacebrew apps. - - Make sure that your Yún is connected to the internet for this example - to function properly. - - The circuit: - - Button connected to Yún, using the Arduino's internal pullup resistor. - - created 2013 - by Julio Terra - - This example code is in the public domain. - - More information about Spacebrew is available at: - http://spacebrew.cc/ - - */ - -#include -#include - -// create a variable of type SpacebrewYun and initialize it with the constructor -SpacebrewYun sb = SpacebrewYun("spacebrewYun Boolean", "Boolean sender and receiver"); - -// variable that holds the last potentiometer value -int last_value = 0; - -// create variables to manage interval between each time we send a string -void setup() { - - // start the serial port - SerialUSB.begin(57600); - - // for debugging, wait until a serial console is connected - delay(4000); - while (!SerialUSB) { - ; - } - - // start-up the bridge - Bridge.begin(); - - // configure the spacebrew object to print status messages to serial - sb.verbose(true); - - // configure the spacebrew publisher and subscriber - sb.addPublish("physical button", "boolean"); - sb.addSubscribe("virtual button", "boolean"); - - // register the string message handler method - sb.onBooleanMessage(handleBoolean); - - // connect to cloud spacebrew server at "sandbox.spacebrew.cc" - sb.connect("sandbox.spacebrew.cc"); - - pinMode(3, INPUT); - digitalWrite(3, HIGH); -} - - -void loop() { - // monitor spacebrew connection for new data - sb.monitor(); - - // connected to spacebrew then send a new value whenever the pot value changes - if (sb.connected()) { - int cur_value = digitalRead(3); - if (last_value != cur_value) { - if (cur_value == HIGH) { - sb.send("physical button", false); - } else { - sb.send("physical button", true); - } - last_value = cur_value; - } - } -} - -// handler method that is called whenever a new string message is received -void handleBoolean(String route, boolean value) { - // print the message that was received - SerialUSB.print("From "); - SerialUSB.print(route); - SerialUSB.print(", received msg: "); - SerialUSB.println(value ? "true" : "false"); -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino deleted file mode 100644 index eda2d17a9..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewRange/spacebrewRange.ino +++ /dev/null @@ -1,88 +0,0 @@ -/* - Spacebrew Range - - Demonstrates how to create a sketch that sends and receives analog - range value to and from Spacebrew. Every time the state of the - potentiometer (or other analog input component) change a spacebrew - message is sent. The sketch also accepts analog range messages from - other Spacebrew apps. - - Make sure that your Yún is connected to the internet for this example - to function properly. - - The circuit: - - Potentiometer connected to Yún. Middle pin connected to analog pin A0, - other pins connected to 5v and GND pins. - - created 2013 - by Julio Terra - - This example code is in the public domain. - - More information about Spacebrew is available at: - http://spacebrew.cc/ - - */ - -#include -#include - -// create a variable of type SpacebrewYun and initialize it with the constructor -SpacebrewYun sb = SpacebrewYun("spacebrewYun Range", "Range sender and receiver"); - -// variable that holds the last potentiometer value -int last_value = 0; - -// create variables to manage interval between each time we send a string -void setup() { - - // start the serial port - SerialUSB.begin(57600); - - // for debugging, wait until a serial console is connected - delay(4000); - while (!SerialUSB) { - ; - } - - // start-up the bridge - Bridge.begin(); - - // configure the spacebrew object to print status messages to serial - sb.verbose(true); - - // configure the spacebrew publisher and subscriber - sb.addPublish("physical pot", "range"); - sb.addSubscribe("virtual pot", "range"); - - // register the string message handler method - sb.onRangeMessage(handleRange); - - // connect to cloud spacebrew server at "sandbox.spacebrew.cc" - sb.connect("sandbox.spacebrew.cc"); -} - - -void loop() { - // monitor spacebrew connection for new data - sb.monitor(); - - // connected to spacebrew then send a new value whenever the pot value changes - if (sb.connected()) { - int cur_value = analogRead(A0); - if (last_value != cur_value) { - sb.send("physical pot", cur_value); - last_value = cur_value; - } - } -} - -// handler method that is called whenever a new string message is received -void handleRange(String route, int value) { - // print the message that was received - SerialUSB.print("From "); - SerialUSB.print(route); - SerialUSB.print(", received msg: "); - SerialUSB.println(value); -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino b/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino deleted file mode 100644 index 189d31129..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/SpacebrewYun/spacebrewString/spacebrewString.ino +++ /dev/null @@ -1,86 +0,0 @@ -/* - Spacebrew String - - Demonstrates how to create a sketch that sends and receives strings - to and from Spacebrew. Every time string data is received it - is output to the Serial monitor. - - Make sure that your Yún is connected to the internet for this example - to function properly. - - The circuit: - - No circuit required - - created 2013 - by Julio Terra - - This example code is in the public domain. - - More information about Spacebrew is available at: - http://spacebrew.cc/ - - */ - -#include -#include - -// create a variable of type SpacebrewYun and initialize it with the constructor -SpacebrewYun sb = SpacebrewYun("spacebrewYun Strings", "String sender and receiver"); - -// create variables to manage interval between each time we send a string -long last_time = 0; -int interval = 2000; - -void setup() { - - // start the serial port - SerialUSB.begin(57600); - - // for debugging, wait until a serial console is connected - delay(4000); - while (!SerialUSB) { - ; - } - - // start-up the bridge - Bridge.begin(); - - // configure the spacebrew object to print status messages to serial - sb.verbose(true); - - // configure the spacebrew publisher and subscriber - sb.addPublish("speak", "string"); - sb.addSubscribe("listen", "string"); - - // register the string message handler method - sb.onStringMessage(handleString); - - // connect to cloud spacebrew server at "sandbox.spacebrew.cc" - sb.connect("sandbox.spacebrew.cc"); -} - - -void loop() { - // monitor spacebrew connection for new data - sb.monitor(); - - // connected to spacebrew then send a string every 2 seconds - if (sb.connected()) { - - // check if it is time to send a new message - if ((millis() - last_time) > interval) { - sb.send("speak", "is anybody out there?"); - last_time = millis(); - } - } -} - -// handler method that is called whenever a new string message is received -void handleString(String route, String value) { - // print the message that was received - SerialUSB.print("From "); - SerialUSB.print(route); - SerialUSB.print(", received msg: "); - SerialUSB.println(value); -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino b/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino deleted file mode 100644 index 3a3ba6701..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/TemperatureWebPanel.ino +++ /dev/null @@ -1,125 +0,0 @@ -/* - Temperature web interface - - This example shows how to serve data from an analog input - via the Arduino Yún's built-in webserver using the Bridge library. - - The circuit: - * TMP36 temperature sensor on analog pin A1 - * SD card attached to SD card slot of the Arduino Yún - - This sketch must be uploaded via wifi. REST API must be set to "open". - - Prepare your SD card with an empty folder in the SD root - named "arduino" and a subfolder of that named "www". - This will ensure that the Yún will create a link - to the SD to the "/mnt/sd" path. - - In this sketch folder is a basic webpage and a copy of zepto.js, a - minimized version of jQuery. When you upload your sketch, these files - will be placed in the /arduino/www/TemperatureWebPanel folder on your SD card. - - You can then go to http://arduino.local/sd/TemperatureWebPanel - to see the output of this sketch. - - You can remove the SD card while the Linux and the - sketch are running but be careful not to remove it while - the system is writing to it. - - created 6 July 2013 - by Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/TemperatureWebPanel - - */ - -#include -#include -#include - -// Listen on default port 5555, the webserver on the Yún -// will forward there all the HTTP requests for us. -BridgeServer server; -String startString; -long hits = 0; - -void setup() { - SerialUSB.begin(9600); - - // Bridge startup - pinMode(13, OUTPUT); - digitalWrite(13, LOW); - Bridge.begin(); - digitalWrite(13, HIGH); - - // using A0 and A2 as vcc and gnd for the TMP36 sensor: - pinMode(A0, OUTPUT); - pinMode(A2, OUTPUT); - digitalWrite(A0, HIGH); - digitalWrite(A2, LOW); - - // Listen for incoming connection only from localhost - // (no one from the external network could connect) - server.listenOnLocalhost(); - server.begin(); - - // get the time that this sketch started: - Process startTime; - startTime.runShellCommand("date"); - while (startTime.available()) { - char c = startTime.read(); - startString += c; - } -} - -void loop() { - // Get clients coming from server - BridgeClient client = server.accept(); - - // There is a new client? - if (client) { - // read the command - String command = client.readString(); - command.trim(); //kill whitespace - SerialUSB.println(command); - // is "temperature" command? - if (command == "temperature") { - - // get the time from the server: - Process time; - time.runShellCommand("date"); - String timeString = ""; - while (time.available()) { - char c = time.read(); - timeString += c; - } - SerialUSB.println(timeString); - int sensorValue = analogRead(A1); - // convert the reading to millivolts: - float voltage = sensorValue * (5000.0f / 1024.0f); - // convert the millivolts to temperature celsius: - float temperature = (voltage - 500.0f) / 10.0f; - // print the temperature: - client.print("Current time on the Yún: "); - client.println(timeString); - client.print("
Current temperature: "); - client.print(temperature); - client.print(" °C"); - client.print("
This sketch has been running since "); - client.print(startString); - client.print("
Hits so far: "); - client.print(hits); - } - - // Close connection and free resources. - client.stop(); - hits++; - } - - delay(50); // Poll every 50ms -} - - - diff --git a/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/index.html b/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/index.html deleted file mode 100644 index c6b674771..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/index.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - 0 - - - diff --git a/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js b/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js deleted file mode 100644 index dbe4e3c3f..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/TemperatureWebPanel/www/zepto.min.js +++ /dev/null @@ -1,2 +0,0 @@ -/* Zepto v1.0-1-ga3cab6c - polyfill zepto detect event ajax form fx - zeptojs.com/license */ -(function(a){String.prototype.trim===a&&(String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"")}),Array.prototype.reduce===a&&(Array.prototype.reduce=function(b){if(this===void 0||this===null)throw new TypeError;var c=Object(this),d=c.length>>>0,e=0,f;if(typeof b!="function")throw new TypeError;if(d==0&&arguments.length==1)throw new TypeError;if(arguments.length>=2)f=arguments[1];else do{if(e in c){f=c[e++];break}if(++e>=d)throw new TypeError}while(!0);while(e0?c.fn.concat.apply([],a):a}function O(a){return a.replace(/::/g,"/").replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/_/g,"-").toLowerCase()}function P(a){return a in j?j[a]:j[a]=new RegExp("(^|\\s)"+a+"(\\s|$)")}function Q(a,b){return typeof b=="number"&&!l[O(a)]?b+"px":b}function R(a){var b,c;return i[a]||(b=h.createElement(a),h.body.appendChild(b),c=k(b,"").getPropertyValue("display"),b.parentNode.removeChild(b),c=="none"&&(c="block"),i[a]=c),i[a]}function S(a){return"children"in a?f.call(a.children):c.map(a.childNodes,function(a){if(a.nodeType==1)return a})}function T(c,d,e){for(b in d)e&&(J(d[b])||K(d[b]))?(J(d[b])&&!J(c[b])&&(c[b]={}),K(d[b])&&!K(c[b])&&(c[b]=[]),T(c[b],d[b],e)):d[b]!==a&&(c[b]=d[b])}function U(b,d){return d===a?c(b):c(b).filter(d)}function V(a,b,c,d){return F(b)?b.call(a,c,d):b}function W(a,b,c){c==null?a.removeAttribute(b):a.setAttribute(b,c)}function X(b,c){var d=b.className,e=d&&d.baseVal!==a;if(c===a)return e?d.baseVal:d;e?d.baseVal=c:b.className=c}function Y(a){var b;try{return a?a=="true"||(a=="false"?!1:a=="null"?null:isNaN(b=Number(a))?/^[\[\{]/.test(a)?c.parseJSON(a):a:b):a}catch(d){return a}}function Z(a,b){b(a);for(var c in a.childNodes)Z(a.childNodes[c],b)}var a,b,c,d,e=[],f=e.slice,g=e.filter,h=window.document,i={},j={},k=h.defaultView.getComputedStyle,l={"column-count":1,columns:1,"font-weight":1,"line-height":1,opacity:1,"z-index":1,zoom:1},m=/^\s*<(\w+|!)[^>]*>/,n=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,o=/^(?:body|html)$/i,p=["val","css","html","text","data","width","height","offset"],q=["after","prepend","before","append"],r=h.createElement("table"),s=h.createElement("tr"),t={tr:h.createElement("tbody"),tbody:r,thead:r,tfoot:r,td:s,th:s,"*":h.createElement("div")},u=/complete|loaded|interactive/,v=/^\.([\w-]+)$/,w=/^#([\w-]*)$/,x=/^[\w-]+$/,y={},z=y.toString,A={},B,C,D=h.createElement("div");return A.matches=function(a,b){if(!a||a.nodeType!==1)return!1;var c=a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.matchesSelector;if(c)return c.call(a,b);var d,e=a.parentNode,f=!e;return f&&(e=D).appendChild(a),d=~A.qsa(e,b).indexOf(a),f&&D.removeChild(a),d},B=function(a){return a.replace(/-+(.)?/g,function(a,b){return b?b.toUpperCase():""})},C=function(a){return g.call(a,function(b,c){return a.indexOf(b)==c})},A.fragment=function(b,d,e){b.replace&&(b=b.replace(n,"<$1>")),d===a&&(d=m.test(b)&&RegExp.$1),d in t||(d="*");var g,h,i=t[d];return i.innerHTML=""+b,h=c.each(f.call(i.childNodes),function(){i.removeChild(this)}),J(e)&&(g=c(h),c.each(e,function(a,b){p.indexOf(a)>-1?g[a](b):g.attr(a,b)})),h},A.Z=function(a,b){return a=a||[],a.__proto__=c.fn,a.selector=b||"",a},A.isZ=function(a){return a instanceof A.Z},A.init=function(b,d){if(!b)return A.Z();if(F(b))return c(h).ready(b);if(A.isZ(b))return b;var e;if(K(b))e=M(b);else if(I(b))e=[J(b)?c.extend({},b):b],b=null;else if(m.test(b))e=A.fragment(b.trim(),RegExp.$1,d),b=null;else{if(d!==a)return c(d).find(b);e=A.qsa(h,b)}return A.Z(e,b)},c=function(a,b){return A.init(a,b)},c.extend=function(a){var b,c=f.call(arguments,1);return typeof a=="boolean"&&(b=a,a=c.shift()),c.forEach(function(c){T(a,c,b)}),a},A.qsa=function(a,b){var c;return H(a)&&w.test(b)?(c=a.getElementById(RegExp.$1))?[c]:[]:a.nodeType!==1&&a.nodeType!==9?[]:f.call(v.test(b)?a.getElementsByClassName(RegExp.$1):x.test(b)?a.getElementsByTagName(b):a.querySelectorAll(b))},c.contains=function(a,b){return a!==b&&a.contains(b)},c.type=E,c.isFunction=F,c.isWindow=G,c.isArray=K,c.isPlainObject=J,c.isEmptyObject=function(a){var b;for(b in a)return!1;return!0},c.inArray=function(a,b,c){return e.indexOf.call(b,a,c)},c.camelCase=B,c.trim=function(a){return a.trim()},c.uuid=0,c.support={},c.expr={},c.map=function(a,b){var c,d=[],e,f;if(L(a))for(e=0;e=0?b:b+this.length]},toArray:function(){return this.get()},size:function(){return this.length},remove:function(){return this.each(function(){this.parentNode!=null&&this.parentNode.removeChild(this)})},each:function(a){return e.every.call(this,function(b,c){return a.call(b,c,b)!==!1}),this},filter:function(a){return F(a)?this.not(this.not(a)):c(g.call(this,function(b){return A.matches(b,a)}))},add:function(a,b){return c(C(this.concat(c(a,b))))},is:function(a){return this.length>0&&A.matches(this[0],a)},not:function(b){var d=[];if(F(b)&&b.call!==a)this.each(function(a){b.call(this,a)||d.push(this)});else{var e=typeof b=="string"?this.filter(b):L(b)&&F(b.item)?f.call(b):c(b);this.forEach(function(a){e.indexOf(a)<0&&d.push(a)})}return c(d)},has:function(a){return this.filter(function(){return I(a)?c.contains(this,a):c(this).find(a).size()})},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){var a=this[0];return a&&!I(a)?a:c(a)},last:function(){var a=this[this.length-1];return a&&!I(a)?a:c(a)},find:function(a){var b,d=this;return typeof a=="object"?b=c(a).filter(function(){var a=this;return e.some.call(d,function(b){return c.contains(b,a)})}):this.length==1?b=c(A.qsa(this[0],a)):b=this.map(function(){return A.qsa(this,a)}),b},closest:function(a,b){var d=this[0],e=!1;typeof a=="object"&&(e=c(a));while(d&&!(e?e.indexOf(d)>=0:A.matches(d,a)))d=d!==b&&!H(d)&&d.parentNode;return c(d)},parents:function(a){var b=[],d=this;while(d.length>0)d=c.map(d,function(a){if((a=a.parentNode)&&!H(a)&&b.indexOf(a)<0)return b.push(a),a});return U(b,a)},parent:function(a){return U(C(this.pluck("parentNode")),a)},children:function(a){return U(this.map(function(){return S(this)}),a)},contents:function(){return this.map(function(){return f.call(this.childNodes)})},siblings:function(a){return U(this.map(function(a,b){return g.call(S(b.parentNode),function(a){return a!==b})}),a)},empty:function(){return this.each(function(){this.innerHTML=""})},pluck:function(a){return c.map(this,function(b){return b[a]})},show:function(){return this.each(function(){this.style.display=="none"&&(this.style.display=null),k(this,"").getPropertyValue("display")=="none"&&(this.style.display=R(this.nodeName))})},replaceWith:function(a){return this.before(a).remove()},wrap:function(a){var b=F(a);if(this[0]&&!b)var d=c(a).get(0),e=d.parentNode||this.length>1;return this.each(function(f){c(this).wrapAll(b?a.call(this,f):e?d.cloneNode(!0):d)})},wrapAll:function(a){if(this[0]){c(this[0]).before(a=c(a));var b;while((b=a.children()).length)a=b.first();c(a).append(this)}return this},wrapInner:function(a){var b=F(a);return this.each(function(d){var e=c(this),f=e.contents(),g=b?a.call(this,d):a;f.length?f.wrapAll(g):e.append(g)})},unwrap:function(){return this.parent().each(function(){c(this).replaceWith(c(this).children())}),this},clone:function(){return this.map(function(){return this.cloneNode(!0)})},hide:function(){return this.css("display","none")},toggle:function(b){return this.each(function(){var d=c(this);(b===a?d.css("display")=="none":b)?d.show():d.hide()})},prev:function(a){return c(this.pluck("previousElementSibling")).filter(a||"*")},next:function(a){return c(this.pluck("nextElementSibling")).filter(a||"*")},html:function(b){return b===a?this.length>0?this[0].innerHTML:null:this.each(function(a){var d=this.innerHTML;c(this).empty().append(V(this,b,a,d))})},text:function(b){return b===a?this.length>0?this[0].textContent:null:this.each(function(){this.textContent=b})},attr:function(c,d){var e;return typeof c=="string"&&d===a?this.length==0||this[0].nodeType!==1?a:c=="value"&&this[0].nodeName=="INPUT"?this.val():!(e=this[0].getAttribute(c))&&c in this[0]?this[0][c]:e:this.each(function(a){if(this.nodeType!==1)return;if(I(c))for(b in c)W(this,b,c[b]);else W(this,c,V(this,d,a,this.getAttribute(c)))})},removeAttr:function(a){return this.each(function(){this.nodeType===1&&W(this,a)})},prop:function(b,c){return c===a?this[0]&&this[0][b]:this.each(function(a){this[b]=V(this,c,a,this[b])})},data:function(b,c){var d=this.attr("data-"+O(b),c);return d!==null?Y(d):a},val:function(b){return b===a?this[0]&&(this[0].multiple?c(this[0]).find("option").filter(function(a){return this.selected}).pluck("value"):this[0].value):this.each(function(a){this.value=V(this,b,a,this.value)})},offset:function(a){if(a)return this.each(function(b){var d=c(this),e=V(this,a,b,d.offset()),f=d.offsetParent().offset(),g={top:e.top-f.top,left:e.left-f.left};d.css("position")=="static"&&(g.position="relative"),d.css(g)});if(this.length==0)return null;var b=this[0].getBoundingClientRect();return{left:b.left+window.pageXOffset,top:b.top+window.pageYOffset,width:Math.round(b.width),height:Math.round(b.height)}},css:function(a,c){if(arguments.length<2&&typeof a=="string")return this[0]&&(this[0].style[B(a)]||k(this[0],"").getPropertyValue(a));var d="";if(E(a)=="string")!c&&c!==0?this.each(function(){this.style.removeProperty(O(a))}):d=O(a)+":"+Q(a,c);else for(b in a)!a[b]&&a[b]!==0?this.each(function(){this.style.removeProperty(O(b))}):d+=O(b)+":"+Q(b,a[b])+";";return this.each(function(){this.style.cssText+=";"+d})},index:function(a){return a?this.indexOf(c(a)[0]):this.parent().children().indexOf(this[0])},hasClass:function(a){return e.some.call(this,function(a){return this.test(X(a))},P(a))},addClass:function(a){return this.each(function(b){d=[];var e=X(this),f=V(this,a,b,e);f.split(/\s+/g).forEach(function(a){c(this).hasClass(a)||d.push(a)},this),d.length&&X(this,e+(e?" ":"")+d.join(" "))})},removeClass:function(b){return this.each(function(c){if(b===a)return X(this,"");d=X(this),V(this,b,c,d).split(/\s+/g).forEach(function(a){d=d.replace(P(a)," ")}),X(this,d.trim())})},toggleClass:function(b,d){return this.each(function(e){var f=c(this),g=V(this,b,e,X(this));g.split(/\s+/g).forEach(function(b){(d===a?!f.hasClass(b):d)?f.addClass(b):f.removeClass(b)})})},scrollTop:function(){if(!this.length)return;return"scrollTop"in this[0]?this[0].scrollTop:this[0].scrollY},position:function(){if(!this.length)return;var a=this[0],b=this.offsetParent(),d=this.offset(),e=o.test(b[0].nodeName)?{top:0,left:0}:b.offset();return d.top-=parseFloat(c(a).css("margin-top"))||0,d.left-=parseFloat(c(a).css("margin-left"))||0,e.top+=parseFloat(c(b[0]).css("border-top-width"))||0,e.left+=parseFloat(c(b[0]).css("border-left-width"))||0,{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||h.body;while(a&&!o.test(a.nodeName)&&c(a).css("position")=="static")a=a.offsetParent;return a})}},c.fn.detach=c.fn.remove,["width","height"].forEach(function(b){c.fn[b]=function(d){var e,f=this[0],g=b.replace(/./,function(a){return a[0].toUpperCase()});return d===a?G(f)?f["inner"+g]:H(f)?f.documentElement["offset"+g]:(e=this.offset())&&e[b]:this.each(function(a){f=c(this),f.css(b,V(this,d,a,f[b]()))})}}),q.forEach(function(a,b){var d=b%2;c.fn[a]=function(){var a,e=c.map(arguments,function(b){return a=E(b),a=="object"||a=="array"||b==null?b:A.fragment(b)}),f,g=this.length>1;return e.length<1?this:this.each(function(a,h){f=d?h:h.parentNode,h=b==0?h.nextSibling:b==1?h.firstChild:b==2?h:null,e.forEach(function(a){if(g)a=a.cloneNode(!0);else if(!f)return c(a).remove();Z(f.insertBefore(a,h),function(a){a.nodeName!=null&&a.nodeName.toUpperCase()==="SCRIPT"&&(!a.type||a.type==="text/javascript")&&!a.src&&window.eval.call(window,a.innerHTML)})})})},c.fn[d?a+"To":"insert"+(b?"Before":"After")]=function(b){return c(b)[a](this),this}}),A.Z.prototype=c.fn,A.uniq=C,A.deserializeValue=Y,c.zepto=A,c}();window.Zepto=Zepto,"$"in window||(window.$=Zepto),function(a){function b(a){var b=this.os={},c=this.browser={},d=a.match(/WebKit\/([\d.]+)/),e=a.match(/(Android)\s+([\d.]+)/),f=a.match(/(iPad).*OS\s([\d_]+)/),g=!f&&a.match(/(iPhone\sOS)\s([\d_]+)/),h=a.match(/(webOS|hpwOS)[\s\/]([\d.]+)/),i=h&&a.match(/TouchPad/),j=a.match(/Kindle\/([\d.]+)/),k=a.match(/Silk\/([\d._]+)/),l=a.match(/(BlackBerry).*Version\/([\d.]+)/),m=a.match(/(BB10).*Version\/([\d.]+)/),n=a.match(/(RIM\sTablet\sOS)\s([\d.]+)/),o=a.match(/PlayBook/),p=a.match(/Chrome\/([\d.]+)/)||a.match(/CriOS\/([\d.]+)/),q=a.match(/Firefox\/([\d.]+)/);if(c.webkit=!!d)c.version=d[1];e&&(b.android=!0,b.version=e[2]),g&&(b.ios=b.iphone=!0,b.version=g[2].replace(/_/g,".")),f&&(b.ios=b.ipad=!0,b.version=f[2].replace(/_/g,".")),h&&(b.webos=!0,b.version=h[2]),i&&(b.touchpad=!0),l&&(b.blackberry=!0,b.version=l[2]),m&&(b.bb10=!0,b.version=m[2]),n&&(b.rimtabletos=!0,b.version=n[2]),o&&(c.playbook=!0),j&&(b.kindle=!0,b.version=j[1]),k&&(c.silk=!0,c.version=k[1]),!k&&b.android&&a.match(/Kindle Fire/)&&(c.silk=!0),p&&(c.chrome=!0,c.version=p[1]),q&&(c.firefox=!0,c.version=q[1]),b.tablet=!!(f||o||e&&!a.match(/Mobile/)||q&&a.match(/Tablet/)),b.phone=!b.tablet&&!!(e||g||h||l||m||p&&a.match(/Android/)||p&&a.match(/CriOS\/([\d.]+)/)||q&&a.match(/Mobile/))}b.call(a,navigator.userAgent),a.__detect=b}(Zepto),function(a){function g(a){return a._zid||(a._zid=d++)}function h(a,b,d,e){b=i(b);if(b.ns)var f=j(b.ns);return(c[g(a)]||[]).filter(function(a){return a&&(!b.e||a.e==b.e)&&(!b.ns||f.test(a.ns))&&(!d||g(a.fn)===g(d))&&(!e||a.sel==e)})}function i(a){var b=(""+a).split(".");return{e:b[0],ns:b.slice(1).sort().join(" ")}}function j(a){return new RegExp("(?:^| )"+a.replace(" "," .* ?")+"(?: |$)")}function k(b,c,d){a.type(b)!="string"?a.each(b,d):b.split(/\s/).forEach(function(a){d(a,c)})}function l(a,b){return a.del&&(a.e=="focus"||a.e=="blur")||!!b}function m(a){return f[a]||a}function n(b,d,e,h,j,n){var o=g(b),p=c[o]||(c[o]=[]);k(d,e,function(c,d){var e=i(c);e.fn=d,e.sel=h,e.e in f&&(d=function(b){var c=b.relatedTarget;if(!c||c!==this&&!a.contains(this,c))return e.fn.apply(this,arguments)}),e.del=j&&j(d,c);var g=e.del||d;e.proxy=function(a){var c=g.apply(b,[a].concat(a.data));return c===!1&&(a.preventDefault(),a.stopPropagation()),c},e.i=p.length,p.push(e),b.addEventListener(m(e.e),e.proxy,l(e,n))})}function o(a,b,d,e,f){var i=g(a);k(b||"",d,function(b,d){h(a,b,d,e).forEach(function(b){delete c[i][b.i],a.removeEventListener(m(b.e),b.proxy,l(b,f))})})}function t(b){var c,d={originalEvent:b};for(c in b)!r.test(c)&&b[c]!==undefined&&(d[c]=b[c]);return a.each(s,function(a,c){d[a]=function(){return this[c]=p,b[a].apply(b,arguments)},d[c]=q}),d}function u(a){if(!("defaultPrevented"in a)){a.defaultPrevented=!1;var b=a.preventDefault;a.preventDefault=function(){this.defaultPrevented=!0,b.call(this)}}}var b=a.zepto.qsa,c={},d=1,e={},f={mouseenter:"mouseover",mouseleave:"mouseout"};e.click=e.mousedown=e.mouseup=e.mousemove="MouseEvents",a.event={add:n,remove:o},a.proxy=function(b,c){if(a.isFunction(b)){var d=function(){return b.apply(c,arguments)};return d._zid=g(b),d}if(typeof c=="string")return a.proxy(b[c],b);throw new TypeError("expected function")},a.fn.bind=function(a,b){return this.each(function(){n(this,a,b)})},a.fn.unbind=function(a,b){return this.each(function(){o(this,a,b)})},a.fn.one=function(a,b){return this.each(function(c,d){n(this,a,b,null,function(a,b){return function(){var c=a.apply(d,arguments);return o(d,b,a),c}})})};var p=function(){return!0},q=function(){return!1},r=/^([A-Z]|layer[XY]$)/,s={preventDefault:"isDefaultPrevented",stopImmediatePropagation:"isImmediatePropagationStopped",stopPropagation:"isPropagationStopped"};a.fn.delegate=function(b,c,d){return this.each(function(e,f){n(f,c,d,b,function(c){return function(d){var e,g=a(d.target).closest(b,f).get(0);if(g)return e=a.extend(t(d),{currentTarget:g,liveFired:f}),c.apply(g,[e].concat([].slice.call(arguments,1)))}})})},a.fn.undelegate=function(a,b,c){return this.each(function(){o(this,b,c,a)})},a.fn.live=function(b,c){return a(document.body).delegate(this.selector,b,c),this},a.fn.die=function(b,c){return a(document.body).undelegate(this.selector,b,c),this},a.fn.on=function(b,c,d){return!c||a.isFunction(c)?this.bind(b,c||d):this.delegate(c,b,d)},a.fn.off=function(b,c,d){return!c||a.isFunction(c)?this.unbind(b,c||d):this.undelegate(c,b,d)},a.fn.trigger=function(b,c){if(typeof b=="string"||a.isPlainObject(b))b=a.Event(b);return u(b),b.data=c,this.each(function(){"dispatchEvent"in this&&this.dispatchEvent(b)})},a.fn.triggerHandler=function(b,c){var d,e;return this.each(function(f,g){d=t(typeof b=="string"?a.Event(b):b),d.data=c,d.target=g,a.each(h(g,b.type||b),function(a,b){e=b.proxy(d);if(d.isImmediatePropagationStopped())return!1})}),e},"focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select keydown keypress keyup error".split(" ").forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.trigger(b)}}),["focus","blur"].forEach(function(b){a.fn[b]=function(a){return a?this.bind(b,a):this.each(function(){try{this[b]()}catch(a){}}),this}}),a.Event=function(a,b){typeof a!="string"&&(b=a,a=b.type);var c=document.createEvent(e[a]||"Events"),d=!0;if(b)for(var f in b)f=="bubbles"?d=!!b[f]:c[f]=b[f];return c.initEvent(a,d,!0,null,null,null,null,null,null,null,null,null,null,null,null),c.isDefaultPrevented=function(){return this.defaultPrevented},c}}(Zepto),function($){function triggerAndReturn(a,b,c){var d=$.Event(b);return $(a).trigger(d,c),!d.defaultPrevented}function triggerGlobal(a,b,c,d){if(a.global)return triggerAndReturn(b||document,c,d)}function ajaxStart(a){a.global&&$.active++===0&&triggerGlobal(a,null,"ajaxStart")}function ajaxStop(a){a.global&&!--$.active&&triggerGlobal(a,null,"ajaxStop")}function ajaxBeforeSend(a,b){var c=b.context;if(b.beforeSend.call(c,a,b)===!1||triggerGlobal(b,c,"ajaxBeforeSend",[a,b])===!1)return!1;triggerGlobal(b,c,"ajaxSend",[a,b])}function ajaxSuccess(a,b,c){var d=c.context,e="success";c.success.call(d,a,e,b),triggerGlobal(c,d,"ajaxSuccess",[b,c,a]),ajaxComplete(e,b,c)}function ajaxError(a,b,c,d){var e=d.context;d.error.call(e,c,b,a),triggerGlobal(d,e,"ajaxError",[c,d,a]),ajaxComplete(b,c,d)}function ajaxComplete(a,b,c){var d=c.context;c.complete.call(d,b,a),triggerGlobal(c,d,"ajaxComplete",[b,c]),ajaxStop(c)}function empty(){}function mimeToDataType(a){return a&&(a=a.split(";",2)[0]),a&&(a==htmlType?"html":a==jsonType?"json":scriptTypeRE.test(a)?"script":xmlTypeRE.test(a)&&"xml")||"text"}function appendQuery(a,b){return(a+"&"+b).replace(/[&?]{1,2}/,"?")}function serializeData(a){a.processData&&a.data&&$.type(a.data)!="string"&&(a.data=$.param(a.data,a.traditional)),a.data&&(!a.type||a.type.toUpperCase()=="GET")&&(a.url=appendQuery(a.url,a.data))}function parseArguments(a,b,c,d){var e=!$.isFunction(b);return{url:a,data:e?b:undefined,success:e?$.isFunction(c)?c:undefined:b,dataType:e?d||c:c}}function serialize(a,b,c,d){var e,f=$.isArray(b);$.each(b,function(b,g){e=$.type(g),d&&(b=c?d:d+"["+(f?"":b)+"]"),!d&&f?a.add(g.name,g.value):e=="array"||!c&&e=="object"?serialize(a,g,c,b):a.add(b,g)})}var jsonpID=0,document=window.document,key,name,rscript=/)<[^<]*)*<\/script>/gi,scriptTypeRE=/^(?:text|application)\/javascript/i,xmlTypeRE=/^(?:text|application)\/xml/i,jsonType="application/json",htmlType="text/html",blankRE=/^\s*$/;$.active=0,$.ajaxJSONP=function(a){if("type"in a){var b="jsonp"+ ++jsonpID,c=document.createElement("script"),d=function(){clearTimeout(g),$(c).remove(),delete window[b]},e=function(c){d();if(!c||c=="timeout")window[b]=empty;ajaxError(null,c||"abort",f,a)},f={abort:e},g;return ajaxBeforeSend(f,a)===!1?(e("abort"),!1):(window[b]=function(b){d(),ajaxSuccess(b,f,a)},c.onerror=function(){e("error")},c.src=a.url.replace(/=\?/,"="+b),$("head").append(c),a.timeout>0&&(g=setTimeout(function(){e("timeout")},a.timeout)),f)}return $.ajax(a)},$.ajaxSettings={type:"GET",beforeSend:empty,success:empty,error:empty,complete:empty,context:null,global:!0,xhr:function(){return new window.XMLHttpRequest},accepts:{script:"text/javascript, application/javascript",json:jsonType,xml:"application/xml, text/xml",html:htmlType,text:"text/plain"},crossDomain:!1,timeout:0,processData:!0,cache:!0},$.ajax=function(options){var settings=$.extend({},options||{});for(key in $.ajaxSettings)settings[key]===undefined&&(settings[key]=$.ajaxSettings[key]);ajaxStart(settings),settings.crossDomain||(settings.crossDomain=/^([\w-]+:)?\/\/([^\/]+)/.test(settings.url)&&RegExp.$2!=window.location.host),settings.url||(settings.url=window.location.toString()),serializeData(settings),settings.cache===!1&&(settings.url=appendQuery(settings.url,"_="+Date.now()));var dataType=settings.dataType,hasPlaceholder=/=\?/.test(settings.url);if(dataType=="jsonp"||hasPlaceholder)return hasPlaceholder||(settings.url=appendQuery(settings.url,"callback=?")),$.ajaxJSONP(settings);var mime=settings.accepts[dataType],baseHeaders={},protocol=/^([\w-]+:)\/\//.test(settings.url)?RegExp.$1:window.location.protocol,xhr=settings.xhr(),abortTimeout;settings.crossDomain||(baseHeaders["X-Requested-With"]="XMLHttpRequest"),mime&&(baseHeaders.Accept=mime,mime.indexOf(",")>-1&&(mime=mime.split(",",2)[0]),xhr.overrideMimeType&&xhr.overrideMimeType(mime));if(settings.contentType||settings.contentType!==!1&&settings.data&&settings.type.toUpperCase()!="GET")baseHeaders["Content-Type"]=settings.contentType||"application/x-www-form-urlencoded";settings.headers=$.extend(baseHeaders,settings.headers||{}),xhr.onreadystatechange=function(){if(xhr.readyState==4){xhr.onreadystatechange=empty,clearTimeout(abortTimeout);var result,error=!1;if(xhr.status>=200&&xhr.status<300||xhr.status==304||xhr.status==0&&protocol=="file:"){dataType=dataType||mimeToDataType(xhr.getResponseHeader("content-type")),result=xhr.responseText;try{dataType=="script"?(1,eval)(result):dataType=="xml"?result=xhr.responseXML:dataType=="json"&&(result=blankRE.test(result)?null:$.parseJSON(result))}catch(e){error=e}error?ajaxError(error,"parsererror",xhr,settings):ajaxSuccess(result,xhr,settings)}else ajaxError(null,xhr.status?"error":"abort",xhr,settings)}};var async="async"in settings?settings.async:!0;xhr.open(settings.type,settings.url,async);for(name in settings.headers)xhr.setRequestHeader(name,settings.headers[name]);return ajaxBeforeSend(xhr,settings)===!1?(xhr.abort(),!1):(settings.timeout>0&&(abortTimeout=setTimeout(function(){xhr.onreadystatechange=empty,xhr.abort(),ajaxError(null,"timeout",xhr,settings)},settings.timeout)),xhr.send(settings.data?settings.data:null),xhr)},$.get=function(a,b,c,d){return $.ajax(parseArguments.apply(null,arguments))},$.post=function(a,b,c,d){var e=parseArguments.apply(null,arguments);return e.type="POST",$.ajax(e)},$.getJSON=function(a,b,c){var d=parseArguments.apply(null,arguments);return d.dataType="json",$.ajax(d)},$.fn.load=function(a,b,c){if(!this.length)return this;var d=this,e=a.split(/\s/),f,g=parseArguments(a,b,c),h=g.success;return e.length>1&&(g.url=e[0],f=e[1]),g.success=function(a){d.html(f?$("
").html(a.replace(rscript,"")).find(f):a),h&&h.apply(d,arguments)},$.ajax(g),this};var escape=encodeURIComponent;$.param=function(a,b){var c=[];return c.add=function(a,b){this.push(escape(a)+"="+escape(b))},serialize(c,a,b),c.join("&").replace(/%20/g,"+")}}(Zepto),function(a){a.fn.serializeArray=function(){var b=[],c;return a(Array.prototype.slice.call(this.get(0).elements)).each(function(){c=a(this);var d=c.attr("type");this.nodeName.toLowerCase()!="fieldset"&&!this.disabled&&d!="submit"&&d!="reset"&&d!="button"&&(d!="radio"&&d!="checkbox"||this.checked)&&b.push({name:c.attr("name"),value:c.val()})}),b},a.fn.serialize=function(){var a=[];return this.serializeArray().forEach(function(b){a.push(encodeURIComponent(b.name)+"="+encodeURIComponent(b.value))}),a.join("&")},a.fn.submit=function(b){if(b)this.bind("submit",b);else if(this.length){var c=a.Event("submit");this.eq(0).trigger(c),c.defaultPrevented||this.get(0).submit()}return this}}(Zepto),function(a,b){function s(a){return t(a.replace(/([a-z])([A-Z])/,"$1-$2"))}function t(a){return a.toLowerCase()}function u(a){return d?d+a:t(a)}var c="",d,e,f,g={Webkit:"webkit",Moz:"",O:"o",ms:"MS"},h=window.document,i=h.createElement("div"),j=/^((translate|rotate|scale)(X|Y|Z|3d)?|matrix(3d)?|perspective|skew(X|Y)?)$/i,k,l,m,n,o,p,q,r={};a.each(g,function(a,e){if(i.style[a+"TransitionProperty"]!==b)return c="-"+t(a)+"-",d=e,!1}),k=c+"transform",r[l=c+"transition-property"]=r[m=c+"transition-duration"]=r[n=c+"transition-timing-function"]=r[o=c+"animation-name"]=r[p=c+"animation-duration"]=r[q=c+"animation-timing-function"]="",a.fx={off:d===b&&i.style.transitionProperty===b,speeds:{_default:400,fast:200,slow:600},cssPrefix:c,transitionEnd:u("TransitionEnd"),animationEnd:u("AnimationEnd")},a.fn.animate=function(b,c,d,e){return a.isPlainObject(c)&&(d=c.easing,e=c.complete,c=c.duration),c&&(c=(typeof c=="number"?c:a.fx.speeds[c]||a.fx.speeds._default)/1e3),this.anim(b,c,d,e)},a.fn.anim=function(c,d,e,f){var g,h={},i,t="",u=this,v,w=a.fx.transitionEnd;d===b&&(d=.4),a.fx.off&&(d=0);if(typeof c=="string")h[o]=c,h[p]=d+"s",h[q]=e||"linear",w=a.fx.animationEnd;else{i=[];for(g in c)j.test(g)?t+=g+"("+c[g]+") ":(h[g]=c[g],i.push(s(g)));t&&(h[k]=t,i.push(k)),d>0&&typeof c=="object"&&(h[l]=i.join(", "),h[m]=d+"s",h[n]=e||"linear")}return v=function(b){if(typeof b!="undefined"){if(b.target!==b.currentTarget)return;a(b.target).unbind(w,v)}a(this).css(r),f&&f.call(this)},d>0&&this.bind(w,v),this.size()&&this.get(0).clientLeft,this.css(h),d<=0&&setTimeout(function(){u.each(function(){v.call(this)})},0),this},i=null}(Zepto) diff --git a/resources/arduino_files/libraries/Bridge/examples/TimeCheck/TimeCheck.ino b/resources/arduino_files/libraries/Bridge/examples/TimeCheck/TimeCheck.ino deleted file mode 100644 index af49b39ba..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/TimeCheck/TimeCheck.ino +++ /dev/null @@ -1,88 +0,0 @@ -/* - Time Check - - Gets the time from Linux via Bridge then parses out hours, - minutes and seconds for the Arduino using an Arduino Yún. - - created 27 May 2013 - modified 21 June 2013 - By Tom Igoe - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/TimeCheck - - */ - - -#include - -Process date; // process used to get the date -int hours, minutes, seconds; // for the results -int lastSecond = -1; // need an impossible value for comparison - -void setup() { - Bridge.begin(); // initialize Bridge - SerialUSB.begin(9600); // initialize serial - - while (!Serial); // wait for Serial Monitor to open - SerialUSB.println("Time Check"); // Title of sketch - - // run an initial date process. Should return: - // hh:mm:ss : - if (!date.running()) { - date.begin("date"); - date.addParameter("+%T"); - date.run(); - } -} - -void loop() { - - if (lastSecond != seconds) { // if a second has passed - // print the time: - if (hours <= 9) { - SerialUSB.print("0"); // adjust for 0-9 - } - SerialUSB.print(hours); - SerialUSB.print(":"); - if (minutes <= 9) { - SerialUSB.print("0"); // adjust for 0-9 - } - SerialUSB.print(minutes); - SerialUSB.print(":"); - if (seconds <= 9) { - SerialUSB.print("0"); // adjust for 0-9 - } - SerialUSB.println(seconds); - - // restart the date process: - if (!date.running()) { - date.begin("date"); - date.addParameter("+%T"); - date.run(); - } - } - - //if there's a result from the date process, parse it: - while (date.available() > 0) { - // get the result of the date process (should be hh:mm:ss): - String timeString = date.readString(); - - // find the colons: - int firstColon = timeString.indexOf(":"); - int secondColon = timeString.lastIndexOf(":"); - - // get the substrings for hour, minute second: - String hourString = timeString.substring(0, firstColon); - String minString = timeString.substring(firstColon + 1, secondColon); - String secString = timeString.substring(secondColon + 1); - - // convert to ints,saving the previous second: - hours = hourString.toInt(); - minutes = minString.toInt(); - lastSecond = seconds; // save to do a time comparison - seconds = secString.toInt(); - } - -} diff --git a/resources/arduino_files/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino b/resources/arduino_files/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino deleted file mode 100644 index 556633ed7..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/WiFiStatus/WiFiStatus.ino +++ /dev/null @@ -1,52 +0,0 @@ -/* - WiFi Status - - This sketch runs a script called "pretty-wifi-info.lua" - installed on your Yún in folder /usr/bin. - It prints information about the status of your wifi connection. - - It uses Serial to print, so you need to connect your Yún to your - computer using a USB cable and select the appropriate port from - the Port menu - - created 18 June 2013 - By Federico Fissore - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/YunWiFiStatus - - */ - -#include - -void setup() { - SerialUSB.begin(9600); // initialize serial communication - while (!SerialUSB); // do nothing until the serial monitor is opened - - SerialUSB.println("Starting bridge...\n"); - pinMode(13, OUTPUT); - digitalWrite(13, LOW); - Bridge.begin(); // make contact with the linux processor - digitalWrite(13, HIGH); // Led on pin 13 turns on when the bridge is ready - - delay(2000); // wait 2 seconds -} - -void loop() { - Process wifiCheck; // initialize a new process - - wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua"); // command you want to run - - // while there's any characters coming back from the - // process, print them to the serial monitor: - while (wifiCheck.available() > 0) { - char c = wifiCheck.read(); - SerialUSB.print(c); - } - - SerialUSB.println(); - - delay(5000); -} - diff --git a/resources/arduino_files/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino b/resources/arduino_files/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino deleted file mode 100644 index 98566d240..000000000 --- a/resources/arduino_files/libraries/Bridge/examples/YunSerialTerminal/YunSerialTerminal.ino +++ /dev/null @@ -1,82 +0,0 @@ -/* - Arduino Yún USB-to-Serial - - Allows you to use the Yún's 32U4 processor as a - serial terminal for the Linux side on the Yún. - - Upload this to an Arduino Yún via serial (not WiFi) then open - the serial monitor at 115200 to see the boot process of Linux. - You can also use the serial monitor as a basic command line - interface for Linux using this sketch. - - From the serial monitor the following commands can be issued: - - '~' followed by '0' -> Set the UART speed to 57600 baud - '~' followed by '1' -> Set the UART speed to 115200 baud - '~' followed by '2' -> Set the UART speed to 250000 baud - '~' followed by '3' -> Set the UART speed to 500000 baud - '~' followed by '~' -> Sends the bridge's shutdown command to - obtain the console. - - The circuit: - Arduino Yún - - created March 2013 - by Massimo Banzi - modified by Cristian Maglie - - This example code is in the public domain. - - http://www.arduino.cc/en/Tutorial/YunSerialTerminal - -*/ - -long linuxBaud = 250000; - -void setup() { - SERIAL_PORT_USBVIRTUAL.begin(115200); // open serial connection via USB-Serial - SERIAL_PORT_HARDWARE.begin(linuxBaud); // open serial connection to Linux -} - -boolean commandMode = false; - -void loop() { - // copy from USB-CDC to UART - int c = SERIAL_PORT_USBVIRTUAL.read(); // read from USB-CDC - if (c != -1) { // got anything? - if (commandMode == false) { // if we aren't in command mode... - if (c == '~') { // Tilde '~' key pressed? - commandMode = true; // enter in command mode - } else { - SERIAL_PORT_HARDWARE.write(c); // otherwise write char to UART - } - } else { // if we are in command mode... - if (c == '0') { // '0' key pressed? - SERIAL_PORT_HARDWARE.begin(57600); // set speed to 57600 - SERIAL_PORT_USBVIRTUAL.println("Speed set to 57600"); - } else if (c == '1') { // '1' key pressed? - SERIAL_PORT_HARDWARE.begin(115200); // set speed to 115200 - SERIAL_PORT_USBVIRTUAL.println("Speed set to 115200"); - } else if (c == '2') { // '2' key pressed? - SERIAL_PORT_HARDWARE.begin(250000); // set speed to 250000 - SERIAL_PORT_USBVIRTUAL.println("Speed set to 250000"); - } else if (c == '3') { // '3' key pressed? - SERIAL_PORT_HARDWARE.begin(500000); // set speed to 500000 - SERIAL_PORT_USBVIRTUAL.println("Speed set to 500000"); - } else if (c == '~') { // '~` key pressed? - SERIAL_PORT_HARDWARE.write((uint8_t *)"\xff\0\0\x05XXXXX\x7f\xf9", 11); // send "bridge shutdown" command - SERIAL_PORT_USBVIRTUAL.println("Sending bridge's shutdown command"); - } else { // any other key pressed? - SERIAL_PORT_HARDWARE.write('~'); // write '~' to UART - SERIAL_PORT_HARDWARE.write(c); // write char to UART - } - commandMode = false; // in all cases exit from command mode - } - } - - // copy from UART to USB-CDC - c = SERIAL_PORT_HARDWARE.read(); // read from UART - if (c != -1) { // got anything? - SERIAL_PORT_USBVIRTUAL.write(c); // write to USB-CDC - } -} diff --git a/resources/arduino_files/libraries/Bridge/keywords.txt b/resources/arduino_files/libraries/Bridge/keywords.txt deleted file mode 100644 index 1f03feec5..000000000 --- a/resources/arduino_files/libraries/Bridge/keywords.txt +++ /dev/null @@ -1,90 +0,0 @@ -####################################### -# Syntax Coloring Map For Bridge -####################################### - -####################################### -# Class (KEYWORD1) -####################################### - -Bridge KEYWORD1 YunBridgeLibrary -FileIO KEYWORD4 YunFileIOConstructor -FileSystem KEYWORD1 YunFileIOConstructor -Console KEYWORD1 YunConsoleConstructor -Process KEYWORD1 YunProcessConstructor -Mailbox KEYWORD1 YunMailboxConstructor -HttpClient KEYWORD1 YunHttpClientConstructor -YunServer KEYWORD1 YunServerConstructor -YunClient KEYWORD1 YunClientConstructor -BridgeServer KEYWORD1 YunServerConstructor -BridgeClient KEYWORD1 YunClientConstructor - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -# methods names in commond -begin KEYWORD2 -end KEYWORD2 -available KEYWORD2 -read KEYWORD2 -peek KEYWORD2 -write KEYWORD2 -flush KEYWORD2 -bool KEYWORD2 - -# Bridge Class -transfer KEYWORD2 -put KEYWORD2 -get KEYWORD2 - -# Console Class -buffer KEYWORD2 -noBuffer KEYWORD2 -connected KEYWORD2 - -# FileIO Class -File KEYWORD2 -BridgeFile KEYWORD2 -seek KEYWORD2 -position KEYWORD2 -size KEYWORD2 -close KEYWORD2 -name KEYWORD2 -isDirectory KEYWORD2 -openNextFile KEYWORD2 -rewindDirectory KEYWORD2 - -# Process Class -addParameter KEYWORD2 -runAsynchronously KEYWORD2 -run KEYWORD2 -running KEYWORD2 -exitValue KEYWORD2 -runShellCommand KEYWORD2 -runShellCommandAsynchronously KEYWORD2 - -# Mailbox Class -readMessage KEYWORD2 -writeMessage KEYWORD2 -writeJSON KEYWORD2 -message Available KEYWORD2 - -# HttpClient Class -getAsynchronously KEYWORD2 -ready KEYWORD2 -getResult KEYWORD2 - -# BridgeServer Class -accept KEYWORD2 -stop KEYWORD2 -connect KEYWORD2 -connected KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### - -FILE_READ LITERAL1 -FILE_WRITE LITERAL1 -FILE_APPEND LITERAL1 diff --git a/resources/arduino_files/libraries/Bridge/library.properties b/resources/arduino_files/libraries/Bridge/library.properties deleted file mode 100644 index e356f1c6a..000000000 --- a/resources/arduino_files/libraries/Bridge/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=Bridge -version=1.6.1 -author=Arduino -maintainer=Arduino -sentence=Enables the communication between the Linux processor and the microcontroller. For Arduino/Genuino Yún, Yún Shield and TRE only. -paragraph=The Bridge library feature: access to the shared storage, run and manage linux processes, open a remote console, access to the linux file system, including the SD card, enstablish http clients or servers. -category=Communication -url=http://www.arduino.cc/en/Reference/YunBridgeLibrary -architectures=* -dot_a_linkage=true diff --git a/resources/arduino_files/libraries/Bridge/src/Bridge.cpp b/resources/arduino_files/libraries/Bridge/src/Bridge.cpp deleted file mode 100644 index 02be3805e..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Bridge.cpp +++ /dev/null @@ -1,281 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Bridge.h" - -BridgeClass::BridgeClass(Stream &_stream) : - index(0), stream(_stream), started(false), max_retries(0) { - // Empty -} - -void BridgeClass::begin() { - if (started) - return; - started = true; - - // Wait for U-boot to finish startup - do { - dropAll(); - delay(1000); - } while (stream.available() > 0); - - while (true) { - // Bridge interrupt: - // - Ask the bridge to close itself - uint8_t quit_cmd[] = {'X', 'X', 'X', 'X', 'X'}; - max_retries = 1; - transfer(quit_cmd, 5); - - // Bridge startup: - // - If the bridge is not running starts it safely - stream.print(CTRL_C); - delay(250); - stream.print(F("\n")); - delay(250); - stream.print(F("\n")); - delay(500); - // Wait for OpenWRT message - // "Press enter to activate console" - stream.print(F("run-bridge\n")); - delay(500); - dropAll(); - - // Reset the brigde to check if it is running - uint8_t cmd[] = {'X', 'X', '1', '0', '0'}; - uint8_t res[4]; - max_retries = 50; - uint16_t l = transfer(cmd, 5, res, 4); - if (l == TRANSFER_TIMEOUT) { - // Bridge didn't start... - // Maybe the board is starting-up? - - // Wait and retry - delay(1000); - continue; - } - if (res[0] != 0) - while (true); - - // Detect bridge version - if (l == 4) { - bridgeVersion = (res[1]-'0')*100 + (res[2]-'0')*10 + (res[3]-'0'); - } else { - // Bridge v1.0.0 didn't send any version info - bridgeVersion = 100; - } - - max_retries = 50; - return; - } -} - -void BridgeClass::put(const char *key, const char *value) { - // TODO: do it in a more efficient way - String cmd = "D"; - uint8_t res[1]; - cmd += key; - cmd += "\xFE"; - cmd += value; - transfer((uint8_t*)cmd.c_str(), cmd.length(), res, 1); -} - -unsigned int BridgeClass::get(const char *key, uint8_t *value, unsigned int maxlen) { - uint8_t cmd[] = {'d'}; - unsigned int l = transfer(cmd, 1, (uint8_t *)key, strlen(key), value, maxlen); - if (l < maxlen) - value[l] = 0; // Zero-terminate string - return l; -} - -#if defined(ARDUINO_ARCH_AVR) -// AVR use an optimized implementation of CRC -#include -#else -// Generic implementation for non-AVR architectures -uint16_t _crc_ccitt_update(uint16_t crc, uint8_t data) -{ - data ^= crc & 0xff; - data ^= data << 4; - return ((((uint16_t)data << 8) | ((crc >> 8) & 0xff)) ^ - (uint8_t)(data >> 4) ^ - ((uint16_t)data << 3)); -} -#endif - -void BridgeClass::crcUpdate(uint8_t c) { - CRC = _crc_ccitt_update(CRC, c); -} - -void BridgeClass::crcReset() { - CRC = 0xFFFF; -} - -void BridgeClass::crcWrite() { - stream.write((char)(CRC >> 8)); - stream.write((char)(CRC & 0xFF)); -} - -bool BridgeClass::crcCheck(uint16_t _CRC) { - return CRC == _CRC; -} - -uint16_t BridgeClass::transfer(const uint8_t *buff1, uint16_t len1, - const uint8_t *buff2, uint16_t len2, - const uint8_t *buff3, uint16_t len3, - uint8_t *rxbuff, uint16_t rxlen) -{ - uint16_t len = len1 + len2 + len3; - uint8_t retries = 0; - for ( ; retries < max_retries; retries++, delay(100), dropAll() /* Delay for retransmission */) { - // Send packet - crcReset(); - stream.write((char)0xFF); // Start of packet (0xFF) - crcUpdate(0xFF); - stream.write((char)index); // Message index - crcUpdate(index); - stream.write((char)((len >> 8) & 0xFF)); // Message length (hi) - crcUpdate((len >> 8) & 0xFF); - stream.write((char)(len & 0xFF)); // Message length (lo) - crcUpdate(len & 0xFF); - for (uint16_t i = 0; i < len1; i++) { // Payload - stream.write((char)buff1[i]); - crcUpdate(buff1[i]); - } - for (uint16_t i = 0; i < len2; i++) { // Payload - stream.write((char)buff2[i]); - crcUpdate(buff2[i]); - } - for (uint16_t i = 0; i < len3; i++) { // Payload - stream.write((char)buff3[i]); - crcUpdate(buff3[i]); - } - crcWrite(); // CRC - - // Wait for ACK in 100ms - if (timedRead(100) != 0xFF) - continue; - crcReset(); - crcUpdate(0xFF); - - // Check packet index - if (timedRead(5) != index) - continue; - crcUpdate(index); - - // Recv len - int lh = timedRead(10); - if (lh < 0) - continue; - crcUpdate(lh); - int ll = timedRead(10); - if (ll < 0) - continue; - crcUpdate(ll); - uint16_t l = lh; - l <<= 8; - l += ll; - - // Recv data - for (uint16_t i = 0; i < l; i++) { - // Cut received data if rxbuffer is too small - if (i >= rxlen) - break; - int c = timedRead(5); - if (c < 0) - continue; - rxbuff[i] = c; - crcUpdate(c); - } - - // Check CRC - int crc_hi = timedRead(5); - if (crc_hi < 0) - continue; - int crc_lo = timedRead(5); - if (crc_lo < 0) - continue; - if (!crcCheck((crc_hi << 8) + crc_lo)) - continue; - - // Increase index - index++; - - // Return bytes received - if (l > rxlen) - return rxlen; - return l; - } - - // Max retries exceeded - return TRANSFER_TIMEOUT; -} - -int BridgeClass::timedRead(unsigned int timeout) { - int c; - unsigned long _startMillis = millis(); - do { - c = stream.read(); - if (c >= 0) return c; - } while (millis() - _startMillis < timeout); - return -1; // -1 indicates timeout -} - -void BridgeClass::dropAll() { - while (stream.available() > 0) { - stream.read(); - } -} - -#if defined(ARDUINO_ARCH_SAM) -#include -#endif - -#if defined(ARDUINO_ARCH_SAM) -void checkForRemoteSketchUpdate(uint8_t pin) { - // The host force pin LOW to signal that a new sketch is coming - pinMode(pin, INPUT_PULLUP); - delay(50); - if (digitalRead(pin) == LOW) { - initiateReset(1); - while (true) - ; // Wait for reset to SAM-BA - } - - // Restore in standard state - pinMode(pin, INPUT); -} -#else -void checkForRemoteSketchUpdate(uint8_t /* pin */) { - // Empty, bootloader is enough. -} -#endif - -// Bridge instance -#if defined(SERIAL_PORT_LINUXBRIDGE) -SerialBridgeClass Bridge(SERIAL_PORT_LINUXBRIDGE); -#elif defined(SERIAL_PORT_HARDWARE) -SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE); -#elif defined(SERIAL_PORT_HARDWARE_OPEN) -SerialBridgeClass Bridge(SERIAL_PORT_HARDWARE_OPEN); -#elif defined(__AVR_ATmega32U4__) // Legacy fallback -// Leonardo variants (where HardwareSerial is Serial1) -SerialBridgeClass Bridge(Serial1); -#else -SerialBridgeClass Bridge(Serial); -#endif - diff --git a/resources/arduino_files/libraries/Bridge/src/Bridge.h b/resources/arduino_files/libraries/Bridge/src/Bridge.h deleted file mode 100644 index 63361f172..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Bridge.h +++ /dev/null @@ -1,125 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef BRIDGE_H_ -#define BRIDGE_H_ - -#ifndef BRIDGE_BAUDRATE -#define BRIDGE_BAUDRATE 250000 -#endif - -#include -#include - -class BridgeClass { - public: - BridgeClass(Stream &_stream); - void begin(); - - // Methods to handle key/value datastore - void put(const char *key, const char *value); - void put(const String &key, const String &value) - { - put(key.c_str(), value.c_str()); - } - unsigned int get(const char *key, uint8_t *buff, unsigned int size); - unsigned int get(const char *key, char *value, unsigned int maxlen) - { - return get(key, reinterpret_cast(value), maxlen); - } - - // Trasnfer a frame (with error correction and response) - uint16_t transfer(const uint8_t *buff1, uint16_t len1, - const uint8_t *buff2, uint16_t len2, - const uint8_t *buff3, uint16_t len3, - uint8_t *rxbuff, uint16_t rxlen); - // multiple inline versions of the same function to allow efficient frame concatenation - uint16_t transfer(const uint8_t *buff1, uint16_t len1) - { - return transfer(buff1, len1, NULL, 0); - } - uint16_t transfer(const uint8_t *buff1, uint16_t len1, - uint8_t *rxbuff, uint16_t rxlen) - { - return transfer(buff1, len1, NULL, 0, rxbuff, rxlen); - } - uint16_t transfer(const uint8_t *buff1, uint16_t len1, - const uint8_t *buff2, uint16_t len2, - uint8_t *rxbuff, uint16_t rxlen) - { - return transfer(buff1, len1, buff2, len2, NULL, 0, rxbuff, rxlen); - } - - uint16_t getBridgeVersion() - { - return bridgeVersion; - } - - static const uint16_t TRANSFER_TIMEOUT = 0xFFFF; - - private: - uint8_t index; - int timedRead(unsigned int timeout); - void dropAll(); - uint16_t bridgeVersion; - - private: - void crcUpdate(uint8_t c); - void crcReset(); - void crcWrite(); - bool crcCheck(uint16_t _CRC); - uint16_t CRC; - - private: - static const char CTRL_C = 3; - Stream &stream; - bool started; - uint8_t max_retries; -}; - -// This subclass uses a serial port Stream -class SerialBridgeClass : public BridgeClass { - public: - SerialBridgeClass(HardwareSerial &_serial) - : BridgeClass(_serial), serial(_serial) { - // Empty - } - - void begin(unsigned long baudrate = BRIDGE_BAUDRATE) { - serial.begin(baudrate); - BridgeClass::begin(); - } - - private: - HardwareSerial &serial; -}; - -extern SerialBridgeClass Bridge; - -// Some microcrontrollers don't start the bootloader after a reset. -// This function is intended to let the microcontroller erase its -// flash after checking a specific signal coming from the external -// device without the need to press the erase button on the board. -// The purpose is to enable a software update that does not require -// a manual interaction with the board. -extern void checkForRemoteSketchUpdate(uint8_t pin = 7); - -#endif /* BRIDGE_H_ */ - -#include -#include diff --git a/resources/arduino_files/libraries/Bridge/src/BridgeClient.cpp b/resources/arduino_files/libraries/Bridge/src/BridgeClient.cpp deleted file mode 100644 index 72a172b23..000000000 --- a/resources/arduino_files/libraries/Bridge/src/BridgeClient.cpp +++ /dev/null @@ -1,173 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -BridgeClient::BridgeClient(uint8_t _h, BridgeClass &_b) : - bridge(_b), handle(_h), opened(true), buffered(0) { -} - -BridgeClient::BridgeClient(BridgeClass &_b) : - bridge(_b), handle(0), opened(false), buffered(0) { -} - -BridgeClient::~BridgeClient() { -} - -BridgeClient& BridgeClient::operator=(const BridgeClient &_x) { - opened = _x.opened; - handle = _x.handle; - return *this; -} - -void BridgeClient::stop() { - if (opened) { - uint8_t cmd[] = {'j', handle}; - bridge.transfer(cmd, 2); - } - opened = false; - buffered = 0; - readPos = 0; -} - -void BridgeClient::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - - // Try to buffer up to 32 characters - readPos = 0; - uint8_t cmd[] = {'K', handle, sizeof(buffer)}; - buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); -} - -int BridgeClient::available() { - // Look if there is new data available - doBuffer(); - return buffered; -} - -int BridgeClient::read() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else { - buffered--; - return buffer[readPos++]; - } -} - -int BridgeClient::read(uint8_t *buff, size_t size) { - size_t readed = 0; - do { - if (buffered == 0) { - doBuffer(); - if (buffered == 0) - return readed; - } - buff[readed++] = buffer[readPos++]; - buffered--; - } while (readed < size); - return readed; -} - -int BridgeClient::peek() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else - return buffer[readPos]; -} - -size_t BridgeClient::write(uint8_t c) { - if (!opened) - return 0; - uint8_t cmd[] = {'l', handle, c}; - bridge.transfer(cmd, 3); - return 1; -} - -size_t BridgeClient::write(const uint8_t *buf, size_t size) { - if (!opened) - return 0; - uint8_t cmd[] = {'l', handle}; - bridge.transfer(cmd, 2, buf, size, NULL, 0); - return size; -} - -void BridgeClient::flush() { -} - -uint8_t BridgeClient::connected() { - if (!opened) - return false; - // Client is "connected" if it has unread bytes - if (available()) - return true; - - uint8_t cmd[] = {'L', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, res, 1); - return (res[0] == 1); -} - -int BridgeClient::connect(IPAddress ip, uint16_t port) { - String address; - address.reserve(18); - address += ip[0]; - address += '.'; - address += ip[1]; - address += '.'; - address += ip[2]; - address += '.'; - address += ip[3]; - return connect(address.c_str(), port); -} - -int BridgeClient::connect(const char *host, uint16_t port) { - uint8_t tmp[] = { - 'C', - static_cast(port >> 8), - static_cast(port) - }; - uint8_t res[1]; - int l = bridge.transfer(tmp, 3, (const uint8_t *)host, strlen(host), res, 1); - if (l == 0) - return 0; - handle = res[0]; - - // wait for connection - uint8_t tmp2[] = { 'c', handle }; - uint8_t res2[1]; - while (true) { - bridge.transfer(tmp2, 2, res2, 1); - if (res2[0] == 0) - break; - delay(1); - } - opened = true; - - // check for successful connection - if (connected()) - return 1; - - stop(); - handle = 0; - return 0; -} - diff --git a/resources/arduino_files/libraries/Bridge/src/BridgeClient.h b/resources/arduino_files/libraries/Bridge/src/BridgeClient.h deleted file mode 100644 index 9dd3ffa91..000000000 --- a/resources/arduino_files/libraries/Bridge/src/BridgeClient.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _BRIDGE_CLIENT_H_ -#define _BRIDGE_CLIENT_H_ - -#include -#include - -class BridgeClient : public Client { - public: - // Constructor with a user provided BridgeClass instance - BridgeClient(uint8_t _h, BridgeClass &_b = Bridge); - BridgeClient(BridgeClass &_b = Bridge); - ~BridgeClient(); - - // Stream methods - // (read message) - virtual int available(); - virtual int read(); - virtual int read(uint8_t *buf, size_t size); - virtual int peek(); - // (write response) - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual void flush(); - // TODO: add optimized function for block write - - virtual operator bool () { - return opened; - } - - BridgeClient& operator=(const BridgeClient &_x); - - virtual void stop(); - virtual uint8_t connected(); - - virtual int connect(IPAddress ip, uint16_t port); - virtual int connect(const char *host, uint16_t port); - - private: - BridgeClass &bridge; - uint8_t handle; - boolean opened; - - private: - void doBuffer(); - uint8_t buffered; - uint8_t readPos; - static const int BUFFER_SIZE = 64; - uint8_t buffer[BUFFER_SIZE]; - -}; - -#endif // _BRIDGE_CLIENT_H_ diff --git a/resources/arduino_files/libraries/Bridge/src/BridgeServer.cpp b/resources/arduino_files/libraries/Bridge/src/BridgeServer.cpp deleted file mode 100644 index a7aa9b0ae..000000000 --- a/resources/arduino_files/libraries/Bridge/src/BridgeServer.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include -#include - -BridgeServer::BridgeServer(uint16_t _p, BridgeClass &_b) : - bridge(_b), port(_p), listening(false), useLocalhost(false) { -} - -void BridgeServer::begin() { - uint8_t tmp[] = { - 'N', - static_cast(port >> 8), - static_cast(port) - }; - uint8_t res[1]; - String address = F("127.0.0.1"); - if (!useLocalhost) - address = F("0.0.0.0"); - bridge.transfer(tmp, 3, (const uint8_t *)address.c_str(), address.length(), res, 1); - listening = (res[0] == 1); -} - -BridgeClient BridgeServer::accept() { - uint8_t cmd[] = {'k'}; - uint8_t res[1]; - unsigned int l = bridge.transfer(cmd, 1, res, 1); - if (l == 0) - return BridgeClient(); - return BridgeClient(res[0]); -} - -size_t BridgeServer::write(uint8_t c) { - uint8_t cmd[] = { 'b', c }; - bridge.transfer(cmd, 2); - return 1; -} - diff --git a/resources/arduino_files/libraries/Bridge/src/BridgeServer.h b/resources/arduino_files/libraries/Bridge/src/BridgeServer.h deleted file mode 100644 index 676a9729b..000000000 --- a/resources/arduino_files/libraries/Bridge/src/BridgeServer.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _BRIDGE_SERVER_H_ -#define _BRIDGE_SERVER_H_ - -#include -#include - -class BridgeClient; - -class BridgeServer : public Server { - public: - // Constructor with a user provided BridgeClass instance - BridgeServer(uint16_t port = 5555, BridgeClass &_b = Bridge); - - void begin(); - BridgeClient accept(); - - virtual size_t write(uint8_t c); - - void listenOnLocalhost() { - useLocalhost = true; - } - void noListenOnLocalhost() { - useLocalhost = false; - } - - private: - BridgeClass &bridge; - uint16_t port; - bool listening; - bool useLocalhost; -}; - -#endif // _BRIDGE_SERVER_H_ diff --git a/resources/arduino_files/libraries/Bridge/src/BridgeUdp.cpp b/resources/arduino_files/libraries/Bridge/src/BridgeUdp.cpp deleted file mode 100644 index ae630e3ab..000000000 --- a/resources/arduino_files/libraries/Bridge/src/BridgeUdp.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* - Copyright (c) 2015 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "BridgeUdp.h" - -BridgeUDP::BridgeUDP(BridgeClass &_b) : - bridge(_b), opened(false), avail(0), buffered(0), readPos(0) { -} - -/* Start BridgeUDP socket, listening at local port PORT */ -uint8_t BridgeUDP::begin(uint16_t port) { - if (opened) - return 0; - uint8_t cmd[] = {'e', (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; - uint8_t res[2]; - bridge.transfer(cmd, 3, res, 2); - if (res[1] == 1) // Error... - return 0; - handle = res[0]; - opened = true; - return 1; -} - -/* Release any resources being used by this BridgeUDP instance */ -void BridgeUDP::stop() -{ - if (!opened) - return; - uint8_t cmd[] = {'q', handle}; - bridge.transfer(cmd, 2); - opened = false; -} - -int BridgeUDP::beginPacket(const char *host, uint16_t port) -{ - if (!opened) - return 0; - uint8_t cmd[] = {'E', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; - uint8_t res[1]; - bridge.transfer(cmd, 4, (const uint8_t *)host, strlen(host), res, 1); - return res[0]; // 1=Success, 0=Error -} - -int BridgeUDP::beginBroadcastPacket(uint16_t port) -{ - if (!opened) - return 0; - uint8_t cmd[] = {'v', handle, (uint8_t)((port >> 8) & 0xFF), (uint8_t)(port & 0xFF)}; - uint8_t res[1]; - bridge.transfer(cmd, 4, res, 1); - return res[0]; // 1=Success, 0=Error -} - -int BridgeUDP::beginPacket(IPAddress ip, uint16_t port) -{ - if (!opened) - return 0; - String address; - address.reserve(18); - address += ip[0]; - address += '.'; - address += ip[1]; - address += '.'; - address += ip[2]; - address += '.'; - address += ip[3]; - return beginPacket(address.c_str(), port); -} - -int BridgeUDP::endPacket() -{ - if (!opened) - return 0; - uint8_t cmd[] = {'H', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, res, 1); - return res[0]; // 1=Success, 0=Error -} - -size_t BridgeUDP::write(const uint8_t *buffer, size_t size) -{ - if (!opened) - return 0; - uint8_t cmd[] = {'h', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, buffer, size, res, 1); - return res[0]; // 1=Success, 0=Error -} - -int BridgeUDP::parsePacket() -{ - if (!opened) - return 0; - buffered = 0; - readPos = 0; - uint8_t cmd[] = {'Q', handle}; - uint8_t res[3]; - bridge.transfer(cmd, 2, res, 3); - if (res[0] == 0) { - // There aren't any packets available - return 0; - } - avail = (res[1] << 8) + res[2]; - return 1; -} - -void BridgeUDP::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - if (avail == 0) - return; - - // Try to buffer up to 32 characters - readPos = 0; - uint8_t cmd[] = {'u', handle, sizeof(buffer)}; - buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); -} - -int BridgeUDP::read() -{ - if (!opened) - return -1; - doBuffer(); - if (buffered == 0) { - return -1; // no chars available - } - buffered--; - avail--; - return buffer[readPos++]; -} - -int BridgeUDP::read(unsigned char* buff, size_t size) -{ - if (!opened) - return -1; - size_t readed = 0; - do { - if (buffered == 0) { - doBuffer(); - if (buffered == 0) - return readed; - } - buff[readed++] = buffer[readPos++]; - buffered--; - avail--; - } while (readed < size); - return readed; -} - -int BridgeUDP::peek() -{ - if (!opened) - return -1; - doBuffer(); - if (buffered == 0) - return -1; // no chars available - return buffer[readPos]; -} - -IPAddress BridgeUDP::remoteIP() -{ - if (!opened) - return -1; - uint8_t cmd[] = {'T', handle}; - uint8_t res[7]; - bridge.transfer(cmd, 2, res, 7); - if (res[0] == 0) - return IPAddress(0,0,0,0); - return IPAddress(res[1], res[2], res[3], res[4]); -} - -uint16_t BridgeUDP::remotePort() -{ - if (!opened) - return -1; - uint8_t cmd[] = {'T', handle}; - uint8_t res[7]; - bridge.transfer(cmd, 2, res, 7); - if (res[0] == 0) - return 0; - return (res[5] << 8) + res[6]; -} diff --git a/resources/arduino_files/libraries/Bridge/src/BridgeUdp.h b/resources/arduino_files/libraries/Bridge/src/BridgeUdp.h deleted file mode 100644 index 73cec54ea..000000000 --- a/resources/arduino_files/libraries/Bridge/src/BridgeUdp.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - Copyright (c) 2015 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#pragma once - -#include -#include "Bridge.h" - -class BridgeUDP : public UDP { - - public: - BridgeUDP(BridgeClass &_b = Bridge); - virtual uint8_t begin(uint16_t); - virtual void stop(); - - virtual int beginPacket(IPAddress ip, uint16_t port); - virtual int beginPacket(const char *host, uint16_t port); - virtual int beginBroadcastPacket(uint16_t port); - virtual int endPacket(); - virtual size_t write(uint8_t d) { return write(&d, 1); } - virtual size_t write(const uint8_t *buffer, size_t size); - - using Print::write; - - virtual int parsePacket(); - /* return number of bytes available in the current packet, - will return zero if parsePacket hasn't been called yet */ - virtual int available() { return avail; } - virtual int read(); - virtual int read(unsigned char* buffer, size_t len); - virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; - virtual int peek(); - virtual void flush() { avail = 0; } - - virtual IPAddress remoteIP(); - virtual uint16_t remotePort(); - - private: - BridgeClass &bridge; - uint8_t handle; - boolean opened; - - private: - void doBuffer(); - uint16_t avail; - uint8_t buffered; - uint8_t readPos; - static const int BUFFER_SIZE = 64; - uint8_t buffer[BUFFER_SIZE]; -}; diff --git a/resources/arduino_files/libraries/Bridge/src/Console.cpp b/resources/arduino_files/libraries/Bridge/src/Console.cpp deleted file mode 100644 index 7e8323d45..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Console.cpp +++ /dev/null @@ -1,150 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -// Default constructor uses global Bridge instance -ConsoleClass::ConsoleClass() : - bridge(Bridge), inBuffered(0), inReadPos(0), inBuffer(NULL), - autoFlush(true) -{ - // Empty -} - -// Constructor with a user provided BridgeClass instance -ConsoleClass::ConsoleClass(BridgeClass &_b) : - bridge(_b), inBuffered(0), inReadPos(0), inBuffer(NULL), - autoFlush(true) -{ - // Empty -} - -ConsoleClass::~ConsoleClass() { - end(); -} - -size_t ConsoleClass::write(uint8_t c) { - if (autoFlush) { - uint8_t tmp[] = { 'P', c }; - bridge.transfer(tmp, 2); - } else { - outBuffer[outBuffered++] = c; - if (outBuffered == outBufferSize) - flush(); - } - return 1; -} - -size_t ConsoleClass::write(const uint8_t *buff, size_t size) { - if (autoFlush) { - uint8_t tmp[] = { 'P' }; - bridge.transfer(tmp, 1, buff, size, NULL, 0); - } else { - size_t sent = size; - while (sent > 0) { - outBuffer[outBuffered++] = *buff++; - sent--; - if (outBuffered == outBufferSize) - flush(); - } - } - return size; -} - -void ConsoleClass::flush() { - if (autoFlush) - return; - - bridge.transfer(outBuffer, outBuffered); - outBuffered = 1; -} - -void ConsoleClass::noBuffer() { - if (autoFlush) - return; - delete[] outBuffer; - autoFlush = true; -} - -void ConsoleClass::buffer(uint8_t size) { - noBuffer(); - if (size == 0) - return; - outBuffer = new uint8_t[size + 1]; - outBuffer[0] = 'P'; // WRITE tag - outBufferSize = size + 1; - outBuffered = 1; - autoFlush = false; -} - -bool ConsoleClass::connected() { - uint8_t tmp = 'a'; - bridge.transfer(&tmp, 1, &tmp, 1); - return tmp == 1; -} - -int ConsoleClass::available() { - // Look if there is new data available - doBuffer(); - return inBuffered; -} - -int ConsoleClass::read() { - doBuffer(); - if (inBuffered == 0) - return -1; // no chars available - else { - inBuffered--; - return inBuffer[inReadPos++]; - } -} - -int ConsoleClass::peek() { - doBuffer(); - if (inBuffered == 0) - return -1; // no chars available - else - return inBuffer[inReadPos]; -} - -void ConsoleClass::doBuffer() { - // If there are already char in buffer exit - if (inBuffered > 0) - return; - - // Try to buffer up to 32 characters - inReadPos = 0; - uint8_t tmp[] = { 'p', BUFFER_SIZE }; - inBuffered = bridge.transfer(tmp, 2, inBuffer, BUFFER_SIZE); -} - -void ConsoleClass::begin() { - bridge.begin(); - end(); - inBuffer = new uint8_t[BUFFER_SIZE]; -} - -void ConsoleClass::end() { - noBuffer(); - if (inBuffer) { - delete[] inBuffer; - inBuffer = NULL; - } -} - -ConsoleClass Console; diff --git a/resources/arduino_files/libraries/Bridge/src/Console.h b/resources/arduino_files/libraries/Bridge/src/Console.h deleted file mode 100644 index ca05b08cf..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Console.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef CONSOLE_H_ -#define CONSOLE_H_ - -#include - -class ConsoleClass : public Stream { - public: - // Default constructor uses global Bridge instance - ConsoleClass(); - // Constructor with a user provided BridgeClass instance - ConsoleClass(BridgeClass &_b); - ~ConsoleClass(); - - void begin(); - void end(); - - void buffer(uint8_t size); - void noBuffer(); - - bool connected(); - - // Stream methods - // (read from console socket) - int available(); - int read(); - int peek(); - // (write to console socket) - size_t write(uint8_t); - size_t write(const uint8_t *buffer, size_t size); - void flush(); - - operator bool () { - return connected(); - } - - private: - BridgeClass &bridge; - - void doBuffer(); - uint8_t inBuffered; - uint8_t inReadPos; - static const int BUFFER_SIZE = 32; - uint8_t *inBuffer; - - bool autoFlush; - uint8_t outBuffered; - uint8_t outBufferSize; - uint8_t *outBuffer; -}; - -extern ConsoleClass Console; - -#endif diff --git a/resources/arduino_files/libraries/Bridge/src/FileIO.cpp b/resources/arduino_files/libraries/Bridge/src/FileIO.cpp deleted file mode 100644 index e24a56796..000000000 --- a/resources/arduino_files/libraries/Bridge/src/FileIO.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -namespace BridgeLib { - -File::File(BridgeClass &b) : bridge(b), mode(255) { - // Empty -} - -File::File(const char *_filename, uint8_t _mode, BridgeClass &b) : bridge(b), mode(_mode) { - filename = _filename; - uint8_t modes[] = {'r', 'w', 'a'}; - uint8_t cmd[] = {'F', modes[mode]}; - uint8_t res[2]; - dirPosition = 1; - bridge.transfer(cmd, 2, (uint8_t*)filename.c_str(), filename.length(), res, 2); - if (res[0] != 0) { // res[0] contains error code - mode = 255; // In case of error keep the file closed - return; - } - handle = res[1]; - buffered = 0; -} - -File::operator bool() { - return (mode != 255); -} - -File::~File() { - close(); -} - -size_t File::write(uint8_t c) { - return write(&c, 1); -} - -size_t File::write(const uint8_t *buf, size_t size) { - if (mode == 255) - return -1; - uint8_t cmd[] = {'g', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, buf, size, res, 1); - if (res[0] != 0) // res[0] contains error code - return -res[0]; - return size; -} - -int File::read() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else { - buffered--; - return buffer[readPos++]; - } -} - -int File::peek() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else - return buffer[readPos]; -} - -boolean File::seek(uint32_t position) { - uint8_t cmd[] = { - 's', - handle, - static_cast(position >> 24), - static_cast(position >> 16), - static_cast(position >> 8), - static_cast(position) - }; - uint8_t res[1]; - bridge.transfer(cmd, 6, res, 1); - if (res[0] == 0) { - // If seek succeed then flush buffers - buffered = 0; - return true; - } - return false; -} - -uint32_t File::position() { - uint8_t cmd[] = {'S', handle}; - uint8_t res[5]; - bridge.transfer(cmd, 2, res, 5); - //err = res[0]; // res[0] contains error code - uint32_t pos; - pos = static_cast(res[1]) << 24; - pos += static_cast(res[2]) << 16; - pos += static_cast(res[3]) << 8; - pos += static_cast(res[4]); - return pos - buffered; -} - -void File::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - - // Try to buffer up to BUFFER_SIZE characters - readPos = 0; - uint8_t cmd[] = {'G', handle, BUFFER_SIZE - 1}; - uint16_t readed = bridge.transfer(cmd, 3, buffer, BUFFER_SIZE); - //err = buff[0]; // First byte is error code - if (readed == BridgeClass::TRANSFER_TIMEOUT || readed == 0) { - // transfer failed to retrieve any data - buffered = 0; - } else { - // transfer retrieved at least one byte of data so skip the error code character - readPos++; - buffered = readed - 1; - } -} - -int File::available() { - // Look if there is new data available - doBuffer(); - return buffered; -} - -void File::flush() { -} - -int File::read(void *buff, uint16_t nbyte) { - uint16_t n = 0; - uint8_t *p = reinterpret_cast(buff); - while (n < nbyte) { - if (buffered == 0) { - doBuffer(); - if (buffered == 0) - break; - } - *p++ = buffer[readPos++]; - buffered--; - n++; - } - return n; -} - -uint32_t File::size() { - if (bridge.getBridgeVersion() < 101) - return 0; - uint8_t cmd[] = {'t', handle}; - uint8_t buff[5]; - bridge.transfer(cmd, 2, buff, 5); - //err = res[0]; // First byte is error code - uint32_t res; - res = ((uint32_t)buff[1]) << 24; - res |= ((uint32_t)buff[2]) << 16; - res |= ((uint32_t)buff[3]) << 8; - res |= ((uint32_t)buff[4]); - return res; -} - -void File::close() { - if (mode == 255) - return; - uint8_t cmd[] = {'f', handle}; - uint8_t ret[1]; - bridge.transfer(cmd, 2, ret, 1); - mode = 255; -} - -const char *File::name() { - return filename.c_str(); -} - - -boolean File::isDirectory() { - uint8_t res[1]; - uint8_t cmd[] = {'i'}; - if (mode != 255) - return 0; - - bridge.transfer(cmd, 1, (uint8_t *)filename.c_str(), filename.length(), res, 1); - return res[0]; -} - - -File File::openNextFile(uint8_t mode) { - Process awk; - char tmp; - String command; - String filepath; - if (dirPosition == 0xFFFF) return File(); - - command = "ls "; - command += filename; - command += " | awk 'NR=="; - command += dirPosition; - command += "'"; - - awk.runShellCommand(command); - - while (awk.running()); - - command = ""; - - while (awk.available()) { - tmp = awk.read(); - if (tmp != '\n') command += tmp; - } - if (command.length() == 0) - return File(); - dirPosition++; - filepath = filename + "/" + command; - return File(filepath.c_str(), mode); - -} - -void File::rewindDirectory(void) { - dirPosition = 1; -} - - - - - - -boolean FileSystemClass::begin() { - return true; -} - -File FileSystemClass::open(const char *filename, uint8_t mode) { - return File(filename, mode); -} - -boolean FileSystemClass::exists(const char *filepath) { - Process ls; - ls.begin("ls"); - ls.addParameter(filepath); - int res = ls.run(); - return (res == 0); -} - -boolean FileSystemClass::mkdir(const char *filepath) { - Process mk; - mk.begin("mkdir"); - mk.addParameter("-p"); - mk.addParameter(filepath); - int res = mk.run(); - return (res == 0); -} - -boolean FileSystemClass::remove(const char *filepath) { - Process rm; - rm.begin("rm"); - rm.addParameter(filepath); - int res = rm.run(); - return (res == 0); -} - -boolean FileSystemClass::rmdir(const char *filepath) { - Process rm; - rm.begin("rmdir"); - rm.addParameter(filepath); - int res = rm.run(); - return (res == 0); -} - -FileSystemClass FileSystem; - -} diff --git a/resources/arduino_files/libraries/Bridge/src/FileIO.h b/resources/arduino_files/libraries/Bridge/src/FileIO.h deleted file mode 100644 index c5a8e9eac..000000000 --- a/resources/arduino_files/libraries/Bridge/src/FileIO.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef __FILEIO_H__ -#define __FILEIO_H__ - -#include - -#define FILE_READ 0 -#define FILE_WRITE 1 -#define FILE_APPEND 2 - -namespace BridgeLib { - -class File : public Stream { - - public: - File(BridgeClass &b = Bridge); - File(const char *_filename, uint8_t _mode, BridgeClass &b = Bridge); - ~File(); - - virtual size_t write(uint8_t); - virtual size_t write(const uint8_t *buf, size_t size); - virtual int read(); - virtual int peek(); - virtual int available(); - virtual void flush(); - int read(void *buf, uint16_t nbyte); - boolean seek(uint32_t pos); - uint32_t position(); - uint32_t size(); - void close(); - operator bool(); - const char * name(); - boolean isDirectory(); - File openNextFile(uint8_t mode = FILE_READ); - void rewindDirectory(void); - - //using Print::write; - - private: - void doBuffer(); - uint8_t buffered; - uint8_t readPos; - uint16_t dirPosition; - static const int BUFFER_SIZE = 64; - uint8_t buffer[BUFFER_SIZE]; - - - private: - BridgeClass &bridge; - String filename; - uint8_t mode; - uint8_t handle; - -}; - -class FileSystemClass { - public: - FileSystemClass() : bridge(Bridge) { } - FileSystemClass(BridgeClass &_b) : bridge(_b) { } - - boolean begin(); - - // Open the specified file/directory with the supplied mode (e.g. read or - // write, etc). Returns a File object for interacting with the file. - // Note that currently only one file can be open at a time. - File open(const char *filename, uint8_t mode = FILE_READ); - - // Methods to determine if the requested file path exists. - boolean exists(const char *filepath); - - // Create the requested directory hierarchy--if intermediate directories - // do not exist they will be created. - boolean mkdir(const char *filepath); - - // Delete the file. - boolean remove(const char *filepath); - - boolean rmdir(const char *filepath); - - private: - friend class File; - - BridgeClass &bridge; -}; - -extern FileSystemClass FileSystem; - -}; - -// We enclose File and FileSystem classes in namespace BridgeLib to avoid -// conflicts with legacy SD library. - -// This ensure compatibility with older sketches that uses only Bridge lib -// (the user can still use File instead of BridgeFile) -using namespace BridgeLib; - -// This allows sketches to use BridgeLib::File together with SD library -// (you must use BridgeFile instead of File when needed to disambiguate) -typedef BridgeLib::File BridgeFile; -typedef BridgeLib::FileSystemClass BridgeFileSystemClass; -#define BridgeFileSystem BridgeLib::FileSystem - -#endif diff --git a/resources/arduino_files/libraries/Bridge/src/HttpClient.cpp b/resources/arduino_files/libraries/Bridge/src/HttpClient.cpp deleted file mode 100644 index ee1629cc3..000000000 --- a/resources/arduino_files/libraries/Bridge/src/HttpClient.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* - Copyright (c) 2013-2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "HttpClient.h" - -HttpClient::HttpClient() : - insecure(false) { - // Empty -} - -unsigned int HttpClient::get(String &url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - return run(); -} - -unsigned int HttpClient::get(const char *url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::getAsynchronously(String &url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - runAsynchronously(); -} - -void HttpClient::getAsynchronously(const char *url) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addHeader(); - addParameter(url); - runAsynchronously(); -} - -unsigned int HttpClient::post(String &url, String &data) { - return post(url.c_str(), data.c_str()); -} - -unsigned int HttpClient::post(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("POST"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::postAsynchronously(String &url, String &data) { - postAsynchronously(url.c_str(), data.c_str()); -} - -void HttpClient::postAsynchronously(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("POST"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - runAsynchronously(); -} - -unsigned int HttpClient::patch(String &url, String &data) { - return patch(url.c_str(), data.c_str()); -} - -unsigned int HttpClient::patch(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PATCH"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::patchAsynchronously(String &url, String &data) { - patchAsynchronously(url.c_str(), data.c_str()); -} - -void HttpClient::patchAsynchronously(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PATCH"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - runAsynchronously(); -} - -unsigned int HttpClient::put(String &url, String &data) { - return put(url.c_str(), data.c_str()); -} - -unsigned int HttpClient::put(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PUT"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - return run(); -} - -void HttpClient::putAsynchronously(String &url, String &data) { - putAsynchronously(url.c_str(), data.c_str()); -} - -void HttpClient::putAsynchronously(const char *url, const char *data) { - begin("curl"); - if (insecure) { - addParameter("-k"); - } - addParameter("--request"); - addParameter("PUT"); - addParameter("--data"); - addParameter(data); - addHeader(); - addParameter(url); - runAsynchronously(); -} - -boolean HttpClient::ready() { - return !running(); -} - -unsigned int HttpClient::getResult() { - return exitValue(); -} - -void HttpClient::noCheckSSL() { - insecure = true; -} - -void HttpClient::checkSSL() { - insecure = false; -} - -void HttpClient::setHeader(String &header) { - this->header = header; -} - -void HttpClient::setHeader(const char * header) { - this->header = String(header); -} - -void HttpClient::addHeader() { - if (header.length() > 0) { - addParameter("--header"); - addParameter(header); - } -} - diff --git a/resources/arduino_files/libraries/Bridge/src/HttpClient.h b/resources/arduino_files/libraries/Bridge/src/HttpClient.h deleted file mode 100644 index a6e3c77aa..000000000 --- a/resources/arduino_files/libraries/Bridge/src/HttpClient.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - Copyright (c) 2013-2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef HTTPCLIENT_H_ -#define HTTPCLIENT_H_ - -#include - -class HttpClient : public Process { - public: - HttpClient(); - - unsigned int get(String &url); - unsigned int get(const char * url); - void getAsynchronously(String &url); - void getAsynchronously(const char * url); - unsigned int post(String &url, String &data); - unsigned int post(const char * url, const char * data); - void postAsynchronously(String &url, String &data); - void postAsynchronously(const char * url, const char * data); - unsigned int patch(String &url, String &data); - unsigned int patch(const char * url, const char * data); - void patchAsynchronously(String &url, String &data); - void patchAsynchronously(const char * url, const char * data); - unsigned int put(String &url, String &data); - unsigned int put(const char * url, const char * data); - void putAsynchronously(String &url, String &data); - void putAsynchronously(const char * url, const char * data); - void setHeader(String &header); - void setHeader(const char * header); - boolean ready(); - unsigned int getResult(); - void noCheckSSL(); - void checkSSL(); - - private: - boolean insecure; - - private: - void addHeader(); - String header; -}; - -#endif /* HTTPCLIENT_H_ */ diff --git a/resources/arduino_files/libraries/Bridge/src/Mailbox.cpp b/resources/arduino_files/libraries/Bridge/src/Mailbox.cpp deleted file mode 100644 index 0c571f73a..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Mailbox.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -unsigned int MailboxClass::readMessage(uint8_t *buff, unsigned int size) { - uint8_t tmp[] = { 'm' }; - return bridge.transfer(tmp, 1, buff, size); -} - -void MailboxClass::readMessage(String &str, unsigned int maxLength) { - uint8_t tmp[] = { 'm' }; - // XXX: Is there a better way to create the string? - uint8_t buff[maxLength + 1]; - int l = bridge.transfer(tmp, 1, buff, maxLength); - buff[l] = 0; - str = (const char *)buff; -} - -void MailboxClass::writeMessage(const uint8_t *buff, unsigned int size) { - uint8_t cmd[] = {'M'}; - bridge.transfer(cmd, 1, buff, size, NULL, 0); -} - -void MailboxClass::writeMessage(const String& str) { - writeMessage((uint8_t*) str.c_str(), str.length()); -} - -void MailboxClass::writeJSON(const String& str) { - uint8_t cmd[] = {'J'}; - bridge.transfer(cmd, 1, (uint8_t*) str.c_str(), str.length(), NULL, 0); -} - -unsigned int MailboxClass::messageAvailable() { - uint8_t tmp[] = {'n'}; - uint8_t res[2]; - bridge.transfer(tmp, 1, res, 2); - return (res[0] << 8) + res[1]; -} - -MailboxClass Mailbox(Bridge); diff --git a/resources/arduino_files/libraries/Bridge/src/Mailbox.h b/resources/arduino_files/libraries/Bridge/src/Mailbox.h deleted file mode 100644 index b2e383308..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Mailbox.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _MAILBOX_CLASS_H_INCLUDED_ -#define _MAILBOX_CLASS_H_INCLUDED_ - -#include - -class MailboxClass { - public: - MailboxClass(BridgeClass &b = Bridge) : bridge(b) { } - - void begin() { } - void end() { } - - // Receive a message and store it inside a buffer - unsigned int readMessage(uint8_t *buffer, unsigned int size); - // Receive a message and store it inside a String - void readMessage(String &str, unsigned int maxLength = 128); - - // Send a message - void writeMessage(const uint8_t *buffer, unsigned int size); - // Send a message - void writeMessage(const String& str); - // Send a JSON message - void writeJSON(const String& str); - - // Return the size of the next available message, 0 if there are - // no messages in queue. - unsigned int messageAvailable(); - - private: - BridgeClass &bridge; -}; - -extern MailboxClass Mailbox; - -#endif // _MAILBOX_CLASS_H_INCLUDED_ diff --git a/resources/arduino_files/libraries/Bridge/src/Process.cpp b/resources/arduino_files/libraries/Bridge/src/Process.cpp deleted file mode 100644 index 987f0b8ac..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Process.cpp +++ /dev/null @@ -1,142 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include - -Process::~Process() { - close(); -} - -size_t Process::write(uint8_t c) { - uint8_t cmd[] = {'I', handle, c}; - bridge.transfer(cmd, 3); - return 1; -} - -void Process::flush() { -} - -int Process::available() { - // Look if there is new data available - doBuffer(); - return buffered; -} - -int Process::read() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else { - buffered--; - return buffer[readPos++]; - } -} - -int Process::peek() { - doBuffer(); - if (buffered == 0) - return -1; // no chars available - else - return buffer[readPos]; -} - -void Process::doBuffer() { - // If there are already char in buffer exit - if (buffered > 0) - return; - - // Try to buffer up to 32 characters - readPos = 0; - uint8_t cmd[] = {'O', handle, sizeof(buffer)}; - buffered = bridge.transfer(cmd, 3, buffer, sizeof(buffer)); -} - -void Process::begin(const String &command) { - close(); - cmdline = new String(command); -} - -void Process::addParameter(const String ¶m) { - *cmdline += "\xFE"; - *cmdline += param; -} - -void Process::runAsynchronously() { - uint8_t cmd[] = {'R'}; - uint8_t res[2]; - bridge.transfer(cmd, 1, (uint8_t*)cmdline->c_str(), cmdline->length(), res, 2); - handle = res[1]; - - delete cmdline; - cmdline = NULL; - - if (res[0] == 0) // res[0] contains error code - started = true; -} - -boolean Process::running() { - uint8_t cmd[] = {'r', handle}; - uint8_t res[1]; - bridge.transfer(cmd, 2, res, 1); - return (res[0] == 1); -} - -unsigned int Process::exitValue() { - uint8_t cmd[] = {'W', handle}; - uint8_t res[2]; - bridge.transfer(cmd, 2, res, 2); - return (res[0] << 8) + res[1]; -} - -unsigned int Process::run() { - runAsynchronously(); - while (running()) - delay(100); - return exitValue(); -} - -void Process::close() { - if (started) { - uint8_t cmd[] = {'w', handle}; - bridge.transfer(cmd, 2); - } - started = false; -} - -unsigned int Process::runShellCommand(const String &command) { - runShellCommandAsynchronously(command); - while (running()) - delay(100); - return exitValue(); -} - -void Process::runShellCommandAsynchronously(const String &command) { - begin("/bin/ash"); - addParameter("-c"); - addParameter(command); - runAsynchronously(); -} - -// This method is currently unused -//static unsigned int __commandOutputAvailable(uint8_t handle) { -// uint8_t cmd[] = {'o', handle}; -// uint8_t res[1]; -// Bridge.transfer(cmd, 2, res, 1); -// return res[0]; -//} - diff --git a/resources/arduino_files/libraries/Bridge/src/Process.h b/resources/arduino_files/libraries/Bridge/src/Process.h deleted file mode 100644 index 7002764a0..000000000 --- a/resources/arduino_files/libraries/Bridge/src/Process.h +++ /dev/null @@ -1,71 +0,0 @@ -/* - Copyright (c) 2013 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef PROCESS_H_ -#define PROCESS_H_ - -#include - -class Process : public Stream { - public: - // Constructor with a user provided BridgeClass instance - Process(BridgeClass &_b = Bridge) : - bridge(_b), started(false), buffered(0), readPos(0) { } - ~Process(); - - void begin(const String &command); - void addParameter(const String ¶m); - unsigned int run(); - void runAsynchronously(); - boolean running(); - unsigned int exitValue(); - void close(); - - unsigned int runShellCommand(const String &command); - void runShellCommandAsynchronously(const String &command); - - operator bool () { - return started; - } - - // Stream methods - // (read from process stdout) - int available(); - int read(); - int peek(); - // (write to process stdin) - size_t write(uint8_t); - void flush(); - // TODO: add optimized function for block write - - private: - BridgeClass &bridge; - uint8_t handle; - String *cmdline; - boolean started; - - private: - void doBuffer(); - uint8_t buffered; - uint8_t readPos; - static const int BUFFER_SIZE = 64; - uint8_t buffer[BUFFER_SIZE]; - -}; - -#endif diff --git a/resources/arduino_files/libraries/Bridge/src/YunClient.h b/resources/arduino_files/libraries/Bridge/src/YunClient.h deleted file mode 100644 index faff247c9..000000000 --- a/resources/arduino_files/libraries/Bridge/src/YunClient.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (c) 2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _YUN_CLIENT_H_ -#define _YUN_CLIENT_H_ - -#include - -#warning "The use of YunClient is deprecated. Use BridgeClient instead!" -typedef BridgeClient YunClient; - -#endif // _YUN_CLIENT_H_ diff --git a/resources/arduino_files/libraries/Bridge/src/YunServer.h b/resources/arduino_files/libraries/Bridge/src/YunServer.h deleted file mode 100644 index 95d05cd71..000000000 --- a/resources/arduino_files/libraries/Bridge/src/YunServer.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - Copyright (c) 2014 Arduino LLC. All right reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef _YUN_SERVER_H_ -#define _YUN_SERVER_H_ - -#include - -#warning "The use of YunServer is deprecated. Use BridgeServer instead!" -typedef BridgeServer YunServer; - -#endif // _YUN_SERVER_H_ diff --git a/resources/arduino_files/libraries/Firmata/Boards.h b/resources/arduino_files/libraries/Firmata/Boards.h deleted file mode 100644 index e084f9cf8..000000000 --- a/resources/arduino_files/libraries/Firmata/Boards.h +++ /dev/null @@ -1,764 +0,0 @@ -/* - Boards.h - Hardware Abstraction Layer for Firmata library - Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2009-2015 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - Last updated December 19th, 2015 -*/ - -#ifndef Firmata_Boards_h -#define Firmata_Boards_h - -#include - -#if defined(ARDUINO) && ARDUINO >= 100 -#include "Arduino.h" // for digitalRead, digitalWrite, etc -#else -#include "WProgram.h" -#endif - -// Normally Servo.h must be included before Firmata.h (which then includes -// this file). If Servo.h wasn't included, this allows the code to still -// compile, but without support for any Servos. Hopefully that's what the -// user intended by not including Servo.h -#ifndef MAX_SERVOS -#define MAX_SERVOS 0 -#endif - -/* - Firmata Hardware Abstraction Layer - -Firmata is built on top of the hardware abstraction functions of Arduino, -specifically digitalWrite, digitalRead, analogWrite, analogRead, and -pinMode. While these functions offer simple integer pin numbers, Firmata -needs more information than is provided by Arduino. This file provides -all other hardware specific details. To make Firmata support a new board, -only this file should require editing. - -The key concept is every "pin" implemented by Firmata may be mapped to -any pin as implemented by Arduino. Usually a simple 1-to-1 mapping is -best, but such mapping should not be assumed. This hardware abstraction -layer allows Firmata to implement any number of pins which map onto the -Arduino implemented pins in almost any arbitrary way. - - -General Constants: - -These constants provide basic information Firmata requires. - -TOTAL_PINS: The total number of pins Firmata implemented by Firmata. - Usually this will match the number of pins the Arduino functions - implement, including any pins pins capable of analog or digital. - However, Firmata may implement any number of pins. For example, - on Arduino Mini with 8 analog inputs, 6 of these may be used - for digital functions, and 2 are analog only. On such boards, - Firmata can implement more pins than Arduino's pinMode() - function, in order to accommodate those special pins. The - Firmata protocol supports a maximum of 128 pins, so this - constant must not exceed 128. - -TOTAL_ANALOG_PINS: The total number of analog input pins implemented. - The Firmata protocol allows up to 16 analog inputs, accessed - using offsets 0 to 15. Because Firmata presents the analog - inputs using different offsets than the actual pin numbers - (a legacy of Arduino's analogRead function, and the way the - analog input capable pins are physically labeled on all - Arduino boards), the total number of analog input signals - must be specified. 16 is the maximum. - -VERSION_BLINK_PIN: When Firmata starts up, it will blink the version - number. This constant is the Arduino pin number where a - LED is connected. - - -Pin Mapping Macros: - -These macros provide the mapping between pins as implemented by -Firmata protocol and the actual pin numbers used by the Arduino -functions. Even though such mappings are often simple, pin -numbers received by Firmata protocol should always be used as -input to these macros, and the result of the macro should be -used with with any Arduino function. - -When Firmata is extended to support a new pin mode or feature, -a pair of macros should be added and used for all hardware -access. For simple 1:1 mapping, these macros add no actual -overhead, yet their consistent use allows source code which -uses them consistently to be easily adapted to all other boards -with different requirements. - -IS_PIN_XXXX(pin): The IS_PIN macros resolve to true or non-zero - if a pin as implemented by Firmata corresponds to a pin - that actually implements the named feature. - -PIN_TO_XXXX(pin): The PIN_TO macros translate pin numbers as - implemented by Firmata to the pin numbers needed as inputs - to the Arduino functions. The corresponding IS_PIN macro - should always be tested before using a PIN_TO macro, so - these macros only need to handle valid Firmata pin - numbers for the named feature. - - -Port Access Inline Funtions: - -For efficiency, Firmata protocol provides access to digital -input and output pins grouped by 8 bit ports. When these -groups of 8 correspond to actual 8 bit ports as implemented -by the hardware, these inline functions can provide high -speed direct port access. Otherwise, a default implementation -using 8 calls to digitalWrite or digitalRead is used. - -When porting Firmata to a new board, it is recommended to -use the default functions first and focus only on the constants -and macros above. When those are working, if optimized port -access is desired, these inline functions may be extended. -The recommended approach defines a symbol indicating which -optimization to use, and then conditional complication is -used within these functions. - -readPort(port, bitmask): Read an 8 bit port, returning the value. - port: The port number, Firmata pins port*8 to port*8+7 - bitmask: The actual pins to read, indicated by 1 bits. - -writePort(port, value, bitmask): Write an 8 bit port. - port: The port number, Firmata pins port*8 to port*8+7 - value: The 8 bit value to write - bitmask: The actual pins to write, indicated by 1 bits. -*/ - -/*============================================================================== - * Board Specific Configuration - *============================================================================*/ - -#ifndef digitalPinHasPWM -#define digitalPinHasPWM(p) IS_PIN_DIGITAL(p) -#endif - -// Arduino Duemilanove, Diecimila, and NG -#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__) || defined(__AVR_ATmega328__) -#if defined(NUM_ANALOG_INPUTS) && NUM_ANALOG_INPUTS == 6 -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 20 // 14 digital + 6 analog -#else -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS 22 // 14 digital + 8 analog -#endif -#define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) -#define ARDUINO_PINOUT_OPTIMIZE 1 - - -// Wiring (and board) -#elif defined(WIRING) -#define VERSION_BLINK_PIN WLED -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= FIRST_ANALOG_PIN && (p) < (FIRST_ANALOG_PIN+TOTAL_ANALOG_PINS)) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - FIRST_ANALOG_PIN) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// old Arduinos -#elif defined(__AVR_ATmega8__) -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 20 // 14 digital + 6 analog -#define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) -#define ARDUINO_PINOUT_OPTIMIZE 1 - - -// Arduino Mega -#elif defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) -#define TOTAL_ANALOG_PINS 16 -#define TOTAL_PINS 70 // 54 digital + 16 analog -#define VERSION_BLINK_PIN 13 -#define PIN_SERIAL1_RX 19 -#define PIN_SERIAL1_TX 18 -#define PIN_SERIAL2_RX 17 -#define PIN_SERIAL2_TX 16 -#define PIN_SERIAL3_RX 15 -#define PIN_SERIAL3_TX 14 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 54) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// Arduino DUE -#elif defined(__SAM3X8E__) -#define TOTAL_ANALOG_PINS 12 -#define TOTAL_PINS 66 // 54 digital + 12 analog -#define VERSION_BLINK_PIN 13 -#define PIN_SERIAL1_RX 19 -#define PIN_SERIAL1_TX 18 -#define PIN_SERIAL2_RX 17 -#define PIN_SERIAL2_TX 16 -#define PIN_SERIAL3_RX 15 -#define PIN_SERIAL3_TX 14 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 2 && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // 70 71 -#define IS_PIN_SERIAL(p) ((p) > 13 && (p) < 20) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 54) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// Arduino/Genuino MKR1000 -#elif defined(ARDUINO_SAMD_MKR1000) -#define TOTAL_ANALOG_PINS 7 -#define TOTAL_PINS 22 // 8 digital + 3 spi + 2 i2c + 2 uart + 7 analog -#define IS_PIN_DIGITAL(p) (((p) >= 0 && (p) <= 21) && !IS_PIN_SERIAL(p)) -#define IS_PIN_ANALOG(p) ((p) >= 15 && (p) < 15 + TOTAL_ANALOG_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 -#define IS_PIN_I2C(p) ((p) == 11 || (p) == 12) // SDA = 11, SCL = 12 -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == PIN_SERIAL1_RX || (p) == PIN_SERIAL1_TX) //defined in variant.h RX = 13, TX = 14 -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 15) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 - - -// Arduino Zero -// Note this will work with an Arduino Zero Pro, but not with an Arduino M0 Pro -// Arduino M0 Pro does not properly map pins to the board labeled pin numbers -#elif defined(_VARIANT_ARDUINO_ZERO_) -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 25 // 14 digital + 6 analog + 2 i2c + 3 spi -#define TOTAL_PORTS 3 // set when TOTAL_PINS > num digitial I/O pins -#define VERSION_BLINK_PIN LED_BUILTIN -//#define PIN_SERIAL1_RX 0 // already defined in zero core variant.h -//#define PIN_SERIAL1_TX 1 // already defined in zero core variant.h -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 19) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 -#define IS_PIN_I2C(p) ((p) == 20 || (p) == 21) // SDA = 20, SCL = 21 -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) // SS = A2 -#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 - - -// Arduino 101 -#elif defined(_VARIANT_ARDUINO_101_X_) -#define TOTAL_ANALOG_PINS NUM_ANALOG_INPUTS -#define TOTAL_PINS NUM_DIGITAL_PINS // 15 digital (including ATN pin) + 6 analog -#define VERSION_BLINK_PIN LED_BUILTIN -#define PIN_SERIAL1_RX 0 -#define PIN_SERIAL1_TX 1 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 20) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) < 14 + TOTAL_ANALOG_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) // 3, 5, 6, 9 -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) < MAX_SERVOS) // deprecated since v2.4 -#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) // SDA = 18, SCL = 19 -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) // deprecated since v2.4 - - -// Teensy 1.0 -#elif defined(__AVR_AT90USB162__) -#define TOTAL_ANALOG_PINS 0 -#define TOTAL_PINS 21 // 21 digital + no analog -#define VERSION_BLINK_PIN 6 -#define PIN_SERIAL1_RX 2 -#define PIN_SERIAL1_TX 3 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) (0) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) (0) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (0) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Teensy 2.0 -#elif defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY) -#define TOTAL_ANALOG_PINS 12 -#define TOTAL_PINS 25 // 11 digital + 12 analog -#define VERSION_BLINK_PIN 11 -#define PIN_SERIAL1_RX 7 -#define PIN_SERIAL1_TX 8 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 11 && (p) <= 22) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 5 || (p) == 6) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == 7 || (p) == 8) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (((p) < 22) ? 21 - (p) : 11) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Teensy 3.0, 3.1 and 3.2 -#elif defined(__MK20DX128__) || defined(__MK20DX256__) -#define TOTAL_ANALOG_PINS 14 -#define TOTAL_PINS 38 // 24 digital + 10 analog-digital + 4 analog -#define VERSION_BLINK_PIN 13 -#define PIN_SERIAL1_RX 0 -#define PIN_SERIAL1_TX 1 -#define PIN_SERIAL2_RX 9 -#define PIN_SERIAL2_TX 10 -#define PIN_SERIAL3_RX 7 -#define PIN_SERIAL3_TX 8 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 33) -#define IS_PIN_ANALOG(p) (((p) >= 14 && (p) <= 23) || ((p) >= 34 && (p) <= 38)) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) -#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (((p) <= 23) ? (p) - 14 : (p) - 24) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Teensy-LC -#elif defined(__MKL26Z64__) -#define TOTAL_ANALOG_PINS 13 -#define TOTAL_PINS 27 // 27 digital + 13 analog-digital -#define VERSION_BLINK_PIN 13 -#define PIN_SERIAL1_RX 0 -#define PIN_SERIAL1_TX 1 -#define PIN_SERIAL2_RX 9 -#define PIN_SERIAL2_TX 10 -#define PIN_SERIAL3_RX 7 -#define PIN_SERIAL3_TX 8 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) <= 26) -#define IS_PIN_ANALOG(p) ((p) >= 14) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 18 || (p) == 19) -#define IS_PIN_SERIAL(p) (((p) > 6 && (p) < 11) || ((p) == 0 || (p) == 1)) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Teensy++ 1.0 and 2.0 -#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__) -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS 46 // 38 digital + 8 analog -#define VERSION_BLINK_PIN 6 -#define PIN_SERIAL1_RX 2 -#define PIN_SERIAL1_TX 3 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 38 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 0 || (p) == 1) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == 2 || (p) == 3) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 38) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Leonardo -#elif defined(__AVR_ATmega32U4__) -#define TOTAL_ANALOG_PINS 12 -#define TOTAL_PINS 30 // 14 digital + 12 analog + 4 SPI (D14-D17 on ISP header) -#define VERSION_BLINK_PIN 13 -#define PIN_SERIAL1_RX 0 -#define PIN_SERIAL1_TX 1 -#define IS_PIN_DIGITAL(p) ((p) >= 0 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 18 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11 || (p) == 13) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (p) - 18 -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) (p) - - -// Intel Galileo Board (gen 1 and 2) and Intel Edison -#elif defined(ARDUINO_LINUX) -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 20 // 14 digital + 6 analog -#define VERSION_BLINK_PIN 13 -#define PIN_SERIAL1_RX 0 -#define PIN_SERIAL1_TX 1 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 19) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 19) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) (IS_PIN_DIGITAL(p) && (p) - 2 < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == SDA || (p) == SCL) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == 0 || (p) == 1) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// Sanguino -#elif defined(__AVR_ATmega644P__) || defined(__AVR_ATmega644__) -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS 32 // 24 digital + 8 analog -#define VERSION_BLINK_PIN 0 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 24) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// Illuminato -#elif defined(__AVR_ATmega645__) -#define TOTAL_ANALOG_PINS 6 -#define TOTAL_PINS 42 // 36 digital + 6 analog -#define VERSION_BLINK_PIN 13 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) < TOTAL_PINS) -#define IS_PIN_ANALOG(p) ((p) >= 36 && (p) < TOTAL_PINS) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) ((p) >= 0 && (p) < MAX_SERVOS) -#define IS_PIN_I2C(p) ((p) == 4 || (p) == 5) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 36) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - - -// Pic32 chipKIT FubarinoSD -#elif defined(_BOARD_FUBARINO_SD_) -#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 15 -#define TOTAL_PINS NUM_DIGITAL_PINS // 45, All pins can be digital -#define MAX_SERVOS NUM_DIGITAL_PINS -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) 1 -#define IS_PIN_ANALOG(p) ((p) >= 30 && (p) <= 44) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 1 || (p) == 2) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (14 - (p - 30)) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT FubarinoMini -// Note, FubarinoMini analog pin 20 will not function in Firmata as analog input due to limitation in analog mapping -#elif defined(_BOARD_FUBARINO_MINI_) -#define TOTAL_ANALOG_PINS 14 // We have to fake this because of the poor analog pin mapping planning in FubarinoMini -#define TOTAL_PINS NUM_DIGITAL_PINS // 33 -#define MAX_SERVOS NUM_DIGITAL_PINS -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) ((p) != 14 && (p) != 15 && (p) != 31 && (p) != 32) -#define IS_PIN_ANALOG(p) ((p) == 0 || ((p) >= 3 && (p) <= 13)) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 25 || (p) == 26) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (p) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT UNO32 -#elif defined(_BOARD_UNO_) && defined(__PIC32) // NOTE: no _BOARD_UNO32_ to use -#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 -#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital -#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) ((p) >= 2) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT DP32 -#elif defined(_BOARD_DP32_) -#define TOTAL_ANALOG_PINS 15 // Really only has 9, but have to override because of mistake in variant file -#define TOTAL_PINS NUM_DIGITAL_PINS // 19 -#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) (((p) != 1) && ((p) != 4) && ((p) != 5) && ((p) != 15) && ((p) != 16)) -#define IS_PIN_ANALOG(p) ((p) >= 6 && (p) <= 14) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 2 || (p) == 3) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) (p) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT uC32 -#elif defined(_BOARD_UC32_) -#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 12 -#define TOTAL_PINS NUM_DIGITAL_PINS // 47 All pins can be digital -#define MAX_SERVOS NUM_DIGITAL_PINS // All pins can be servo with SoftPWMservo -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) ((p) >= 2) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 45 || (p) == 46) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT WF32 -#elif defined(_BOARD_WF32_) -#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS -#define TOTAL_PINS NUM_DIGITAL_PINS -#define MAX_SERVOS NUM_DIGITAL_PINS -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 49) // Accounts for SD and WiFi dedicated pins -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 14) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT WiFire -#elif defined(_BOARD_WIFIRE_) -#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 14 -#define TOTAL_PINS NUM_DIGITAL_PINS // 71 -#define MAX_SERVOS NUM_DIGITAL_PINS -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) ((p) >= 2 && (p) <= 47) // Accounts for SD and WiFi dedicated pins -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 25) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) <= 25 ? ((p) - 14) : (p) - 36) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT MAX32 -#elif defined(_BOARD_MEGA_) && defined(__PIC32) // NOTE: no _BOARD_MAX32_ to use -#define TOTAL_ANALOG_PINS NUM_ANALOG_PINS // 16 -#define TOTAL_PINS NUM_DIGITAL_PINS // 87 -#define MAX_SERVOS NUM_DIGITAL_PINS -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) ((p) >= 2) -#define IS_PIN_ANALOG(p) ((p) >= 54 && (p) <= 69) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 34 || (p) == 35) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 54) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - - -// Pic32 chipKIT Pi -#elif defined(_BOARD_CHIPKIT_PI_) -#define TOTAL_ANALOG_PINS 16 -#define TOTAL_PINS NUM_DIGITAL_PINS // 19 -#define MAX_SERVOS NUM_DIGITAL_PINS -#define VERSION_BLINK_PIN PIN_LED1 -#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 3) || (((p) >= 8) && ((p) <= 13)) || (((p) >= 14) && ((p) <= 17))) -#define IS_PIN_ANALOG(p) ((p) >= 14 && (p) <= 17) -#define IS_PIN_PWM(p) IS_PIN_DIGITAL(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == 16 || (p) == 17) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) <= 15 ? (p) - 14 : (p) - 12) -//#define PIN_TO_ANALOG(p) (((p) <= 16) ? ((p) - 14) : ((p) - 16)) -#define PIN_TO_PWM(p) (p) -#define PIN_TO_SERVO(p) (p) - -// Pinoccio Scout -// Note: digital pins 9-16 are usable but not labeled on the board numerically. -// SS=9, MOSI=10, MISO=11, SCK=12, RX1=13, TX1=14, SCL=15, SDA=16 -#elif defined(ARDUINO_PINOCCIO) -#define TOTAL_ANALOG_PINS 8 -#define TOTAL_PINS NUM_DIGITAL_PINS // 32 -#define VERSION_BLINK_PIN 23 -#define PIN_SERIAL1_RX 13 -#define PIN_SERIAL1_TX 14 -#define IS_PIN_DIGITAL(p) (((p) >= 2) && ((p) <= 16)) || (((p) >= 24) && ((p) <= 31)) -#define IS_PIN_ANALOG(p) ((p) >= 24 && (p) <= 31) -#define IS_PIN_PWM(p) digitalPinHasPWM(p) -#define IS_PIN_SERVO(p) IS_PIN_DIGITAL(p) -#define IS_PIN_I2C(p) ((p) == SCL || (p) == SDA) -#define IS_PIN_SPI(p) ((p) == SS || (p) == MOSI || (p) == MISO || (p) == SCK) -#define IS_PIN_SERIAL(p) ((p) == 13 || (p) == 14) -#define PIN_TO_DIGITAL(p) (p) -#define PIN_TO_ANALOG(p) ((p) - 24) -#define PIN_TO_PWM(p) PIN_TO_DIGITAL(p) -#define PIN_TO_SERVO(p) ((p) - 2) - -// anything else -#else -#error "Please edit Boards.h with a hardware abstraction for this board" -#endif - -// as long this is not defined for all boards: -#ifndef IS_PIN_SPI -#define IS_PIN_SPI(p) 0 -#endif - -#ifndef IS_PIN_SERIAL -#define IS_PIN_SERIAL(p) 0 -#endif - - -/*============================================================================== - * readPort() - Read an 8 bit port - *============================================================================*/ - -static inline unsigned char readPort(byte, byte) __attribute__((always_inline, unused)); -static inline unsigned char readPort(byte port, byte bitmask) -{ -#if defined(ARDUINO_PINOUT_OPTIMIZE) - if (port == 0) return (PIND & 0xFC) & bitmask; // ignore Rx/Tx 0/1 - if (port == 1) return ((PINB & 0x3F) | ((PINC & 0x03) << 6)) & bitmask; - if (port == 2) return ((PINC & 0x3C) >> 2) & bitmask; - return 0; -#else - unsigned char out = 0, pin = port * 8; - if (IS_PIN_DIGITAL(pin + 0) && (bitmask & 0x01) && digitalRead(PIN_TO_DIGITAL(pin + 0))) out |= 0x01; - if (IS_PIN_DIGITAL(pin + 1) && (bitmask & 0x02) && digitalRead(PIN_TO_DIGITAL(pin + 1))) out |= 0x02; - if (IS_PIN_DIGITAL(pin + 2) && (bitmask & 0x04) && digitalRead(PIN_TO_DIGITAL(pin + 2))) out |= 0x04; - if (IS_PIN_DIGITAL(pin + 3) && (bitmask & 0x08) && digitalRead(PIN_TO_DIGITAL(pin + 3))) out |= 0x08; - if (IS_PIN_DIGITAL(pin + 4) && (bitmask & 0x10) && digitalRead(PIN_TO_DIGITAL(pin + 4))) out |= 0x10; - if (IS_PIN_DIGITAL(pin + 5) && (bitmask & 0x20) && digitalRead(PIN_TO_DIGITAL(pin + 5))) out |= 0x20; - if (IS_PIN_DIGITAL(pin + 6) && (bitmask & 0x40) && digitalRead(PIN_TO_DIGITAL(pin + 6))) out |= 0x40; - if (IS_PIN_DIGITAL(pin + 7) && (bitmask & 0x80) && digitalRead(PIN_TO_DIGITAL(pin + 7))) out |= 0x80; - return out; -#endif -} - -/*============================================================================== - * writePort() - Write an 8 bit port, only touch pins specified by a bitmask - *============================================================================*/ - -static inline unsigned char writePort(byte, byte, byte) __attribute__((always_inline, unused)); -static inline unsigned char writePort(byte port, byte value, byte bitmask) -{ -#if defined(ARDUINO_PINOUT_OPTIMIZE) - if (port == 0) { - bitmask = bitmask & 0xFC; // do not touch Tx & Rx pins - byte valD = value & bitmask; - byte maskD = ~bitmask; - cli(); - PORTD = (PORTD & maskD) | valD; - sei(); - } else if (port == 1) { - byte valB = (value & bitmask) & 0x3F; - byte valC = (value & bitmask) >> 6; - byte maskB = ~(bitmask & 0x3F); - byte maskC = ~((bitmask & 0xC0) >> 6); - cli(); - PORTB = (PORTB & maskB) | valB; - PORTC = (PORTC & maskC) | valC; - sei(); - } else if (port == 2) { - bitmask = bitmask & 0x0F; - byte valC = (value & bitmask) << 2; - byte maskC = ~(bitmask << 2); - cli(); - PORTC = (PORTC & maskC) | valC; - sei(); - } - return 1; -#else - byte pin = port * 8; - if ((bitmask & 0x01)) digitalWrite(PIN_TO_DIGITAL(pin + 0), (value & 0x01)); - if ((bitmask & 0x02)) digitalWrite(PIN_TO_DIGITAL(pin + 1), (value & 0x02)); - if ((bitmask & 0x04)) digitalWrite(PIN_TO_DIGITAL(pin + 2), (value & 0x04)); - if ((bitmask & 0x08)) digitalWrite(PIN_TO_DIGITAL(pin + 3), (value & 0x08)); - if ((bitmask & 0x10)) digitalWrite(PIN_TO_DIGITAL(pin + 4), (value & 0x10)); - if ((bitmask & 0x20)) digitalWrite(PIN_TO_DIGITAL(pin + 5), (value & 0x20)); - if ((bitmask & 0x40)) digitalWrite(PIN_TO_DIGITAL(pin + 6), (value & 0x40)); - if ((bitmask & 0x80)) digitalWrite(PIN_TO_DIGITAL(pin + 7), (value & 0x80)); - return 1; -#endif -} - - - - -#ifndef TOTAL_PORTS -#define TOTAL_PORTS ((TOTAL_PINS + 7) / 8) -#endif - - -#endif /* Firmata_Boards_h */ diff --git a/resources/arduino_files/libraries/Firmata/Firmata.cpp b/resources/arduino_files/libraries/Firmata/Firmata.cpp deleted file mode 100644 index 5e5d4b799..000000000 --- a/resources/arduino_files/libraries/Firmata/Firmata.cpp +++ /dev/null @@ -1,668 +0,0 @@ -/* - Firmata.cpp - Firmata library v2.5.2 - 2016-2-15 - Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. -*/ - -//****************************************************************************** -//* Includes -//****************************************************************************** - -#include "Firmata.h" -#include "HardwareSerial.h" - -extern "C" { -#include -#include -} - -//****************************************************************************** -//* Support Functions -//****************************************************************************** - -/** - * Split a 16-bit byte into two 7-bit values and write each value. - * @param value The 16-bit value to be split and written separately. - */ -void FirmataClass::sendValueAsTwo7bitBytes(int value) -{ - FirmataStream->write(value & B01111111); // LSB - FirmataStream->write(value >> 7 & B01111111); // MSB -} - -/** - * A helper method to write the beginning of a Sysex message transmission. - */ -void FirmataClass::startSysex(void) -{ - FirmataStream->write(START_SYSEX); -} - -/** - * A helper method to write the end of a Sysex message transmission. - */ -void FirmataClass::endSysex(void) -{ - FirmataStream->write(END_SYSEX); -} - -//****************************************************************************** -//* Constructors -//****************************************************************************** - -/** - * The Firmata class. - * An instance named "Firmata" is created automatically for the user. - */ -FirmataClass::FirmataClass() -{ - firmwareVersionCount = 0; - firmwareVersionVector = 0; - systemReset(); -} - -//****************************************************************************** -//* Public Methods -//****************************************************************************** - -/** - * Initialize the default Serial transport at the default baud of 57600. - */ -void FirmataClass::begin(void) -{ - begin(57600); -} - -/** - * Initialize the default Serial transport and override the default baud. - * Sends the protocol version to the host application followed by the firmware version and name. - * blinkVersion is also called. To skip the call to blinkVersion, call Firmata.disableBlinkVersion() - * before calling Firmata.begin(baud). - * @param speed The baud to use. 57600 baud is the default value. - */ -void FirmataClass::begin(long speed) -{ - Serial.begin(speed); - FirmataStream = &Serial; - blinkVersion(); - printVersion(); // send the protocol version - printFirmwareVersion(); // send the firmware name and version -} - -/** - * Reassign the Firmata stream transport. - * @param s A reference to the Stream transport object. This can be any type of - * transport that implements the Stream interface. Some examples include Ethernet, WiFi - * and other UARTs on the board (Serial1, Serial2, etc). - */ -void FirmataClass::begin(Stream &s) -{ - FirmataStream = &s; - // do not call blinkVersion() here because some hardware such as the - // Ethernet shield use pin 13 - printVersion(); - printFirmwareVersion(); -} - -/** - * Send the Firmata protocol version to the Firmata host application. - */ -void FirmataClass::printVersion(void) -{ - FirmataStream->write(REPORT_VERSION); - FirmataStream->write(FIRMATA_PROTOCOL_MAJOR_VERSION); - FirmataStream->write(FIRMATA_PROTOCOL_MINOR_VERSION); -} - -/** - * Blink the Firmata protocol version to the onboard LEDs (if the board has an onboard LED). - * If VERSION_BLINK_PIN is not defined in Boards.h for a particular board, then this method - * does nothing. - * The first series of flashes indicates the firmware major version (2 flashes = 2). - * The second series of flashes indicates the firmware minor version (5 flashes = 5). - */ -void FirmataClass::blinkVersion(void) -{ -#if defined(VERSION_BLINK_PIN) - if (blinkVersionDisabled) return; - // flash the pin with the protocol version - pinMode(VERSION_BLINK_PIN, OUTPUT); - strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MAJOR_VERSION, 40, 210); - delay(250); - strobeBlinkPin(VERSION_BLINK_PIN, FIRMATA_FIRMWARE_MINOR_VERSION, 40, 210); - delay(125); -#endif -} - -/** - * Provides a means to disable the version blink sequence on the onboard LED, trimming startup - * time by a couple of seconds. - * Call this before Firmata.begin(). It only applies when using the default Serial transport. - */ -void FirmataClass::disableBlinkVersion() -{ - blinkVersionDisabled = true; -} - -/** - * Sends the firmware name and version to the Firmata host application. The major and minor version - * numbers are the first 2 bytes in the message. The following bytes are the characters of the - * firmware name. - */ -void FirmataClass::printFirmwareVersion(void) -{ - byte i; - - if (firmwareVersionCount) { // make sure that the name has been set before reporting - startSysex(); - FirmataStream->write(REPORT_FIRMWARE); - FirmataStream->write(firmwareVersionVector[0]); // major version number - FirmataStream->write(firmwareVersionVector[1]); // minor version number - for (i = 2; i < firmwareVersionCount; ++i) { - sendValueAsTwo7bitBytes(firmwareVersionVector[i]); - } - endSysex(); - } -} - -/** - * Sets the name and version of the firmware. This is not the same version as the Firmata protocol - * (although at times the firmware version and protocol version may be the same number). - * @param name A pointer to the name char array - * @param major The major version number - * @param minor The minor version number - */ -void FirmataClass::setFirmwareNameAndVersion(const char *name, byte major, byte minor) -{ - const char *firmwareName; - const char *extension; - - // parse out ".cpp" and "applet/" that comes from using __FILE__ - extension = strstr(name, ".cpp"); - firmwareName = strrchr(name, '/'); - - if (!firmwareName) { - // windows - firmwareName = strrchr(name, '\\'); - } - if (!firmwareName) { - // user passed firmware name - firmwareName = name; - } else { - firmwareName ++; - } - - if (!extension) { - firmwareVersionCount = strlen(firmwareName) + 2; - } else { - firmwareVersionCount = extension - firmwareName + 2; - } - - // in case anyone calls setFirmwareNameAndVersion more than once - free(firmwareVersionVector); - - firmwareVersionVector = (byte *) malloc(firmwareVersionCount + 1); - firmwareVersionVector[firmwareVersionCount] = 0; - firmwareVersionVector[0] = major; - firmwareVersionVector[1] = minor; - strncpy((char *)firmwareVersionVector + 2, firmwareName, firmwareVersionCount - 2); -} - -//------------------------------------------------------------------------------ -// Serial Receive Handling - -/** - * A wrapper for Stream::available() - * @return The number of bytes remaining in the input stream buffer. - */ -int FirmataClass::available(void) -{ - return FirmataStream->available(); -} - -/** - * Process incoming sysex messages. Handles REPORT_FIRMWARE and STRING_DATA internally. - * Calls callback function for STRING_DATA and all other sysex messages. - * @private - */ -void FirmataClass::processSysexMessage(void) -{ - switch (storedInputData[0]) { //first byte in buffer is command - case REPORT_FIRMWARE: - printFirmwareVersion(); - break; - case STRING_DATA: - if (currentStringCallback) { - byte bufferLength = (sysexBytesRead - 1) / 2; - byte i = 1; - byte j = 0; - while (j < bufferLength) { - // The string length will only be at most half the size of the - // stored input buffer so we can decode the string within the buffer. - storedInputData[j] = storedInputData[i]; - i++; - storedInputData[j] += (storedInputData[i] << 7); - i++; - j++; - } - // Make sure string is null terminated. This may be the case for data - // coming from client libraries in languages that don't null terminate - // strings. - if (storedInputData[j - 1] != '\0') { - storedInputData[j] = '\0'; - } - (*currentStringCallback)((char *)&storedInputData[0]); - } - break; - default: - if (currentSysexCallback) - (*currentSysexCallback)(storedInputData[0], sysexBytesRead - 1, storedInputData + 1); - } -} - -/** - * Read a single int from the input stream. If the value is not = -1, pass it on to parse(byte) - */ -void FirmataClass::processInput(void) -{ - int inputData = FirmataStream->read(); // this is 'int' to handle -1 when no data - if (inputData != -1) { - parse(inputData); - } -} - -/** - * Parse data from the input stream. - * @param inputData A single byte to be added to the parser. - */ -void FirmataClass::parse(byte inputData) -{ - int command; - - if (parsingSysex) { - if (inputData == END_SYSEX) { - //stop sysex byte - parsingSysex = false; - //fire off handler function - processSysexMessage(); - } else { - //normal data byte - add to buffer - storedInputData[sysexBytesRead] = inputData; - sysexBytesRead++; - } - } else if ( (waitForData > 0) && (inputData < 128) ) { - waitForData--; - storedInputData[waitForData] = inputData; - if ( (waitForData == 0) && executeMultiByteCommand ) { // got the whole message - switch (executeMultiByteCommand) { - case ANALOG_MESSAGE: - if (currentAnalogCallback) { - (*currentAnalogCallback)(multiByteChannel, - (storedInputData[0] << 7) - + storedInputData[1]); - } - break; - case DIGITAL_MESSAGE: - if (currentDigitalCallback) { - (*currentDigitalCallback)(multiByteChannel, - (storedInputData[0] << 7) - + storedInputData[1]); - } - break; - case SET_PIN_MODE: - if (currentPinModeCallback) - (*currentPinModeCallback)(storedInputData[1], storedInputData[0]); - break; - case SET_DIGITAL_PIN_VALUE: - if (currentPinValueCallback) - (*currentPinValueCallback)(storedInputData[1], storedInputData[0]); - break; - case REPORT_ANALOG: - if (currentReportAnalogCallback) - (*currentReportAnalogCallback)(multiByteChannel, storedInputData[0]); - break; - case REPORT_DIGITAL: - if (currentReportDigitalCallback) - (*currentReportDigitalCallback)(multiByteChannel, storedInputData[0]); - break; - } - executeMultiByteCommand = 0; - } - } else { - // remove channel info from command byte if less than 0xF0 - if (inputData < 0xF0) { - command = inputData & 0xF0; - multiByteChannel = inputData & 0x0F; - } else { - command = inputData; - // commands in the 0xF* range don't use channel data - } - switch (command) { - case ANALOG_MESSAGE: - case DIGITAL_MESSAGE: - case SET_PIN_MODE: - case SET_DIGITAL_PIN_VALUE: - waitForData = 2; // two data bytes needed - executeMultiByteCommand = command; - break; - case REPORT_ANALOG: - case REPORT_DIGITAL: - waitForData = 1; // one data byte needed - executeMultiByteCommand = command; - break; - case START_SYSEX: - parsingSysex = true; - sysexBytesRead = 0; - break; - case SYSTEM_RESET: - systemReset(); - break; - case REPORT_VERSION: - Firmata.printVersion(); - break; - } - } -} - -/** - * @return Returns true if the parser is actively parsing data. - */ -boolean FirmataClass::isParsingMessage(void) -{ - return (waitForData > 0 || parsingSysex); -} - -//------------------------------------------------------------------------------ -// Output Stream Handling - -/** - * Send an analog message to the Firmata host application. The range of pins is limited to [0..15] - * when using the ANALOG_MESSAGE. The maximum value of the ANALOG_MESSAGE is limited to 14 bits - * (16384). To increase the pin range or value, see the documentation for the EXTENDED_ANALOG - * message. - * @param pin The analog pin to send the value of (limited to pins 0 - 15). - * @param value The value of the analog pin (0 - 1024 for 10-bit analog, 0 - 4096 for 12-bit, etc). - * The maximum value is 14-bits (16384). - */ -void FirmataClass::sendAnalog(byte pin, int value) -{ - // pin can only be 0-15, so chop higher bits - FirmataStream->write(ANALOG_MESSAGE | (pin & 0xF)); - sendValueAsTwo7bitBytes(value); -} - -/* (intentionally left out asterix here) - * STUB - NOT IMPLEMENTED - * Send a single digital pin value to the Firmata host application. - * @param pin The digital pin to send the value of. - * @param value The value of the pin. - */ -void FirmataClass::sendDigital(byte pin, int value) -{ - /* TODO add single pin digital messages to the protocol, this needs to - * track the last digital data sent so that it can be sure to change just - * one bit in the packet. This is complicated by the fact that the - * numbering of the pins will probably differ on Arduino, Wiring, and - * other boards. - */ - - // TODO: the digital message should not be sent on the serial port every - // time sendDigital() is called. Instead, it should add it to an int - // which will be sent on a schedule. If a pin changes more than once - // before the digital message is sent on the serial port, it should send a - // digital message for each change. - - // if(value == 0) - // sendDigitalPortPair(); -} - - -/** - * Send an 8-bit port in a single digital message (protocol v2 and later). - * Send 14-bits in a single digital message (protocol v1). - * @param portNumber The port number to send. Note that this is not the same as a "port" on the - * physical microcontroller. Ports are defined in order per every 8 pins in ascending order - * of the Arduino digital pin numbering scheme. Port 0 = pins D0 - D7, port 1 = pins D8 - D15, etc. - * @param portData The value of the port. The value of each pin in the port is represented by a bit. - */ -void FirmataClass::sendDigitalPort(byte portNumber, int portData) -{ - FirmataStream->write(DIGITAL_MESSAGE | (portNumber & 0xF)); - FirmataStream->write((byte)portData % 128); // Tx bits 0-6 (protocol v1 and higher) - FirmataStream->write(portData >> 7); // Tx bits 7-13 (bit 7 only for protocol v2 and higher) -} - -/** - * Send a sysex message where all values after the command byte are packet as 2 7-bit bytes - * (this is not always the case so this function is not always used to send sysex messages). - * @param command The sysex command byte. - * @param bytec The number of data bytes in the message (excludes start, command and end bytes). - * @param bytev A pointer to the array of data bytes to send in the message. - */ -void FirmataClass::sendSysex(byte command, byte bytec, byte *bytev) -{ - byte i; - startSysex(); - FirmataStream->write(command); - for (i = 0; i < bytec; i++) { - sendValueAsTwo7bitBytes(bytev[i]); - } - endSysex(); -} - -/** - * Send a string to the Firmata host application. - * @param command Must be STRING_DATA - * @param string A pointer to the char string - */ -void FirmataClass::sendString(byte command, const char *string) -{ - if (command == STRING_DATA) { - sendSysex(command, strlen(string), (byte *)string); - } -} - -/** - * Send a string to the Firmata host application. - * @param string A pointer to the char string - */ -void FirmataClass::sendString(const char *string) -{ - sendString(STRING_DATA, string); -} - -/** - * A wrapper for Stream::available(). - * Write a single byte to the output stream. - * @param c The byte to be written. - */ -void FirmataClass::write(byte c) -{ - FirmataStream->write(c); -} - -/** - * Attach a generic sysex callback function to a command (options are: ANALOG_MESSAGE, - * DIGITAL_MESSAGE, REPORT_ANALOG, REPORT DIGITAL, SET_PIN_MODE and SET_DIGITAL_PIN_VALUE). - * @param command The ID of the command to attach a callback function to. - * @param newFunction A reference to the callback function to attach. - */ -void FirmataClass::attach(byte command, callbackFunction newFunction) -{ - switch (command) { - case ANALOG_MESSAGE: currentAnalogCallback = newFunction; break; - case DIGITAL_MESSAGE: currentDigitalCallback = newFunction; break; - case REPORT_ANALOG: currentReportAnalogCallback = newFunction; break; - case REPORT_DIGITAL: currentReportDigitalCallback = newFunction; break; - case SET_PIN_MODE: currentPinModeCallback = newFunction; break; - case SET_DIGITAL_PIN_VALUE: currentPinValueCallback = newFunction; break; - } -} - -/** - * Attach a callback function for the SYSTEM_RESET command. - * @param command Must be set to SYSTEM_RESET or it will be ignored. - * @param newFunction A reference to the system reset callback function to attach. - */ -void FirmataClass::attach(byte command, systemResetCallbackFunction newFunction) -{ - switch (command) { - case SYSTEM_RESET: currentSystemResetCallback = newFunction; break; - } -} - -/** - * Attach a callback function for the STRING_DATA command. - * @param command Must be set to STRING_DATA or it will be ignored. - * @param newFunction A reference to the string callback function to attach. - */ -void FirmataClass::attach(byte command, stringCallbackFunction newFunction) -{ - switch (command) { - case STRING_DATA: currentStringCallback = newFunction; break; - } -} - -/** - * Attach a generic sysex callback function to sysex command. - * @param command The ID of the command to attach a callback function to. - * @param newFunction A reference to the sysex callback function to attach. - */ -void FirmataClass::attach(byte command, sysexCallbackFunction newFunction) -{ - currentSysexCallback = newFunction; -} - -/** - * Detach a callback function for a specified command (such as SYSTEM_RESET, STRING_DATA, - * ANALOG_MESSAGE, DIGITAL_MESSAGE, etc). - * @param command The ID of the command to detatch the callback function from. - */ -void FirmataClass::detach(byte command) -{ - switch (command) { - case SYSTEM_RESET: currentSystemResetCallback = NULL; break; - case STRING_DATA: currentStringCallback = NULL; break; - case START_SYSEX: currentSysexCallback = NULL; break; - default: - attach(command, (callbackFunction)NULL); - } -} - -/** - * @param pin The pin to get the configuration of. - * @return The configuration of the specified pin. - */ -byte FirmataClass::getPinMode(byte pin) -{ - return pinConfig[pin]; -} - -/** - * Set the pin mode/configuration. The pin configuration (or mode) in Firmata represents the - * current function of the pin. Examples are digital input or output, analog input, pwm, i2c, - * serial (uart), etc. - * @param pin The pin to configure. - * @param config The configuration value for the specified pin. - */ -void FirmataClass::setPinMode(byte pin, byte config) -{ - if (pinConfig[pin] == PIN_MODE_IGNORE) - return; - - pinConfig[pin] = config; -} - -/** - * @param pin The pin to get the state of. - * @return The state of the specified pin. - */ -int FirmataClass::getPinState(byte pin) -{ - return pinState[pin]; -} - -/** - * Set the pin state. The pin state of an output pin is the pin value. The state of an - * input pin is 0, unless the pin has it's internal pull up resistor enabled, then the value is 1. - * @param pin The pin to set the state of - * @param state Set the state of the specified pin - */ -void FirmataClass::setPinState(byte pin, int state) -{ - pinState[pin] = state; -} - -// sysex callbacks -/* - * this is too complicated for analogReceive, but maybe for Sysex? - void FirmataClass::attachSysex(sysexFunction newFunction) - { - byte i; - byte tmpCount = analogReceiveFunctionCount; - analogReceiveFunction* tmpArray = analogReceiveFunctionArray; - analogReceiveFunctionCount++; - analogReceiveFunctionArray = (analogReceiveFunction*) calloc(analogReceiveFunctionCount, sizeof(analogReceiveFunction)); - for(i = 0; i < tmpCount; i++) { - analogReceiveFunctionArray[i] = tmpArray[i]; - } - analogReceiveFunctionArray[tmpCount] = newFunction; - free(tmpArray); - } -*/ - -//****************************************************************************** -//* Private Methods -//****************************************************************************** - -/** - * Resets the system state upon a SYSTEM_RESET message from the host software. - * @private - */ -void FirmataClass::systemReset(void) -{ - byte i; - - waitForData = 0; // this flag says the next serial input will be data - executeMultiByteCommand = 0; // execute this after getting multi-byte data - multiByteChannel = 0; // channel data for multiByteCommands - - for (i = 0; i < MAX_DATA_BYTES; i++) { - storedInputData[i] = 0; - } - - parsingSysex = false; - sysexBytesRead = 0; - - if (currentSystemResetCallback) - (*currentSystemResetCallback)(); -} - -/** - * Flashing the pin for the version number - * @private - * @param pin The pin the LED is attached to. - * @param count The number of times to flash the LED. - * @param onInterval The number of milliseconds for the LED to be ON during each interval. - * @param offInterval The number of milliseconds for the LED to be OFF during each interval. - */ -void FirmataClass::strobeBlinkPin(byte pin, int count, int onInterval, int offInterval) -{ - byte i; - for (i = 0; i < count; i++) { - delay(offInterval); - digitalWrite(pin, HIGH); - delay(onInterval); - digitalWrite(pin, LOW); - } -} - -// make one instance for the user to use -FirmataClass Firmata; diff --git a/resources/arduino_files/libraries/Firmata/Firmata.h b/resources/arduino_files/libraries/Firmata/Firmata.h deleted file mode 100644 index 569bdf7e4..000000000 --- a/resources/arduino_files/libraries/Firmata/Firmata.h +++ /dev/null @@ -1,224 +0,0 @@ -/* - Firmata.h - Firmata library v2.5.2 - 2016-2-15 - Copyright (c) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2009-2015 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. -*/ - -#ifndef Firmata_h -#define Firmata_h - -#include "Boards.h" /* Hardware Abstraction Layer + Wiring/Arduino */ - -/* Version numbers for the protocol. The protocol is still changing, so these - * version numbers are important. - * Query using the REPORT_VERSION message. - */ -#define FIRMATA_PROTOCOL_MAJOR_VERSION 2 // for non-compatible changes -#define FIRMATA_PROTOCOL_MINOR_VERSION 5 // for backwards compatible changes -#define FIRMATA_PROTOCOL_BUGFIX_VERSION 1 // for bugfix releases - -/* Version numbers for the Firmata library. - * The firmware version will not always equal the protocol version going forward. - * Query using the REPORT_FIRMWARE message. - */ -#define FIRMATA_FIRMWARE_MAJOR_VERSION 2 -#define FIRMATA_FIRMWARE_MINOR_VERSION 5 -#define FIRMATA_FIRMWARE_BUGFIX_VERSION 2 - -/* DEPRECATED as of Firmata v2.5.1. As of 2.5.1 there are separate version numbers for - * the protocol version and the firmware version. - */ -#define FIRMATA_MAJOR_VERSION 2 // same as FIRMATA_PROTOCOL_MAJOR_VERSION -#define FIRMATA_MINOR_VERSION 5 // same as FIRMATA_PROTOCOL_MINOR_VERSION -#define FIRMATA_BUGFIX_VERSION 1 // same as FIRMATA_PROTOCOL_BUGFIX_VERSION - -#define MAX_DATA_BYTES 64 // max number of data bytes in incoming messages - -// Arduino 101 also defines SET_PIN_MODE as a macro in scss_registers.h -#ifdef SET_PIN_MODE -#undef SET_PIN_MODE -#endif - -// message command bytes (128-255/0x80-0xFF) -#define DIGITAL_MESSAGE 0x90 // send data for a digital port (collection of 8 pins) -#define ANALOG_MESSAGE 0xE0 // send data for an analog pin (or PWM) -#define REPORT_ANALOG 0xC0 // enable analog input by pin # -#define REPORT_DIGITAL 0xD0 // enable digital input by port pair -// -#define SET_PIN_MODE 0xF4 // set a pin to INPUT/OUTPUT/PWM/etc -#define SET_DIGITAL_PIN_VALUE 0xF5 // set value of an individual digital pin -// -#define REPORT_VERSION 0xF9 // report protocol version -#define SYSTEM_RESET 0xFF // reset from MIDI -// -#define START_SYSEX 0xF0 // start a MIDI Sysex message -#define END_SYSEX 0xF7 // end a MIDI Sysex message - -// extended command set using sysex (0-127/0x00-0x7F) -/* 0x00-0x0F reserved for user-defined commands */ -#define SERIAL_MESSAGE 0x60 // communicate with serial devices, including other boards -#define ENCODER_DATA 0x61 // reply with encoders current positions -#define SERVO_CONFIG 0x70 // set max angle, minPulse, maxPulse, freq -#define STRING_DATA 0x71 // a string message with 14-bits per char -#define STEPPER_DATA 0x72 // control a stepper motor -#define ONEWIRE_DATA 0x73 // send an OneWire read/write/reset/select/skip/search request -#define SHIFT_DATA 0x75 // a bitstream to/from a shift register -#define I2C_REQUEST 0x76 // send an I2C read/write request -#define I2C_REPLY 0x77 // a reply to an I2C read request -#define I2C_CONFIG 0x78 // config I2C settings such as delay times and power pins -#define EXTENDED_ANALOG 0x6F // analog write (PWM, Servo, etc) to any pin -#define PIN_STATE_QUERY 0x6D // ask for a pin's current mode and value -#define PIN_STATE_RESPONSE 0x6E // reply with pin's current mode and value -#define CAPABILITY_QUERY 0x6B // ask for supported modes and resolution of all pins -#define CAPABILITY_RESPONSE 0x6C // reply with supported modes and resolution -#define ANALOG_MAPPING_QUERY 0x69 // ask for mapping of analog to pin numbers -#define ANALOG_MAPPING_RESPONSE 0x6A // reply with mapping info -#define REPORT_FIRMWARE 0x79 // report name and version of the firmware -#define SAMPLING_INTERVAL 0x7A // set the poll rate of the main loop -#define SCHEDULER_DATA 0x7B // send a createtask/deletetask/addtotask/schedule/querytasks/querytask request to the scheduler -#define SYSEX_NON_REALTIME 0x7E // MIDI Reserved for non-realtime messages -#define SYSEX_REALTIME 0x7F // MIDI Reserved for realtime messages -// these are DEPRECATED to make the naming more consistent -#define FIRMATA_STRING 0x71 // same as STRING_DATA -#define SYSEX_I2C_REQUEST 0x76 // same as I2C_REQUEST -#define SYSEX_I2C_REPLY 0x77 // same as I2C_REPLY -#define SYSEX_SAMPLING_INTERVAL 0x7A // same as SAMPLING_INTERVAL - -// pin modes -//#define INPUT 0x00 // defined in Arduino.h -//#define OUTPUT 0x01 // defined in Arduino.h -#define PIN_MODE_ANALOG 0x02 // analog pin in analogInput mode -#define PIN_MODE_PWM 0x03 // digital pin in PWM output mode -#define PIN_MODE_SERVO 0x04 // digital pin in Servo output mode -#define PIN_MODE_SHIFT 0x05 // shiftIn/shiftOut mode -#define PIN_MODE_I2C 0x06 // pin included in I2C setup -#define PIN_MODE_ONEWIRE 0x07 // pin configured for 1-wire -#define PIN_MODE_STEPPER 0x08 // pin configured for stepper motor -#define PIN_MODE_ENCODER 0x09 // pin configured for rotary encoders -#define PIN_MODE_SERIAL 0x0A // pin configured for serial communication -#define PIN_MODE_PULLUP 0x0B // enable internal pull-up resistor for pin -#define PIN_MODE_IGNORE 0x7F // pin configured to be ignored by digitalWrite and capabilityResponse -#define TOTAL_PIN_MODES 13 -// DEPRECATED as of Firmata v2.5 -#define ANALOG 0x02 // same as PIN_MODE_ANALOG -#define PWM 0x03 // same as PIN_MODE_PWM -#define SERVO 0x04 // same as PIN_MODE_SERVO -#define SHIFT 0x05 // same as PIN_MODE_SHIFT -#define I2C 0x06 // same as PIN_MODE_I2C -#define ONEWIRE 0x07 // same as PIN_MODE_ONEWIRE -#define STEPPER 0x08 // same as PIN_MODE_STEPPER -#define ENCODER 0x09 // same as PIN_MODE_ENCODER -#define IGNORE 0x7F // same as PIN_MODE_IGNORE - -extern "C" { - // callback function types - typedef void (*callbackFunction)(byte, int); - typedef void (*systemResetCallbackFunction)(void); - typedef void (*stringCallbackFunction)(char *); - typedef void (*sysexCallbackFunction)(byte command, byte argc, byte *argv); -} - -// TODO make it a subclass of a generic Serial/Stream base class -class FirmataClass -{ - public: - FirmataClass(); - /* Arduino constructors */ - void begin(); - void begin(long); - void begin(Stream &s); - /* querying functions */ - void printVersion(void); - void blinkVersion(void); - void printFirmwareVersion(void); - //void setFirmwareVersion(byte major, byte minor); // see macro below - void setFirmwareNameAndVersion(const char *name, byte major, byte minor); - void disableBlinkVersion(); - /* serial receive handling */ - int available(void); - void processInput(void); - void parse(unsigned char value); - boolean isParsingMessage(void); - /* serial send handling */ - void sendAnalog(byte pin, int value); - void sendDigital(byte pin, int value); // TODO implement this - void sendDigitalPort(byte portNumber, int portData); - void sendString(const char *string); - void sendString(byte command, const char *string); - void sendSysex(byte command, byte bytec, byte *bytev); - void write(byte c); - /* attach & detach callback functions to messages */ - void attach(byte command, callbackFunction newFunction); - void attach(byte command, systemResetCallbackFunction newFunction); - void attach(byte command, stringCallbackFunction newFunction); - void attach(byte command, sysexCallbackFunction newFunction); - void detach(byte command); - - /* access pin state and config */ - byte getPinMode(byte pin); - void setPinMode(byte pin, byte config); - /* access pin state */ - int getPinState(byte pin); - void setPinState(byte pin, int state); - - /* utility methods */ - void sendValueAsTwo7bitBytes(int value); - void startSysex(void); - void endSysex(void); - - private: - Stream *FirmataStream; - /* firmware name and version */ - byte firmwareVersionCount; - byte *firmwareVersionVector; - /* input message handling */ - byte waitForData; // this flag says the next serial input will be data - byte executeMultiByteCommand; // execute this after getting multi-byte data - byte multiByteChannel; // channel data for multiByteCommands - byte storedInputData[MAX_DATA_BYTES]; // multi-byte data - /* sysex */ - boolean parsingSysex; - int sysexBytesRead; - /* pin configuration */ - byte pinConfig[TOTAL_PINS]; - int pinState[TOTAL_PINS]; - - /* callback functions */ - callbackFunction currentAnalogCallback; - callbackFunction currentDigitalCallback; - callbackFunction currentReportAnalogCallback; - callbackFunction currentReportDigitalCallback; - callbackFunction currentPinModeCallback; - callbackFunction currentPinValueCallback; - systemResetCallbackFunction currentSystemResetCallback; - stringCallbackFunction currentStringCallback; - sysexCallbackFunction currentSysexCallback; - - boolean blinkVersionDisabled = false; - - /* private methods ------------------------------ */ - void processSysexMessage(void); - void systemReset(void); - void strobeBlinkPin(byte pin, int count, int onInterval, int offInterval); -}; - -extern FirmataClass Firmata; - -/*============================================================================== - * MACROS - *============================================================================*/ - -/* shortcut for setFirmwareNameAndVersion() that uses __FILE__ to set the - * firmware name. It needs to be a macro so that __FILE__ is included in the - * firmware source file rather than the library source file. - */ -#define setFirmwareVersion(x, y) setFirmwareNameAndVersion(__FILE__, x, y) - -#endif /* Firmata_h */ diff --git a/resources/arduino_files/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino deleted file mode 100644 index 7cfcd60c3..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/AllInputsFirmata/AllInputsFirmata.ino +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* - * This firmware reads all inputs and sends them as fast as it can. It was - * inspired by the ease-of-use of the Arduino2Max program. - * - * This example code is in the public domain. - */ -#include - -byte pin; - -int analogValue; -int previousAnalogValues[TOTAL_ANALOG_PINS]; - -byte portStatus[TOTAL_PORTS]; // each bit: 1=pin is digital input, 0=other/ignore -byte previousPINs[TOTAL_PORTS]; - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -/* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you - get long, random delays. So only read analogs every 20ms or so */ -int samplingInterval = 19; // how often to run the main loop (in ms) - -void sendPort(byte portNumber, byte portValue) -{ - portValue = portValue & portStatus[portNumber]; - if (previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -void setup() -{ - byte i, port, status; - - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - - for (pin = 0; pin < TOTAL_PINS; pin++) { - if IS_PIN_DIGITAL(pin) pinMode(PIN_TO_DIGITAL(pin), INPUT); - } - - for (port = 0; port < TOTAL_PORTS; port++) { - status = 0; - for (i = 0; i < 8; i++) { - if (IS_PIN_DIGITAL(port * 8 + i)) status |= (1 << i); - } - portStatus[port] = status; - } - - Firmata.begin(57600); -} - -void loop() -{ - byte i; - - for (i = 0; i < TOTAL_PORTS; i++) { - sendPort(i, readPort(i, 0xff)); - } - /* make sure that the FTDI buffer doesn't go over 60 bytes, otherwise you - get long, random delays. So only read analogs every 20ms or so */ - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - while (Firmata.available()) { - Firmata.processInput(); - } - for (pin = 0; pin < TOTAL_ANALOG_PINS; pin++) { - analogValue = analogRead(pin); - if (analogValue != previousAnalogValues[pin]) { - Firmata.sendAnalog(pin, analogValue); - previousAnalogValues[pin] = analogValue; - } - } - } -} - - diff --git a/resources/arduino_files/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino deleted file mode 100644 index 8373f88dd..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/AnalogFirmata/AnalogFirmata.ino +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* This firmware supports as many analog ports as possible, all analog inputs, - * four PWM outputs, and two with servo support. - * - * This example code is in the public domain. - */ -#include -#include - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* servos */ -Servo servo9, servo10; // one instance per pin -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting -int analogPin = 0; // counter for reading analog pins -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis - - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void analogWriteCallback(byte pin, int value) -{ - switch (pin) { - case 9: servo9.write(value); break; - case 10: servo10.write(value); break; - case 3: - case 5: - case 6: - case 11: // PWM pins - analogWrite(pin, value); - break; - } -} -// ----------------------------------------------------------------------------- -// sets bits in a bit array (int) to toggle the reporting of the analogIns -void reportAnalogCallback(byte pin, int value) -{ - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << pin); - } - else { // everything but 0 enables reporting of that pin - analogInputsToReport = analogInputsToReport | (1 << pin); - } - // TODO: save status to EEPROM here, if changed -} - -/*============================================================================== - * SETUP() - *============================================================================*/ -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - - servo9.attach(9); - servo10.attach(10); - Firmata.begin(57600); -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - while (Firmata.available()) - Firmata.processInput(); - currentMillis = millis(); - if (currentMillis - previousMillis > 20) { - previousMillis += 20; // run this every 20ms - for (analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) { - if ( analogInputsToReport & (1 << analogPin) ) - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } -} - diff --git a/resources/arduino_files/libraries/Firmata/examples/EchoString/EchoString.ino b/resources/arduino_files/libraries/Firmata/examples/EchoString/EchoString.ino deleted file mode 100644 index 9849806a3..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/EchoString/EchoString.ino +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* This sketch accepts strings and raw sysex messages and echos them back. - * - * This example code is in the public domain. - */ -#include - -void stringCallback(char *myString) -{ - Firmata.sendString(myString); -} - - -void sysexCallback(byte command, byte argc, byte *argv) -{ - Firmata.sendSysex(command, argc, argv); -} - -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - Firmata.attach(STRING_DATA, stringCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.begin(57600); -} - -void loop() -{ - while (Firmata.available()) { - Firmata.processInput(); - } -} - - diff --git a/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino deleted file mode 100644 index 62dd54ea3..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/OldStandardFirmata/OldStandardFirmata.ino +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - */ - -/* - * This is an old version of StandardFirmata (v2.0). It is kept here because - * its the last version that works on an ATMEGA8 chip. Also, it can be used - * for host software that has not been updated to a newer version of the - * protocol. It also uses the old baud rate of 115200 rather than 57600. - */ - -#include -#include - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting -int analogPin = 0; // counter for reading analog pins - -/* digital pins */ -byte reportPINs[TOTAL_PORTS]; // PIN == input port -byte previousPINs[TOTAL_PORTS]; // PIN == input port -byte pinStatus[TOTAL_PINS]; // store pin status, default OUTPUT -byte portStatus[TOTAL_PORTS]; - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis - - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void outputPort(byte portNumber, byte portValue) -{ - portValue = portValue & ~ portStatus[portNumber]; - if (previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - Firmata.sendDigitalPort(portNumber, portValue); - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Serial output queue using Serial.print() */ -void checkDigitalInputs(void) -{ - byte i, tmp; - for (i = 0; i < TOTAL_PORTS; i++) { - if (reportPINs[i]) { - switch (i) { - case 0: outputPort(0, PIND & ~ B00000011); break; // ignore Rx/Tx 0/1 - case 1: outputPort(1, PINB); break; - case 2: outputPort(2, PINC); break; - } - } - } -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) { - byte port = 0; - byte offset = 0; - - if (pin < 8) { - port = 0; - offset = 0; - } else if (pin < 14) { - port = 1; - offset = 8; - } else if (pin < 22) { - port = 2; - offset = 14; - } - - if (pin > 1) { // ignore RxTx (pins 0 and 1) - pinStatus[pin] = mode; - switch (mode) { - case INPUT: - pinMode(pin, INPUT); - portStatus[port] = portStatus[port] & ~ (1 << (pin - offset)); - break; - case OUTPUT: - digitalWrite(pin, LOW); // disable PWM - case PWM: - pinMode(pin, OUTPUT); - portStatus[port] = portStatus[port] | (1 << (pin - offset)); - break; - //case ANALOG: // TODO figure this out - default: - Firmata.sendString(""); - } - // TODO: save status to EEPROM here, if changed - } -} - -void analogWriteCallback(byte pin, int value) -{ - setPinModeCallback(pin, PIN_MODE_PWM); - analogWrite(pin, value); -} - -void digitalWriteCallback(byte port, int value) -{ - switch (port) { - case 0: // pins 2-7 (don't change Rx/Tx, pins 0 and 1) - // 0xFF03 == B1111111100000011 0x03 == B00000011 - PORTD = (value & ~ 0xFF03) | (PORTD & 0x03); - break; - case 1: // pins 8-13 (14,15 are disabled for the crystal) - PORTB = (byte)value; - break; - case 2: // analog pins used as digital - PORTC = (byte)value; - break; - } -} - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte pin, int value) -{ - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << pin); - } - else { // everything but 0 enables reporting of that pin - analogInputsToReport = analogInputsToReport | (1 << pin); - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - reportPINs[port] = (byte)value; - if (port == 2) // turn off analog reporting when used as digital - analogInputsToReport = 0; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ -void setup() -{ - byte i; - - Firmata.setFirmwareVersion(2, 0); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - - portStatus[0] = B00000011; // ignore Tx/RX pins - portStatus[1] = B11000000; // ignore 14/15 pins - portStatus[2] = B00000000; - - // for(i=0; i 20) { - previousMillis += 20; // run this every 20ms - /* SERIALREAD - Serial.read() uses a 128 byte circular buffer, so handle - * all serialReads at once, i.e. empty the buffer */ - while (Firmata.available()) - Firmata.processInput(); - /* SEND FTDI WRITE BUFFER - make sure that the FTDI buffer doesn't go over - * 60 bytes. use a timer to sending an event character every 4 ms to - * trigger the buffer to dump. */ - - /* ANALOGREAD - right after the event character, do all of the - * analogReads(). These only need to be done every 4ms. */ - for (analogPin = 0; analogPin < TOTAL_ANALOG_PINS; analogPin++) { - if ( analogInputsToReport & (1 << analogPin) ) { - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } -} diff --git a/resources/arduino_files/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino deleted file mode 100644 index 1ccc411d4..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/ServoFirmata/ServoFirmata.ino +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* This firmware supports as many servos as possible using the Servo library - * included in Arduino 0017 - * - * This example code is in the public domain. - */ - -#include -#include - -Servo servos[MAX_SERVOS]; -byte servoPinMap[TOTAL_PINS]; -byte servoCount = 0; - -void analogWriteCallback(byte pin, int value) -{ - if (IS_PIN_DIGITAL(pin)) { - servos[servoPinMap[pin]].write(value); - } -} - -void systemResetCallback() -{ - servoCount = 0; -} - -void setup() -{ - byte pin; - - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - - Firmata.begin(57600); - systemResetCallback(); - - // attach servos from first digital pin up to max number of - // servos supported for the board - for (pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - if (servoCount < MAX_SERVOS) { - servoPinMap[pin] = servoCount; - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); - servoCount++; - } - } - } -} - -void loop() -{ - while (Firmata.available()) - Firmata.processInput(); -} diff --git a/resources/arduino_files/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino deleted file mode 100644 index f4a3eaabe..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/SimpleAnalogFirmata/SimpleAnalogFirmata.ino +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* Supports as many analog inputs and analog PWM outputs as possible. - * - * This example code is in the public domain. - */ -#include - -byte analogPin = 0; - -void analogWriteCallback(byte pin, int value) -{ - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), value); - } -} - -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.begin(57600); -} - -void loop() -{ - while (Firmata.available()) { - Firmata.processInput(); - } - // do one analogRead per loop, so if PC is sending a lot of - // analog write messages, we will only delay 1 analogRead - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - analogPin = analogPin + 1; - if (analogPin >= TOTAL_ANALOG_PINS) analogPin = 0; -} - diff --git a/resources/arduino_files/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino deleted file mode 100644 index 56d388e92..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/SimpleDigitalFirmata/SimpleDigitalFirmata.ino +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Firmata is a generic protocol for communicating with microcontrollers - * from software on a host computer. It is intended to work with - * any host computer software package. - * - * To download a host software package, please clink on the following link - * to open the download page in your default browser. - * - * http://firmata.org/wiki/Download - */ - -/* Supports as many digital inputs and outputs as possible. - * - * This example code is in the public domain. - */ -#include - -byte previousPIN[TOTAL_PORTS]; // PIN means PORT for input -byte previousPORT[TOTAL_PORTS]; - -void outputPort(byte portNumber, byte portValue) -{ - // only send the data when it changes, otherwise you get too many messages! - if (previousPIN[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPIN[portNumber] = portValue; - } -} - -void setPinModeCallback(byte pin, int mode) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), mode); - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte i; - byte currentPinValue, previousPinValue; - - if (port < TOTAL_PORTS && value != previousPORT[port]) { - for (i = 0; i < 8; i++) { - currentPinValue = (byte) value & (1 << i); - previousPinValue = previousPORT[port] & (1 << i); - if (currentPinValue != previousPinValue) { - digitalWrite(i + (port * 8), currentPinValue); - } - } - previousPORT[port] = value; - } -} - -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.begin(57600); -} - -void loop() -{ - byte i; - - for (i = 0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, 0xff)); - } - - while (Firmata.available()) { - Firmata.processInput(); - } -} diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino deleted file mode 100644 index e969e5a8c..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmata/StandardFirmata.ino +++ /dev/null @@ -1,815 +0,0 @@ -/* - Firmata is a generic protocol for communicating with microcontrollers - from software on a host computer. It is intended to work with - any host computer software package. - - To download a host software package, please clink on the following link - to open the list of Firmata client libraries your default browser. - - https://github.com/firmata/arduino#firmata-client-libraries - - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -#include -#include -#include - -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 -#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 -#define I2C_END_TX_MASK B01000000 -#define I2C_STOP_TX 1 -#define I2C_RESTART_TX 0 -#define I2C_MAX_QUERIES 8 -#define I2C_REGISTER_NOT_SPECIFIED -1 - -// the minimum interval for sampling analog input -#define MINIMUM_SAMPLING_INTERVAL 1 - - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -#ifdef FIRMATA_SERIAL_FEATURE -SerialFirmata serialFeature; -#endif - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting - -/* digital input ports */ -byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence -byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent - -/* pins configuration */ -byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -unsigned int samplingInterval = 19; // how often to run the main loop (in ms) - -/* i2c data */ -struct i2c_device_info { - byte addr; - int reg; - byte bytes; - byte stopTX; -}; - -/* for i2c read continuous more */ -i2c_device_info query[I2C_MAX_QUERIES]; - -byte i2cRxData[32]; -boolean isI2CEnabled = false; -signed char queryIndex = -1; -// default delay time between i2c read request and Wire.requestFrom() -unsigned int i2cReadDelayTime = 0; - -Servo servos[MAX_SERVOS]; -byte servoPinMap[TOTAL_PINS]; -byte detachedServos[MAX_SERVOS]; -byte detachedServoCount = 0; -byte servoCount = 0; - -boolean isResetting = false; - - -/* utility functions */ -void wireWrite(byte data) -{ -#if ARDUINO >= 100 - Wire.write((byte)data); -#else - Wire.send(data); -#endif -} - -byte wireRead(void) -{ -#if ARDUINO >= 100 - return Wire.read(); -#else - return Wire.receive(); -#endif -} - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void attachServo(byte pin, int minPulse, int maxPulse) -{ - if (servoCount < MAX_SERVOS) { - // reuse indexes of detached servos until all have been reallocated - if (detachedServoCount > 0) { - servoPinMap[pin] = detachedServos[detachedServoCount - 1]; - if (detachedServoCount > 0) detachedServoCount--; - } else { - servoPinMap[pin] = servoCount; - servoCount++; - } - if (minPulse > 0 && maxPulse > 0) { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); - } else { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); - } - } else { - Firmata.sendString("Max servos attached"); - } -} - -void detachServo(byte pin) -{ - servos[servoPinMap[pin]].detach(); - // if we're detaching the last servo, decrement the count - // otherwise store the index of the detached servo - if (servoPinMap[pin] == servoCount && servoCount > 0) { - servoCount--; - } else if (servoCount > 0) { - // keep track of detached servos because we want to reuse their indexes - // before incrementing the count of attached servos - detachedServoCount++; - detachedServos[detachedServoCount - 1] = servoPinMap[pin]; - } - - servoPinMap[pin] = 255; -} - -void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { - // allow I2C requests that don't require a register read - // for example, some devices using an interrupt pin to signify new data available - // do not always require the register read so upon interrupt you call Wire.requestFrom() - if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - wireWrite((byte)theRegister); - Wire.endTransmission(stopTX); // default = true - // do not set a value of 0 - if (i2cReadDelayTime > 0) { - // delay is necessary for some devices such as WiiNunchuck - delayMicroseconds(i2cReadDelayTime); - } - } else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom - - // check to be sure correct number of bytes were returned by slave - if (numBytes < Wire.available()) { - Firmata.sendString("I2C: Too many bytes received"); - } else if (numBytes > Wire.available()) { - Firmata.sendString("I2C: Too few bytes received"); - } - - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - - for (int i = 0; i < numBytes && Wire.available(); i++) { - i2cRxData[2 + i] = wireRead(); - } - - // send slave address, register and received bytes - Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); -} - -void outputPort(byte portNumber, byte portValue, byte forceSend) -{ - // pins not configured as INPUT are cleared to zeros - portValue = portValue & portConfigInputs[portNumber]; - // only send if the value is different than previously sent - if (forceSend || previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Serial output queue using Serial.print() */ -void checkDigitalInputs(void) -{ - /* Using non-looping code allows constants to be given to readPort(). - * The compiler will apply substantial optimizations if the inputs - * to readPort() are compile-time constants. */ - if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); - if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); - if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); - if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); - if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); - if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); - if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); - if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); - if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); - if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); - if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); - if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); - if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); - if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); - if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); - if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) -{ - if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) - return; - - if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { - // disable i2c so pins can be used for other functions - // the following if statements should reconfigure the pins properly - disableI2CPins(); - } - if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - } - if (IS_PIN_ANALOG(pin)) { - reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting - } - if (IS_PIN_DIGITAL(pin)) { - if (mode == INPUT || mode == PIN_MODE_PULLUP) { - portConfigInputs[pin / 8] |= (1 << (pin & 7)); - } else { - portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); - } - } - Firmata.setPinState(pin, 0); - switch (mode) { - case PIN_MODE_ANALOG: - if (IS_PIN_ANALOG(pin)) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - } - Firmata.setPinMode(pin, PIN_MODE_ANALOG); - } - break; - case INPUT: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - Firmata.setPinMode(pin, INPUT); - } - break; - case PIN_MODE_PULLUP: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); - Firmata.setPinMode(pin, PIN_MODE_PULLUP); - Firmata.setPinState(pin, 1); - } - break; - case OUTPUT: - if (IS_PIN_DIGITAL(pin)) { - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - Firmata.setPinMode(pin, OUTPUT); - } - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_PWM(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), 0); - Firmata.setPinMode(pin, PIN_MODE_PWM); - } - break; - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) { - Firmata.setPinMode(pin, PIN_MODE_SERVO); - if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { - // pass -1 for min and max pulse values to use default values set - // by Servo library - attachServo(pin, -1, -1); - } - } - break; - case PIN_MODE_I2C: - if (IS_PIN_I2C(pin)) { - // mark the pin as i2c - // the user must call I2C_CONFIG to enable I2C for a device - Firmata.setPinMode(pin, PIN_MODE_I2C); - } - break; - case PIN_MODE_SERIAL: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); -#endif - break; - default: - Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM - } - // TODO: save status to EEPROM here, if changed -} - -/* - * Sets the value of an individual pin. Useful if you want to set a pin value but - * are not tracking the digital port state. - * Can only be used on pins configured as OUTPUT. - * Cannot be used to enable pull-ups on Digital INPUT pins. - */ -void setPinValueCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { - if (Firmata.getPinMode(pin) == OUTPUT) { - Firmata.setPinState(pin, value); - digitalWrite(PIN_TO_DIGITAL(pin), value); - } - } -} - -void analogWriteCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS) { - switch (Firmata.getPinMode(pin)) { - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) - servos[servoPinMap[pin]].write(value); - Firmata.setPinState(pin, value); - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) - analogWrite(PIN_TO_PWM(pin), value); - Firmata.setPinState(pin, value); - break; - } - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; - - if (port < TOTAL_PORTS) { - // create a mask of the pins on this port that are writable. - lastPin = port * 8 + 8; - if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; - for (pin = port * 8; pin < lastPin; pin++) { - // do not disturb non-digital pins (eg, Rx & Tx) - if (IS_PIN_DIGITAL(pin)) { - // do not touch pins in PWM, ANALOG, SERVO or other modes - if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { - pinValue = ((byte)value & mask) ? 1 : 0; - if (Firmata.getPinMode(pin) == OUTPUT) { - pinWriteMask |= mask; - } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { - // only handle INPUT here for backwards compatibility -#if ARDUINO > 100 - pinMode(pin, INPUT_PULLUP); -#else - // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier - pinWriteMask |= mask; -#endif - } - Firmata.setPinState(pin, pinValue); - } - } - mask = mask << 1; - } - writePort(port, (byte)value, pinWriteMask); - } -} - - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte analogPin, int value) -{ - if (analogPin < TOTAL_ANALOG_PINS) { - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); - } else { - analogInputsToReport = analogInputsToReport | (1 << analogPin); - // prevent during system reset or all analog pin values will be reported - // which may report noise for unconnected analog pins - if (!isResetting) { - // Send pin value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - if (port < TOTAL_PORTS) { - reportPINs[port] = (byte)value; - // Send port value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); - } - // do not disable analog reporting on these 8 pins, to allow some - // pins used for digital, others analog. Instead, allow both types - // of reporting to be enabled, but check if the pin is configured - // as analog when sampling the analog inputs. Likewise, while - // scanning digital pins, portConfigInputs will mask off values from any - // pins configured as analog -} - -/*============================================================================== - * SYSEX-BASED commands - *============================================================================*/ - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte stopTX; - byte slaveAddress; - byte data; - int slaveRegister; - unsigned int delayTime; - - switch (command) { - case I2C_REQUEST: - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { - Firmata.sendString("10-bit addressing not supported"); - return; - } - else { - slaveAddress = argv[0]; - } - - // need to invert the logic here since 0 will be default for client - // libraries that have not updated to add support for restart tx - if (argv[1] & I2C_END_TX_MASK) { - stopTX = I2C_RESTART_TX; - } - else { - stopTX = I2C_STOP_TX; // default - } - - switch (mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - wireWrite(data); - } - Wire.endTransmission(); - delayMicroseconds(70); - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= I2C_MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - queryIndex++; - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = slaveRegister; - query[queryIndex].bytes = data; - query[queryIndex].stopTX = stopTX; - break; - case I2C_STOP_READING: - byte queryIndexToSkip; - // if read continuous mode is enabled for only 1 i2c device, disable - // read continuous reporting for that device - if (queryIndex <= 0) { - queryIndex = -1; - } else { - queryIndexToSkip = 0; - // if read continuous mode is enabled for multiple devices, - // determine which device to stop reading and remove it's data from - // the array, shifiting other array data to fill the space - for (byte i = 0; i < queryIndex + 1; i++) { - if (query[i].addr == slaveAddress) { - queryIndexToSkip = i; - break; - } - } - - for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { - if (i < I2C_MAX_QUERIES) { - query[i].addr = query[i + 1].addr; - query[i].reg = query[i + 1].reg; - query[i].bytes = query[i + 1].bytes; - query[i].stopTX = query[i + 1].stopTX; - } - } - queryIndex--; - } - break; - default: - break; - } - break; - case I2C_CONFIG: - delayTime = (argv[0] + (argv[1] << 7)); - - if (delayTime > 0) { - i2cReadDelayTime = delayTime; - } - - if (!isI2CEnabled) { - enableI2CPins(); - } - - break; - case SERVO_CONFIG: - if (argc > 4) { - // these vars are here for clarity, they'll optimized away by the compiler - byte pin = argv[0]; - int minPulse = argv[1] + (argv[2] << 7); - int maxPulse = argv[3] + (argv[4] << 7); - - if (IS_PIN_DIGITAL(pin)) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - attachServo(pin, minPulse, maxPulse); - setPinModeCallback(pin, PIN_MODE_SERVO); - } - } - break; - case SAMPLING_INTERVAL: - if (argc > 1) { - samplingInterval = argv[0] + (argv[1] << 7); - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - } else { - //Firmata.sendString("Not enough data"); - } - break; - case EXTENDED_ANALOG: - if (argc > 1) { - int val = argv[1]; - if (argc > 2) val |= (argv[2] << 7); - if (argc > 3) val |= (argv[3] << 14); - analogWriteCallback(argv[0], val); - } - break; - case CAPABILITY_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(CAPABILITY_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - Firmata.write((byte)INPUT); - Firmata.write(1); - Firmata.write((byte)PIN_MODE_PULLUP); - Firmata.write(1); - Firmata.write((byte)OUTPUT); - Firmata.write(1); - } - if (IS_PIN_ANALOG(pin)) { - Firmata.write(PIN_MODE_ANALOG); - Firmata.write(10); // 10 = 10-bit resolution - } - if (IS_PIN_PWM(pin)) { - Firmata.write(PIN_MODE_PWM); - Firmata.write(8); // 8 = 8-bit resolution - } - if (IS_PIN_DIGITAL(pin)) { - Firmata.write(PIN_MODE_SERVO); - Firmata.write(14); - } - if (IS_PIN_I2C(pin)) { - Firmata.write(PIN_MODE_I2C); - Firmata.write(1); // TODO: could assign a number to map to SCL or SDA - } -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleCapability(pin); -#endif - Firmata.write(127); - } - Firmata.write(END_SYSEX); - break; - case PIN_STATE_QUERY: - if (argc > 0) { - byte pin = argv[0]; - Firmata.write(START_SYSEX); - Firmata.write(PIN_STATE_RESPONSE); - Firmata.write(pin); - if (pin < TOTAL_PINS) { - Firmata.write(Firmata.getPinMode(pin)); - Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); - if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); - if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); - } - Firmata.write(END_SYSEX); - } - break; - case ANALOG_MAPPING_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(ANALOG_MAPPING_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); - } - Firmata.write(END_SYSEX); - break; - - case SERIAL_MESSAGE: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleSysex(command, argc, argv); -#endif - break; - } -} - -void enableI2CPins() -{ - byte i; - // is there a faster way to do this? would probaby require importing - // Arduino.h to get SCL and SDA pins - for (i = 0; i < TOTAL_PINS; i++) { - if (IS_PIN_I2C(i)) { - // mark pins as i2c so they are ignore in non i2c data requests - setPinModeCallback(i, PIN_MODE_I2C); - } - } - - isI2CEnabled = true; - - Wire.begin(); -} - -/* disable the i2c pins so they can be used for other functions */ -void disableI2CPins() { - isI2CEnabled = false; - // disable read continuous mode for all devices - queryIndex = -1; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ - -void systemResetCallback() -{ - isResetting = true; - - // initialize a defalt state - // TODO: option to load config from EEPROM instead of default - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.reset(); -#endif - - if (isI2CEnabled) { - disableI2CPins(); - } - - for (byte i = 0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; // by default, reporting off - portConfigInputs[i] = 0; // until activated - previousPINs[i] = 0; - } - - for (byte i = 0; i < TOTAL_PINS; i++) { - // pins with analog capability default to analog input - // otherwise, pins default to digital output - if (IS_PIN_ANALOG(i)) { - // turns off pullup, configures everything - setPinModeCallback(i, PIN_MODE_ANALOG); - } else if (IS_PIN_DIGITAL(i)) { - // sets the output to 0, configures portConfigInputs - setPinModeCallback(i, OUTPUT); - } - - servoPinMap[i] = 255; - } - // by default, do not report any analog inputs - analogInputsToReport = 0; - - detachedServoCount = 0; - servoCount = 0; - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - /* - TODO: this can never execute, since no pins default to digital input - but it will be needed when/if we support EEPROM stored config - for (byte i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - */ - isResetting = false; -} - -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - - // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega, - // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this: - // Serial1.begin(57600); - // Firmata.begin(Serial1); - // However do not do this if you are using SERIAL_MESSAGE - - Firmata.begin(57600); - while (!Serial) { - ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101 - } - - systemResetCallback(); // reset to default config -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - byte pin, analogPin; - - /* DIGITALREAD - as fast as possible, check for changes and output them to the - * FTDI buffer using Serial.print() */ - checkDigitalInputs(); - - /* STREAMREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while (Firmata.available()) - Firmata.processInput(); - - // TODO - ensure that Stream buffer doesn't go over 60 bytes - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - /* ANALOGREAD - do all analogReads() at the configured sampling interval */ - for (pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { - analogPin = PIN_TO_ANALOG(pin); - if (analogInputsToReport & (1 << analogPin)) { - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // report i2c data for all device with read continuous mode enabled - if (queryIndex > -1) { - for (byte i = 0; i < queryIndex + 1; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); - } - } - } - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.update(); -#endif -} diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino deleted file mode 100644 index 11437a65a..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataChipKIT/StandardFirmataChipKIT.ino +++ /dev/null @@ -1,793 +0,0 @@ -/* - Firmata is a generic protocol for communicating with microcontrollers - from software on a host computer. It is intended to work with - any host computer software package. - - To download a host software package, please clink on the following link - to open the list of Firmata client libraries your default browser. - - https://github.com/firmata/arduino#firmata-client-libraries - - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - Copyright (C) 2015 Brian Schmalz. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -#include // Gives us PWM and Servo on every pin -#include -#include - -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 -#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 -#define I2C_END_TX_MASK B01000000 -#define I2C_STOP_TX 1 -#define I2C_RESTART_TX 0 -#define I2C_MAX_QUERIES 8 -#define I2C_REGISTER_NOT_SPECIFIED -1 - -// the minimum interval for sampling analog input -#define MINIMUM_SAMPLING_INTERVAL 1 - - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting - -/* digital input ports */ -byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence -byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent - -/* pins configuration */ -byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -unsigned int samplingInterval = 19; // how often to run the main loop (in ms) - -/* i2c data */ -struct i2c_device_info { - byte addr; - int reg; - byte bytes; - byte stopTX; -}; - -/* for i2c read continuous more */ -i2c_device_info query[I2C_MAX_QUERIES]; - -byte i2cRxData[32]; -boolean isI2CEnabled = false; -signed char queryIndex = -1; -// default delay time between i2c read request and Wire.requestFrom() -unsigned int i2cReadDelayTime = 0; - -SoftServo servos[MAX_SERVOS]; -byte servoPinMap[TOTAL_PINS]; -byte detachedServos[MAX_SERVOS]; -byte detachedServoCount = 0; -byte servoCount = 0; - -boolean isResetting = false; - -/* utility functions */ -void wireWrite(byte data) -{ -#if ARDUINO >= 100 - Wire.write((byte)data); -#else - Wire.send(data); -#endif -} - -byte wireRead(void) -{ -#if ARDUINO >= 100 - return Wire.read(); -#else - return Wire.receive(); -#endif -} - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void attachServo(byte pin, int minPulse, int maxPulse) -{ - if (servoCount < MAX_SERVOS) { - // reuse indexes of detached servos until all have been reallocated - if (detachedServoCount > 0) { - servoPinMap[pin] = detachedServos[detachedServoCount - 1]; - if (detachedServoCount > 0) detachedServoCount--; - } else { - servoPinMap[pin] = servoCount; - servoCount++; - } - if (minPulse > 0 && maxPulse > 0) { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); - } else { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); - } - } else { - Firmata.sendString("Max servos attached"); - } -} - -void detachServo(byte pin) -{ - servos[servoPinMap[pin]].detach(); - // if we're detaching the last servo, decrement the count - // otherwise store the index of the detached servo - if (servoPinMap[pin] == servoCount && servoCount > 0) { - servoCount--; - } else if (servoCount > 0) { - // keep track of detached servos because we want to reuse their indexes - // before incrementing the count of attached servos - detachedServoCount++; - detachedServos[detachedServoCount - 1] = servoPinMap[pin]; - } - - servoPinMap[pin] = 255; -} - -void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { - // allow I2C requests that don't require a register read - // for example, some devices using an interrupt pin to signify new data available - // do not always require the register read so upon interrupt you call Wire.requestFrom() - if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - wireWrite((byte)theRegister); - Wire.endTransmission(stopTX); // default = true - // do not set a value of 0 - if (i2cReadDelayTime > 0) { - // delay is necessary for some devices such as WiiNunchuck - delayMicroseconds(i2cReadDelayTime); - } - } else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom - - // check to be sure correct number of bytes were returned by slave - if (numBytes < Wire.available()) { - Firmata.sendString("I2C: Too many bytes received"); - } else if (numBytes > Wire.available()) { - Firmata.sendString("I2C: Too few bytes received"); - } - - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - - for (int i = 0; i < numBytes && Wire.available(); i++) { - i2cRxData[2 + i] = wireRead(); - } - - // send slave address, register and received bytes - Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); -} - -void outputPort(byte portNumber, byte portValue, byte forceSend) -{ - // pins not configured as INPUT are cleared to zeros - portValue = portValue & portConfigInputs[portNumber]; - // only send if the value is different than previously sent - if (forceSend || previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Serial output queue using Serial.print() */ -void checkDigitalInputs(void) -{ - /* Using non-looping code allows constants to be given to readPort(). - * The compiler will apply substantial optimizations if the inputs - * to readPort() are compile-time constants. */ - if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); - if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); - if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); - if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); - if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); - if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); - if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); - if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); - if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); - if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); - if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); - if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); - if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); - if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); - if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); - if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); -} - -// ----------------------------------------------------------------------------- -/* Sets a pin that is in Servo mode to a particular output value - * (i.e. pulse width). Different boards may have different ways of - * setting servo values, so putting it in a function keeps things cleaner. - */ -void servoWrite(byte pin, int value) -{ - SoftPWMServoPWMWrite(PIN_TO_PWM(pin), value); -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) -{ - if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) - return; - - if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { - // disable i2c so pins can be used for other functions - // the following if statements should reconfigure the pins properly - disableI2CPins(); - } - if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - } - if (IS_PIN_ANALOG(pin)) { - reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting - } - if (IS_PIN_DIGITAL(pin)) { - if (mode == INPUT || mode == PIN_MODE_PULLUP) { - portConfigInputs[pin / 8] |= (1 << (pin & 7)); - } else { - portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); - } - } - Firmata.setPinState(pin, 0); - switch (mode) { - case PIN_MODE_ANALOG: - if (IS_PIN_ANALOG(pin)) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - } - Firmata.setPinMode(pin, PIN_MODE_ANALOG); - } - break; - case INPUT: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - Firmata.setPinMode(pin, INPUT); - } - break; - case PIN_MODE_PULLUP: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); - Firmata.setPinMode(pin, PIN_MODE_PULLUP); - Firmata.setPinState(pin, 1); - } - break; - case OUTPUT: - if (IS_PIN_DIGITAL(pin)) { - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - Firmata.setPinMode(pin, OUTPUT); - } - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_PWM(pin), OUTPUT); - servoWrite(PIN_TO_PWM(pin), 0); - Firmata.setPinMode(pin, PIN_MODE_PWM); - } - break; - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) { - Firmata.setPinMode(pin, PIN_MODE_SERVO); - if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { - // pass -1 for min and max pulse values to use default values set - // by Servo library - attachServo(pin, -1, -1); - } - } - break; - case PIN_MODE_I2C: - if (IS_PIN_I2C(pin)) { - // mark the pin as i2c - // the user must call I2C_CONFIG to enable I2C for a device - Firmata.setPinMode(pin, PIN_MODE_I2C); - } - break; - default: - Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM - } - // TODO: save status to EEPROM here, if changed -} - -/* - * Sets the value of an individual pin. Useful if you want to set a pin value but - * are not tracking the digital port state. - * Can only be used on pins configured as OUTPUT. - * Cannot be used to enable pull-ups on Digital INPUT pins. - */ -void setPinValueCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { - if (Firmata.getPinMode(pin) == OUTPUT) { - Firmata.setPinState(pin, value); - digitalWrite(PIN_TO_DIGITAL(pin), value); - } - } -} - -void analogWriteCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS) { - switch (Firmata.getPinMode(pin)) { - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) - servos[servoPinMap[pin]].write(value); - Firmata.setPinState(pin, value); - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) - servoWrite(PIN_TO_PWM(pin), value); - Firmata.setPinState(pin, value); - break; - } - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; - - if (port < TOTAL_PORTS) { - // create a mask of the pins on this port that are writable. - lastPin = port * 8 + 8; - if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; - for (pin = port * 8; pin < lastPin; pin++) { - // do not disturb non-digital pins (eg, Rx & Tx) - if (IS_PIN_DIGITAL(pin)) { - // do not touch pins in PWM, ANALOG, SERVO or other modes - if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { - pinValue = ((byte)value & mask) ? 1 : 0; - if (Firmata.getPinMode(pin) == OUTPUT) { - pinWriteMask |= mask; - } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { - // only handle INPUT here for backwards compatibility -#if ARDUINO > 100 - pinMode(pin, INPUT_PULLUP); -#else - // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier - pinWriteMask |= mask; -#endif - } - Firmata.setPinState(pin, pinValue); - } - } - mask = mask << 1; - } - writePort(port, (byte)value, pinWriteMask); - } -} - - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte analogPin, int value) -{ - if (analogPin < TOTAL_ANALOG_PINS) { - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); - } else { - analogInputsToReport = analogInputsToReport | (1 << analogPin); - // prevent during system reset or all analog pin values will be reported - // which may report noise for unconnected analog pins - if (!isResetting) { - // Send pin value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - if (port < TOTAL_PORTS) { - reportPINs[port] = (byte)value; - // Send port value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); - } - // do not disable analog reporting on these 8 pins, to allow some - // pins used for digital, others analog. Instead, allow both types - // of reporting to be enabled, but check if the pin is configured - // as analog when sampling the analog inputs. Likewise, while - // scanning digital pins, portConfigInputs will mask off values from any - // pins configured as analog -} - -/*============================================================================== - * SYSEX-BASED commands - *============================================================================*/ - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte stopTX; - byte slaveAddress; - byte data; - int slaveRegister; - unsigned int delayTime; - - switch (command) { - case I2C_REQUEST: - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { - Firmata.sendString("10-bit addressing not supported"); - return; - } - else { - slaveAddress = argv[0]; - } - - // need to invert the logic here since 0 will be default for client - // libraries that have not updated to add support for restart tx - if (argv[1] & I2C_END_TX_MASK) { - stopTX = I2C_RESTART_TX; - } - else { - stopTX = I2C_STOP_TX; // default - } - - switch (mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - wireWrite(data); - } - Wire.endTransmission(); - delayMicroseconds(70); - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= I2C_MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - queryIndex++; - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = slaveRegister; - query[queryIndex].bytes = data; - query[queryIndex].stopTX = stopTX; - break; - case I2C_STOP_READING: - byte queryIndexToSkip; - // if read continuous mode is enabled for only 1 i2c device, disable - // read continuous reporting for that device - if (queryIndex <= 0) { - queryIndex = -1; - } else { - queryIndexToSkip = 0; - // if read continuous mode is enabled for multiple devices, - // determine which device to stop reading and remove it's data from - // the array, shifiting other array data to fill the space - for (byte i = 0; i < queryIndex + 1; i++) { - if (query[i].addr == slaveAddress) { - queryIndexToSkip = i; - break; - } - } - - for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { - if (i < I2C_MAX_QUERIES) { - query[i].addr = query[i + 1].addr; - query[i].reg = query[i + 1].reg; - query[i].bytes = query[i + 1].bytes; - query[i].stopTX = query[i + 1].stopTX; - } - } - queryIndex--; - } - break; - default: - break; - } - break; - case I2C_CONFIG: - delayTime = (argv[0] + (argv[1] << 7)); - - if (delayTime > 0) { - i2cReadDelayTime = delayTime; - } - - if (!isI2CEnabled) { - enableI2CPins(); - } - - break; - case SERVO_CONFIG: - if (argc > 4) { - // these vars are here for clarity, they'll optimized away by the compiler - byte pin = argv[0]; - int minPulse = argv[1] + (argv[2] << 7); - int maxPulse = argv[3] + (argv[4] << 7); - - if (IS_PIN_DIGITAL(pin)) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - attachServo(pin, minPulse, maxPulse); - setPinModeCallback(pin, PIN_MODE_SERVO); - } - } - break; - case SAMPLING_INTERVAL: - if (argc > 1) { - samplingInterval = argv[0] + (argv[1] << 7); - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - } else { - //Firmata.sendString("Not enough data"); - } - break; - case EXTENDED_ANALOG: - if (argc > 1) { - int val = argv[1]; - if (argc > 2) val |= (argv[2] << 7); - if (argc > 3) val |= (argv[3] << 14); - analogWriteCallback(argv[0], val); - } - break; - case CAPABILITY_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(CAPABILITY_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - Firmata.write((byte)INPUT); - Firmata.write(1); - Firmata.write((byte)PIN_MODE_PULLUP); - Firmata.write(1); - Firmata.write((byte)OUTPUT); - Firmata.write(1); - } - if (IS_PIN_ANALOG(pin)) { - Firmata.write(PIN_MODE_ANALOG); - Firmata.write(10); // 10 = 10-bit resolution - } - if (IS_PIN_PWM(pin)) { - Firmata.write(PIN_MODE_PWM); - Firmata.write(8); // 8 = 8-bit resolution - } - if (IS_PIN_DIGITAL(pin)) { - Firmata.write(PIN_MODE_SERVO); - Firmata.write(14); - } - if (IS_PIN_I2C(pin)) { - Firmata.write(PIN_MODE_I2C); - Firmata.write(1); // TODO: could assign a number to map to SCL or SDA - } - Firmata.write(127); - } - Firmata.write(END_SYSEX); - break; - case PIN_STATE_QUERY: - if (argc > 0) { - byte pin = argv[0]; - Firmata.write(START_SYSEX); - Firmata.write(PIN_STATE_RESPONSE); - Firmata.write(pin); - if (pin < TOTAL_PINS) { - Firmata.write(Firmata.getPinMode(pin)); - Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); - if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); - if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); - } - Firmata.write(END_SYSEX); - } - break; - case ANALOG_MAPPING_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(ANALOG_MAPPING_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); - } - Firmata.write(END_SYSEX); - break; - } -} - -void enableI2CPins() -{ - byte i; - // is there a faster way to do this? would probaby require importing - // Arduino.h to get SCL and SDA pins - for (i = 0; i < TOTAL_PINS; i++) { - if (IS_PIN_I2C(i)) { - // mark pins as i2c so they are ignore in non i2c data requests - setPinModeCallback(i, PIN_MODE_I2C); - } - } - - isI2CEnabled = true; - - Wire.begin(); -} - -/* disable the i2c pins so they can be used for other functions */ -void disableI2CPins() { - isI2CEnabled = false; - // disable read continuous mode for all devices - queryIndex = -1; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ - -void systemResetCallback() -{ - isResetting = true; - // initialize a defalt state - // TODO: option to load config from EEPROM instead of default - if (isI2CEnabled) { - disableI2CPins(); - } - - for (byte i = 0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; // by default, reporting off - portConfigInputs[i] = 0; // until activated - previousPINs[i] = 0; - } - - for (byte i = 0; i < TOTAL_PINS; i++) { - // pins with analog capability default to analog input - // otherwise, pins default to digital output - if (IS_PIN_ANALOG(i)) { - // turns off pullup, configures everything - setPinModeCallback(i, PIN_MODE_ANALOG); - } else if (IS_PIN_DIGITAL(i)) { - // sets the output to 0, configures portConfigInputs - setPinModeCallback(i, OUTPUT); - } - - servoPinMap[i] = 255; - } - // by default, do not report any analog inputs - analogInputsToReport = 0; - - detachedServoCount = 0; - servoCount = 0; - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - /* - TODO: this can never execute, since no pins default to digital input - but it will be needed when/if we support EEPROM stored config - for (byte i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - */ - isResetting = false; -} - -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - - /* For chipKIT Pi board, we need to use Serial1. All others just use Serial. */ -#if defined(_BOARD_CHIPKIT_PI_) - Serial1.begin(57600); - Firmata.begin(Serial1); -#else - Firmata.begin(57600); -#endif - systemResetCallback(); // reset to default config -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - byte pin, analogPin; - - /* DIGITALREAD - as fast as possible, check for changes and output them to the - * FTDI buffer using Serial.print() */ - checkDigitalInputs(); - - /* STREAMREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while (Firmata.available()) - Firmata.processInput(); - - // TODO - ensure that Stream buffer doesn't go over 60 bytes - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - /* ANALOGREAD - do all analogReads() at the configured sampling interval */ - for (pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { - analogPin = PIN_TO_ANALOG(pin); - if (analogInputsToReport & (1 << analogPin)) { - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // report i2c data for all device with read continuous mode enabled - if (queryIndex > -1) { - for (byte i = 0; i < queryIndex + 1; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); - } - } - } -} diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino deleted file mode 100644 index d0f1e585a..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/StandardFirmataEthernet.ino +++ /dev/null @@ -1,910 +0,0 @@ -/* - Firmata is a generic protocol for communicating with microcontrollers - from software on a host computer. It is intended to work with - any host computer software package. - - To download a host software package, please clink on the following link - to open the list of Firmata client libraries your default browser. - - https://github.com/firmata/arduino#firmata-client-libraries - - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -/* - README - - StandardFirmataEthernet is a client implementation. You will need a Firmata client library with - a network transport that can act as a server in order to establish a connection between - StandardFirmataEthernet and the Firmata client application. - - To use StandardFirmataEthernet you will need to have one of the following - boards or shields: - - - Arduino Ethernet shield (or clone) - - Arduino Ethernet board (or clone) - - Arduino Yun - - Follow the instructions in the ethernetConfig.h file (ethernetConfig.h tab in Arduino IDE) to - configure your particular hardware. - - NOTE: If you are using an Arduino Ethernet shield you cannot use the following pins on - the following boards. Firmata will ignore any requests to use these pins: - - - Arduino Uno or other ATMega328 boards: (D4, D10, D11, D12, D13) - - Arduino Mega: (D4, D10, D50, D51, D52, D53) - - Arduino Leonardo: (D4, D10) - - Arduino Due: (D4, D10) - - Arduino Zero: (D4, D10) - - If you are using an ArduinoEthernet board, the following pins cannot be used (same as Uno): - - D4, D10, D11, D12, D13 -*/ - -#include -#include -#include - -/* - * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your connection - * that may help in the event of connection issues. If defined, some boards may not begin executing this sketch - * until the Serial console is opened. - */ -//#define SERIAL_DEBUG -#include "utility/firmataDebug.h" - -// follow the instructions in ethernetConfig.h to configure your particular hardware -#include "ethernetConfig.h" -#include "utility/EthernetClientStream.h" - -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 -#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 -#define I2C_END_TX_MASK B01000000 -#define I2C_STOP_TX 1 -#define I2C_RESTART_TX 0 -#define I2C_MAX_QUERIES 8 -#define I2C_REGISTER_NOT_SPECIFIED -1 - -// the minimum interval for sampling analog input -#define MINIMUM_SAMPLING_INTERVAL 1 - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -/* network */ -#if defined remote_ip && !defined remote_host -#ifdef local_ip -EthernetClientStream stream(client, local_ip, remote_ip, NULL, remote_port); -#else -EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), remote_ip, NULL, remote_port); -#endif -#endif - -#if !defined remote_ip && defined remote_host -#ifdef local_ip -EthernetClientStream stream(client, local_ip, IPAddress(0, 0, 0, 0), remote_host, remote_port); -#else -EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), IPAddress(0, 0, 0, 0), remote_host, remote_port); -#endif -#endif - -#ifdef FIRMATA_SERIAL_FEATURE -SerialFirmata serialFeature; -#endif - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting - -/* digital input ports */ -byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence -byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent - -/* pins configuration */ -byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) - -/* i2c data */ -struct i2c_device_info { - byte addr; - int reg; - byte bytes; - byte stopTX; -}; - -/* for i2c read continuous mode */ -i2c_device_info query[I2C_MAX_QUERIES]; - -byte i2cRxData[32]; -boolean isI2CEnabled = false; -signed char queryIndex = -1; -// default delay time between i2c read request and Wire.requestFrom() -unsigned int i2cReadDelayTime = 0; - -Servo servos[MAX_SERVOS]; -byte servoPinMap[TOTAL_PINS]; -byte detachedServos[MAX_SERVOS]; -byte detachedServoCount = 0; -byte servoCount = 0; - -boolean isResetting = false; - -/* utility functions */ -void wireWrite(byte data) -{ -#if ARDUINO >= 100 - Wire.write((byte)data); -#else - Wire.send(data); -#endif -} - -byte wireRead(void) -{ -#if ARDUINO >= 100 - return Wire.read(); -#else - return Wire.receive(); -#endif -} - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void attachServo(byte pin, int minPulse, int maxPulse) -{ - if (servoCount < MAX_SERVOS) { - // reuse indexes of detached servos until all have been reallocated - if (detachedServoCount > 0) { - servoPinMap[pin] = detachedServos[detachedServoCount - 1]; - if (detachedServoCount > 0) detachedServoCount--; - } else { - servoPinMap[pin] = servoCount; - servoCount++; - } - if (minPulse > 0 && maxPulse > 0) { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); - } else { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); - } - } else { - Firmata.sendString("Max servos attached"); - } -} - -void detachServo(byte pin) -{ - servos[servoPinMap[pin]].detach(); - // if we're detaching the last servo, decrement the count - // otherwise store the index of the detached servo - if (servoPinMap[pin] == servoCount && servoCount > 0) { - servoCount--; - } else if (servoCount > 0) { - // keep track of detached servos because we want to reuse their indexes - // before incrementing the count of attached servos - detachedServoCount++; - detachedServos[detachedServoCount - 1] = servoPinMap[pin]; - } - - servoPinMap[pin] = 255; -} - -void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { - // allow I2C requests that don't require a register read - // for example, some devices using an interrupt pin to signify new data available - // do not always require the register read so upon interrupt you call Wire.requestFrom() - if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - wireWrite((byte)theRegister); - Wire.endTransmission(stopTX); // default = true - // do not set a value of 0 - if (i2cReadDelayTime > 0) { - // delay is necessary for some devices such as WiiNunchuck - delayMicroseconds(i2cReadDelayTime); - } - } else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom - - // check to be sure correct number of bytes were returned by slave - if (numBytes < Wire.available()) { - Firmata.sendString("I2C: Too many bytes received"); - } else if (numBytes > Wire.available()) { - Firmata.sendString("I2C: Too few bytes received"); - } - - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - - for (int i = 0; i < numBytes && Wire.available(); i++) { - i2cRxData[2 + i] = wireRead(); - } - - // send slave address, register and received bytes - Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); -} - -void outputPort(byte portNumber, byte portValue, byte forceSend) -{ - // pins not configured as INPUT are cleared to zeros - portValue = portValue & portConfigInputs[portNumber]; - // only send if the value is different than previously sent - if (forceSend || previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Stream output queue using Stream.write() */ -void checkDigitalInputs(void) -{ - /* Using non-looping code allows constants to be given to readPort(). - * The compiler will apply substantial optimizations if the inputs - * to readPort() are compile-time constants. */ - if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); - if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); - if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); - if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); - if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); - if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); - if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); - if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); - if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); - if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); - if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); - if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); - if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); - if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); - if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); - if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) -{ - if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) - return; - - if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { - // disable i2c so pins can be used for other functions - // the following if statements should reconfigure the pins properly - disableI2CPins(); - } - if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - } - if (IS_PIN_ANALOG(pin)) { - reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting - } - if (IS_PIN_DIGITAL(pin)) { - if (mode == INPUT || mode == PIN_MODE_PULLUP) { - portConfigInputs[pin / 8] |= (1 << (pin & 7)); - } else { - portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); - } - } - Firmata.setPinState(pin, 0); - switch (mode) { - case PIN_MODE_ANALOG: - if (IS_PIN_ANALOG(pin)) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - } - Firmata.setPinMode(pin, PIN_MODE_ANALOG); - } - break; - case INPUT: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - Firmata.setPinMode(pin, INPUT); - } - break; - case PIN_MODE_PULLUP: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); - Firmata.setPinMode(pin, PIN_MODE_PULLUP); - Firmata.setPinState(pin, 1); - } - break; - case OUTPUT: - if (IS_PIN_DIGITAL(pin)) { - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - Firmata.setPinMode(pin, OUTPUT); - } - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_PWM(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), 0); - Firmata.setPinMode(pin, PIN_MODE_PWM); - } - break; - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) { - Firmata.setPinMode(pin, PIN_MODE_SERVO); - if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { - // pass -1 for min and max pulse values to use default values set - // by Servo library - attachServo(pin, -1, -1); - } - } - break; - case PIN_MODE_I2C: - if (IS_PIN_I2C(pin)) { - // mark the pin as i2c - // the user must call I2C_CONFIG to enable I2C for a device - Firmata.setPinMode(pin, PIN_MODE_I2C); - } - break; - case PIN_MODE_SERIAL: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); -#endif - break; - default: - Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM - } - // TODO: save status to EEPROM here, if changed -} - -/* - * Sets the value of an individual pin. Useful if you want to set a pin value but - * are not tracking the digital port state. - * Can only be used on pins configured as OUTPUT. - * Cannot be used to enable pull-ups on Digital INPUT pins. - */ -void setPinValueCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { - if (Firmata.getPinMode(pin) == OUTPUT) { - Firmata.setPinState(pin, value); - digitalWrite(PIN_TO_DIGITAL(pin), value); - } - } -} - -void analogWriteCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS) { - switch (Firmata.getPinMode(pin)) { - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) - servos[servoPinMap[pin]].write(value); - Firmata.setPinState(pin, value); - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) - analogWrite(PIN_TO_PWM(pin), value); - Firmata.setPinState(pin, value); - break; - } - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; - - if (port < TOTAL_PORTS) { - // create a mask of the pins on this port that are writable. - lastPin = port * 8 + 8; - if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; - for (pin = port * 8; pin < lastPin; pin++) { - // do not disturb non-digital pins (eg, Rx & Tx) - if (IS_PIN_DIGITAL(pin)) { - // do not touch pins in PWM, ANALOG, SERVO or other modes - if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { - pinValue = ((byte)value & mask) ? 1 : 0; - if (Firmata.getPinMode(pin) == OUTPUT) { - pinWriteMask |= mask; - } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { - // only handle INPUT here for backwards compatibility -#if ARDUINO > 100 - pinMode(pin, INPUT_PULLUP); -#else - // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier - pinWriteMask |= mask; -#endif - } - Firmata.setPinState(pin, pinValue); - } - } - mask = mask << 1; - } - writePort(port, (byte)value, pinWriteMask); - } -} - - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte analogPin, int value) -{ - if (analogPin < TOTAL_ANALOG_PINS) { - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); - } else { - analogInputsToReport = analogInputsToReport | (1 << analogPin); - // prevent during system reset or all analog pin values will be reported - // which may report noise for unconnected analog pins - if (!isResetting) { - // Send pin value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - if (port < TOTAL_PORTS) { - reportPINs[port] = (byte)value; - // Send port value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); - } - // do not disable analog reporting on these 8 pins, to allow some - // pins used for digital, others analog. Instead, allow both types - // of reporting to be enabled, but check if the pin is configured - // as analog when sampling the analog inputs. Likewise, while - // scanning digital pins, portConfigInputs will mask off values from any - // pins configured as analog -} - -/*============================================================================== - * SYSEX-BASED commands - *============================================================================*/ - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte stopTX; - byte slaveAddress; - byte data; - int slaveRegister; - unsigned int delayTime; - - switch (command) { - case I2C_REQUEST: - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { - Firmata.sendString("10-bit addressing not supported"); - return; - } - else { - slaveAddress = argv[0]; - } - - // need to invert the logic here since 0 will be default for client - // libraries that have not updated to add support for restart tx - if (argv[1] & I2C_END_TX_MASK) { - stopTX = I2C_RESTART_TX; - } - else { - stopTX = I2C_STOP_TX; // default - } - - switch (mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - wireWrite(data); - } - Wire.endTransmission(); - delayMicroseconds(70); - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= I2C_MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - queryIndex++; - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = slaveRegister; - query[queryIndex].bytes = data; - query[queryIndex].stopTX = stopTX; - break; - case I2C_STOP_READING: - byte queryIndexToSkip; - // if read continuous mode is enabled for only 1 i2c device, disable - // read continuous reporting for that device - if (queryIndex <= 0) { - queryIndex = -1; - } else { - queryIndexToSkip = 0; - // if read continuous mode is enabled for multiple devices, - // determine which device to stop reading and remove it's data from - // the array, shifiting other array data to fill the space - for (byte i = 0; i < queryIndex + 1; i++) { - if (query[i].addr == slaveAddress) { - queryIndexToSkip = i; - break; - } - } - - for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { - if (i < I2C_MAX_QUERIES) { - query[i].addr = query[i + 1].addr; - query[i].reg = query[i + 1].reg; - query[i].bytes = query[i + 1].bytes; - query[i].stopTX = query[i + 1].stopTX; - } - } - queryIndex--; - } - break; - default: - break; - } - break; - case I2C_CONFIG: - delayTime = (argv[0] + (argv[1] << 7)); - - if (delayTime > 0) { - i2cReadDelayTime = delayTime; - } - - if (!isI2CEnabled) { - enableI2CPins(); - } - - break; - case SERVO_CONFIG: - if (argc > 4) { - // these vars are here for clarity, they'll optimized away by the compiler - byte pin = argv[0]; - int minPulse = argv[1] + (argv[2] << 7); - int maxPulse = argv[3] + (argv[4] << 7); - - if (IS_PIN_DIGITAL(pin)) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - attachServo(pin, minPulse, maxPulse); - setPinModeCallback(pin, PIN_MODE_SERVO); - } - } - break; - case SAMPLING_INTERVAL: - if (argc > 1) { - samplingInterval = argv[0] + (argv[1] << 7); - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - } else { - //Firmata.sendString("Not enough data"); - } - break; - case EXTENDED_ANALOG: - if (argc > 1) { - int val = argv[1]; - if (argc > 2) val |= (argv[2] << 7); - if (argc > 3) val |= (argv[3] << 14); - analogWriteCallback(argv[0], val); - } - break; - case CAPABILITY_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(CAPABILITY_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - Firmata.write((byte)INPUT); - Firmata.write(1); - Firmata.write((byte)PIN_MODE_PULLUP); - Firmata.write(1); - Firmata.write((byte)OUTPUT); - Firmata.write(1); - } - if (IS_PIN_ANALOG(pin)) { - Firmata.write(PIN_MODE_ANALOG); - Firmata.write(10); // 10 = 10-bit resolution - } - if (IS_PIN_PWM(pin)) { - Firmata.write(PIN_MODE_PWM); - Firmata.write(8); // 8 = 8-bit resolution - } - if (IS_PIN_DIGITAL(pin)) { - Firmata.write(PIN_MODE_SERVO); - Firmata.write(14); - } - if (IS_PIN_I2C(pin)) { - Firmata.write(PIN_MODE_I2C); - Firmata.write(1); // TODO: could assign a number to map to SCL or SDA - } -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleCapability(pin); -#endif - Firmata.write(127); - } - Firmata.write(END_SYSEX); - break; - case PIN_STATE_QUERY: - if (argc > 0) { - byte pin = argv[0]; - Firmata.write(START_SYSEX); - Firmata.write(PIN_STATE_RESPONSE); - Firmata.write(pin); - if (pin < TOTAL_PINS) { - Firmata.write(Firmata.getPinMode(pin)); - Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); - if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); - if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); - } - Firmata.write(END_SYSEX); - } - break; - case ANALOG_MAPPING_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(ANALOG_MAPPING_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); - } - Firmata.write(END_SYSEX); - break; - - case SERIAL_MESSAGE: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleSysex(command, argc, argv); -#endif - break; - } -} - -void enableI2CPins() -{ - byte i; - // is there a faster way to do this? would probaby require importing - // Arduino.h to get SCL and SDA pins - for (i = 0; i < TOTAL_PINS; i++) { - if (IS_PIN_I2C(i)) { - // mark pins as i2c so they are ignore in non i2c data requests - setPinModeCallback(i, PIN_MODE_I2C); - } - } - - isI2CEnabled = true; - - Wire.begin(); -} - -/* disable the i2c pins so they can be used for other functions */ -void disableI2CPins() { - isI2CEnabled = false; - // disable read continuous mode for all devices - queryIndex = -1; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ - -void systemResetCallback() -{ - isResetting = true; - - // initialize a defalt state - // TODO: option to load config from EEPROM instead of default - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.reset(); -#endif - - if (isI2CEnabled) { - disableI2CPins(); - } - - for (byte i = 0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; // by default, reporting off - portConfigInputs[i] = 0; // until activated - previousPINs[i] = 0; - } - - for (byte i = 0; i < TOTAL_PINS; i++) { - // pins with analog capability default to analog input - // otherwise, pins default to digital output - if (IS_PIN_ANALOG(i)) { - // turns off pullup, configures everything - setPinModeCallback(i, PIN_MODE_ANALOG); - } else if (IS_PIN_DIGITAL(i)) { - // sets the output to 0, configures portConfigInputs - setPinModeCallback(i, OUTPUT); - } - - servoPinMap[i] = 255; - } - // by default, do not report any analog inputs - analogInputsToReport = 0; - - detachedServoCount = 0; - servoCount = 0; - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - /* - TODO: this can never execute, since no pins default to digital input - but it will be needed when/if we support EEPROM stored config - for (byte i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - */ - isResetting = false; -} - -void setup() -{ - DEBUG_BEGIN(9600); - -#ifdef YUN_ETHERNET - Bridge.begin(); -#else -#ifdef local_ip - Ethernet.begin((uint8_t *)mac, local_ip); //start ethernet -#else - Ethernet.begin((uint8_t *)mac); //start ethernet using dhcp -#endif -#endif - - DEBUG_PRINTLN("connecting..."); - - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - -#ifdef WIZ5100_ETHERNET - // StandardFirmataEthernet communicates with Ethernet shields over SPI. Therefore all - // SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. - // add Pin 10 and configure pin 53 as output if using a MEGA with an Ethernet shield. - - for (byte i = 0; i < TOTAL_PINS; i++) { - if (IS_IGNORE_ETHERNET_SHIELD(i) - #if defined(__AVR_ATmega32U4__) - || 24 == i // On Leonardo, pin 24 maps to D4 and pin 28 maps to D10 - || 28 == i - #endif - ) { - Firmata.setPinMode(i, PIN_MODE_IGNORE); - } - } - - // Arduino Ethernet and Arduino EthernetShield have SD SS wired to D4 - pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata - digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; -#endif // WIZ5100_ETHERNET - -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA -#endif - - // start up Network Firmata: - Firmata.begin(stream); - systemResetCallback(); // reset to default config -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - byte pin, analogPin; - - /* DIGITALREAD - as fast as possible, check for changes and output them to the - * Stream buffer using Stream.write() */ - checkDigitalInputs(); - - /* STREAMREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while (Firmata.available()) - Firmata.processInput(); - - // TODO - ensure that Stream buffer doesn't go over 60 bytes - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - /* ANALOGREAD - do all analogReads() at the configured sampling interval */ - for (pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { - analogPin = PIN_TO_ANALOG(pin); - if (analogInputsToReport & (1 << analogPin)) { - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // report i2c data for all device with read continuous mode enabled - if (queryIndex > -1) { - for (byte i = 0; i < queryIndex + 1; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); - } - } - } - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.update(); -#endif - -#if !defined local_ip && !defined YUN_ETHERNET - // only necessary when using DHCP, ensures local IP is updated appropriately if it changes - if (Ethernet.maintain()) { - stream.maintain(Ethernet.localIP()); - } -#endif - -} diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h deleted file mode 100644 index 4cccaa00a..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernet/ethernetConfig.h +++ /dev/null @@ -1,85 +0,0 @@ -/*============================================================================== - * NETWORK CONFIGURATION - * - * You must configure your particular hardware. Follow the steps below. - * - * Currently StandardFirmataEthernet is configured as a client. An option to - * configure as a server may be added in the future. - *============================================================================*/ - -// STEP 1 [REQUIRED] -// Uncomment / comment the appropriate set of includes for your hardware (OPTION A or B) -// Option A is enabled by default. - -/* - * OPTION A: Configure for Arduino Ethernet board or Arduino Ethernet shield (or clone) - * - * To configure StandardFirmataEthernet to use the original WIZ5100-based - * ethernet shield or Arduino Ethernet uncomment the WIZ5100_ETHERNET define below - */ -#define WIZ5100_ETHERNET - -#ifdef WIZ5100_ETHERNET -#include -#include -EthernetClient client; -#endif - -/* - * OPTION B: Configure for Arduin Yun - * - * The Ethernet port on the Arduino Yun board can be used with Firmata in this configuration. - * - * To execute StandardFirmataEthernet on Yun uncomment the YUN_ETHERNET define below and make - * sure the WIZ5100_ETHERNET define (above) is commented out. - * - * On Yun there's no need to configure local_ip and mac address as this is automatically - * configured on the linux-side of Yun. - */ -//#define YUN_ETHERNET - -#ifdef YUN_ETHERNET -#include -#include -YunClient client; -#endif - - -// STEP 2 [REQUIRED for all boards and shields] -// replace with IP of the server you want to connect to, comment out if using 'remote_host' -#define remote_ip IPAddress(10, 0, 0, 3) -// *** REMOTE HOST IS NOT YET WORKING *** -// replace with hostname of server you want to connect to, comment out if using 'remote_ip' -// #define remote_host "server.local" - -// STEP 3 [REQUIRED unless using Arduin Yun] -// Replace with the port that your server is listening on -#define remote_port 3030 - -// STEP 4 [REQUIRED unless using Arduino Yun OR if not using DHCP] -// Replace with your board or ethernet shield's IP address -// Comment out if you want to use DHCP -#define local_ip IPAddress(10, 0, 0, 15) - -// STEP 5 [REQUIRED unless using Arduino Yun] -// replace with ethernet shield mac. Must be unique for your network -const byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x53, 0xE5}; - -/*============================================================================== - * CONFIGURATION ERROR CHECK (don't change anything here) - *============================================================================*/ - -#if !defined WIZ5100_ETHERNET && !defined YUN_ETHERNET -#error "you must define either WIZ5100_ETHERNET or YUN_ETHERNET in ethernetConfig.h" -#endif - -#if defined remote_ip && defined remote_host -#error "cannot define both remote_ip and remote_host at the same time in ethernetConfig.h" -#endif - -/*============================================================================== - * PIN IGNORE MACROS (don't change anything here) - *============================================================================*/ - -// ignore SPI pins, pin 10 (Ethernet SS) and pin 4 (SS for SD-Card on Ethernet shield) -#define IS_IGNORE_ETHERNET_SHIELD(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 10) diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino deleted file mode 100644 index a1d13aba0..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/StandardFirmataEthernetPlus.ino +++ /dev/null @@ -1,909 +0,0 @@ -/* - Firmata is a generic protocol for communicating with microcontrollers - from software on a host computer. It is intended to work with - any host computer software package. - - To download a host software package, please clink on the following link - to open the list of Firmata client libraries your default browser. - - https://github.com/firmata/arduino#firmata-client-libraries - - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -/* - README - - StandardFirmataEthernetPlus is a client implementation. You will need a Firmata client library - with a network transport that can act as a server in order to establish a connection between - StandardFirmataEthernetPlus and the Firmata client application. - - StandardFirmataEthernetPlus adds additional features that may exceed the Flash and - RAM sizes of Arduino boards such as ATMega328p (Uno) and ATMega32u4 - (Leonardo, Micro, Yun, etc). It is best to use StandardFirmataPlus with a board that - has > 32k Flash and > 3k RAM such as: Arduino Mega, Arduino Due, Teensy 3.0/3.1/3.2, etc. - - This sketch consumes too much Flash and RAM to run reliably on an - Arduino Leonardo, Yun, ATMega32u4-based board. Use StandardFirmataEthernet.ino instead - for those boards and other boards that do not meet the Flash and RAM requirements. - - To use StandardFirmataEthernet you will need to have one of the following - boards or shields: - - - Arduino Ethernet shield (or clone) - - Arduino Ethernet board (or clone) - - Follow the instructions in the ethernetConfig.h file (ethernetConfig.h tab in Arduino IDE) to - configure your particular hardware. - - NOTE: If you are using an Arduino Ethernet shield you cannot use the following pins on - the following boards. Firmata will ignore any requests to use these pins: - - - Arduino Mega: (D4, D10, D50, D51, D52, D53) - - Arduino Due: (D4, D10) - - Arduino Zero: (D4, D10) - - Arduino Uno or other ATMega328p boards: (D4, D10, D11, D12, D13) - - If you are using an ArduinoEthernet board, the following pins cannot be used (same as Uno): - - D4, D10, D11, D12, D13 -*/ - -#include -#include -#include - -/* - * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your connection - * that may help in the event of connection issues. If defined, some boards may not begin executing this sketch - * until the Serial console is opened. - */ -//#define SERIAL_DEBUG -#include "utility/firmataDebug.h" - -// follow the instructions in ethernetConfig.h to configure your particular hardware -#include "ethernetConfig.h" -#include "utility/EthernetClientStream.h" - -#include "utility/SerialFirmata.h" - -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 -#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 -#define I2C_END_TX_MASK B01000000 -#define I2C_STOP_TX 1 -#define I2C_RESTART_TX 0 -#define I2C_MAX_QUERIES 8 -#define I2C_REGISTER_NOT_SPECIFIED -1 - -// the minimum interval for sampling analog input -#define MINIMUM_SAMPLING_INTERVAL 1 - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -#if defined remote_ip && !defined remote_host -#ifdef local_ip -EthernetClientStream stream(client, local_ip, remote_ip, NULL, remote_port); -#else -EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), remote_ip, NULL, remote_port); -#endif -#endif - -#if !defined remote_ip && defined remote_host -#ifdef local_ip -EthernetClientStream stream(client, local_ip, IPAddress(0, 0, 0, 0), remote_host, remote_port); -#else -EthernetClientStream stream(client, IPAddress(0, 0, 0, 0), IPAddress(0, 0, 0, 0), remote_host, remote_port); -#endif -#endif - -#ifdef FIRMATA_SERIAL_FEATURE -SerialFirmata serialFeature; -#endif - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting - -/* digital input ports */ -byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence -byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent - -/* pins configuration */ -byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) - -/* i2c data */ -struct i2c_device_info { - byte addr; - int reg; - byte bytes; - byte stopTX; -}; - -/* for i2c read continuous mode */ -i2c_device_info query[I2C_MAX_QUERIES]; - -byte i2cRxData[32]; -boolean isI2CEnabled = false; -signed char queryIndex = -1; -// default delay time between i2c read request and Wire.requestFrom() -unsigned int i2cReadDelayTime = 0; - -Servo servos[MAX_SERVOS]; -byte servoPinMap[TOTAL_PINS]; -byte detachedServos[MAX_SERVOS]; -byte detachedServoCount = 0; -byte servoCount = 0; - -boolean isResetting = false; - -/* utility functions */ -void wireWrite(byte data) -{ -#if ARDUINO >= 100 - Wire.write((byte)data); -#else - Wire.send(data); -#endif -} - -byte wireRead(void) -{ -#if ARDUINO >= 100 - return Wire.read(); -#else - return Wire.receive(); -#endif -} - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void attachServo(byte pin, int minPulse, int maxPulse) -{ - if (servoCount < MAX_SERVOS) { - // reuse indexes of detached servos until all have been reallocated - if (detachedServoCount > 0) { - servoPinMap[pin] = detachedServos[detachedServoCount - 1]; - if (detachedServoCount > 0) detachedServoCount--; - } else { - servoPinMap[pin] = servoCount; - servoCount++; - } - if (minPulse > 0 && maxPulse > 0) { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); - } else { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); - } - } else { - Firmata.sendString("Max servos attached"); - } -} - -void detachServo(byte pin) -{ - servos[servoPinMap[pin]].detach(); - // if we're detaching the last servo, decrement the count - // otherwise store the index of the detached servo - if (servoPinMap[pin] == servoCount && servoCount > 0) { - servoCount--; - } else if (servoCount > 0) { - // keep track of detached servos because we want to reuse their indexes - // before incrementing the count of attached servos - detachedServoCount++; - detachedServos[detachedServoCount - 1] = servoPinMap[pin]; - } - - servoPinMap[pin] = 255; -} - -void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { - // allow I2C requests that don't require a register read - // for example, some devices using an interrupt pin to signify new data available - // do not always require the register read so upon interrupt you call Wire.requestFrom() - if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - wireWrite((byte)theRegister); - Wire.endTransmission(stopTX); // default = true - // do not set a value of 0 - if (i2cReadDelayTime > 0) { - // delay is necessary for some devices such as WiiNunchuck - delayMicroseconds(i2cReadDelayTime); - } - } else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom - - // check to be sure correct number of bytes were returned by slave - if (numBytes < Wire.available()) { - Firmata.sendString("I2C: Too many bytes received"); - } else if (numBytes > Wire.available()) { - Firmata.sendString("I2C: Too few bytes received"); - } - - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - - for (int i = 0; i < numBytes && Wire.available(); i++) { - i2cRxData[2 + i] = wireRead(); - } - - // send slave address, register and received bytes - Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); -} - -void outputPort(byte portNumber, byte portValue, byte forceSend) -{ - // pins not configured as INPUT are cleared to zeros - portValue = portValue & portConfigInputs[portNumber]; - // only send if the value is different than previously sent - if (forceSend || previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Stream output queue using Stream.write() */ -void checkDigitalInputs(void) -{ - /* Using non-looping code allows constants to be given to readPort(). - * The compiler will apply substantial optimizations if the inputs - * to readPort() are compile-time constants. */ - if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); - if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); - if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); - if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); - if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); - if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); - if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); - if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); - if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); - if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); - if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); - if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); - if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); - if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); - if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); - if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) -{ - if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) - return; - - if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { - // disable i2c so pins can be used for other functions - // the following if statements should reconfigure the pins properly - disableI2CPins(); - } - if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - } - if (IS_PIN_ANALOG(pin)) { - reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting - } - if (IS_PIN_DIGITAL(pin)) { - if (mode == INPUT || mode == PIN_MODE_PULLUP) { - portConfigInputs[pin / 8] |= (1 << (pin & 7)); - } else { - portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); - } - } - Firmata.setPinState(pin, 0); - switch (mode) { - case PIN_MODE_ANALOG: - if (IS_PIN_ANALOG(pin)) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - } - Firmata.setPinMode(pin, PIN_MODE_ANALOG); - } - break; - case INPUT: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - Firmata.setPinMode(pin, INPUT); - } - break; - case PIN_MODE_PULLUP: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); - Firmata.setPinMode(pin, PIN_MODE_PULLUP); - Firmata.setPinState(pin, 1); - } - break; - case OUTPUT: - if (IS_PIN_DIGITAL(pin)) { - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - Firmata.setPinMode(pin, OUTPUT); - } - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_PWM(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), 0); - Firmata.setPinMode(pin, PIN_MODE_PWM); - } - break; - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) { - Firmata.setPinMode(pin, PIN_MODE_SERVO); - if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { - // pass -1 for min and max pulse values to use default values set - // by Servo library - attachServo(pin, -1, -1); - } - } - break; - case PIN_MODE_I2C: - if (IS_PIN_I2C(pin)) { - // mark the pin as i2c - // the user must call I2C_CONFIG to enable I2C for a device - Firmata.setPinMode(pin, PIN_MODE_I2C); - } - break; - case PIN_MODE_SERIAL: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); -#endif - break; - default: - Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM - } - // TODO: save status to EEPROM here, if changed -} - -/* - * Sets the value of an individual pin. Useful if you want to set a pin value but - * are not tracking the digital port state. - * Can only be used on pins configured as OUTPUT. - * Cannot be used to enable pull-ups on Digital INPUT pins. - */ -void setPinValueCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { - if (Firmata.getPinMode(pin) == OUTPUT) { - Firmata.setPinState(pin, value); - digitalWrite(PIN_TO_DIGITAL(pin), value); - } - } -} - -void analogWriteCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS) { - switch (Firmata.getPinMode(pin)) { - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) - servos[servoPinMap[pin]].write(value); - Firmata.setPinState(pin, value); - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) - analogWrite(PIN_TO_PWM(pin), value); - Firmata.setPinState(pin, value); - break; - } - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; - - if (port < TOTAL_PORTS) { - // create a mask of the pins on this port that are writable. - lastPin = port * 8 + 8; - if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; - for (pin = port * 8; pin < lastPin; pin++) { - // do not disturb non-digital pins (eg, Rx & Tx) - if (IS_PIN_DIGITAL(pin)) { - // do not touch pins in PWM, ANALOG, SERVO or other modes - if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { - pinValue = ((byte)value & mask) ? 1 : 0; - if (Firmata.getPinMode(pin) == OUTPUT) { - pinWriteMask |= mask; - } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { - // only handle INPUT here for backwards compatibility -#if ARDUINO > 100 - pinMode(pin, INPUT_PULLUP); -#else - // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier - pinWriteMask |= mask; -#endif - } - Firmata.setPinState(pin, pinValue); - } - } - mask = mask << 1; - } - writePort(port, (byte)value, pinWriteMask); - } -} - - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte analogPin, int value) -{ - if (analogPin < TOTAL_ANALOG_PINS) { - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); - } else { - analogInputsToReport = analogInputsToReport | (1 << analogPin); - // prevent during system reset or all analog pin values will be reported - // which may report noise for unconnected analog pins - if (!isResetting) { - // Send pin value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - if (port < TOTAL_PORTS) { - reportPINs[port] = (byte)value; - // Send port value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); - } - // do not disable analog reporting on these 8 pins, to allow some - // pins used for digital, others analog. Instead, allow both types - // of reporting to be enabled, but check if the pin is configured - // as analog when sampling the analog inputs. Likewise, while - // scanning digital pins, portConfigInputs will mask off values from any - // pins configured as analog -} - -/*============================================================================== - * SYSEX-BASED commands - *============================================================================*/ - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte stopTX; - byte slaveAddress; - byte data; - int slaveRegister; - unsigned int delayTime; - - switch (command) { - case I2C_REQUEST: - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { - Firmata.sendString("10-bit addressing not supported"); - return; - } - else { - slaveAddress = argv[0]; - } - - // need to invert the logic here since 0 will be default for client - // libraries that have not updated to add support for restart tx - if (argv[1] & I2C_END_TX_MASK) { - stopTX = I2C_RESTART_TX; - } - else { - stopTX = I2C_STOP_TX; // default - } - - switch (mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - wireWrite(data); - } - Wire.endTransmission(); - delayMicroseconds(70); - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= I2C_MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - queryIndex++; - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = slaveRegister; - query[queryIndex].bytes = data; - query[queryIndex].stopTX = stopTX; - break; - case I2C_STOP_READING: - byte queryIndexToSkip; - // if read continuous mode is enabled for only 1 i2c device, disable - // read continuous reporting for that device - if (queryIndex <= 0) { - queryIndex = -1; - } else { - queryIndexToSkip = 0; - // if read continuous mode is enabled for multiple devices, - // determine which device to stop reading and remove it's data from - // the array, shifiting other array data to fill the space - for (byte i = 0; i < queryIndex + 1; i++) { - if (query[i].addr == slaveAddress) { - queryIndexToSkip = i; - break; - } - } - - for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { - if (i < I2C_MAX_QUERIES) { - query[i].addr = query[i + 1].addr; - query[i].reg = query[i + 1].reg; - query[i].bytes = query[i + 1].bytes; - query[i].stopTX = query[i + 1].stopTX; - } - } - queryIndex--; - } - break; - default: - break; - } - break; - case I2C_CONFIG: - delayTime = (argv[0] + (argv[1] << 7)); - - if (delayTime > 0) { - i2cReadDelayTime = delayTime; - } - - if (!isI2CEnabled) { - enableI2CPins(); - } - - break; - case SERVO_CONFIG: - if (argc > 4) { - // these vars are here for clarity, they'll optimized away by the compiler - byte pin = argv[0]; - int minPulse = argv[1] + (argv[2] << 7); - int maxPulse = argv[3] + (argv[4] << 7); - - if (IS_PIN_DIGITAL(pin)) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - attachServo(pin, minPulse, maxPulse); - setPinModeCallback(pin, PIN_MODE_SERVO); - } - } - break; - case SAMPLING_INTERVAL: - if (argc > 1) { - samplingInterval = argv[0] + (argv[1] << 7); - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - } else { - //Firmata.sendString("Not enough data"); - } - break; - case EXTENDED_ANALOG: - if (argc > 1) { - int val = argv[1]; - if (argc > 2) val |= (argv[2] << 7); - if (argc > 3) val |= (argv[3] << 14); - analogWriteCallback(argv[0], val); - } - break; - case CAPABILITY_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(CAPABILITY_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - Firmata.write((byte)INPUT); - Firmata.write(1); - Firmata.write((byte)PIN_MODE_PULLUP); - Firmata.write(1); - Firmata.write((byte)OUTPUT); - Firmata.write(1); - } - if (IS_PIN_ANALOG(pin)) { - Firmata.write(PIN_MODE_ANALOG); - Firmata.write(10); // 10 = 10-bit resolution - } - if (IS_PIN_PWM(pin)) { - Firmata.write(PIN_MODE_PWM); - Firmata.write(8); // 8 = 8-bit resolution - } - if (IS_PIN_DIGITAL(pin)) { - Firmata.write(PIN_MODE_SERVO); - Firmata.write(14); - } - if (IS_PIN_I2C(pin)) { - Firmata.write(PIN_MODE_I2C); - Firmata.write(1); // TODO: could assign a number to map to SCL or SDA - } -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleCapability(pin); -#endif - Firmata.write(127); - } - Firmata.write(END_SYSEX); - break; - case PIN_STATE_QUERY: - if (argc > 0) { - byte pin = argv[0]; - Firmata.write(START_SYSEX); - Firmata.write(PIN_STATE_RESPONSE); - Firmata.write(pin); - if (pin < TOTAL_PINS) { - Firmata.write(Firmata.getPinMode(pin)); - Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); - if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); - if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); - } - Firmata.write(END_SYSEX); - } - break; - case ANALOG_MAPPING_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(ANALOG_MAPPING_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); - } - Firmata.write(END_SYSEX); - break; - - case SERIAL_MESSAGE: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleSysex(command, argc, argv); -#endif - break; - } -} - -void enableI2CPins() -{ - byte i; - // is there a faster way to do this? would probaby require importing - // Arduino.h to get SCL and SDA pins - for (i = 0; i < TOTAL_PINS; i++) { - if (IS_PIN_I2C(i)) { - // mark pins as i2c so they are ignore in non i2c data requests - setPinModeCallback(i, PIN_MODE_I2C); - } - } - - isI2CEnabled = true; - - Wire.begin(); -} - -/* disable the i2c pins so they can be used for other functions */ -void disableI2CPins() { - isI2CEnabled = false; - // disable read continuous mode for all devices - queryIndex = -1; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ - -void systemResetCallback() -{ - isResetting = true; - - // initialize a defalt state - // TODO: option to load config from EEPROM instead of default - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.reset(); -#endif - - if (isI2CEnabled) { - disableI2CPins(); - } - - for (byte i = 0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; // by default, reporting off - portConfigInputs[i] = 0; // until activated - previousPINs[i] = 0; - } - - for (byte i = 0; i < TOTAL_PINS; i++) { - // pins with analog capability default to analog input - // otherwise, pins default to digital output - if (IS_PIN_ANALOG(i)) { - // turns off pullup, configures everything - setPinModeCallback(i, PIN_MODE_ANALOG); - } else if (IS_PIN_DIGITAL(i)) { - // sets the output to 0, configures portConfigInputs - setPinModeCallback(i, OUTPUT); - } - - servoPinMap[i] = 255; - } - // by default, do not report any analog inputs - analogInputsToReport = 0; - - detachedServoCount = 0; - servoCount = 0; - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - /* - TODO: this can never execute, since no pins default to digital input - but it will be needed when/if we support EEPROM stored config - for (byte i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - */ - isResetting = false; -} - -void setup() -{ - DEBUG_BEGIN(9600); - -#ifdef local_ip - Ethernet.begin((uint8_t *)mac, local_ip); //start ethernet -#else - Ethernet.begin((uint8_t *)mac); //start ethernet using dhcp -#endif - - DEBUG_PRINTLN("connecting..."); - - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - -#ifdef WIZ5100_ETHERNET - // StandardFirmataEthernetPlus communicates with Ethernet shields over SPI. Therefore all - // SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. - // add Pin 10 and configure pin 53 as output if using a MEGA with an Ethernet shield. - - for (byte i = 0; i < TOTAL_PINS; i++) { - if (IS_IGNORE_ETHERNET_SHIELD(i)) { - Firmata.setPinMode(i, PIN_MODE_IGNORE); - } - } - - // Arduino Ethernet and Arduino EthernetShield have SD SS wired to D4 - pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata - digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; -#endif // WIZ5100_ETHERNET - -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA -#endif - - // start up Network Firmata: - Firmata.begin(stream); - systemResetCallback(); // reset to default config -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - byte pin, analogPin; - - /* DIGITALREAD - as fast as possible, check for changes and output them to the - * Stream buffer using Stream.write() */ - checkDigitalInputs(); - - /* STREAMREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while (Firmata.available()) - Firmata.processInput(); - - // TODO - ensure that Stream buffer doesn't go over 60 bytes - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - /* ANALOGREAD - do all analogReads() at the configured sampling interval */ - for (pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { - analogPin = PIN_TO_ANALOG(pin); - if (analogInputsToReport & (1 << analogPin)) { - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // report i2c data for all device with read continuous mode enabled - if (queryIndex > -1) { - for (byte i = 0; i < queryIndex + 1; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); - } - } - } - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.update(); -#endif - -#if !defined local_ip - // only necessary when using DHCP, ensures local IP is updated appropriately if it changes - if (Ethernet.maintain()) { - stream.maintain(Ethernet.localIP()); - } -#endif - -} diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h deleted file mode 100644 index 105a87923..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataEthernetPlus/ethernetConfig.h +++ /dev/null @@ -1,55 +0,0 @@ -/*============================================================================== - * NETWORK CONFIGURATION - * - * You must configure your particular hardware. Follow the steps below. - * - * Currently StandardFirmataEthernetPlus is configured as a client. An option to - * configure as a server may be added in the future. - *============================================================================*/ - -/* - * Only WIZ5100-based shields and boards are currently supported for - * StandardFirmataEthernetPlus. - */ -#define WIZ5100_ETHERNET - -#ifdef WIZ5100_ETHERNET -#include -#include -EthernetClient client; -#endif - -// STEP 1 [REQUIRED for all boards and shields] -// replace with IP of the server you want to connect to, comment out if using 'remote_host' -#define remote_ip IPAddress(10, 0, 0, 3) -// *** REMOTE HOST IS NOT YET WORKING *** -// replace with hostname of server you want to connect to, comment out if using 'remote_ip' -// #define remote_host "server.local" - -// STEP 2 [REQUIRED] -// Replace with the port that your server is listening on -#define remote_port 3030 - -// STEP 3 [REQUIRED unless using DHCP] -// Replace with your board or ethernet shield's IP address -// Comment out if you want to use DHCP -#define local_ip IPAddress(10, 0, 0, 15) - -// STEP 4 [REQUIRED] -// replace with ethernet shield mac. Must be unique for your network -const byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x53, 0xE5}; - -/*============================================================================== - * CONFIGURATION ERROR CHECK (don't change anything here) - *============================================================================*/ - -#if defined remote_ip && defined remote_host -#error "cannot define both remote_ip and remote_host at the same time in ethernetConfig.h" -#endif - -/*============================================================================== - * PIN IGNORE MACROS (don't change anything here) - *============================================================================*/ - -// ignore SPI pins, pin 10 (Ethernet SS) and pin 4 (SS for SD-Card on Ethernet shield) -#define IS_IGNORE_ETHERNET_SHIELD(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 10) diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino deleted file mode 100644 index 657a9da1f..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataPlus/StandardFirmataPlus.ino +++ /dev/null @@ -1,838 +0,0 @@ -/* - Firmata is a generic protocol for communicating with microcontrollers - from software on a host computer. It is intended to work with - any host computer software package. - - To download a host software package, please clink on the following link - to open the list of Firmata client libraries your default browser. - - https://github.com/firmata/arduino#firmata-client-libraries - - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -/* - README - - StandardFirmataPlus adds additional features that may exceed the Flash and - RAM sizes of Arduino boards such as ATMega328p (Uno) and ATMega32u4 - (Leonardo, Micro, Yun, etc). It is best to use StandardFirmataPlus with higher - memory boards such as the Arduino Mega, Arduino Due, Teensy 3.0/3.1/3.2. - - All Firmata examples that are appended with "Plus" add the following features: - - - Ability to interface with serial devices using UART, USART, or SoftwareSerial - depending on the capatilities of the board. - - At the time of this writing, StandardFirmataPlus will still compile and run - on ATMega328p and ATMega32u4-based boards, but future versions of this sketch - may not as new features are added. -*/ - -#include -#include -#include - -#include "utility/SerialFirmata.h" - -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 -#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 -#define I2C_END_TX_MASK B01000000 -#define I2C_STOP_TX 1 -#define I2C_RESTART_TX 0 -#define I2C_MAX_QUERIES 8 -#define I2C_REGISTER_NOT_SPECIFIED -1 - -// the minimum interval for sampling analog input -#define MINIMUM_SAMPLING_INTERVAL 1 - - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -#ifdef FIRMATA_SERIAL_FEATURE -SerialFirmata serialFeature; -#endif - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting - -/* digital input ports */ -byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence -byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent - -/* pins configuration */ -byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -unsigned int samplingInterval = 19; // how often to run the main loop (in ms) - -/* i2c data */ -struct i2c_device_info { - byte addr; - int reg; - byte bytes; - byte stopTX; -}; - -/* for i2c read continuous more */ -i2c_device_info query[I2C_MAX_QUERIES]; - -byte i2cRxData[32]; -boolean isI2CEnabled = false; -signed char queryIndex = -1; -// default delay time between i2c read request and Wire.requestFrom() -unsigned int i2cReadDelayTime = 0; - -Servo servos[MAX_SERVOS]; -byte servoPinMap[TOTAL_PINS]; -byte detachedServos[MAX_SERVOS]; -byte detachedServoCount = 0; -byte servoCount = 0; - -boolean isResetting = false; - - -/* utility functions */ -void wireWrite(byte data) -{ -#if ARDUINO >= 100 - Wire.write((byte)data); -#else - Wire.send(data); -#endif -} - -byte wireRead(void) -{ -#if ARDUINO >= 100 - return Wire.read(); -#else - return Wire.receive(); -#endif -} - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void attachServo(byte pin, int minPulse, int maxPulse) -{ - if (servoCount < MAX_SERVOS) { - // reuse indexes of detached servos until all have been reallocated - if (detachedServoCount > 0) { - servoPinMap[pin] = detachedServos[detachedServoCount - 1]; - if (detachedServoCount > 0) detachedServoCount--; - } else { - servoPinMap[pin] = servoCount; - servoCount++; - } - if (minPulse > 0 && maxPulse > 0) { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); - } else { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); - } - } else { - Firmata.sendString("Max servos attached"); - } -} - -void detachServo(byte pin) -{ - servos[servoPinMap[pin]].detach(); - // if we're detaching the last servo, decrement the count - // otherwise store the index of the detached servo - if (servoPinMap[pin] == servoCount && servoCount > 0) { - servoCount--; - } else if (servoCount > 0) { - // keep track of detached servos because we want to reuse their indexes - // before incrementing the count of attached servos - detachedServoCount++; - detachedServos[detachedServoCount - 1] = servoPinMap[pin]; - } - - servoPinMap[pin] = 255; -} - -void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { - // allow I2C requests that don't require a register read - // for example, some devices using an interrupt pin to signify new data available - // do not always require the register read so upon interrupt you call Wire.requestFrom() - if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - wireWrite((byte)theRegister); - Wire.endTransmission(stopTX); // default = true - // do not set a value of 0 - if (i2cReadDelayTime > 0) { - // delay is necessary for some devices such as WiiNunchuck - delayMicroseconds(i2cReadDelayTime); - } - } else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom - - // check to be sure correct number of bytes were returned by slave - if (numBytes < Wire.available()) { - Firmata.sendString("I2C: Too many bytes received"); - } else if (numBytes > Wire.available()) { - Firmata.sendString("I2C: Too few bytes received"); - } - - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - - for (int i = 0; i < numBytes && Wire.available(); i++) { - i2cRxData[2 + i] = wireRead(); - } - - // send slave address, register and received bytes - Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); -} - -void outputPort(byte portNumber, byte portValue, byte forceSend) -{ - // pins not configured as INPUT are cleared to zeros - portValue = portValue & portConfigInputs[portNumber]; - // only send if the value is different than previously sent - if (forceSend || previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Serial output queue using Serial.print() */ -void checkDigitalInputs(void) -{ - /* Using non-looping code allows constants to be given to readPort(). - * The compiler will apply substantial optimizations if the inputs - * to readPort() are compile-time constants. */ - if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); - if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); - if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); - if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); - if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); - if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); - if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); - if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); - if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); - if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); - if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); - if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); - if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); - if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); - if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); - if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) -{ - if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) - return; - - if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { - // disable i2c so pins can be used for other functions - // the following if statements should reconfigure the pins properly - disableI2CPins(); - } - if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - } - if (IS_PIN_ANALOG(pin)) { - reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting - } - if (IS_PIN_DIGITAL(pin)) { - if (mode == INPUT || mode == PIN_MODE_PULLUP) { - portConfigInputs[pin / 8] |= (1 << (pin & 7)); - } else { - portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); - } - } - Firmata.setPinState(pin, 0); - switch (mode) { - case PIN_MODE_ANALOG: - if (IS_PIN_ANALOG(pin)) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - } - Firmata.setPinMode(pin, PIN_MODE_ANALOG); - } - break; - case INPUT: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - Firmata.setPinMode(pin, INPUT); - } - break; - case PIN_MODE_PULLUP: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); - Firmata.setPinMode(pin, PIN_MODE_PULLUP); - Firmata.setPinState(pin, 1); - } - break; - case OUTPUT: - if (IS_PIN_DIGITAL(pin)) { - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - Firmata.setPinMode(pin, OUTPUT); - } - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_PWM(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), 0); - Firmata.setPinMode(pin, PIN_MODE_PWM); - } - break; - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) { - Firmata.setPinMode(pin, PIN_MODE_SERVO); - if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { - // pass -1 for min and max pulse values to use default values set - // by Servo library - attachServo(pin, -1, -1); - } - } - break; - case PIN_MODE_I2C: - if (IS_PIN_I2C(pin)) { - // mark the pin as i2c - // the user must call I2C_CONFIG to enable I2C for a device - Firmata.setPinMode(pin, PIN_MODE_I2C); - } - break; - case PIN_MODE_SERIAL: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); -#endif - break; - default: - Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM - } - // TODO: save status to EEPROM here, if changed -} - -/* - * Sets the value of an individual pin. Useful if you want to set a pin value but - * are not tracking the digital port state. - * Can only be used on pins configured as OUTPUT. - * Cannot be used to enable pull-ups on Digital INPUT pins. - */ -void setPinValueCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { - if (Firmata.getPinMode(pin) == OUTPUT) { - Firmata.setPinState(pin, value); - digitalWrite(PIN_TO_DIGITAL(pin), value); - } - } -} - -void analogWriteCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS) { - switch (Firmata.getPinMode(pin)) { - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) - servos[servoPinMap[pin]].write(value); - Firmata.setPinState(pin, value); - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) - analogWrite(PIN_TO_PWM(pin), value); - Firmata.setPinState(pin, value); - break; - } - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; - - if (port < TOTAL_PORTS) { - // create a mask of the pins on this port that are writable. - lastPin = port * 8 + 8; - if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; - for (pin = port * 8; pin < lastPin; pin++) { - // do not disturb non-digital pins (eg, Rx & Tx) - if (IS_PIN_DIGITAL(pin)) { - // do not touch pins in PWM, ANALOG, SERVO or other modes - if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { - pinValue = ((byte)value & mask) ? 1 : 0; - if (Firmata.getPinMode(pin) == OUTPUT) { - pinWriteMask |= mask; - } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { - // only handle INPUT here for backwards compatibility -#if ARDUINO > 100 - pinMode(pin, INPUT_PULLUP); -#else - // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier - pinWriteMask |= mask; -#endif - } - Firmata.setPinState(pin, pinValue); - } - } - mask = mask << 1; - } - writePort(port, (byte)value, pinWriteMask); - } -} - - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte analogPin, int value) -{ - if (analogPin < TOTAL_ANALOG_PINS) { - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); - } else { - analogInputsToReport = analogInputsToReport | (1 << analogPin); - // prevent during system reset or all analog pin values will be reported - // which may report noise for unconnected analog pins - if (!isResetting) { - // Send pin value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - if (port < TOTAL_PORTS) { - reportPINs[port] = (byte)value; - // Send port value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); - } - // do not disable analog reporting on these 8 pins, to allow some - // pins used for digital, others analog. Instead, allow both types - // of reporting to be enabled, but check if the pin is configured - // as analog when sampling the analog inputs. Likewise, while - // scanning digital pins, portConfigInputs will mask off values from any - // pins configured as analog -} - -/*============================================================================== - * SYSEX-BASED commands - *============================================================================*/ - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte stopTX; - byte slaveAddress; - byte data; - int slaveRegister; - unsigned int delayTime; - - switch (command) { - case I2C_REQUEST: - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { - Firmata.sendString("10-bit addressing not supported"); - return; - } - else { - slaveAddress = argv[0]; - } - - // need to invert the logic here since 0 will be default for client - // libraries that have not updated to add support for restart tx - if (argv[1] & I2C_END_TX_MASK) { - stopTX = I2C_RESTART_TX; - } - else { - stopTX = I2C_STOP_TX; // default - } - - switch (mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - wireWrite(data); - } - Wire.endTransmission(); - delayMicroseconds(70); - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= I2C_MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - queryIndex++; - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = slaveRegister; - query[queryIndex].bytes = data; - query[queryIndex].stopTX = stopTX; - break; - case I2C_STOP_READING: - byte queryIndexToSkip; - // if read continuous mode is enabled for only 1 i2c device, disable - // read continuous reporting for that device - if (queryIndex <= 0) { - queryIndex = -1; - } else { - queryIndexToSkip = 0; - // if read continuous mode is enabled for multiple devices, - // determine which device to stop reading and remove it's data from - // the array, shifiting other array data to fill the space - for (byte i = 0; i < queryIndex + 1; i++) { - if (query[i].addr == slaveAddress) { - queryIndexToSkip = i; - break; - } - } - - for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { - if (i < I2C_MAX_QUERIES) { - query[i].addr = query[i + 1].addr; - query[i].reg = query[i + 1].reg; - query[i].bytes = query[i + 1].bytes; - query[i].stopTX = query[i + 1].stopTX; - } - } - queryIndex--; - } - break; - default: - break; - } - break; - case I2C_CONFIG: - delayTime = (argv[0] + (argv[1] << 7)); - - if (delayTime > 0) { - i2cReadDelayTime = delayTime; - } - - if (!isI2CEnabled) { - enableI2CPins(); - } - - break; - case SERVO_CONFIG: - if (argc > 4) { - // these vars are here for clarity, they'll optimized away by the compiler - byte pin = argv[0]; - int minPulse = argv[1] + (argv[2] << 7); - int maxPulse = argv[3] + (argv[4] << 7); - - if (IS_PIN_DIGITAL(pin)) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - attachServo(pin, minPulse, maxPulse); - setPinModeCallback(pin, PIN_MODE_SERVO); - } - } - break; - case SAMPLING_INTERVAL: - if (argc > 1) { - samplingInterval = argv[0] + (argv[1] << 7); - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - } else { - //Firmata.sendString("Not enough data"); - } - break; - case EXTENDED_ANALOG: - if (argc > 1) { - int val = argv[1]; - if (argc > 2) val |= (argv[2] << 7); - if (argc > 3) val |= (argv[3] << 14); - analogWriteCallback(argv[0], val); - } - break; - case CAPABILITY_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(CAPABILITY_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - Firmata.write((byte)INPUT); - Firmata.write(1); - Firmata.write((byte)PIN_MODE_PULLUP); - Firmata.write(1); - Firmata.write((byte)OUTPUT); - Firmata.write(1); - } - if (IS_PIN_ANALOG(pin)) { - Firmata.write(PIN_MODE_ANALOG); - Firmata.write(10); // 10 = 10-bit resolution - } - if (IS_PIN_PWM(pin)) { - Firmata.write(PIN_MODE_PWM); - Firmata.write(8); // 8 = 8-bit resolution - } - if (IS_PIN_DIGITAL(pin)) { - Firmata.write(PIN_MODE_SERVO); - Firmata.write(14); - } - if (IS_PIN_I2C(pin)) { - Firmata.write(PIN_MODE_I2C); - Firmata.write(1); // TODO: could assign a number to map to SCL or SDA - } -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleCapability(pin); -#endif - Firmata.write(127); - } - Firmata.write(END_SYSEX); - break; - case PIN_STATE_QUERY: - if (argc > 0) { - byte pin = argv[0]; - Firmata.write(START_SYSEX); - Firmata.write(PIN_STATE_RESPONSE); - Firmata.write(pin); - if (pin < TOTAL_PINS) { - Firmata.write(Firmata.getPinMode(pin)); - Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); - if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); - if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); - } - Firmata.write(END_SYSEX); - } - break; - case ANALOG_MAPPING_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(ANALOG_MAPPING_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); - } - Firmata.write(END_SYSEX); - break; - - case SERIAL_MESSAGE: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleSysex(command, argc, argv); -#endif - break; - } -} - -void enableI2CPins() -{ - byte i; - // is there a faster way to do this? would probaby require importing - // Arduino.h to get SCL and SDA pins - for (i = 0; i < TOTAL_PINS; i++) { - if (IS_PIN_I2C(i)) { - // mark pins as i2c so they are ignore in non i2c data requests - setPinModeCallback(i, PIN_MODE_I2C); - } - } - - isI2CEnabled = true; - - Wire.begin(); -} - -/* disable the i2c pins so they can be used for other functions */ -void disableI2CPins() { - isI2CEnabled = false; - // disable read continuous mode for all devices - queryIndex = -1; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ - -void systemResetCallback() -{ - isResetting = true; - - // initialize a defalt state - // TODO: option to load config from EEPROM instead of default - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.reset(); -#endif - - if (isI2CEnabled) { - disableI2CPins(); - } - - for (byte i = 0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; // by default, reporting off - portConfigInputs[i] = 0; // until activated - previousPINs[i] = 0; - } - - for (byte i = 0; i < TOTAL_PINS; i++) { - // pins with analog capability default to analog input - // otherwise, pins default to digital output - if (IS_PIN_ANALOG(i)) { - // turns off pullup, configures everything - setPinModeCallback(i, PIN_MODE_ANALOG); - } else if (IS_PIN_DIGITAL(i)) { - // sets the output to 0, configures portConfigInputs - setPinModeCallback(i, OUTPUT); - } - - servoPinMap[i] = 255; - } - // by default, do not report any analog inputs - analogInputsToReport = 0; - - detachedServoCount = 0; - servoCount = 0; - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - /* - TODO: this can never execute, since no pins default to digital input - but it will be needed when/if we support EEPROM stored config - for (byte i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - */ - isResetting = false; -} - -void setup() -{ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - - // Save a couple of seconds by disabling the startup blink sequence. - Firmata.disableBlinkVersion(); - - // to use a port other than Serial, such as Serial1 on an Arduino Leonardo or Mega, - // Call begin(baud) on the alternate serial port and pass it to Firmata to begin like this: - // Serial1.begin(57600); - // Firmata.begin(Serial1); - // However do not do this if you are using SERIAL_MESSAGE - - Firmata.begin(57600); - while (!Serial) { - ; // wait for serial port to connect. Needed for ATmega32u4-based boards and Arduino 101 - } - - systemResetCallback(); // reset to default config -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - byte pin, analogPin; - - /* DIGITALREAD - as fast as possible, check for changes and output them to the - * FTDI buffer using Serial.print() */ - checkDigitalInputs(); - - /* STREAMREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while (Firmata.available()) - Firmata.processInput(); - - // TODO - ensure that Stream buffer doesn't go over 60 bytes - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - /* ANALOGREAD - do all analogReads() at the configured sampling interval */ - for (pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { - analogPin = PIN_TO_ANALOG(pin); - if (analogInputsToReport & (1 << analogPin)) { - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // report i2c data for all device with read continuous mode enabled - if (queryIndex > -1) { - for (byte i = 0; i < queryIndex + 1; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); - } - } - } - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.update(); -#endif -} diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino deleted file mode 100644 index bc616fec8..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/StandardFirmataWiFi.ino +++ /dev/null @@ -1,1023 +0,0 @@ -/* - Firmata is a generic protocol for communicating with microcontrollers - from software on a host computer. It is intended to work with - any host computer software package. - - To download a host software package, please clink on the following link - to open the list of Firmata client libraries your default browser. - - https://github.com/firmata/arduino#firmata-client-libraries - - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - Copyright (C) 2015-2016 Jesse Frush. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -/* - README - - StandardFirmataWiFi is a WiFi server application. You will need a Firmata client library with - a network transport in order to establish a connection with StandardFirmataWiFi. - - To use StandardFirmataWiFi you will need to have one of the following - boards or shields: - - - Arduino WiFi Shield (or clone) - - Arduino WiFi Shield 101 - - Arduino MKR1000 board (built-in WiFi 101) - - Adafruit HUZZAH CC3000 WiFi Shield (support coming soon) - - Follow the instructions in the wifiConfig.h file (wifiConfig.h tab in Arduino IDE) to - configure your particular hardware. - - Dependencies: - - WiFi Shield 101 requires version 0.7.0 or higher of the WiFi101 library (available in Arduino - 1.6.8 or higher, or update the library via the Arduino Library Manager or clone from source: - https://github.com/arduino-libraries/WiFi101) - - In order to use the WiFi Shield 101 with Firmata you will need a board with at least - 35k of Flash memory. This means you cannot use the WiFi Shield 101 with an Arduino Uno - or any other ATmega328p-based microcontroller or with an Arduino Leonardo or other - ATmega32u4-based microcontroller. Some boards that will work are: - - - Arduino Zero - - Arduino Due - - Arduino 101 - - Arduino Mega - - NOTE: If you are using an Arduino WiFi (legacy) shield you cannot use the following pins on - the following boards. Firmata will ignore any requests to use these pins: - - - Arduino Uno or other ATMega328 boards: (D4, D7, D10, D11, D12, D13) - - Arduino Mega: (D4, D7, D10, D50, D51, D52, D53) - - Arduino Due, Zero or Leonardo: (D4, D7, D10) - - If you are using an Arduino WiFi 101 shield you cannot use the following pins on the following - boards: - - - Arduino Due or Zero: (D5, D7, D10) - - Arduino Mega: (D5, D7, D10, D50, D52, D53) -*/ - -#include -#include -#include - -/* - * Uncomment the #define SERIAL_DEBUG line below to receive serial output messages relating to your - * connection that may help in the event of connection issues. If defined, some boards may not begin - * executing this sketch until the Serial console is opened. - */ -//#define SERIAL_DEBUG -#include "utility/firmataDebug.h" - -/* - * Uncomment the following include to enable interfacing with Serial devices via hardware or - * software serial. Note that if enabled, this sketch will likely consume too much memory to run on - * an Arduino Uno or Leonardo or other ATmega328p-based or ATmega32u4-based boards. - */ -//#include "utility/SerialFirmata.h" - -// follow the instructions in wifiConfig.h to configure your particular hardware -#include "wifiConfig.h" - -#define I2C_WRITE B00000000 -#define I2C_READ B00001000 -#define I2C_READ_CONTINUOUSLY B00010000 -#define I2C_STOP_READING B00011000 -#define I2C_READ_WRITE_MODE_MASK B00011000 -#define I2C_10BIT_ADDRESS_MODE_MASK B00100000 -#define I2C_END_TX_MASK B01000000 -#define I2C_STOP_TX 1 -#define I2C_RESTART_TX 0 -#define I2C_MAX_QUERIES 8 -#define I2C_REGISTER_NOT_SPECIFIED -1 - -// the minimum interval for sampling analog input -#define MINIMUM_SAMPLING_INTERVAL 1 - -#define WIFI_MAX_CONN_ATTEMPTS 3 - -/*============================================================================== - * GLOBAL VARIABLES - *============================================================================*/ - -#ifdef FIRMATA_SERIAL_FEATURE -SerialFirmata serialFeature; -#endif - -#ifdef STATIC_IP_ADDRESS -IPAddress local_ip(STATIC_IP_ADDRESS); -#endif - -int wifiConnectionAttemptCounter = 0; -int wifiStatus = WL_IDLE_STATUS; - -/* analog inputs */ -int analogInputsToReport = 0; // bitwise array to store pin reporting - -/* digital input ports */ -byte reportPINs[TOTAL_PORTS]; // 1 = report this port, 0 = silence -byte previousPINs[TOTAL_PORTS]; // previous 8 bits sent - -/* pins configuration */ -byte portConfigInputs[TOTAL_PORTS]; // each bit: 1 = pin in INPUT, 0 = anything else - -/* timer variables */ -unsigned long currentMillis; // store the current value from millis() -unsigned long previousMillis; // for comparison with currentMillis -unsigned int samplingInterval = 19; // how often to sample analog inputs (in ms) - -/* i2c data */ -struct i2c_device_info { - byte addr; - int reg; - byte bytes; - byte stopTX; -}; - -/* for i2c read continuous mode */ -i2c_device_info query[I2C_MAX_QUERIES]; - -byte i2cRxData[32]; -boolean isI2CEnabled = false; -signed char queryIndex = -1; -// default delay time between i2c read request and Wire.requestFrom() -unsigned int i2cReadDelayTime = 0; - -Servo servos[MAX_SERVOS]; -byte servoPinMap[TOTAL_PINS]; -byte detachedServos[MAX_SERVOS]; -byte detachedServoCount = 0; -byte servoCount = 0; - -boolean isResetting = false; - -/* utility functions */ -void wireWrite(byte data) -{ -#if ARDUINO >= 100 - Wire.write((byte)data); -#else - Wire.send(data); -#endif -} - -byte wireRead(void) -{ -#if ARDUINO >= 100 - return Wire.read(); -#else - return Wire.receive(); -#endif -} - -/*============================================================================== - * FUNCTIONS - *============================================================================*/ - -void attachServo(byte pin, int minPulse, int maxPulse) -{ - if (servoCount < MAX_SERVOS) { - // reuse indexes of detached servos until all have been reallocated - if (detachedServoCount > 0) { - servoPinMap[pin] = detachedServos[detachedServoCount - 1]; - if (detachedServoCount > 0) detachedServoCount--; - } else { - servoPinMap[pin] = servoCount; - servoCount++; - } - if (minPulse > 0 && maxPulse > 0) { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin), minPulse, maxPulse); - } else { - servos[servoPinMap[pin]].attach(PIN_TO_DIGITAL(pin)); - } - } else { - Firmata.sendString("Max servos attached"); - } -} - -void detachServo(byte pin) -{ - servos[servoPinMap[pin]].detach(); - // if we're detaching the last servo, decrement the count - // otherwise store the index of the detached servo - if (servoPinMap[pin] == servoCount && servoCount > 0) { - servoCount--; - } else if (servoCount > 0) { - // keep track of detached servos because we want to reuse their indexes - // before incrementing the count of attached servos - detachedServoCount++; - detachedServos[detachedServoCount - 1] = servoPinMap[pin]; - } - - servoPinMap[pin] = 255; -} - -void readAndReportData(byte address, int theRegister, byte numBytes, byte stopTX) { - // allow I2C requests that don't require a register read - // for example, some devices using an interrupt pin to signify new data available - // do not always require the register read so upon interrupt you call Wire.requestFrom() - if (theRegister != I2C_REGISTER_NOT_SPECIFIED) { - Wire.beginTransmission(address); - wireWrite((byte)theRegister); - Wire.endTransmission(stopTX); // default = true - // do not set a value of 0 - if (i2cReadDelayTime > 0) { - // delay is necessary for some devices such as WiiNunchuck - delayMicroseconds(i2cReadDelayTime); - } - } else { - theRegister = 0; // fill the register with a dummy value - } - - Wire.requestFrom(address, numBytes); // all bytes are returned in requestFrom - - // check to be sure correct number of bytes were returned by slave - if (numBytes < Wire.available()) { - Firmata.sendString("I2C: Too many bytes received"); - } else if (numBytes > Wire.available()) { - Firmata.sendString("I2C: Too few bytes received"); - } - - i2cRxData[0] = address; - i2cRxData[1] = theRegister; - - for (int i = 0; i < numBytes && Wire.available(); i++) { - i2cRxData[2 + i] = wireRead(); - } - - // send slave address, register and received bytes - Firmata.sendSysex(SYSEX_I2C_REPLY, numBytes + 2, i2cRxData); -} - -void outputPort(byte portNumber, byte portValue, byte forceSend) -{ - // pins not configured as INPUT are cleared to zeros - portValue = portValue & portConfigInputs[portNumber]; - // only send if the value is different than previously sent - if (forceSend || previousPINs[portNumber] != portValue) { - Firmata.sendDigitalPort(portNumber, portValue); - previousPINs[portNumber] = portValue; - } -} - -/* ----------------------------------------------------------------------------- - * check all the active digital inputs for change of state, then add any events - * to the Stream output queue using Stream.write() */ -void checkDigitalInputs(void) -{ - /* Using non-looping code allows constants to be given to readPort(). - * The compiler will apply substantial optimizations if the inputs - * to readPort() are compile-time constants. */ - if (TOTAL_PORTS > 0 && reportPINs[0]) outputPort(0, readPort(0, portConfigInputs[0]), false); - if (TOTAL_PORTS > 1 && reportPINs[1]) outputPort(1, readPort(1, portConfigInputs[1]), false); - if (TOTAL_PORTS > 2 && reportPINs[2]) outputPort(2, readPort(2, portConfigInputs[2]), false); - if (TOTAL_PORTS > 3 && reportPINs[3]) outputPort(3, readPort(3, portConfigInputs[3]), false); - if (TOTAL_PORTS > 4 && reportPINs[4]) outputPort(4, readPort(4, portConfigInputs[4]), false); - if (TOTAL_PORTS > 5 && reportPINs[5]) outputPort(5, readPort(5, portConfigInputs[5]), false); - if (TOTAL_PORTS > 6 && reportPINs[6]) outputPort(6, readPort(6, portConfigInputs[6]), false); - if (TOTAL_PORTS > 7 && reportPINs[7]) outputPort(7, readPort(7, portConfigInputs[7]), false); - if (TOTAL_PORTS > 8 && reportPINs[8]) outputPort(8, readPort(8, portConfigInputs[8]), false); - if (TOTAL_PORTS > 9 && reportPINs[9]) outputPort(9, readPort(9, portConfigInputs[9]), false); - if (TOTAL_PORTS > 10 && reportPINs[10]) outputPort(10, readPort(10, portConfigInputs[10]), false); - if (TOTAL_PORTS > 11 && reportPINs[11]) outputPort(11, readPort(11, portConfigInputs[11]), false); - if (TOTAL_PORTS > 12 && reportPINs[12]) outputPort(12, readPort(12, portConfigInputs[12]), false); - if (TOTAL_PORTS > 13 && reportPINs[13]) outputPort(13, readPort(13, portConfigInputs[13]), false); - if (TOTAL_PORTS > 14 && reportPINs[14]) outputPort(14, readPort(14, portConfigInputs[14]), false); - if (TOTAL_PORTS > 15 && reportPINs[15]) outputPort(15, readPort(15, portConfigInputs[15]), false); -} - -// ----------------------------------------------------------------------------- -/* sets the pin mode to the correct state and sets the relevant bits in the - * two bit-arrays that track Digital I/O and PWM status - */ -void setPinModeCallback(byte pin, int mode) -{ - if (Firmata.getPinMode(pin) == PIN_MODE_IGNORE) - return; - - if (Firmata.getPinMode(pin) == PIN_MODE_I2C && isI2CEnabled && mode != PIN_MODE_I2C) { - // disable i2c so pins can be used for other functions - // the following if statements should reconfigure the pins properly - disableI2CPins(); - } - if (IS_PIN_DIGITAL(pin) && mode != PIN_MODE_SERVO) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - } - if (IS_PIN_ANALOG(pin)) { - reportAnalogCallback(PIN_TO_ANALOG(pin), mode == PIN_MODE_ANALOG ? 1 : 0); // turn on/off reporting - } - if (IS_PIN_DIGITAL(pin)) { - if (mode == INPUT || mode == PIN_MODE_PULLUP) { - portConfigInputs[pin / 8] |= (1 << (pin & 7)); - } else { - portConfigInputs[pin / 8] &= ~(1 << (pin & 7)); - } - } - Firmata.setPinState(pin, 0); - switch (mode) { - case PIN_MODE_ANALOG: - if (IS_PIN_ANALOG(pin)) { - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - } - Firmata.setPinMode(pin, PIN_MODE_ANALOG); - } - break; - case INPUT: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT); // disable output driver -#if ARDUINO <= 100 - // deprecated since Arduino 1.0.1 - TODO: drop support in Firmata 2.6 - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups -#endif - Firmata.setPinMode(pin, INPUT); - } - break; - case PIN_MODE_PULLUP: - if (IS_PIN_DIGITAL(pin)) { - pinMode(PIN_TO_DIGITAL(pin), INPUT_PULLUP); - Firmata.setPinMode(pin, PIN_MODE_PULLUP); - Firmata.setPinState(pin, 1); - } - break; - case OUTPUT: - if (IS_PIN_DIGITAL(pin)) { - digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable PWM - pinMode(PIN_TO_DIGITAL(pin), OUTPUT); - Firmata.setPinMode(pin, OUTPUT); - } - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) { - pinMode(PIN_TO_PWM(pin), OUTPUT); - analogWrite(PIN_TO_PWM(pin), 0); - Firmata.setPinMode(pin, PIN_MODE_PWM); - } - break; - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) { - Firmata.setPinMode(pin, PIN_MODE_SERVO); - if (servoPinMap[pin] == 255 || !servos[servoPinMap[pin]].attached()) { - // pass -1 for min and max pulse values to use default values set - // by Servo library - attachServo(pin, -1, -1); - } - } - break; - case PIN_MODE_I2C: - if (IS_PIN_I2C(pin)) { - // mark the pin as i2c - // the user must call I2C_CONFIG to enable I2C for a device - Firmata.setPinMode(pin, PIN_MODE_I2C); - } - break; - case PIN_MODE_SERIAL: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handlePinMode(pin, PIN_MODE_SERIAL); -#endif - break; - default: - Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM - } - // TODO: save status to EEPROM here, if changed -} - -/* - * Sets the value of an individual pin. Useful if you want to set a pin value but - * are not tracking the digital port state. - * Can only be used on pins configured as OUTPUT. - * Cannot be used to enable pull-ups on Digital INPUT pins. - */ -void setPinValueCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) { - if (Firmata.getPinMode(pin) == OUTPUT) { - Firmata.setPinState(pin, value); - digitalWrite(PIN_TO_DIGITAL(pin), value); - } - } -} - -void analogWriteCallback(byte pin, int value) -{ - if (pin < TOTAL_PINS) { - switch (Firmata.getPinMode(pin)) { - case PIN_MODE_SERVO: - if (IS_PIN_DIGITAL(pin)) - servos[servoPinMap[pin]].write(value); - Firmata.setPinState(pin, value); - break; - case PIN_MODE_PWM: - if (IS_PIN_PWM(pin)) - analogWrite(PIN_TO_PWM(pin), value); - Firmata.setPinState(pin, value); - break; - } - } -} - -void digitalWriteCallback(byte port, int value) -{ - byte pin, lastPin, pinValue, mask = 1, pinWriteMask = 0; - - if (port < TOTAL_PORTS) { - // create a mask of the pins on this port that are writable. - lastPin = port * 8 + 8; - if (lastPin > TOTAL_PINS) lastPin = TOTAL_PINS; - for (pin = port * 8; pin < lastPin; pin++) { - // do not disturb non-digital pins (eg, Rx & Tx) - if (IS_PIN_DIGITAL(pin)) { - // do not touch pins in PWM, ANALOG, SERVO or other modes - if (Firmata.getPinMode(pin) == OUTPUT || Firmata.getPinMode(pin) == INPUT) { - pinValue = ((byte)value & mask) ? 1 : 0; - if (Firmata.getPinMode(pin) == OUTPUT) { - pinWriteMask |= mask; - } else if (Firmata.getPinMode(pin) == INPUT && pinValue == 1 && Firmata.getPinState(pin) != 1) { - // only handle INPUT here for backwards compatibility -#if ARDUINO > 100 - pinMode(pin, INPUT_PULLUP); -#else - // only write to the INPUT pin to enable pullups if Arduino v1.0.0 or earlier - pinWriteMask |= mask; -#endif - } - Firmata.setPinState(pin, pinValue); - } - } - mask = mask << 1; - } - writePort(port, (byte)value, pinWriteMask); - } -} - - -// ----------------------------------------------------------------------------- -/* sets bits in a bit array (int) to toggle the reporting of the analogIns - */ -//void FirmataClass::setAnalogPinReporting(byte pin, byte state) { -//} -void reportAnalogCallback(byte analogPin, int value) -{ - if (analogPin < TOTAL_ANALOG_PINS) { - if (value == 0) { - analogInputsToReport = analogInputsToReport & ~ (1 << analogPin); - } else { - analogInputsToReport = analogInputsToReport | (1 << analogPin); - // prevent during system reset or all analog pin values will be reported - // which may report noise for unconnected analog pins - if (!isResetting) { - // Send pin value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // TODO: save status to EEPROM here, if changed -} - -void reportDigitalCallback(byte port, int value) -{ - if (port < TOTAL_PORTS) { - reportPINs[port] = (byte)value; - // Send port value immediately. This is helpful when connected via - // ethernet, wi-fi or bluetooth so pin states can be known upon - // reconnecting. - if (value) outputPort(port, readPort(port, portConfigInputs[port]), true); - } - // do not disable analog reporting on these 8 pins, to allow some - // pins used for digital, others analog. Instead, allow both types - // of reporting to be enabled, but check if the pin is configured - // as analog when sampling the analog inputs. Likewise, while - // scanning digital pins, portConfigInputs will mask off values from any - // pins configured as analog -} - -/*============================================================================== - * SYSEX-BASED commands - *============================================================================*/ - -void sysexCallback(byte command, byte argc, byte *argv) -{ - byte mode; - byte stopTX; - byte slaveAddress; - byte data; - int slaveRegister; - unsigned int delayTime; - - switch (command) { - case I2C_REQUEST: - mode = argv[1] & I2C_READ_WRITE_MODE_MASK; - if (argv[1] & I2C_10BIT_ADDRESS_MODE_MASK) { - Firmata.sendString("10-bit addressing not supported"); - return; - } - else { - slaveAddress = argv[0]; - } - - // need to invert the logic here since 0 will be default for client - // libraries that have not updated to add support for restart tx - if (argv[1] & I2C_END_TX_MASK) { - stopTX = I2C_RESTART_TX; - } - else { - stopTX = I2C_STOP_TX; // default - } - - switch (mode) { - case I2C_WRITE: - Wire.beginTransmission(slaveAddress); - for (byte i = 2; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - wireWrite(data); - } - Wire.endTransmission(); - delayMicroseconds(70); - break; - case I2C_READ: - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - readAndReportData(slaveAddress, (int)slaveRegister, data, stopTX); - break; - case I2C_READ_CONTINUOUSLY: - if ((queryIndex + 1) >= I2C_MAX_QUERIES) { - // too many queries, just ignore - Firmata.sendString("too many queries"); - break; - } - if (argc == 6) { - // a slave register is specified - slaveRegister = argv[2] + (argv[3] << 7); - data = argv[4] + (argv[5] << 7); // bytes to read - } - else { - // a slave register is NOT specified - slaveRegister = (int)I2C_REGISTER_NOT_SPECIFIED; - data = argv[2] + (argv[3] << 7); // bytes to read - } - queryIndex++; - query[queryIndex].addr = slaveAddress; - query[queryIndex].reg = slaveRegister; - query[queryIndex].bytes = data; - query[queryIndex].stopTX = stopTX; - break; - case I2C_STOP_READING: - byte queryIndexToSkip; - // if read continuous mode is enabled for only 1 i2c device, disable - // read continuous reporting for that device - if (queryIndex <= 0) { - queryIndex = -1; - } else { - queryIndexToSkip = 0; - // if read continuous mode is enabled for multiple devices, - // determine which device to stop reading and remove it's data from - // the array, shifiting other array data to fill the space - for (byte i = 0; i < queryIndex + 1; i++) { - if (query[i].addr == slaveAddress) { - queryIndexToSkip = i; - break; - } - } - - for (byte i = queryIndexToSkip; i < queryIndex + 1; i++) { - if (i < I2C_MAX_QUERIES) { - query[i].addr = query[i + 1].addr; - query[i].reg = query[i + 1].reg; - query[i].bytes = query[i + 1].bytes; - query[i].stopTX = query[i + 1].stopTX; - } - } - queryIndex--; - } - break; - default: - break; - } - break; - case I2C_CONFIG: - delayTime = (argv[0] + (argv[1] << 7)); - - if (delayTime > 0) { - i2cReadDelayTime = delayTime; - } - - if (!isI2CEnabled) { - enableI2CPins(); - } - - break; - case SERVO_CONFIG: - if (argc > 4) { - // these vars are here for clarity, they'll optimized away by the compiler - byte pin = argv[0]; - int minPulse = argv[1] + (argv[2] << 7); - int maxPulse = argv[3] + (argv[4] << 7); - - if (IS_PIN_DIGITAL(pin)) { - if (servoPinMap[pin] < MAX_SERVOS && servos[servoPinMap[pin]].attached()) { - detachServo(pin); - } - attachServo(pin, minPulse, maxPulse); - setPinModeCallback(pin, PIN_MODE_SERVO); - } - } - break; - case SAMPLING_INTERVAL: - if (argc > 1) { - samplingInterval = argv[0] + (argv[1] << 7); - if (samplingInterval < MINIMUM_SAMPLING_INTERVAL) { - samplingInterval = MINIMUM_SAMPLING_INTERVAL; - } - } else { - //Firmata.sendString("Not enough data"); - } - break; - case EXTENDED_ANALOG: - if (argc > 1) { - int val = argv[1]; - if (argc > 2) val |= (argv[2] << 7); - if (argc > 3) val |= (argv[3] << 14); - analogWriteCallback(argv[0], val); - } - break; - case CAPABILITY_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(CAPABILITY_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_DIGITAL(pin)) { - Firmata.write((byte)INPUT); - Firmata.write(1); - Firmata.write((byte)PIN_MODE_PULLUP); - Firmata.write(1); - Firmata.write((byte)OUTPUT); - Firmata.write(1); - } - if (IS_PIN_ANALOG(pin)) { - Firmata.write(PIN_MODE_ANALOG); - Firmata.write(10); // 10 = 10-bit resolution - } - if (IS_PIN_PWM(pin)) { - Firmata.write(PIN_MODE_PWM); - Firmata.write(8); // 8 = 8-bit resolution - } - if (IS_PIN_DIGITAL(pin)) { - Firmata.write(PIN_MODE_SERVO); - Firmata.write(14); - } - if (IS_PIN_I2C(pin)) { - Firmata.write(PIN_MODE_I2C); - Firmata.write(1); // TODO: could assign a number to map to SCL or SDA - } -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleCapability(pin); -#endif - Firmata.write(127); - } - Firmata.write(END_SYSEX); - break; - case PIN_STATE_QUERY: - if (argc > 0) { - byte pin = argv[0]; - Firmata.write(START_SYSEX); - Firmata.write(PIN_STATE_RESPONSE); - Firmata.write(pin); - if (pin < TOTAL_PINS) { - Firmata.write(Firmata.getPinMode(pin)); - Firmata.write((byte)Firmata.getPinState(pin) & 0x7F); - if (Firmata.getPinState(pin) & 0xFF80) Firmata.write((byte)(Firmata.getPinState(pin) >> 7) & 0x7F); - if (Firmata.getPinState(pin) & 0xC000) Firmata.write((byte)(Firmata.getPinState(pin) >> 14) & 0x7F); - } - Firmata.write(END_SYSEX); - } - break; - case ANALOG_MAPPING_QUERY: - Firmata.write(START_SYSEX); - Firmata.write(ANALOG_MAPPING_RESPONSE); - for (byte pin = 0; pin < TOTAL_PINS; pin++) { - Firmata.write(IS_PIN_ANALOG(pin) ? PIN_TO_ANALOG(pin) : 127); - } - Firmata.write(END_SYSEX); - break; - - case SERIAL_MESSAGE: -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.handleSysex(command, argc, argv); -#endif - break; - } -} - -void enableI2CPins() -{ - byte i; - // is there a faster way to do this? would probaby require importing - // Arduino.h to get SCL and SDA pins - for (i = 0; i < TOTAL_PINS; i++) { - if (IS_PIN_I2C(i)) { - // mark pins as i2c so they are ignore in non i2c data requests - setPinModeCallback(i, PIN_MODE_I2C); - } - } - - isI2CEnabled = true; - - Wire.begin(); -} - -/* disable the i2c pins so they can be used for other functions */ -void disableI2CPins() { - isI2CEnabled = false; - // disable read continuous mode for all devices - queryIndex = -1; -} - -/*============================================================================== - * SETUP() - *============================================================================*/ - -void systemResetCallback() -{ - isResetting = true; - - // initialize a defalt state - // TODO: option to load config from EEPROM instead of default - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.reset(); -#endif - - if (isI2CEnabled) { - disableI2CPins(); - } - - for (byte i = 0; i < TOTAL_PORTS; i++) { - reportPINs[i] = false; // by default, reporting off - portConfigInputs[i] = 0; // until activated - previousPINs[i] = 0; - } - - for (byte i = 0; i < TOTAL_PINS; i++) { - // pins with analog capability default to analog input - // otherwise, pins default to digital output - if (IS_PIN_ANALOG(i)) { - // turns off pullup, configures everything - setPinModeCallback(i, PIN_MODE_ANALOG); - } else if (IS_PIN_DIGITAL(i)) { - // sets the output to 0, configures portConfigInputs - setPinModeCallback(i, OUTPUT); - } - - servoPinMap[i] = 255; - } - // by default, do not report any analog inputs - analogInputsToReport = 0; - - detachedServoCount = 0; - servoCount = 0; - - /* send digital inputs to set the initial state on the host computer, - * since once in the loop(), this firmware will only send on change */ - /* - TODO: this can never execute, since no pins default to digital input - but it will be needed when/if we support EEPROM stored config - for (byte i=0; i < TOTAL_PORTS; i++) { - outputPort(i, readPort(i, portConfigInputs[i]), true); - } - */ - isResetting = false; -} - -void printWifiStatus() { -#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - if ( WiFi.status() != WL_CONNECTED ) - { - DEBUG_PRINT( "WiFi connection failed. Status value: " ); - DEBUG_PRINTLN( WiFi.status() ); - } - else -#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - { - // print the SSID of the network you're attached to: - DEBUG_PRINT( "SSID: " ); - -#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - DEBUG_PRINTLN( WiFi.SSID() ); -#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - - // print your WiFi shield's IP address: - DEBUG_PRINT( "IP Address: " ); - -#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - IPAddress ip = WiFi.localIP(); - DEBUG_PRINTLN( ip ); -#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - - // print the received signal strength: - DEBUG_PRINT( "signal strength (RSSI): " ); - -#if defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - long rssi = WiFi.RSSI(); - DEBUG_PRINT( rssi ); -#endif //defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) - - DEBUG_PRINTLN( " dBm" ); - } -} - -void setup() -{ - /* - * WIFI SETUP - */ - DEBUG_BEGIN(9600); - - /* - * This statement will clarify how a connection is being made - */ - DEBUG_PRINT( "StandardFirmataWiFi will attempt a WiFi connection " ); -#if defined(WIFI_101) - DEBUG_PRINTLN( "using the WiFi 101 library." ); -#elif defined(ARDUINO_WIFI_SHIELD) - DEBUG_PRINTLN( "using the legacy WiFi library." ); -#elif defined(HUZZAH_WIFI) - DEBUG_PRINTLN( "using the HUZZAH WiFi library." ); - //else should never happen here as error-checking in wifiConfig.h will catch this -#endif //defined(WIFI_101) - - /* - * Configure WiFi IP Address - */ -#ifdef STATIC_IP_ADDRESS - DEBUG_PRINT( "Using static IP: " ); - DEBUG_PRINTLN( local_ip ); - //you can also provide a static IP in the begin() functions, but this simplifies - //ifdef logic in this sketch due to support for all different encryption types. - stream.config( local_ip ); -#else - DEBUG_PRINTLN( "IP will be requested from DHCP ..." ); -#endif - - /* - * Configure WiFi security - */ -#if defined(WIFI_WEP_SECURITY) - while (wifiStatus != WL_CONNECTED) { - DEBUG_PRINT( "Attempting to connect to WEP SSID: " ); - DEBUG_PRINTLN(ssid); - wifiStatus = stream.begin( ssid, wep_index, wep_key, SERVER_PORT ); - delay(5000); // TODO - determine minimum delay - if (++wifiConnectionAttemptCounter > WIFI_MAX_CONN_ATTEMPTS) break; - } - -#elif defined(WIFI_WPA_SECURITY) - while (wifiStatus != WL_CONNECTED) { - DEBUG_PRINT( "Attempting to connect to WPA SSID: " ); - DEBUG_PRINTLN(ssid); - wifiStatus = stream.begin(ssid, wpa_passphrase, SERVER_PORT); - delay(5000); // TODO - determine minimum delay - if (++wifiConnectionAttemptCounter > WIFI_MAX_CONN_ATTEMPTS) break; - } - -#else //OPEN network - while (wifiStatus != WL_CONNECTED) { - DEBUG_PRINTLN( "Attempting to connect to open SSID: " ); - DEBUG_PRINTLN(ssid); - wifiStatus = stream.begin(ssid, SERVER_PORT); - delay(5000); // TODO - determine minimum delay - if (++wifiConnectionAttemptCounter > WIFI_MAX_CONN_ATTEMPTS) break; - } -#endif //defined(WIFI_WEP_SECURITY) - - DEBUG_PRINTLN( "WiFi setup done" ); - printWifiStatus(); - - /* - * FIRMATA SETUP - */ - Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION); - - Firmata.attach(ANALOG_MESSAGE, analogWriteCallback); - Firmata.attach(DIGITAL_MESSAGE, digitalWriteCallback); - Firmata.attach(REPORT_ANALOG, reportAnalogCallback); - Firmata.attach(REPORT_DIGITAL, reportDigitalCallback); - Firmata.attach(SET_PIN_MODE, setPinModeCallback); - Firmata.attach(SET_DIGITAL_PIN_VALUE, setPinValueCallback); - Firmata.attach(START_SYSEX, sysexCallback); - Firmata.attach(SYSTEM_RESET, systemResetCallback); - - // StandardFirmataWiFi communicates with WiFi shields over SPI. Therefore all - // SPI pins must be set to IGNORE. Otherwise Firmata would break SPI communication. - // Additional pins may also need to be ignored depending on the particular board or - // shield in use. - - for (byte i = 0; i < TOTAL_PINS; i++) { -#if defined(ARDUINO_WIFI_SHIELD) - if (IS_IGNORE_WIFI_SHIELD(i) - #if defined(__AVR_ATmega32U4__) - || 24 == i // On Leonardo, pin 24 maps to D4 and pin 28 maps to D10 - || 28 == i - #endif //defined(__AVR_ATmega32U4__) - ) { -#elif defined (WIFI_101) - if (IS_IGNORE_WIFI101_SHIELD(i)) { -#elif defined (HUZZAH_WIFI) - // TODO - if (false) { -#else - if (false) { -#endif - Firmata.setPinMode(i, PIN_MODE_IGNORE); - } - } - - //Set up controls for the Arduino WiFi Shield SS for the SD Card -#ifdef ARDUINO_WIFI_SHIELD - // Arduino WiFi, Arduino WiFi Shield and Arduino Yun all have SD SS wired to D4 - pinMode(PIN_TO_DIGITAL(4), OUTPUT); // switch off SD card bypassing Firmata - digitalWrite(PIN_TO_DIGITAL(4), HIGH); // SS is active low; - -#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - pinMode(PIN_TO_DIGITAL(53), OUTPUT); // configure hardware SS as output on MEGA -#endif //defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) - -#endif //ARDUINO_WIFI_SHIELD - - // start up Network Firmata: - Firmata.begin(stream); - systemResetCallback(); // reset to default config -} - -/*============================================================================== - * LOOP() - *============================================================================*/ -void loop() -{ - byte pin, analogPin; - - /* DIGITALREAD - as fast as possible, check for changes and output them to the - * Stream buffer using Stream.write() */ - checkDigitalInputs(); - - /* STREAMREAD - processing incoming messagse as soon as possible, while still - * checking digital inputs. */ - while (Firmata.available()) { - Firmata.processInput(); - } - - // TODO - ensure that Stream buffer doesn't go over 60 bytes - - currentMillis = millis(); - if (currentMillis - previousMillis > samplingInterval) { - previousMillis += samplingInterval; - /* ANALOGREAD - do all analogReads() at the configured sampling interval */ - for (pin = 0; pin < TOTAL_PINS; pin++) { - if (IS_PIN_ANALOG(pin) && Firmata.getPinMode(pin) == PIN_MODE_ANALOG) { - analogPin = PIN_TO_ANALOG(pin); - if (analogInputsToReport & (1 << analogPin)) { - Firmata.sendAnalog(analogPin, analogRead(analogPin)); - } - } - } - // report i2c data for all device with read continuous mode enabled - if (queryIndex > -1) { - for (byte i = 0; i < queryIndex + 1; i++) { - readAndReportData(query[i].addr, query[i].reg, query[i].bytes, query[i].stopTX); - } - } - } - -#ifdef FIRMATA_SERIAL_FEATURE - serialFeature.update(); -#endif - - stream.maintain(); -} diff --git a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h b/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h deleted file mode 100644 index 3cd4b5cd9..000000000 --- a/resources/arduino_files/libraries/Firmata/examples/StandardFirmataWiFi/wifiConfig.h +++ /dev/null @@ -1,155 +0,0 @@ -/*============================================================================== - * WIFI CONFIGURATION - * - * You must configure your particular hardware. Follow the steps below. - * - * Currently StandardFirmataWiFi is configured as a server. An option to - * configure as a client may be added in the future. - *============================================================================*/ - -// STEP 1 [REQUIRED] -// Uncomment / comment the appropriate set of includes for your hardware (OPTION A, B or C) -// Option A is enabled by default. - -/* - * OPTION A: Configure for Arduino WiFi shield - * - * This will configure StandardFirmataWiFi to use the original WiFi library (deprecated) provided - * with the Arduino IDE. It is supported by the Arduino WiFi shield (a discontinued product) and - * is compatible with 802.11 B/G networks. - * - * To configure StandardFirmataWiFi to use the Arduino WiFi shield - * leave the #define below uncommented. - */ -#define ARDUINO_WIFI_SHIELD - -//do not modify these next 4 lines -#ifdef ARDUINO_WIFI_SHIELD -#include "utility/WiFiStream.h" -WiFiStream stream; -#endif - -/* - * OPTION B: Configure for WiFi 101 - * - * This will configure StandardFirmataWiFi to use the WiFi101 library, which works with the Arduino WiFi101 - * shield and devices that have the WiFi101 chip built in (such as the MKR1000). It is compatible - * with 802.11 B/G/N networks. - * - * To enable, uncomment the #define WIFI_101 below and verify the #define values under - * options A and C are commented out. - * - * IMPORTANT: You must have the WiFI 101 library installed. To easily install this library, opent the library manager via: - * Arduino IDE Menus: Sketch > Include Library > Manage Libraries > filter search for "WiFi101" > Select the result and click 'install' - */ -//#define WIFI_101 - -//do not modify these next 4 lines -#ifdef WIFI_101 -#include "utility/WiFi101Stream.h" -WiFi101Stream stream; -#endif - -/* - * OPTION C: Configure for HUZZAH - * - * HUZZAH is not yet supported, this will be added in a later revision to StandardFirmataWiFi - */ - -//------------------------------ -// TODO -//------------------------------ -//#define HUZZAH_WIFI - - -// STEP 2 [REQUIRED for all boards and shields] -// replace this with your wireless network SSID -char ssid[] = "your_network_name"; - -// STEP 3 [OPTIONAL for all boards and shields] -// if you want to use a static IP (v4) address, uncomment the line below. You can also change the IP. -// if this line is commented out, the WiFi shield will attempt to get an IP from the DHCP server -// #define STATIC_IP_ADDRESS 192,168,1,113 - -// STEP 4 [REQUIRED for all boards and shields] -// define your port number here, you will need this to open a TCP connection to your Arduino -#define SERVER_PORT 3030 - -// STEP 5 [REQUIRED for all boards and shields] -// determine your network security type (OPTION A, B, or C). Option A is the most common, and the default. - - -/* - * OPTION A: WPA / WPA2 - * - * WPA is the most common network security type. A passphrase is required to connect to this type. - * - * To enable, leave #define WIFI_WPA_SECURITY uncommented below, set your wpa_passphrase value appropriately, - * and do not uncomment the #define values under options B and C - */ -#define WIFI_WPA_SECURITY - -#ifdef WIFI_WPA_SECURITY -char wpa_passphrase[] = "your_wpa_passphrase"; -#endif //WIFI_WPA_SECURITY - -/* - * OPTION B: WEP - * - * WEP is a less common (and regarded as less safe) security type. A WEP key and its associated index are required - * to connect to this type. - * - * To enable, Uncomment the #define below, set your wep_index and wep_key values appropriately, and verify - * the #define values under options A and C are commented out. - */ -//#define WIFI_WEP_SECURITY - -#ifdef WIFI_WEP_SECURITY -//The wep_index below is a zero-indexed value. -//Valid indices are [0-3], even if your router/gateway numbers your keys [1-4]. -byte wep_index = 0; -char wep_key[] = "your_wep_key"; -#endif //WIFI_WEP_SECURITY - - -/* - * OPTION C: Open network (no security) - * - * Open networks have no security, can be connected to by any device that knows the ssid, and are unsafe. - * - * To enable, uncomment #define WIFI_NO_SECURITY below and verify the #define values - * under options A and B are commented out. - */ -//#define WIFI_NO_SECURITY - -/*============================================================================== - * CONFIGURATION ERROR CHECK (don't change anything here) - *============================================================================*/ - -#if ((defined(ARDUINO_WIFI_SHIELD) && (defined(WIFI_101) || defined(HUZZAH_WIFI))) || (defined(WIFI_101) && defined(HUZZAH_WIFI))) -#error "you may not define more than one wifi device type in wifiConfig.h." -#endif //WIFI device type check - -#if !(defined(ARDUINO_WIFI_SHIELD) || defined(WIFI_101) || defined(HUZZAH_WIFI)) -#error "you must define a wifi device type in wifiConfig.h." -#endif - -#if ((defined(WIFI_NO_SECURITY) && (defined(WIFI_WEP_SECURITY) || defined(WIFI_WPA_SECURITY))) || (defined(WIFI_WEP_SECURITY) && defined(WIFI_WPA_SECURITY))) -#error "you may not define more than one security type at the same time in wifiConfig.h." -#endif //WIFI_* security define check - -#if !(defined(WIFI_NO_SECURITY) || defined(WIFI_WEP_SECURITY) || defined(WIFI_WPA_SECURITY)) -#error "you must define a wifi security type in wifiConfig.h." -#endif //WIFI_* security define check - -/*============================================================================== - * PIN IGNORE MACROS (don't change anything here) - *============================================================================*/ - -// ignore SPI pins, pin 5 (reset WiFi101 shield), pin 7 (WiFi handshake) and pin 10 (WiFi SS) -// also don't ignore SS pin if it's not pin 10 -// TODO - need to differentiate between Arduino WiFi1 101 Shield and Arduino MKR1000 -#define IS_IGNORE_WIFI101_SHIELD(p) ((p) == 10 || (IS_PIN_SPI(p) && (p) != SS) || (p) == 5 || (p) == 7) - -// ignore SPI pins, pin 4 (SS for SD-Card on WiFi-shield), pin 7 (WiFi handshake) and pin 10 (WiFi SS) -#define IS_IGNORE_WIFI_SHIELD(p) ((IS_PIN_SPI(p) || (p) == 4) || (p) == 7 || (p) == 10) diff --git a/resources/arduino_files/libraries/Firmata/extras/LICENSE.txt b/resources/arduino_files/libraries/Firmata/extras/LICENSE.txt deleted file mode 100644 index 77cec6dd1..000000000 --- a/resources/arduino_files/libraries/Firmata/extras/LICENSE.txt +++ /dev/null @@ -1,458 +0,0 @@ - - GNU LESSER GENERAL PUBLIC LICENSE - Version 2.1, February 1999 - - Copyright (C) 1991, 1999 Free Software Foundation, Inc. - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -Licenses are intended to guarantee your freedom to share and change -free software--to make sure the software is free for all its users. - - This license, the Lesser General Public License, applies to some -specially designated software packages--typically libraries--of the -Free Software Foundation and other authors who decide to use it. You -can use it too, but we suggest you first think carefully about whether -this license or the ordinary General Public License is the better -strategy to use in any particular case, based on the explanations below. - - When we speak of free software, we are referring to freedom of use, -not price. Our General Public Licenses are designed to make sure that -you have the freedom to distribute copies of free software (and charge -for this service if you wish); that you receive source code or can get -it if you want it; that you can change the software and use pieces of -it in new free programs; and that you are informed that you can do -these things. - - To protect your rights, we need to make restrictions that forbid -distributors to deny you these rights or to ask you to surrender these -rights. These restrictions translate to certain responsibilities for -you if you distribute copies of the library or if you modify it. - - For example, if you distribute copies of the library, whether gratis -or for a fee, you must give the recipients all the rights that we gave -you. You must make sure that they, too, receive or can get the source -code. If you link other code with the library, you must provide -complete object files to the recipients, so that they can relink them -with the library after making changes to the library and recompiling -it. And you must show them these terms so they know their rights. - - We protect your rights with a two-step method: (1) we copyright the -library, and (2) we offer you this license, which gives you legal -permission to copy, distribute and/or modify the library. - - To protect each distributor, we want to make it very clear that -there is no warranty for the free library. Also, if the library is -modified by someone else and passed on, the recipients should know -that what they have is not the original version, so that the original -author's reputation will not be affected by problems that might be -introduced by others. - - Finally, software patents pose a constant threat to the existence of -any free program. We wish to make sure that a company cannot -effectively restrict the users of a free program by obtaining a -restrictive license from a patent holder. Therefore, we insist that -any patent license obtained for a version of the library must be -consistent with the full freedom of use specified in this license. - - Most GNU software, including some libraries, is covered by the -ordinary GNU General Public License. This license, the GNU Lesser -General Public License, applies to certain designated libraries, and -is quite different from the ordinary General Public License. We use -this license for certain libraries in order to permit linking those -libraries into non-free programs. - - When a program is linked with a library, whether statically or using -a shared library, the combination of the two is legally speaking a -combined work, a derivative of the original library. The ordinary -General Public License therefore permits such linking only if the -entire combination fits its criteria of freedom. The Lesser General -Public License permits more lax criteria for linking other code with -the library. - - We call this license the "Lesser" General Public License because it -does Less to protect the user's freedom than the ordinary General -Public License. It also provides other free software developers Less -of an advantage over competing non-free programs. These disadvantages -are the reason we use the ordinary General Public License for many -libraries. However, the Lesser license provides advantages in certain -special circumstances. - - For example, on rare occasions, there may be a special need to -encourage the widest possible use of a certain library, so that it becomes -a de-facto standard. To achieve this, non-free programs must be -allowed to use the library. A more frequent case is that a free -library does the same job as widely used non-free libraries. In this -case, there is little to gain by limiting the free library to free -software only, so we use the Lesser General Public License. - - In other cases, permission to use a particular library in non-free -programs enables a greater number of people to use a large body of -free software. For example, permission to use the GNU C Library in -non-free programs enables many more people to use the whole GNU -operating system, as well as its variant, the GNU/Linux operating -system. - - Although the Lesser General Public License is Less protective of the -users' freedom, it does ensure that the user of a program that is -linked with the Library has the freedom and the wherewithal to run -that program using a modified version of the Library. - - The precise terms and conditions for copying, distribution and -modification follow. Pay close attention to the difference between a -"work based on the library" and a "work that uses the library". The -former contains code derived from the library, whereas the latter must -be combined with the library in order to run. - - GNU LESSER GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License Agreement applies to any software library or other -program which contains a notice placed by the copyright holder or -other authorized party saying it may be distributed under the terms of -this Lesser General Public License (also called "this License"). -Each licensee is addressed as "you". - - A "library" means a collection of software functions and/or data -prepared so as to be conveniently linked with application programs -(which use some of those functions and data) to form executables. - - The "Library", below, refers to any such software library or work -which has been distributed under these terms. A "work based on the -Library" means either the Library or any derivative work under -copyright law: that is to say, a work containing the Library or a -portion of it, either verbatim or with modifications and/or translated -straightforwardly into another language. (Hereinafter, translation is -included without limitation in the term "modification".) - - "Source code" for a work means the preferred form of the work for -making modifications to it. For a library, complete source code means -all the source code for all modules it contains, plus any associated -interface definition files, plus the scripts used to control compilation -and installation of the library. - - Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running a program using the Library is not restricted, and output from -such a program is covered only if its contents constitute a work based -on the Library (independent of the use of the Library in a tool for -writing it). Whether that is true depends on what the Library does -and what the program that uses the Library does. - - 1. You may copy and distribute verbatim copies of the Library's -complete source code as you receive it, in any medium, provided that -you conspicuously and appropriately publish on each copy an -appropriate copyright notice and disclaimer of warranty; keep intact -all the notices that refer to this License and to the absence of any -warranty; and distribute a copy of this License along with the -Library. - - You may charge a fee for the physical act of transferring a copy, -and you may at your option offer warranty protection in exchange for a -fee. - - 2. You may modify your copy or copies of the Library or any portion -of it, thus forming a work based on the Library, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) The modified work must itself be a software library. - - b) You must cause the files modified to carry prominent notices - stating that you changed the files and the date of any change. - - c) You must cause the whole of the work to be licensed at no - charge to all third parties under the terms of this License. - - d) If a facility in the modified Library refers to a function or a - table of data to be supplied by an application program that uses - the facility, other than as an argument passed when the facility - is invoked, then you must make a good faith effort to ensure that, - in the event an application does not supply such function or - table, the facility still operates, and performs whatever part of - its purpose remains meaningful. - - (For example, a function in a library to compute square roots has - a purpose that is entirely well-defined independent of the - application. Therefore, Subsection 2d requires that any - application-supplied function or table used by this function must - be optional: if the application does not supply it, the square - root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Library, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Library, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote -it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library -with the Library (or with a work based on the Library) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may opt to apply the terms of the ordinary GNU General Public -License instead of this License to a given copy of the Library. To do -this, you must alter all the notices that refer to this License, so -that they refer to the ordinary GNU General Public License, version 2, -instead of to this License. (If a newer version than version 2 of the -ordinary GNU General Public License has appeared, then you can specify -that version instead if you wish.) Do not make any other change in -these notices. - - Once this change is made in a given copy, it is irreversible for -that copy, so the ordinary GNU General Public License applies to all -subsequent copies and derivative works made from that copy. - - This option is useful when you wish to copy part of the code of -the Library into a program that is not a library. - - 4. You may copy and distribute the Library (or a portion or -derivative of it, under Section 2) in object code or executable form -under the terms of Sections 1 and 2 above provided that you accompany -it with the complete corresponding machine-readable source code, which -must be distributed under the terms of Sections 1 and 2 above on a -medium customarily used for software interchange. - - If distribution of object code is made by offering access to copy -from a designated place, then offering equivalent access to copy the -source code from the same place satisfies the requirement to -distribute the source code, even though third parties are not -compelled to copy the source along with the object code. - - 5. A program that contains no derivative of any portion of the -Library, but is designed to work with the Library by being compiled or -linked with it, is called a "work that uses the Library". Such a -work, in isolation, is not a derivative work of the Library, and -therefore falls outside the scope of this License. - - However, linking a "work that uses the Library" with the Library -creates an executable that is a derivative of the Library (because it -contains portions of the Library), rather than a "work that uses the -library". The executable is therefore covered by this License. -Section 6 states terms for distribution of such executables. - - When a "work that uses the Library" uses material from a header file -that is part of the Library, the object code for the work may be a -derivative work of the Library even though the source code is not. -Whether this is true is especially significant if the work can be -linked without the Library, or if the work is itself a library. The -threshold for this to be true is not precisely defined by law. - - If such an object file uses only numerical parameters, data -structure layouts and accessors, and small macros and small inline -functions (ten lines or less in length), then the use of the object -file is unrestricted, regardless of whether it is legally a derivative -work. (Executables containing this object code plus portions of the -Library will still fall under Section 6.) - - Otherwise, if the work is a derivative of the Library, you may -distribute the object code for the work under the terms of Section 6. -Any executables containing that work also fall under Section 6, -whether or not they are linked directly with the Library itself. - - 6. As an exception to the Sections above, you may also combine or -link a "work that uses the Library" with the Library to produce a -work containing portions of the Library, and distribute that work -under terms of your choice, provided that the terms permit -modification of the work for the customer's own use and reverse -engineering for debugging such modifications. - - You must give prominent notice with each copy of the work that the -Library is used in it and that the Library and its use are covered by -this License. You must supply a copy of this License. If the work -during execution displays copyright notices, you must include the -copyright notice for the Library among them, as well as a reference -directing the user to the copy of this License. Also, you must do one -of these things: - - a) Accompany the work with the complete corresponding - machine-readable source code for the Library including whatever - changes were used in the work (which must be distributed under - Sections 1 and 2 above); and, if the work is an executable linked - with the Library, with the complete machine-readable "work that - uses the Library", as object code and/or source code, so that the - user can modify the Library and then relink to produce a modified - executable containing the modified Library. (It is understood - that the user who changes the contents of definitions files in the - Library will not necessarily be able to recompile the application - to use the modified definitions.) - - b) Use a suitable shared library mechanism for linking with the - Library. A suitable mechanism is one that (1) uses at run time a - copy of the library already present on the user's computer system, - rather than copying library functions into the executable, and (2) - will operate properly with a modified version of the library, if - the user installs one, as long as the modified version is - interface-compatible with the version that the work was made with. - - c) Accompany the work with a written offer, valid for at - least three years, to give the same user the materials - specified in Subsection 6a, above, for a charge no more - than the cost of performing this distribution. - - d) If distribution of the work is made by offering access to copy - from a designated place, offer equivalent access to copy the above - specified materials from the same place. - - e) Verify that the user has already received a copy of these - materials or that you have already sent this user a copy. - - For an executable, the required form of the "work that uses the -Library" must include any data and utility programs needed for -reproducing the executable from it. However, as a special exception, -the materials to be distributed need not include anything that is -normally distributed (in either source or binary form) with the major -components (compiler, kernel, and so on) of the operating system on -which the executable runs, unless that component itself accompanies -the executable. - - It may happen that this requirement contradicts the license -restrictions of other proprietary libraries that do not normally -accompany the operating system. Such a contradiction means you cannot -use both them and the Library together in an executable that you -distribute. - - 7. You may place library facilities that are a work based on the -Library side-by-side in a single library together with other library -facilities not covered by this License, and distribute such a combined -library, provided that the separate distribution of the work based on -the Library and of the other library facilities is otherwise -permitted, and provided that you do these two things: - - a) Accompany the combined library with a copy of the same work - based on the Library, uncombined with any other library - facilities. This must be distributed under the terms of the - Sections above. - - b) Give prominent notice with the combined library of the fact - that part of it is a work based on the Library, and explaining - where to find the accompanying uncombined form of the same work. - - 8. You may not copy, modify, sublicense, link with, or distribute -the Library except as expressly provided under this License. Any -attempt otherwise to copy, modify, sublicense, link with, or -distribute the Library is void, and will automatically terminate your -rights under this License. However, parties who have received copies, -or rights, from you under this License will not have their licenses -terminated so long as such parties remain in full compliance. - - 9. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Library or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Library (or any work based on the -Library), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Library or works based on it. - - 10. Each time you redistribute the Library (or any work based on the -Library), the recipient automatically receives a license from the -original licensor to copy, distribute, link with or modify the Library -subject to these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties with -this License. - - 11. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Library at all. For example, if a patent -license would not permit royalty-free redistribution of the Library by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any -particular circumstance, the balance of the section is intended to apply, -and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 12. If the distribution and/or use of the Library is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Library under this License may add -an explicit geographical distribution limitation excluding those countries, -so that distribution is permitted only in or among countries not thus -excluded. In such case, this License incorporates the limitation as if -written in the body of this License. - - 13. The Free Software Foundation may publish revised and/or new -versions of the Lesser General Public License from time to time. -Such new versions will be similar in spirit to the present version, -but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library -specifies a version number of this License which applies to it and -"any later version", you have the option of following the terms and -conditions either of that version or of any later version published by -the Free Software Foundation. If the Library does not specify a -license version number, you may choose any version ever published by -the Free Software Foundation. - - 14. If you wish to incorporate parts of the Library into other free -programs whose distribution conditions are incompatible with these, -write to the author to ask for permission. For software which is -copyrighted by the Free Software Foundation, write to the Free -Software Foundation; we sometimes make exceptions for this. Our -decision will be guided by the two goals of preserving the free status -of all derivatives of our free software and of promoting the sharing -and reuse of software generally. - - NO WARRANTY - - 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO -WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. -EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR -OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY -KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE -LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME -THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN -WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY -AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU -FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR -CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE -LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING -RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A -FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF -SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGES. - diff --git a/resources/arduino_files/libraries/Firmata/extras/revisions.txt b/resources/arduino_files/libraries/Firmata/extras/revisions.txt deleted file mode 100644 index 7d129327c..000000000 --- a/resources/arduino_files/libraries/Firmata/extras/revisions.txt +++ /dev/null @@ -1,202 +0,0 @@ -FIRMATA 2.5.2 - Feb 15, 2016 - -[core library] -* Added Wi-Fi transport (Jesse Frush) -* Added support for Arduino MKR1000 (Jesse Frush) -* Moved Serial feature to own class SerialFimata -* Moved pin config and pin state handling to Firmata.cpp -* Added new method disableBlinkVersion to provide a way to optionally bypass startup blink sequence - -[StandardFirmata & variants] -* Added StandardFirmataWiFi (Jesse Frush) -* Added ethernetConfig.h for StandardFirmataEthernet and StandardFirmtaEthernetPlus -* Removed serialUtils.h and using SerialFirmata class instead for Serial feature - -FIRMATA 2.5.1 - Dec 26, 2015 - -[core library] -* Added support for Arduino 101 -* Make VERSION_BLINK_PIN optional -* Separate protocol version from firmware version. - Use FIRMATA_PROTOCOL_VERSION_[MAJOR/MINOR/BUGFIX] for protocol and use - FIRMATA_FIRMWARE_VERSION_[MAJOR/MINOR/BUGFIX] for firmware (library version). - -[StandardFirmata & variants] -* Added ability to auto-restart I2C transmission by setting bit 6 of byte 3 - of the I2C_REQUEST message. - -FIRMATA 2.5.0 - Nov 7, 2015 - -[core library] -* Added Serial feature for interfacing with serial devices via hardware - or software serial. See github.com/firmata/protocol/serial.md for details -* Added ability to set the value of a pin by sending a single value instead - of a port value. See 'set digital pin value' in github.com/firmata/protocol/protocol.md - for details -* Added support for Arduino Zero board -* Added support for Teensy LC board (copied from Teensy Firmata lib) -* Added support for Pinoccio Scout board (Pawel Szymczykowski) -* Lowered minimun sampling interval from 10 to 1 millisecond -* Added new pin mode (PIN_MODE_PULLUP) for setting the INPUT_PULLUP pin mode -* Changed pin mode defines to safer names (old names still included but - deprecated) - see Firmata.h - -[StandardFirmata & variants] -* Created new StandardFirmataPlus that implements the Serial feature - Note: The new Serial features is only implemented in the "Plus" versions of - StandardFirmata. -* Created new StandardFirmataEthernetPlus that implements the Serial feature -* Fixed issue where StandardFirmata was not compiling for Intel Galileo boards -* Moved StandardFirmataYun to its own repo (github.com/firmata/StandardFirmataYun) - -FIRMATA 2.4.4 - Aug 9, 2015 - -[core library] -* Added support for chipKIT boards (Brian Schmalz, Rick Anderson and Keith Vogel) -* Added support for ATmega328 boards (previously only ATmega328p was supported) - -[StandardFirmata] -* Added StandardFirmataChipKIT for ChipKIT boards (Brian Schmalz, Rick Anderson and Keith Vogel) -* Ensure Serial is ready on Leonardo and other ATMega32u4-based boards - -FIRMATA 2.4.3 - Apr 11, 2015 - -[core library] -* Added debug macros (utility/firmataDebug.h) -* Added Norbert Truchsess' EthernetClientStream lib from the configurable branch - -[examples] -* Added StandardFirmataEthernet to enable Firmata over Ethernet -* Minor updates to StandardFirmata and StandardFirmataYun - -FIRMATA 2.4.2 - Mar 16, 2015 - -[core library] -* Add support for Teesy 3.1 (Olivier Louvignes) - -FIRMATA 2.4.1 - Feb 7, 2015 - -[core library] -* Fixed off-by-one bug in setFirmwareNameAndVersion (Brian Schmalz) - -[StandardFirmata] -* Prevent analog values from being reported during system reset - -FIRMATA 2.4.0 - Dec 21, 2014 - -Changes from 2.3.6 to 2.4 that may impact existing Firmata client implementations: - -* When sending a string from the client application to the board (STRING_DATA) a -static buffer is now used for the incoming string in place of a dynamically allocated -block of memory (see Firmata.cpp lines 181 - 205). In Firmata 2.3.6 and older, -the dynamically allocated block was never freed, causing a memory leak. If your -client library had freed this memory in the string callback method, that code -will break in Firmata 2.4. If the string data needs to persist beyond the string -callback, it should be copied within the string callback. - -* As of Firmata 2.4, when digital port reporting or analog pin reporting is enabled, -the value of the port (digital) or pin (analog) is immediately sent back to the client -application. This will likely not have a negative impact on existing client -implementations, but may be unexpected. This feature was added to better support -non-serial streams (such as Ethernet, Wi-Fi, Bluetooth, etc) that may lose -connectivity and need a quick way to get the current state of the pins upon -reestablishing a connection. - -[core library] -* Changed sendValueAsTwo7bitBytes, startSysex and endSysex from private to - public methods. -* Added Intel Galileo to Boards.h -* Renamed FirmataSerial to FirmataStream -* Updated to latest Arduino library format -* writePort function in Boards.h now returns 1 (to suppress compiler warning) -* Updated syntax highlighting (keywords.txt) -* Fixed IS_PIN_SPI ifndef condition in boards.h -* Added constants to Firmata.h to reserve configurable firmata features -* Fixed issue where firmwareName was not reported correctly in Windows -* Ensure incoming String via STRING_DATA command is null-terminated -* Fixed memory leak when receiving String via STRING_DATA command - (note this change may break existing code if you were manually deallocating - the incoming string in your string callback function. See code for details) -* Added ability for user to specify a filename when calling setFirmwareNameAndVersion -* Increased input data buffer size from 32 to 64 bytes - -[StandardFirmata] -* Updated I2C_READ_CONTINUOUSLY to work with or without slaveRegister (Rick Waldron) -* Added Yun variant of StandardFirmata -* When a digital port is enabled, its value is now immediately sent to the client -* When an analog pin is enabled, its value is now immediately sent to the client -* Changed the way servo pins are mapped to enable use of servos on - a wider range of pins, including analog pins. -* Fixed management of unexpected sized I2C replies (Nahuel Greco) -* Fixed a bug when removing a monitored device with I2C_STOP_Reading (Nahuel Greco) -* Fixed conditional expression in I2C_STOP_READING case -* Changed samplingInterval from type int to type unsigned int -* Shortened error message strings to save a few bytes - -[examples] -* Updated FirmataServo example to use new pin mapping technique -* Removed makefiles from examples (because they were not being updated) -* Updated all examples to set current firmware version - -FIRMATA 2.3.6 - Jun 18, 2013 (Version included with Arduino core libraries) - -[core library] -* Fixed bug introduced in 2.3.5 that broke ability to use Ethernet. - -FIRMATA 2.3.5 - May 21, 2013 - -[core library] -* Added Arduino Due to Boards.h -* Added Teensy 3.0 to Boards.h -* Updated unit tests to use ArduinoUnit v2.0 -* Renamed pin13strobe to strobeBlinkPin -* Removed blinkVersion method from begin method for non-serial streams -* Fixed memory leak in setting firmware version (Matthew Murdoch) -* Added unit tests for a few core functions (Matthew Murdoch) -* Added IS_PIN_SPI macro to all board definitions in Board.h (Norbert Truchsess) - -FIRMATA 2.3.4 - Feb 11, 2013 - -[core library] -* Fixed Stream implementation so Firmata can be used with Streams other than - Serial (Norbert Truchsess) - -FIRMATA 2.3.3 - Oct 6, 2012 - -[core library] -* Added write method to expose FirmataSerial.write -* Added Arduino Leonardo to Boards.h - -[StandardFirmata] -* Changed all instances of Serial.write to Firmata.write -* Fixed delayMicroseconds(0) bug in readAndReportData - -FIRMATA 2.3.0 - 2.3.2 - -* Removed angle from servo config -* Changed file extensions from .pde to .ino -* Added MEGA2560 to Boards.h -* Added I2C pins to Boards.h -* Modified examples to be compatible with Arduino 0022 and 1.0 or greater -* Removed I2CFirmata example -* Changes to StandardFirmata - * Added I2C support - * Added system reset message to reset all pins to default config on sysex reset - -FIRMATA 2.2 (changes prior to Firmata 2.3.0 were not well documented) - -* changes undocumented - -FIRMATA 2.1 - -* added support for changing the sampling interval -* added Servo support - -FIRMATA 2.0 - -* changed to 8-bit port-based digital messages to mirror ports from previous 14-bit ports modeled after the standard Arduino board. -* switched order of version message so major version is reported first - -FIRMATA 1.0 - -* switched to MIDI-compatible packet format (though the message interpretation differs) diff --git a/resources/arduino_files/libraries/Firmata/keywords.txt b/resources/arduino_files/libraries/Firmata/keywords.txt deleted file mode 100644 index 5ab13d05d..000000000 --- a/resources/arduino_files/libraries/Firmata/keywords.txt +++ /dev/null @@ -1,90 +0,0 @@ -####################################### -# Syntax Coloring Map For Firmata -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Firmata KEYWORD1 Firmata -callbackFunction KEYWORD1 callbackFunction -systemResetCallbackFunction KEYWORD1 systemResetCallbackFunction -stringCallbackFunction KEYWORD1 stringCallbackFunction -sysexCallbackFunction KEYWORD1 sysexCallbackFunction - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -printVersion KEYWORD2 -blinkVersion KEYWORD2 -printFirmwareVersion KEYWORD2 -setFirmwareVersion KEYWORD2 -setFirmwareNameAndVersion KEYWORD2 -available KEYWORD2 -processInput KEYWORD2 -isParsingMessage KEYWORD2 -parse KEYWORD2 -sendAnalog KEYWORD2 -sendDigital KEYWORD2 -sendDigitalPort KEYWORD2 -sendString KEYWORD2 -sendSysex KEYWORD2 -getPinMode KEYWORD2 -setPinMode KEYWORD2 -getPinState KEYWORD2 -setPinState KEYWORD2 -attach KEYWORD2 -detach KEYWORD2 -write KEYWORD2 -sendValueAsTwo7bitBytes KEYWORD2 -startSysex KEYWORD2 -endSysex KEYWORD2 -writePort KEYWORD2 -readPort KEYWORD2 -disableBlinkVersion KEYWORD2 - - -####################################### -# Constants (LITERAL1) -####################################### - -FIRMATA_MAJOR_VERSION LITERAL1 -FIRMATA_MINOR_VERSION LITERAL1 -FIRMATA_BUGFIX_VERSION LITERAL1 - -MAX_DATA_BYTES LITERAL1 - -DIGITAL_MESSAGE LITERAL1 -ANALOG_MESSAGE LITERAL1 -REPORT_ANALOG LITERAL1 -REPORT_DIGITAL LITERAL1 -REPORT_VERSION LITERAL1 -SET_PIN_MODE LITERAL1 -SET_DIGITAL_PIN_VALUE LITERAL1 -SYSTEM_RESET LITERAL1 -START_SYSEX LITERAL1 -END_SYSEX LITERAL1 -REPORT_FIRMWARE LITERAL1 -STRING_DATA LITERAL1 - -PIN_MODE_ANALOG LITERAL1 -PIN_MODE_PWM LITERAL1 -PIN_MODE_SERVO LITERAL1 -PIN_MODE_SHIFT LITERAL1 -PIN_MODE_I2C LITERAL1 -PIN_MODE_ONEWIRE LITERAL1 -PIN_MODE_STEPPER LITERAL1 -PIN_MODE_ENCODER LITERAL1 -PIN_MODE_SERIAL LITERAL1 -PIN_MODE_PULLUP LITERAL1 -PIN_MODE_IGNORE LITERAL1 - -TOTAL_PINS LITERAL1 -TOTAL_ANALOG_PINS LITERAL1 -TOTAL_DIGITAL_PINS LITERAL1 -TOTAL_PIN_MODES LITERAL1 -TOTAL_PORTS LITERAL1 -ANALOG_PORT LITERAL1 -MAX_SERVOS LITERAL1 diff --git a/resources/arduino_files/libraries/Firmata/library.properties b/resources/arduino_files/libraries/Firmata/library.properties deleted file mode 100644 index 53f26f187..000000000 --- a/resources/arduino_files/libraries/Firmata/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Firmata -version=2.5.2 -author=Firmata Developers -maintainer=https://github.com/firmata/arduino -sentence=Enables the communication with computer apps using a standard serial protocol. For all Arduino boards. -paragraph=The Firmata library implements the Firmata protocol for communicating with software on the host computer. This allows you to write custom firmware without having to create your own protocol and objects for the programming environment that you are using. -category=Device Control -url=https://github.com/firmata/arduino -architectures=* diff --git a/resources/arduino_files/libraries/Firmata/readme.md b/resources/arduino_files/libraries/Firmata/readme.md deleted file mode 100644 index b1ecaf181..000000000 --- a/resources/arduino_files/libraries/Firmata/readme.md +++ /dev/null @@ -1,177 +0,0 @@ -#Firmata - -[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/firmata/arduino?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) - -Firmata is a protocol for communicating with microcontrollers from software on a host computer. The [protocol](https://github.com/firmata/protocol) can be implemented in firmware on any microcontroller architecture as well as software on any host computer software package. The Arduino repository described here is a Firmata library for Arduino and Arduino-compatible devices. If you would like to contribute to Firmata, please see the [Contributing](#contributing) section below. - -##Usage - -There are two main models of usage of Firmata. In one model, the author of the Arduino sketch uses the various methods provided by the Firmata library to selectively send and receive data between the Arduino device and the software running on the host computer. For example, a user can send analog data to the host using ``` Firmata.sendAnalog(analogPin, analogRead(analogPin)) ``` or send data packed in a string using ``` Firmata.sendString(stringToSend) ```. See File -> Examples -> Firmata -> AnalogFirmata & EchoString respectively for examples. - -The second and more common model is to load a general purpose sketch called StandardFirmata (or one of the variants such as StandardFirmataPlus or StandardFirmataEthernet depending on your needs) on the Arduino board and then use the host computer exclusively to interact with the Arduino board. StandardFirmata is located in the Arduino IDE in File -> Examples -> Firmata. - -##Firmata Client Libraries -Most of the time you will be interacting with Arduino with a client library on the host computers. Several Firmata client libraries have been implemented in a variety of popular programming languages: - -* processing - * [https://github.com/firmata/processing] - * [http://funnel.cc] -* python - * [https://github.com/MrYsLab/pymata-aio] - * [https://github.com/MrYsLab/PyMata] - * [https://github.com/tino/pyFirmata] - * [https://github.com/lupeke/python-firmata] - * [https://github.com/firmata/pyduino] -* perl - * [https://github.com/ntruchsess/perl-firmata] - * [https://github.com/rcaputo/rx-firmata] -* ruby - * [https://github.com/hardbap/firmata] - * [https://github.com/PlasticLizard/rufinol] - * [http://funnel.cc] -* clojure - * [https://github.com/nakkaya/clodiuno] - * [https://github.com/peterschwarz/clj-firmata] -* javascript - * [https://github.com/jgautier/firmata] - * [https://github.com/rwldrn/johnny-five] - * [http://breakoutjs.com] -* java - * [https://github.com/kurbatov/firmata4j] - * [https://github.com/4ntoine/Firmata] - * [https://github.com/reapzor/FiloFirmata] -* .NET - * [https://github.com/SolidSoils/Arduino] - * [http://www.imagitronics.org/projects/firmatanet/] -* Flash/AS3 - * [http://funnel.cc] - * [http://code.google.com/p/as3glue/] -* PHP - * [https://bitbucket.org/ThomasWeinert/carica-firmata] - * [https://github.com/oasynnoum/phpmake_firmata] -* Haskell - * [http://hackage.haskell.org/package/hArduino] -* iOS - * [https://github.com/jacobrosenthal/iosfirmata] -* Dart - * [https://github.com/nfrancois/firmata] -* Max/MSP - * [http://www.maxuino.org/] -* Elixir - * [https://github.com/kfatehi/firmata] -* Modelica - * [https://www.wolfram.com/system-modeler/libraries/model-plug/] -* golang - * [https://github.com/kraman/go-firmata] - -Note: The above libraries may support various versions of the Firmata protocol and therefore may not support all features of the latest Firmata spec nor all Arduino and Arduino-compatible boards. Refer to the respective projects for details. - -##Updating Firmata in the Arduino IDE - Arduino 1.6.4 and higher - -If you want to update to the latest stable version: - -1. Open the Arduino IDE and navigate to: `Sketch > Include Library > Manage Libraries` -2. Filter by "Firmata" and click on the "Firmata by Firmata Developers" item in the list of results. -3. Click the `Select version` dropdown and select the most recent version (note you can also install previous versions) -4. Click `Install`. - -###Cloning Firmata - -If you are contributing to Firmata or otherwise need a version newer than the latest tagged release, you can clone Firmata directly to your Arduino/libraries/ directory (where 3rd party libraries are installed). This only works for Arduino 1.6.4 and higher, for older versions you need to clone into the Arduino application directory (see section below titled "Using the Source code rather than release archive"). Be sure to change the name to Firmata as follows: - -```bash -$ git clone git@github.com:firmata/arduino.git ~/Documents/Arduino/libraries/Firmata -``` - -*Update path above if you're using Windows or Linux or changed the default Arduino directory on OS X* - - -##Updating Firmata in the Arduino IDE - older versions (<= 1.6.3 or 1.0.x) - -Download the latest [release](https://github.com/firmata/arduino/releases/tag/2.5.2) (for Arduino 1.0.x or Arduino 1.5.6 or higher) and replace the existing Firmata folder in your Arduino application. See the instructions below for your platform. - -*Note that Arduino 1.5.0 - 1.5.5 are not supported. Please use Arduino 1.5.6 or higher (or Arduino 1.0.5 or 1.0.6).* - -###Mac OSX: - -The Firmata library is contained within the Arduino package. - -1. Navigate to the Arduino application -2. Right click on the application icon and select `Show Package Contents` -3. Navigate to: `/Contents/Resources/Java/libraries/` and replace the existing -`Firmata` folder with latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.2) (note there is a different download -for Arduino 1.0.x vs 1.6.x) -4. Restart the Arduino application and the latest version of Firmata will be available. - -*If you are using the Java 7 version of Arduino 1.5.7 or higher, the file path -will differ slightly: `Contents/Java/libraries/Firmata` (no Resources directory).* - -###Windows: - -1. Navigate to `c:/Program\ Files/arduino-1.x/libraries/` and replace the existing -`Firmata` folder with the latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.2) (note there is a different download -for Arduino 1.0.x vs 1.6.x). -2. Restart the Arduino application and the latest version of Firmata will be available. - -*Update the path and Arduino version as necessary* - -###Linux: - -1. Navigate to `~/arduino-1.x/libraries/` and replace the existing -`Firmata` folder with the latest [Firmata release](https://github.com/firmata/arduino/releases/tag/2.5.2) (note there is a different download -for Arduino 1.0.x vs 1.6.x). -2. Restart the Arduino application and the latest version of Firmata will be available. - -*Update the path and Arduino version as necessary* - -###Using the Source code rather than release archive (only for versions older than Arduino 1.6.3) - -*It is recommended you update to Arduino 1.6.4 or higher if possible, that way you can clone directly into the external Arduino/libraries/ directory which persists between Arduino application updates. Otherwise you will need to move your clone each time you update to a newer version of the Arduino IDE.* - -If you're stuck with an older version of the IDE, then follow these keep reading otherwise jump up to the "Cloning Firmata section above". - -Clone this repo directly into the core Arduino application libraries directory. If you are using -Arduino 1.5.x or <= 1.6.3, the repo directory structure will not match the Arduino -library format, however it should still compile as long as you are using Arduino 1.5.7 -or higher. - -You will first need to remove the existing Firmata library, then clone firmata/arduino -into an empty Firmata directory: - -```bash -$ rm -r /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata -$ git clone git@github.com:firmata/arduino.git /Applications/Arduino.app/Contents/Resources/Java/libraries/Firmata -``` - -*Update paths if you're using Windows or Linux* - -To generate properly formatted versions of Firmata (for Arduino 1.0.x and Arduino 1.6.x), run the -`release.sh` script. - - - -##Contributing - -If you discover a bug or would like to propose a new feature, please open a new [issue](https://github.com/firmata/arduino/issues?sort=created&state=open). Due to the limited memory of standard Arduino boards we cannot add every requested feature to StandardFirmata. Requests to add new features to StandardFirmata will be evaluated by the Firmata developers. However it is still possible to add new features to other Firmata implementations (Firmata is a protocol whereas StandardFirmata is just one of many possible implementations). - -To contribute, fork this repository and create a new topic branch for the bug, feature or other existing issue you are addressing. Submit the pull request against the *master* branch. - -If you would like to contribute but don't have a specific bugfix or new feature to contribute, you can take on an existing issue, see issues labeled "pull-request-encouraged". Add a comment to the issue to express your intent to begin work and/or to get any additional information about the issue. - -You must thoroughly test your contributed code. In your pull request, describe tests performed to ensure that no existing code is broken and that any changes maintain backwards compatibility with the existing api. Test on multiple Arduino board variants if possible. We hope to enable some form of automated (or at least semi-automated) testing in the future, but for now any tests will need to be executed manually by the contributor and reviewers. - -Use [Artistic Style](http://astyle.sourceforge.net/) (astyle) to format your code. Set the following rules for the astyle formatter: - -``` -style = "" -indent-spaces = 2 -indent-classes = true -indent-switches = true -indent-cases = true -indent-col1-comments = true -pad-oper = true -pad-header = true -keep-one-line-statements = true -``` - -If you happen to use Sublime Text, [this astyle plugin](https://github.com/timonwong/SublimeAStyleFormatter) is helpful. Set the above rules in the user settings file. diff --git a/resources/arduino_files/libraries/Firmata/release.sh b/resources/arduino_files/libraries/Firmata/release.sh deleted file mode 100644 index 9c3f32992..000000000 --- a/resources/arduino_files/libraries/Firmata/release.sh +++ /dev/null @@ -1,35 +0,0 @@ -#!/bin/sh - -# use this script to package Firmata for distribution - -# package for Arduino 1.0.x -mkdir -p temp/Firmata -cp -r examples temp/Firmata -cp -r extras temp/Firmata -cp -r utility temp/Firmata -cp Boards.h temp/Firmata -cp Firmata.cpp temp/Firmata -cp Firmata.h temp/Firmata -cp keywords.txt temp/Firmata -cp readme.md temp/Firmata -cd temp -find . -name "*.DS_Store" -type f -delete -zip -r Firmata.zip ./Firmata/ -cd .. -mv ./temp/Firmata.zip Firmata-2.5.2.zip - -#package for Arduino 1.6.x -cp library.properties temp/Firmata -cd temp/Firmata -mv readme.md ./extras/ -mkdir src -mv Boards.h ./src/ -mv Firmata.cpp ./src/ -mv Firmata.h ./src/ -mv utility ./src/ -cd .. -find . -name "*.DS_Store" -type f -delete -zip -r Firmata.zip ./Firmata/ -cd .. -mv ./temp/Firmata.zip Arduino-1.6.x-Firmata-2.5.2.zip -rm -r ./temp diff --git a/resources/arduino_files/libraries/Firmata/test/firmata_test/firmata_test.ino b/resources/arduino_files/libraries/Firmata/test/firmata_test/firmata_test.ino deleted file mode 100644 index ce40afa57..000000000 --- a/resources/arduino_files/libraries/Firmata/test/firmata_test/firmata_test.ino +++ /dev/null @@ -1,136 +0,0 @@ -/* - * To run this test suite, you must first install the ArduinoUnit library - * to your Arduino/libraries/ directory. - * You can get ArduinoUnit here: https://github.com/mmurdoch/arduinounit - * Download version 2.0 or greater or install it via the Arduino library manager. - */ - -#include -#include - -void setup() -{ - Serial.begin(9600); -} - -void loop() -{ - Test::run(); -} - -test(beginPrintsVersion) -{ - FakeStream stream; - - Firmata.begin(stream); - - char expected[] = { - REPORT_VERSION, - FIRMATA_PROTOCOL_MAJOR_VERSION, - FIRMATA_PROTOCOL_MINOR_VERSION, - 0 - }; - assertEqual(expected, stream.bytesWritten()); -} - -void processMessage(const byte *message, size_t length) -{ - FakeStream stream; - Firmata.begin(stream); - - for (size_t i = 0; i < length; i++) { - stream.nextByte(message[i]); - Firmata.processInput(); - } -} - -byte _digitalPort; -int _digitalPortValue; -void writeToDigitalPort(byte port, int value) -{ - _digitalPort = port; - _digitalPortValue = value; -} - -void setupDigitalPort() -{ - _digitalPort = 0; - _digitalPortValue = 0; -} - -test(processWriteDigital_0) -{ - setupDigitalPort(); - Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); - - byte message[] = { DIGITAL_MESSAGE, 0, 0 }; - processMessage(message, 3); - - assertEqual(0, _digitalPortValue); -} - -test(processWriteDigital_127) -{ - setupDigitalPort(); - Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); - - byte message[] = { DIGITAL_MESSAGE, 127, 0 }; - processMessage(message, 3); - - assertEqual(127, _digitalPortValue); -} - -test(processWriteDigital_128) -{ - setupDigitalPort(); - Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); - - byte message[] = { DIGITAL_MESSAGE, 0, 1 }; - processMessage(message, 3); - - assertEqual(128, _digitalPortValue); -} - -test(processWriteLargestDigitalValue) -{ - setupDigitalPort(); - Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); - - byte message[] = { DIGITAL_MESSAGE, 0x7F, 0x7F }; - processMessage(message, 3); - - // Maximum of 14 bits can be set (B0011111111111111) - assertEqual(0x3FFF, _digitalPortValue); -} - -test(defaultDigitalWritePortIsZero) -{ - setupDigitalPort(); - Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); - - byte message[] = { DIGITAL_MESSAGE, 0, 0 }; - processMessage(message, 3); - - assertEqual(0, _digitalPort); -} - -test(specifiedDigitalWritePort) -{ - setupDigitalPort(); - Firmata.attach(DIGITAL_MESSAGE, writeToDigitalPort); - - byte message[] = { DIGITAL_MESSAGE + 1, 0, 0 }; - processMessage(message, 3); - - assertEqual(1, _digitalPort); -} - -test(setFirmwareVersionDoesNotLeakMemory) -{ - Firmata.setFirmwareVersion(1, 0); - int initialMemory = freeMemory(); - - Firmata.setFirmwareVersion(1, 0); - - assertEqual(0, initialMemory - freeMemory()); -} diff --git a/resources/arduino_files/libraries/Firmata/test/readme.md b/resources/arduino_files/libraries/Firmata/test/readme.md deleted file mode 100644 index 726cbcba7..000000000 --- a/resources/arduino_files/libraries/Firmata/test/readme.md +++ /dev/null @@ -1,13 +0,0 @@ -#Testing Firmata - -Tests tests are written using the [ArduinoUnit](https://github.com/mmurdoch/arduinounit) library (version 2.0). - -Follow the instructions in the [ArduinoUnit readme](https://github.com/mmurdoch/arduinounit/blob/master/readme.md) to install the library. - -Compile and upload the test sketch as you would any other sketch. Then open the -Serial Monitor to view the test results. - -If you make changes to Firmata.cpp, run the tests in /test/ to ensure -that your changes have not produced any unexpected errors. - -You should also perform manual tests against actual hardware. diff --git a/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.cpp b/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.cpp deleted file mode 100644 index 34078e312..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.cpp +++ /dev/null @@ -1,114 +0,0 @@ -/* - EthernetClientStream.cpp - An Arduino-Stream that wraps an instance of Client reconnecting to - the remote-ip in a transparent way. A disconnected client may be - recognized by the returnvalues -1 from calls to peek or read and - a 0 from calls to write. - - Copyright (C) 2013 Norbert Truchsess. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - formatted using the GNU C formatting and indenting - */ - -#include "EthernetClientStream.h" -#include - -//#define SERIAL_DEBUG -#include "firmataDebug.h" - -#define MILLIS_RECONNECT 5000 - -EthernetClientStream::EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port) -: client(client), - localip(localip), - ip(ip), - host(host), - port(port), - connected(false) -{ -} - -int -EthernetClientStream::available() -{ - return maintain() ? client.available() : 0; -} - -int -EthernetClientStream::read() -{ - return maintain() ? client.read() : -1; -} - -int -EthernetClientStream::peek() -{ - return maintain() ? client.peek() : -1; -} - -void EthernetClientStream::flush() -{ - if (maintain()) - client.flush(); -} - -size_t -EthernetClientStream::write(uint8_t c) -{ - return maintain() ? client.write(c) : 0; -} - -void -EthernetClientStream::maintain(IPAddress localip) -{ -// temporary hack to Firmata to compile for Intel Galileo -// the issue is documented here: https://github.com/firmata/arduino/issues/218 -#if !defined(ARDUINO_LINUX) - // ensure the local IP is updated in the case that it is changed by the DHCP server - if (this->localip != localip) - { - this->localip = localip; - if (connected) - stop(); - } -#endif -} - -void -EthernetClientStream::stop() -{ - client.stop(); - connected = false; - time_connect = millis(); -} - -bool -EthernetClientStream::maintain() -{ - if (client && client.connected()) - return true; - - if (connected) - { - stop(); - } - // if the client is disconnected, attempt to reconnect every 5 seconds - else if (millis()-time_connect >= MILLIS_RECONNECT) - { - connected = host ? client.connect(host, port) : client.connect(ip, port); - if (!connected) { - time_connect = millis(); - DEBUG_PRINTLN("connection failed. attempting to reconnect..."); - } else { - DEBUG_PRINTLN("connected"); - } - } - return connected; -} diff --git a/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.h b/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.h deleted file mode 100644 index bae34ce9f..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/EthernetClientStream.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - EthernetClientStream.h - An Arduino-Stream that wraps an instance of Client reconnecting to - the remote-ip in a transparent way. A disconnected client may be - recognized by the returnvalues -1 from calls to peek or read and - a 0 from calls to write. - - Copyright (C) 2013 Norbert Truchsess. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - formatted using the GNU C formatting and indenting - */ - -#ifndef ETHERNETCLIENTSTREAM_H -#define ETHERNETCLIENTSTREAM_H - -#include -#include -#include -#include -#include - -class EthernetClientStream : public Stream -{ -public: - EthernetClientStream(Client &client, IPAddress localip, IPAddress ip, const char* host, uint16_t port); - int available(); - int read(); - int peek(); - void flush(); - size_t write(uint8_t); - void maintain(IPAddress localip); - -private: - Client &client; - IPAddress localip; - IPAddress ip; - const char* host; - uint16_t port; - bool connected; - uint32_t time_connect; - bool maintain(); - void stop(); -}; - -#endif diff --git a/resources/arduino_files/libraries/Firmata/utility/FirmataFeature.h b/resources/arduino_files/libraries/Firmata/utility/FirmataFeature.h deleted file mode 100644 index d5e229d0d..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/FirmataFeature.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - FirmataFeature.h - Copyright (C) 2006-2008 Hans-Christoph Steiner. All rights reserved. - Copyright (C) 2010-2011 Paul Stoffregen. All rights reserved. - Copyright (C) 2009 Shigeru Kobayashi. All rights reserved. - Copyright (C) 2013 Norbert Truchsess. All rights reserved. - Copyright (C) 2009-2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - Interface for Firmata feature classes. - - This version of FirmataFeature.h differs from the ConfigurableFirmata - version in the following ways: - - - Imports Firmata.h rather than ConfigurableFirmata.h - - See file LICENSE.txt for further informations on licensing terms. -*/ - -#ifndef FirmataFeature_h -#define FirmataFeature_h - -#include - -class FirmataFeature -{ - public: - virtual void handleCapability(byte pin) = 0; - virtual boolean handlePinMode(byte pin, int mode) = 0; - virtual boolean handleSysex(byte command, byte argc, byte* argv) = 0; - virtual void reset() = 0; -}; - -#endif diff --git a/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.cpp b/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.cpp deleted file mode 100644 index 9dba3f2ba..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.cpp +++ /dev/null @@ -1,328 +0,0 @@ -/* - SerialFirmata.cpp - Copyright (C) 2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - This version of SerialFirmata.cpp differs from the ConfigurableFirmata - version in the following ways: - - - handlePinMode calls Firmata::setPinMode - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -#include "SerialFirmata.h" - -SerialFirmata::SerialFirmata() -{ - swSerial0 = NULL; - swSerial1 = NULL; - swSerial2 = NULL; - swSerial3 = NULL; - - serialIndex = -1; -} - -boolean SerialFirmata::handlePinMode(byte pin, int mode) -{ - // used for both HW and SW serial - if (mode == PIN_MODE_SERIAL) { - Firmata.setPinMode(pin, PIN_MODE_SERIAL); - return true; - } - return false; -} - -void SerialFirmata::handleCapability(byte pin) -{ - if (IS_PIN_SERIAL(pin)) { - Firmata.write(PIN_MODE_SERIAL); - Firmata.write(getSerialPinType(pin)); - } -} - -boolean SerialFirmata::handleSysex(byte command, byte argc, byte *argv) -{ - if (command == SERIAL_MESSAGE) { - - Stream *serialPort; - byte mode = argv[0] & SERIAL_MODE_MASK; - byte portId = argv[0] & SERIAL_PORT_ID_MASK; - - switch (mode) { - case SERIAL_CONFIG: - { - long baud = (long)argv[1] | ((long)argv[2] << 7) | ((long)argv[3] << 14); - serial_pins pins; - - if (portId < 8) { - serialPort = getPortFromId(portId); - if (serialPort != NULL) { - pins = getSerialPinNumbers(portId); - if (pins.rx != 0 && pins.tx != 0) { - Firmata.setPinMode(pins.rx, PIN_MODE_SERIAL); - Firmata.setPinMode(pins.tx, PIN_MODE_SERIAL); - // Fixes an issue where some serial devices would not work properly with Arduino Due - // because all Arduino pins are set to OUTPUT by default in StandardFirmata. - pinMode(pins.rx, INPUT); - } - ((HardwareSerial*)serialPort)->begin(baud); - } - } else { -#if defined(SoftwareSerial_h) - byte swTxPin, swRxPin; - if (argc > 4) { - swRxPin = argv[4]; - swTxPin = argv[5]; - } else { - // RX and TX pins must be specified when using SW serial - Firmata.sendString("Specify serial RX and TX pins"); - return false; - } - switch (portId) { - case SW_SERIAL0: - if (swSerial0 == NULL) { - swSerial0 = new SoftwareSerial(swRxPin, swTxPin); - } - break; - case SW_SERIAL1: - if (swSerial1 == NULL) { - swSerial1 = new SoftwareSerial(swRxPin, swTxPin); - } - break; - case SW_SERIAL2: - if (swSerial2 == NULL) { - swSerial2 = new SoftwareSerial(swRxPin, swTxPin); - } - break; - case SW_SERIAL3: - if (swSerial3 == NULL) { - swSerial3 = new SoftwareSerial(swRxPin, swTxPin); - } - break; - } - serialPort = getPortFromId(portId); - if (serialPort != NULL) { - Firmata.setPinMode(swRxPin, PIN_MODE_SERIAL); - Firmata.setPinMode(swTxPin, PIN_MODE_SERIAL); - ((SoftwareSerial*)serialPort)->begin(baud); - } -#endif - } - break; // SERIAL_CONFIG - } - case SERIAL_WRITE: - { - byte data; - serialPort = getPortFromId(portId); - if (serialPort == NULL) { - break; - } - for (byte i = 1; i < argc; i += 2) { - data = argv[i] + (argv[i + 1] << 7); - serialPort->write(data); - } - break; // SERIAL_WRITE - } - case SERIAL_READ: - if (argv[1] == SERIAL_READ_CONTINUOUSLY) { - if (serialIndex + 1 >= MAX_SERIAL_PORTS) { - break; - } - - if (argc > 2) { - // maximum number of bytes to read from buffer per iteration of loop() - serialBytesToRead[portId] = (int)argv[2] | ((int)argv[3] << 7); - } else { - // read all available bytes per iteration of loop() - serialBytesToRead[portId] = 0; - } - serialIndex++; - reportSerial[serialIndex] = portId; - } else if (argv[1] == SERIAL_STOP_READING) { - byte serialIndexToSkip = 0; - if (serialIndex <= 0) { - serialIndex = -1; - } else { - for (byte i = 0; i < serialIndex + 1; i++) { - if (reportSerial[i] == portId) { - serialIndexToSkip = i; - break; - } - } - // shift elements over to fill space left by removed element - for (byte i = serialIndexToSkip; i < serialIndex + 1; i++) { - if (i < MAX_SERIAL_PORTS) { - reportSerial[i] = reportSerial[i + 1]; - } - } - serialIndex--; - } - } - break; // SERIAL_READ - case SERIAL_CLOSE: - serialPort = getPortFromId(portId); - if (serialPort != NULL) { - if (portId < 8) { - ((HardwareSerial*)serialPort)->end(); - } else { -#if defined(SoftwareSerial_h) - ((SoftwareSerial*)serialPort)->end(); - if (serialPort != NULL) { - free(serialPort); - serialPort = NULL; - } -#endif - } - } - break; // SERIAL_CLOSE - case SERIAL_FLUSH: - serialPort = getPortFromId(portId); - if (serialPort != NULL) { - getPortFromId(portId)->flush(); - } - break; // SERIAL_FLUSH -#if defined(SoftwareSerial_h) - case SERIAL_LISTEN: - // can only call listen() on software serial ports - if (portId > 7) { - serialPort = getPortFromId(portId); - if (serialPort != NULL) { - ((SoftwareSerial*)serialPort)->listen(); - } - } - break; // SERIAL_LISTEN -#endif - } // end switch - return true; - } - return false; -} - -void SerialFirmata::update() -{ - checkSerial(); -} - -void SerialFirmata::reset() -{ -#if defined(SoftwareSerial_h) - Stream *serialPort; - // free memory allocated for SoftwareSerial ports - for (byte i = SW_SERIAL0; i < SW_SERIAL3 + 1; i++) { - serialPort = getPortFromId(i); - if (serialPort != NULL) { - free(serialPort); - serialPort = NULL; - } - } -#endif - - serialIndex = -1; - for (byte i = 0; i < SERIAL_READ_ARR_LEN; i++) { - serialBytesToRead[i] = 0; - } -} - -// get a pointer to the serial port associated with the specified port id -Stream* SerialFirmata::getPortFromId(byte portId) -{ - switch (portId) { - case HW_SERIAL0: - // block use of Serial (typically pins 0 and 1) until ability to reclaim Serial is implemented - //return &Serial; - return NULL; -#if defined(PIN_SERIAL1_RX) - case HW_SERIAL1: - return &Serial1; -#endif -#if defined(PIN_SERIAL2_RX) - case HW_SERIAL2: - return &Serial2; -#endif -#if defined(PIN_SERIAL3_RX) - case HW_SERIAL3: - return &Serial3; -#endif -#if defined(SoftwareSerial_h) - case SW_SERIAL0: - if (swSerial0 != NULL) { - // instances of SoftwareSerial are already pointers so simply return the instance - return swSerial0; - } - break; - case SW_SERIAL1: - if (swSerial1 != NULL) { - return swSerial1; - } - break; - case SW_SERIAL2: - if (swSerial2 != NULL) { - return swSerial2; - } - break; - case SW_SERIAL3: - if (swSerial3 != NULL) { - return swSerial3; - } - break; -#endif - } - return NULL; -} - -// Check serial ports that have READ_CONTINUOUS mode set and relay any data -// for each port to the device attached to that port. -void SerialFirmata::checkSerial() -{ - byte portId, serialData; - int bytesToRead = 0; - int numBytesToRead = 0; - Stream* serialPort; - - if (serialIndex > -1) { - - // loop through all reporting (READ_CONTINUOUS) serial ports - for (byte i = 0; i < serialIndex + 1; i++) { - portId = reportSerial[i]; - bytesToRead = serialBytesToRead[portId]; - serialPort = getPortFromId(portId); - if (serialPort == NULL) { - continue; - } -#if defined(SoftwareSerial_h) - // only the SoftwareSerial port that is "listening" can read data - if (portId > 7 && !((SoftwareSerial*)serialPort)->isListening()) { - continue; - } -#endif - if (serialPort->available() > 0) { - Firmata.write(START_SYSEX); - Firmata.write(SERIAL_MESSAGE); - Firmata.write(SERIAL_REPLY | portId); - - if (bytesToRead == 0 || (serialPort->available() <= bytesToRead)) { - numBytesToRead = serialPort->available(); - } else { - numBytesToRead = bytesToRead; - } - - // relay serial data to the serial device - while (numBytesToRead > 0) { - serialData = serialPort->read(); - Firmata.write(serialData & 0x7F); - Firmata.write((serialData >> 7) & 0x7F); - numBytesToRead--; - } - Firmata.write(END_SYSEX); - } - - } - } -} diff --git a/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.h b/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.h deleted file mode 100644 index b3357f44b..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/SerialFirmata.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - SerialFirmata.h - Copyright (C) 2016 Jeff Hoefs. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - - This version of SerialFirmata.h differs from the ConfigurableFirmata - version in the following ways: - - - Defines FIRMATA_SERIAL_FEATURE (could add to Configurable version as well) - - Imports Firmata.h rather than ConfigurableFirmata.h - - Last updated by Jeff Hoefs: January 10th, 2016 -*/ - -#ifndef SerialFirmata_h -#define SerialFirmata_h - -#include -#include "FirmataFeature.h" -// SoftwareSerial is currently only supported for AVR-based boards and the Arduino 101 -// The third condition checks if the IDE is in the 1.0.x series, if so, include SoftwareSerial -// since it should be available to all boards in that IDE. -#if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ARC32) || (ARDUINO >= 100 && ARDUINO < 10500) -#include -#endif - -#define FIRMATA_SERIAL_FEATURE - -// Serial port Ids -#define HW_SERIAL0 0x00 -#define HW_SERIAL1 0x01 -#define HW_SERIAL2 0x02 -#define HW_SERIAL3 0x03 -// extensible up to 0x07 - -#define SW_SERIAL0 0x08 -#define SW_SERIAL1 0x09 -#define SW_SERIAL2 0x0A -#define SW_SERIAL3 0x0B -// extensible up to 0x0F - -#define SERIAL_PORT_ID_MASK 0x0F -#define MAX_SERIAL_PORTS 8 -#define SERIAL_READ_ARR_LEN 12 - -// map configuration query response resolution value to serial pin type -#define RES_RX1 0x02 -#define RES_TX1 0x03 -#define RES_RX2 0x04 -#define RES_TX2 0x05 -#define RES_RX3 0x06 -#define RES_TX3 0x07 - -// Serial command bytes -#define SERIAL_CONFIG 0x10 -#define SERIAL_WRITE 0x20 -#define SERIAL_READ 0x30 -#define SERIAL_REPLY 0x40 -#define SERIAL_CLOSE 0x50 -#define SERIAL_FLUSH 0x60 -#define SERIAL_LISTEN 0x70 - -// Serial read modes -#define SERIAL_READ_CONTINUOUSLY 0x00 -#define SERIAL_STOP_READING 0x01 -#define SERIAL_MODE_MASK 0xF0 - -namespace { - - struct serial_pins { - uint8_t rx; - uint8_t tx; - }; - - /* - * Get the serial serial pin type (RX1, TX1, RX2, TX2, etc) for the specified pin. - */ - inline uint8_t getSerialPinType(uint8_t pin) { - #if defined(PIN_SERIAL_RX) - // TODO when use of HW_SERIAL0 is enabled - #endif - #if defined(PIN_SERIAL1_RX) - if (pin == PIN_SERIAL1_RX) return RES_RX1; - if (pin == PIN_SERIAL1_TX) return RES_TX1; - #endif - #if defined(PIN_SERIAL2_RX) - if (pin == PIN_SERIAL2_RX) return RES_RX2; - if (pin == PIN_SERIAL2_TX) return RES_TX2; - #endif - #if defined(PIN_SERIAL3_RX) - if (pin == PIN_SERIAL3_RX) return RES_RX3; - if (pin == PIN_SERIAL3_TX) return RES_TX3; - #endif - return 0; - } - - /* - * Get the RX and TX pins numbers for the specified HW serial port. - */ - inline serial_pins getSerialPinNumbers(uint8_t portId) { - serial_pins pins; - switch (portId) { - #if defined(PIN_SERIAL_RX) - // case HW_SERIAL0: - // // TODO when use of HW_SERIAL0 is enabled - // break; - #endif - #if defined(PIN_SERIAL1_RX) - case HW_SERIAL1: - pins.rx = PIN_SERIAL1_RX; - pins.tx = PIN_SERIAL1_TX; - break; - #endif - #if defined(PIN_SERIAL2_RX) - case HW_SERIAL2: - pins.rx = PIN_SERIAL2_RX; - pins.tx = PIN_SERIAL2_TX; - break; - #endif - #if defined(PIN_SERIAL3_RX) - case HW_SERIAL3: - pins.rx = PIN_SERIAL3_RX; - pins.tx = PIN_SERIAL3_TX; - break; - #endif - default: - pins.rx = 0; - pins.tx = 0; - } - return pins; - } - -} // end namespace - - -class SerialFirmata: public FirmataFeature -{ - public: - SerialFirmata(); - boolean handlePinMode(byte pin, int mode); - void handleCapability(byte pin); - boolean handleSysex(byte command, byte argc, byte* argv); - void update(); - void reset(); - void checkSerial(); - - private: - byte reportSerial[MAX_SERIAL_PORTS]; - int serialBytesToRead[SERIAL_READ_ARR_LEN]; - signed char serialIndex; - - Stream *swSerial0; - Stream *swSerial1; - Stream *swSerial2; - Stream *swSerial3; - - Stream* getPortFromId(byte portId); - -}; - -#endif /* SerialFirmata_h */ diff --git a/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.cpp b/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.cpp deleted file mode 100644 index 3beaf40e7..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.cpp +++ /dev/null @@ -1,4 +0,0 @@ -/* - * Implementation is in WiFi101Stream.h to avoid linker issues. Legacy WiFi and modern WiFi101 both define WiFiClass which - * will cause linker errors whenever Firmata.h is included. - */ diff --git a/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.h b/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.h deleted file mode 100644 index eb95cf51d..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/WiFi101Stream.h +++ /dev/null @@ -1,259 +0,0 @@ -/* - WiFi101Stream.h - An Arduino Stream that wraps an instance of a WiFi101 server. For use - with Arduino WiFi 101 shield, Arduino MKR1000 and other boards and - shields that are compatible with the Arduino WiFi101 library. - - Copyright (C) 2015-2016 Jesse Frush. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - */ - -#ifndef WIFI101_STREAM_H -#define WIFI101_STREAM_H - -#include -#include -#include - - -class WiFi101Stream : public Stream -{ -private: - WiFiServer _server = WiFiServer(23); - WiFiClient _client; - - //configuration members - IPAddress _local_ip; - uint16_t _port = 0; - uint8_t _key_idx = 0; //WEP - const char *_key = nullptr; //WEP - const char *_passphrase = nullptr; //WPA - char *_ssid = nullptr; - - inline int connect_client() - { - if( !( _client && _client.connected() ) ) - { - WiFiClient newClient = _server.available(); - if( !newClient ) - { - return 0; - } - - _client = newClient; - } - return 1; - } - - inline bool is_ready() - { - uint8_t status = WiFi.status(); - return !( status == WL_NO_SHIELD || status == WL_CONNECTED ); - } - -public: - WiFi101Stream() {}; - - // allows another way to configure a static IP before begin is called - inline void config(IPAddress local_ip) - { - _local_ip = local_ip; - WiFi.config( local_ip ); - } - - // get DCHP IP - inline IPAddress localIP() - { - return WiFi.localIP(); - } - - inline bool maintain() - { - if( connect_client() ) return true; - - stop(); - int result = 0; - if( WiFi.status() != WL_CONNECTED ) - { - if( _local_ip ) - { - WiFi.config( _local_ip ); - } - - if( _passphrase ) - { - result = WiFi.begin( _ssid, _passphrase); - } - else if( _key_idx && _key ) - { - result = WiFi.begin( _ssid, _key_idx, _key ); - } - else - { - result = WiFi.begin( _ssid ); - } - } - if( result == 0 ) return false; - - _server = WiFiServer( _port ); - _server.begin(); - return result; - } - -/****************************************************************************** - * Connection functions with DHCP - ******************************************************************************/ - - //OPEN networks - inline int begin(char *ssid, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - int result = WiFi.begin( ssid ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WEP-encrypted networks - inline int begin(char *ssid, uint8_t key_idx, const char *key, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _key_idx = key_idx; - _key = key; - - int result = WiFi.begin( ssid, key_idx, key ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WPA-encrypted networks - inline int begin(char *ssid, const char *passphrase, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _passphrase = passphrase; - - int result = WiFi.begin( ssid, passphrase); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - -/****************************************************************************** - * Connection functions without DHCP - ******************************************************************************/ - - //OPEN networks with static IP - inline int begin(char *ssid, IPAddress local_ip, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _local_ip = local_ip; - - WiFi.config( local_ip ); - int result = WiFi.begin( ssid ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WEP-encrypted networks with static IP - inline int begin(char *ssid, IPAddress local_ip, uint8_t key_idx, const char *key, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _local_ip = local_ip; - _key_idx = key_idx; - _key = key; - - WiFi.config( local_ip ); - int result = WiFi.begin( ssid, key_idx, key ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WPA-encrypted networks with static IP - inline int begin(char *ssid, IPAddress local_ip, const char *passphrase, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _local_ip = local_ip; - _passphrase = passphrase; - - WiFi.config( local_ip ); - int result = WiFi.begin( ssid, passphrase); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - -/****************************************************************************** - * Stream implementations - ******************************************************************************/ - - inline int available() - { - return connect_client() ? _client.available() : 0; - } - - inline void flush() - { - if( _client ) _client.flush(); - } - - inline int peek() - { - return connect_client() ? _client.peek(): 0; - } - - inline int read() - { - return connect_client() ? _client.read() : -1; - } - - inline void stop() - { - _client.stop(); - } - - inline size_t write(uint8_t byte) - { - if( connect_client() ) _client.write( byte ); - } -}; - -#endif //WIFI101_STREAM_H diff --git a/resources/arduino_files/libraries/Firmata/utility/WiFiStream.cpp b/resources/arduino_files/libraries/Firmata/utility/WiFiStream.cpp deleted file mode 100644 index 9b54a5ace..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/WiFiStream.cpp +++ /dev/null @@ -1,4 +0,0 @@ -/* - * Implementation is in WiFiStream.h to avoid linker issues. Legacy WiFi and modern WiFi101 both define WiFiClass which - * will cause linker errors whenever Firmata.h is included. - */ diff --git a/resources/arduino_files/libraries/Firmata/utility/WiFiStream.h b/resources/arduino_files/libraries/Firmata/utility/WiFiStream.h deleted file mode 100644 index fdcb483a3..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/WiFiStream.h +++ /dev/null @@ -1,258 +0,0 @@ -/* - WiFiStream.h - An Arduino Stream that wraps an instance of a WiFi server. For use - with legacy Arduino WiFi shield and other boards and sheilds that - are compatible with the Arduino WiFi library. - - Copyright (C) 2015-2016 Jesse Frush. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - See file LICENSE.txt for further informations on licensing terms. - */ - -#ifndef WIFI_STREAM_H -#define WIFI_STREAM_H - -#include -#include -#include - -class WiFiStream : public Stream -{ -private: - WiFiServer _server = WiFiServer(23); - WiFiClient _client; - - //configuration members - IPAddress _local_ip; - uint16_t _port = 0; - uint8_t _key_idx = 0; //WEP - const char *_key = nullptr; //WEP - const char *_passphrase = nullptr; //WPA - char *_ssid = nullptr; - - inline int connect_client() - { - if( !( _client && _client.connected() ) ) - { - WiFiClient newClient = _server.available(); - if( !newClient ) - { - return 0; - } - - _client = newClient; - } - return 1; - } - - inline bool is_ready() - { - uint8_t status = WiFi.status(); - return !( status == WL_NO_SHIELD || status == WL_CONNECTED ); - } - -public: - WiFiStream() {}; - - // allows another way to configure a static IP before begin is called - inline void config(IPAddress local_ip) - { - _local_ip = local_ip; - WiFi.config( local_ip ); - } - - // get DCHP IP - inline IPAddress localIP() - { - return WiFi.localIP(); - } - - inline bool maintain() - { - if( connect_client() ) return true; - - stop(); - int result = 0; - if( WiFi.status() != WL_CONNECTED ) - { - if( _local_ip ) - { - WiFi.config( _local_ip ); - } - - if( _passphrase ) - { - result = WiFi.begin( _ssid, _passphrase); - } - else if( _key_idx && _key ) - { - result = WiFi.begin( _ssid, _key_idx, _key ); - } - else - { - result = WiFi.begin( _ssid ); - } - } - if( result == 0 ) return false; - - _server = WiFiServer( _port ); - _server.begin(); - return result; - } - -/****************************************************************************** - * Connection functions with DHCP - ******************************************************************************/ - - //OPEN networks - inline int begin(char *ssid, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - int result = WiFi.begin( ssid ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WEP-encrypted networks - inline int begin(char *ssid, uint8_t key_idx, const char *key, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _key_idx = key_idx; - _key = key; - - int result = WiFi.begin( ssid, key_idx, key ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WPA-encrypted networks - inline int begin(char *ssid, const char *passphrase, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _passphrase = passphrase; - - int result = WiFi.begin( ssid, passphrase); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - -/****************************************************************************** - * Connection functions without DHCP - ******************************************************************************/ - - //OPEN networks with static IP - inline int begin(char *ssid, IPAddress local_ip, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _local_ip = local_ip; - - WiFi.config( local_ip ); - int result = WiFi.begin( ssid ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WEP-encrypted networks with static IP - inline int begin(char *ssid, IPAddress local_ip, uint8_t key_idx, const char *key, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _local_ip = local_ip; - _key_idx = key_idx; - _key = key; - - WiFi.config( local_ip ); - int result = WiFi.begin( ssid, key_idx, key ); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - - //WPA-encrypted networks with static IP - inline int begin(char *ssid, IPAddress local_ip, const char *passphrase, uint16_t port) - { - if( !is_ready() ) return 0; - - _ssid = ssid; - _port = port; - _local_ip = local_ip; - _passphrase = passphrase; - - WiFi.config( local_ip ); - int result = WiFi.begin( ssid, passphrase); - if( result == 0 ) return 0; - - _server = WiFiServer( port ); - _server.begin(); - return result; - } - -/****************************************************************************** - * Stream implementations - ******************************************************************************/ - - inline int available() - { - return connect_client() ? _client.available() : 0; - } - - inline void flush() - { - if( _client ) _client.flush(); - } - - inline int peek() - { - return connect_client() ? _client.peek(): 0; - } - - inline int read() - { - return connect_client() ? _client.read() : -1; - } - - inline void stop() - { - _client.stop(); - } - - inline size_t write(uint8_t byte) - { - if( connect_client() ) _client.write( byte ); - } -}; - -#endif //WIFI_STREAM_H diff --git a/resources/arduino_files/libraries/Firmata/utility/firmataDebug.h b/resources/arduino_files/libraries/Firmata/utility/firmataDebug.h deleted file mode 100644 index 6e364b0c7..000000000 --- a/resources/arduino_files/libraries/Firmata/utility/firmataDebug.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef FIRMATA_DEBUG_H -#define FIRMATA_DEBUG_H - -#ifdef SERIAL_DEBUG - #define DEBUG_BEGIN(baud) Serial.begin(baud); while(!Serial) {;} - #define DEBUG_PRINTLN(x) Serial.println (x) - #define DEBUG_PRINT(x) Serial.print (x) -#else - #define DEBUG_BEGIN(baud) - #define DEBUG_PRINTLN(x) - #define DEBUG_PRINT(x) -#endif - -#endif /* FIRMATA_DEBUG_H */ diff --git a/resources/arduino_files/libraries/Keyboard/README.adoc b/resources/arduino_files/libraries/Keyboard/README.adoc deleted file mode 100644 index 0d77d9a83..000000000 --- a/resources/arduino_files/libraries/Keyboard/README.adoc +++ /dev/null @@ -1,25 +0,0 @@ -= Keyboard Library for Arduino = - -This library allows an Arduino board with USB capabilites to act as a Keyboard. -Being based on HID library you need to include "HID.h" in your sketch. - -For more information about this library please visit us at -http://www.arduino.cc/en/Reference/Keyboard - -== License == - -Copyright (c) Arduino LLC. All right reserved. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/resources/arduino_files/libraries/Keyboard/keywords.txt b/resources/arduino_files/libraries/Keyboard/keywords.txt deleted file mode 100644 index 2078f0329..000000000 --- a/resources/arduino_files/libraries/Keyboard/keywords.txt +++ /dev/null @@ -1,24 +0,0 @@ -####################################### -# Syntax Coloring Map For Keyboard -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Keyboard KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -write KEYWORD2 -press KEYWORD2 -release KEYWORD2 -releaseAll KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/resources/arduino_files/libraries/Keyboard/library.properties b/resources/arduino_files/libraries/Keyboard/library.properties deleted file mode 100644 index 4fa367a08..000000000 --- a/resources/arduino_files/libraries/Keyboard/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Keyboard -version=1.0.1 -author=Arduino -maintainer=Arduino -sentence=Allows an Arduino/Genuino board with USB capabilites to act as a Keyboard. -paragraph=This library plugs on the HID library. It can be used with or without other HID-based libraries (Mouse, Gamepad etc) -category=Device Control -url=http://www.arduino.cc/en/Reference/Keyboard -architectures=* diff --git a/resources/arduino_files/libraries/Keyboard/src/Keyboard.cpp b/resources/arduino_files/libraries/Keyboard/src/Keyboard.cpp deleted file mode 100644 index 48f085219..000000000 --- a/resources/arduino_files/libraries/Keyboard/src/Keyboard.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/* - Keyboard.cpp - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Keyboard.h" - -#if defined(_USING_HID) - -//================================================================================ -//================================================================================ -// Keyboard - -static const uint8_t _hidReportDescriptor[] PROGMEM = { - - // Keyboard - 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47 - 0x09, 0x06, // USAGE (Keyboard) - 0xa1, 0x01, // COLLECTION (Application) - 0x85, 0x02, // REPORT_ID (2) - 0x05, 0x07, // USAGE_PAGE (Keyboard) - - 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl) - 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x01, // LOGICAL_MAXIMUM (1) - 0x75, 0x01, // REPORT_SIZE (1) - - 0x95, 0x08, // REPORT_COUNT (8) - 0x81, 0x02, // INPUT (Data,Var,Abs) - 0x95, 0x01, // REPORT_COUNT (1) - 0x75, 0x08, // REPORT_SIZE (8) - 0x81, 0x03, // INPUT (Cnst,Var,Abs) - - 0x95, 0x06, // REPORT_COUNT (6) - 0x75, 0x08, // REPORT_SIZE (8) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x65, // LOGICAL_MAXIMUM (101) - 0x05, 0x07, // USAGE_PAGE (Keyboard) - - 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated)) - 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application) - 0x81, 0x00, // INPUT (Data,Ary,Abs) - 0xc0, // END_COLLECTION -}; - -Keyboard_::Keyboard_(void) -{ - static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); - HID().AppendDescriptor(&node); -} - -void Keyboard_::begin(void) -{ -} - -void Keyboard_::end(void) -{ -} - -void Keyboard_::sendReport(KeyReport* keys) -{ - HID().SendReport(2,keys,sizeof(KeyReport)); -} - -extern -const uint8_t _asciimap[128] PROGMEM; - -#define SHIFT 0x80 -const uint8_t _asciimap[128] = -{ - 0x00, // NUL - 0x00, // SOH - 0x00, // STX - 0x00, // ETX - 0x00, // EOT - 0x00, // ENQ - 0x00, // ACK - 0x00, // BEL - 0x2a, // BS Backspace - 0x2b, // TAB Tab - 0x28, // LF Enter - 0x00, // VT - 0x00, // FF - 0x00, // CR - 0x00, // SO - 0x00, // SI - 0x00, // DEL - 0x00, // DC1 - 0x00, // DC2 - 0x00, // DC3 - 0x00, // DC4 - 0x00, // NAK - 0x00, // SYN - 0x00, // ETB - 0x00, // CAN - 0x00, // EM - 0x00, // SUB - 0x00, // ESC - 0x00, // FS - 0x00, // GS - 0x00, // RS - 0x00, // US - - 0x2c, // ' ' - 0x1e|SHIFT, // ! - 0x34|SHIFT, // " - 0x20|SHIFT, // # - 0x21|SHIFT, // $ - 0x22|SHIFT, // % - 0x24|SHIFT, // & - 0x34, // ' - 0x26|SHIFT, // ( - 0x27|SHIFT, // ) - 0x25|SHIFT, // * - 0x2e|SHIFT, // + - 0x36, // , - 0x2d, // - - 0x37, // . - 0x38, // / - 0x27, // 0 - 0x1e, // 1 - 0x1f, // 2 - 0x20, // 3 - 0x21, // 4 - 0x22, // 5 - 0x23, // 6 - 0x24, // 7 - 0x25, // 8 - 0x26, // 9 - 0x33|SHIFT, // : - 0x33, // ; - 0x36|SHIFT, // < - 0x2e, // = - 0x37|SHIFT, // > - 0x38|SHIFT, // ? - 0x1f|SHIFT, // @ - 0x04|SHIFT, // A - 0x05|SHIFT, // B - 0x06|SHIFT, // C - 0x07|SHIFT, // D - 0x08|SHIFT, // E - 0x09|SHIFT, // F - 0x0a|SHIFT, // G - 0x0b|SHIFT, // H - 0x0c|SHIFT, // I - 0x0d|SHIFT, // J - 0x0e|SHIFT, // K - 0x0f|SHIFT, // L - 0x10|SHIFT, // M - 0x11|SHIFT, // N - 0x12|SHIFT, // O - 0x13|SHIFT, // P - 0x14|SHIFT, // Q - 0x15|SHIFT, // R - 0x16|SHIFT, // S - 0x17|SHIFT, // T - 0x18|SHIFT, // U - 0x19|SHIFT, // V - 0x1a|SHIFT, // W - 0x1b|SHIFT, // X - 0x1c|SHIFT, // Y - 0x1d|SHIFT, // Z - 0x2f, // [ - 0x31, // bslash - 0x30, // ] - 0x23|SHIFT, // ^ - 0x2d|SHIFT, // _ - 0x35, // ` - 0x04, // a - 0x05, // b - 0x06, // c - 0x07, // d - 0x08, // e - 0x09, // f - 0x0a, // g - 0x0b, // h - 0x0c, // i - 0x0d, // j - 0x0e, // k - 0x0f, // l - 0x10, // m - 0x11, // n - 0x12, // o - 0x13, // p - 0x14, // q - 0x15, // r - 0x16, // s - 0x17, // t - 0x18, // u - 0x19, // v - 0x1a, // w - 0x1b, // x - 0x1c, // y - 0x1d, // z - 0x2f|SHIFT, // { - 0x31|SHIFT, // | - 0x30|SHIFT, // } - 0x35|SHIFT, // ~ - 0 // DEL -}; - - -uint8_t USBPutChar(uint8_t c); - -// press() adds the specified key (printing, non-printing, or modifier) -// to the persistent key report and sends the report. Because of the way -// USB HID works, the host acts like the key remains pressed until we -// call release(), releaseAll(), or otherwise clear the report and resend. -size_t Keyboard_::press(uint8_t k) -{ - uint8_t i; - if (k >= 136) { // it's a non-printing key (not a modifier) - k = k - 136; - } else if (k >= 128) { // it's a modifier key - _keyReport.modifiers |= (1<<(k-128)); - k = 0; - } else { // it's a printing key - k = pgm_read_byte(_asciimap + k); - if (!k) { - setWriteError(); - return 0; - } - if (k & 0x80) { // it's a capital letter or other character reached with shift - _keyReport.modifiers |= 0x02; // the left shift modifier - k &= 0x7F; - } - } - - // Add k to the key report only if it's not already present - // and if there is an empty slot. - if (_keyReport.keys[0] != k && _keyReport.keys[1] != k && - _keyReport.keys[2] != k && _keyReport.keys[3] != k && - _keyReport.keys[4] != k && _keyReport.keys[5] != k) { - - for (i=0; i<6; i++) { - if (_keyReport.keys[i] == 0x00) { - _keyReport.keys[i] = k; - break; - } - } - if (i == 6) { - setWriteError(); - return 0; - } - } - sendReport(&_keyReport); - return 1; -} - -// release() takes the specified key out of the persistent key report and -// sends the report. This tells the OS the key is no longer pressed and that -// it shouldn't be repeated any more. -size_t Keyboard_::release(uint8_t k) -{ - uint8_t i; - if (k >= 136) { // it's a non-printing key (not a modifier) - k = k - 136; - } else if (k >= 128) { // it's a modifier key - _keyReport.modifiers &= ~(1<<(k-128)); - k = 0; - } else { // it's a printing key - k = pgm_read_byte(_asciimap + k); - if (!k) { - return 0; - } - if (k & 0x80) { // it's a capital letter or other character reached with shift - _keyReport.modifiers &= ~(0x02); // the left shift modifier - k &= 0x7F; - } - } - - // Test the key report to see if k is present. Clear it if it exists. - // Check all positions in case the key is present more than once (which it shouldn't be) - for (i=0; i<6; i++) { - if (0 != k && _keyReport.keys[i] == k) { - _keyReport.keys[i] = 0x00; - } - } - - sendReport(&_keyReport); - return 1; -} - -void Keyboard_::releaseAll(void) -{ - _keyReport.keys[0] = 0; - _keyReport.keys[1] = 0; - _keyReport.keys[2] = 0; - _keyReport.keys[3] = 0; - _keyReport.keys[4] = 0; - _keyReport.keys[5] = 0; - _keyReport.modifiers = 0; - sendReport(&_keyReport); -} - -size_t Keyboard_::write(uint8_t c) -{ - uint8_t p = press(c); // Keydown - release(c); // Keyup - return p; // just return the result of press() since release() almost always returns 1 -} - -Keyboard_ Keyboard; - -#endif diff --git a/resources/arduino_files/libraries/Keyboard/src/Keyboard.h b/resources/arduino_files/libraries/Keyboard/src/Keyboard.h deleted file mode 100644 index 8f173f31c..000000000 --- a/resources/arduino_files/libraries/Keyboard/src/Keyboard.h +++ /dev/null @@ -1,99 +0,0 @@ -/* - Keyboard.h - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef KEYBOARD_h -#define KEYBOARD_h - -#include "HID.h" - -#if !defined(_USING_HID) - -#warning "Using legacy HID core (non pluggable)" - -#else - -//================================================================================ -//================================================================================ -// Keyboard - -#define KEY_LEFT_CTRL 0x80 -#define KEY_LEFT_SHIFT 0x81 -#define KEY_LEFT_ALT 0x82 -#define KEY_LEFT_GUI 0x83 -#define KEY_RIGHT_CTRL 0x84 -#define KEY_RIGHT_SHIFT 0x85 -#define KEY_RIGHT_ALT 0x86 -#define KEY_RIGHT_GUI 0x87 - -#define KEY_UP_ARROW 0xDA -#define KEY_DOWN_ARROW 0xD9 -#define KEY_LEFT_ARROW 0xD8 -#define KEY_RIGHT_ARROW 0xD7 -#define KEY_BACKSPACE 0xB2 -#define KEY_TAB 0xB3 -#define KEY_RETURN 0xB0 -#define KEY_ESC 0xB1 -#define KEY_INSERT 0xD1 -#define KEY_DELETE 0xD4 -#define KEY_PAGE_UP 0xD3 -#define KEY_PAGE_DOWN 0xD6 -#define KEY_HOME 0xD2 -#define KEY_END 0xD5 -#define KEY_CAPS_LOCK 0xC1 -#define KEY_F1 0xC2 -#define KEY_F2 0xC3 -#define KEY_F3 0xC4 -#define KEY_F4 0xC5 -#define KEY_F5 0xC6 -#define KEY_F6 0xC7 -#define KEY_F7 0xC8 -#define KEY_F8 0xC9 -#define KEY_F9 0xCA -#define KEY_F10 0xCB -#define KEY_F11 0xCC -#define KEY_F12 0xCD - -// Low level key report: up to 6 keys and shift, ctrl etc at once -typedef struct -{ - uint8_t modifiers; - uint8_t reserved; - uint8_t keys[6]; -} KeyReport; - -class Keyboard_ : public Print -{ -private: - KeyReport _keyReport; - void sendReport(KeyReport* keys); -public: - Keyboard_(void); - void begin(void); - void end(void); - size_t write(uint8_t k); - size_t press(uint8_t k); - size_t release(uint8_t k); - void releaseAll(void); -}; -extern Keyboard_ Keyboard; - -#endif -#endif diff --git a/resources/arduino_files/libraries/Mouse/README.adoc b/resources/arduino_files/libraries/Mouse/README.adoc deleted file mode 100644 index 3e61306c6..000000000 --- a/resources/arduino_files/libraries/Mouse/README.adoc +++ /dev/null @@ -1,25 +0,0 @@ -= Mouse Library for Arduino = - -This library allows an Arduino board with USB capabilites to act as a Mouse. -Being based on HID library you need to include "HID.h" in your sketch - -For more information about this library please visit us at -http://www.arduino.cc/en/Reference/Mouse - -== License == - -Copyright (c) Arduino LLC. All right reserved. - -This library is free software; you can redistribute it and/or -modify it under the terms of the GNU Lesser General Public -License as published by the Free Software Foundation; either -version 2.1 of the License, or (at your option) any later version. - -This library is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -Lesser General Public License for more details. - -You should have received a copy of the GNU Lesser General Public -License along with this library; if not, write to the Free Software -Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA diff --git a/resources/arduino_files/libraries/Mouse/keywords.txt b/resources/arduino_files/libraries/Mouse/keywords.txt deleted file mode 100644 index 258c48eeb..000000000 --- a/resources/arduino_files/libraries/Mouse/keywords.txt +++ /dev/null @@ -1,24 +0,0 @@ -####################################### -# Syntax Coloring Map For Keyboard -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Mouse KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -click KEYWORD2 -move KEYWORD2 -press KEYWORD2 -release KEYWORD2 -isPressed KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### diff --git a/resources/arduino_files/libraries/Mouse/library.properties b/resources/arduino_files/libraries/Mouse/library.properties deleted file mode 100644 index 6e60f0125..000000000 --- a/resources/arduino_files/libraries/Mouse/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Mouse -version=1.0.1 -author=Arduino -maintainer=Arduino -sentence=Allows an Arduino/Genuino board with USB capabilites to act as a Mouse. -paragraph=This library plugs on the HID library. Can be used with or without other HID-based libraries (Keyboard, Gamepad etc) -category=Device Control -url=http://www.arduino.cc/en/Reference/Mouse -architectures=* diff --git a/resources/arduino_files/libraries/Mouse/src/Mouse.cpp b/resources/arduino_files/libraries/Mouse/src/Mouse.cpp deleted file mode 100644 index b2a2cd7b8..000000000 --- a/resources/arduino_files/libraries/Mouse/src/Mouse.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - Mouse.cpp - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Mouse.h" - -#if defined(_USING_HID) - -static const uint8_t _hidReportDescriptor[] PROGMEM = { - - // Mouse - 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54 - 0x09, 0x02, // USAGE (Mouse) - 0xa1, 0x01, // COLLECTION (Application) - 0x09, 0x01, // USAGE (Pointer) - 0xa1, 0x00, // COLLECTION (Physical) - 0x85, 0x01, // REPORT_ID (1) - 0x05, 0x09, // USAGE_PAGE (Button) - 0x19, 0x01, // USAGE_MINIMUM (Button 1) - 0x29, 0x03, // USAGE_MAXIMUM (Button 3) - 0x15, 0x00, // LOGICAL_MINIMUM (0) - 0x25, 0x01, // LOGICAL_MAXIMUM (1) - 0x95, 0x03, // REPORT_COUNT (3) - 0x75, 0x01, // REPORT_SIZE (1) - 0x81, 0x02, // INPUT (Data,Var,Abs) - 0x95, 0x01, // REPORT_COUNT (1) - 0x75, 0x05, // REPORT_SIZE (5) - 0x81, 0x03, // INPUT (Cnst,Var,Abs) - 0x05, 0x01, // USAGE_PAGE (Generic Desktop) - 0x09, 0x30, // USAGE (X) - 0x09, 0x31, // USAGE (Y) - 0x09, 0x38, // USAGE (Wheel) - 0x15, 0x81, // LOGICAL_MINIMUM (-127) - 0x25, 0x7f, // LOGICAL_MAXIMUM (127) - 0x75, 0x08, // REPORT_SIZE (8) - 0x95, 0x03, // REPORT_COUNT (3) - 0x81, 0x06, // INPUT (Data,Var,Rel) - 0xc0, // END_COLLECTION - 0xc0, // END_COLLECTION -}; - -//================================================================================ -//================================================================================ -// Mouse - -Mouse_::Mouse_(void) : _buttons(0) -{ - static HIDSubDescriptor node(_hidReportDescriptor, sizeof(_hidReportDescriptor)); - HID().AppendDescriptor(&node); -} - -void Mouse_::begin(void) -{ -} - -void Mouse_::end(void) -{ -} - -void Mouse_::click(uint8_t b) -{ - _buttons = b; - move(0,0,0); - _buttons = 0; - move(0,0,0); -} - -void Mouse_::move(signed char x, signed char y, signed char wheel) -{ - uint8_t m[4]; - m[0] = _buttons; - m[1] = x; - m[2] = y; - m[3] = wheel; - HID().SendReport(1,m,4); -} - -void Mouse_::buttons(uint8_t b) -{ - if (b != _buttons) - { - _buttons = b; - move(0,0,0); - } -} - -void Mouse_::press(uint8_t b) -{ - buttons(_buttons | b); -} - -void Mouse_::release(uint8_t b) -{ - buttons(_buttons & ~b); -} - -bool Mouse_::isPressed(uint8_t b) -{ - if ((b & _buttons) > 0) - return true; - return false; -} - -Mouse_ Mouse; - -#endif diff --git a/resources/arduino_files/libraries/Mouse/src/Mouse.h b/resources/arduino_files/libraries/Mouse/src/Mouse.h deleted file mode 100644 index 2672b5c93..000000000 --- a/resources/arduino_files/libraries/Mouse/src/Mouse.h +++ /dev/null @@ -1,60 +0,0 @@ -/* - Mouse.h - - Copyright (c) 2015, Arduino LLC - Original code (pre-library): Copyright (c) 2011, Peter Barrett - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef MOUSE_h -#define MOUSE_h - -#include "HID.h" - -#if !defined(_USING_HID) - -#warning "Using legacy HID core (non pluggable)" - -#else - -//================================================================================ -//================================================================================ -// Mouse - -#define MOUSE_LEFT 1 -#define MOUSE_RIGHT 2 -#define MOUSE_MIDDLE 4 -#define MOUSE_ALL (MOUSE_LEFT | MOUSE_RIGHT | MOUSE_MIDDLE) - -class Mouse_ -{ -private: - uint8_t _buttons; - void buttons(uint8_t b); -public: - Mouse_(void); - void begin(void); - void end(void); - void click(uint8_t b = MOUSE_LEFT); - void move(signed char x, signed char y, signed char wheel = 0); - void press(uint8_t b = MOUSE_LEFT); // press LEFT by default - void release(uint8_t b = MOUSE_LEFT); // release LEFT by default - bool isPressed(uint8_t b = MOUSE_LEFT); // check LEFT by default -}; -extern Mouse_ Mouse; - -#endif -#endif \ No newline at end of file From ab8d6a3cd65f3e266e393a72d293428c651a99c7 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Tue, 21 Nov 2017 13:33:55 +1100 Subject: [PATCH 74/79] Create README.md --- README.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 000000000..675b1389e --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +# PACE +Panoptes Arduino Code for Electronics + +> :warning: This repository has been merged with [POCS](https://github.com/panoptes/POCS). No new development will take place here but the repository is left for historical reasons. From 2bc303ff7a814c6ed1848b1cf6d16bb1c3a9f3a9 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Tue, 21 Nov 2017 13:34:19 +1100 Subject: [PATCH 75/79] Create LICENSE --- LICENSE | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..9fba9eea7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Project PANOPTES + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. From 5380606abf5181900bdbbe1d3ef7a3755fda83e5 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 3 Dec 2017 18:01:41 +1100 Subject: [PATCH 76/79] Merging PACE --- LICENSE | 21 --------------------- README.md | 4 ---- 2 files changed, 25 deletions(-) delete mode 100644 LICENSE delete mode 100644 README.md diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 9fba9eea7..000000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 Project PANOPTES - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 675b1389e..000000000 --- a/README.md +++ /dev/null @@ -1,4 +0,0 @@ -# PACE -Panoptes Arduino Code for Electronics - -> :warning: This repository has been merged with [POCS](https://github.com/panoptes/POCS). No new development will take place here but the repository is left for historical reasons. From 14b421e33f81060e17f50992432bbc86c051c807 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 3 Dec 2017 18:10:08 +1100 Subject: [PATCH 77/79] Removing unused arduino sketches --- .../Profet_2_Current_Sensing.ino | 23 ------------- .../telemetry_board/mount_Current_Sensing.ino | 33 ------------------- 2 files changed, 56 deletions(-) delete mode 100644 resources/arduino_files/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino delete mode 100644 resources/arduino_files/telemetry_board/mount_Current_Sensing.ino diff --git a/resources/arduino_files/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino b/resources/arduino_files/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino deleted file mode 100644 index 6c1b603b8..000000000 --- a/resources/arduino_files/telemetry_board/Profet_2_Current_Sensing/Profet_2_Current_Sensing.ino +++ /dev/null @@ -1,23 +0,0 @@ -int analogValue = A2; -//IS-2 Current sense of PROFET 2 -void setup() { -pinMode(9, OUTPUT); -//DEN_1 DIAGNOSIS enable -pinMode(A2, INPUT); - -pinMode(8, OUTPUT); -//OUT2_0 -Serial.begin(9600); -} - -void loop() { - // put your main code here, to run repeatedly: -digitalWrite(9, HIGH); -digitalWrite(8, HIGH); - -analogValue = analogRead(A2); -float voltage = analogValue * (21/ 1023.0); -//for 8 volts use 35 -Serial.println(voltage); -delay(750); -} diff --git a/resources/arduino_files/telemetry_board/mount_Current_Sensing.ino b/resources/arduino_files/telemetry_board/mount_Current_Sensing.ino deleted file mode 100644 index 870351fc4..000000000 --- a/resources/arduino_files/telemetry_board/mount_Current_Sensing.ino +++ /dev/null @@ -1,33 +0,0 @@ -const int numReadings = 30; // sample size of readings -int readings[numReadings]; // the readings from the analog input -int readIndex = 0; // the index of the current reading -int total = 0; // the running total -int average = 0; // the average -int analogValue = A2; //IS-2 Current sense of PROFET 2 - -void setup() { -pinMode(9, OUTPUT); //DEN_1 DIAGNOSIS enable -pinMode(A2, INPUT); //IS-2 Current sense of PROFET 2 -pinMode(8, OUTPUT); //OUT2_0 -Serial.begin(9600); - for (int thisReading = 0; thisReading < numReadings; thisReading++) { - readings[thisReading] = 0; // initialize all the readings to 0: - } -} - -void loop() { -digitalWrite(9, HIGH); //DEN_1 DIAGNOSIS enable -digitalWrite(8, HIGH); //OUT2_0 -float voltage = analogRead(analogValue); //IS-2 Current sense of PROFET 2 -total = total - readings[readIndex]; // subtract the last reading: -readings[readIndex] = voltage; // read from the sensor: -total = total + readings[readIndex]; // add the reading to the total: -readIndex = readIndex + 1; // advance to the next position in the array: - if (readIndex >= numReadings) { // if we're at the end of the array... - readIndex = 0; // ...wrap around to the beginning: - } - float average = total / numReadings; // calculate the average: - Serial.println(average * (17/ 1023.0)); // send it to the computer as ASCII digits - //(17/ 1023.0) converts the readings from 12 volts to current - delay(100); // delay in between reads for stability -} From 58b0fc65e72e3f183064d00a32c5114547904f23 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Sun, 3 Dec 2017 20:49:31 +1100 Subject: [PATCH 78/79] Adding changelog entry --- Changelog.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Changelog.md b/Changelog.md index db3772138..1c6c4dd6b 100644 --- a/Changelog.md +++ b/Changelog.md @@ -1,4 +1,6 @@ ## [Unreleased] +### Added +- Merge PACE into POCS ## [0.5.1] - 2017-12-02 ### Added From 6b3929e7ee913330758d4d7f2863ac66823d4e75 Mon Sep 17 00:00:00 2001 From: Wilfred Tyler Gee Date: Mon, 4 Dec 2017 11:39:52 +1100 Subject: [PATCH 79/79] Version number updates (#166) * Change terminology to match semantic versioning * Don't hard-code version number in test (closes #154) --- pocs/tests/test_observatory.py | 3 ++- pocs/version.py | 5 ++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/pocs/tests/test_observatory.py b/pocs/tests/test_observatory.py index 5798426e5..bd3c10257 100644 --- a/pocs/tests/test_observatory.py +++ b/pocs/tests/test_observatory.py @@ -8,6 +8,7 @@ from pocs.scheduler.dispatch import Scheduler from pocs.scheduler.observation import Observation from pocs.utils import error +from pocs.version import version has_camera = pytest.mark.skipif( not pytest.config.getoption("--camera"), @@ -168,7 +169,7 @@ def test_standard_headers(observatory): test_headers = { 'airmass': 1.091778, - 'creator': 'POCSv0.5.1', + 'creator': 'POCSv{}'.format(version), 'elevation': 3400.0, 'ha_mnt': 1.6844671878927793, 'latitude': 19.54, diff --git a/pocs/version.py b/pocs/version.py index 940779fc9..63c170546 100644 --- a/pocs/version.py +++ b/pocs/version.py @@ -1,6 +1,5 @@ -# this file was automatically generated major = 0 minor = 5 -release = 1 +patch = 1 -version = '{}.{}.{}'.format(major, minor, release) +version = '{}.{}.{}'.format(major, minor, patch)