Sketch used from SparkFun Repo

Sketch used from SparkFun Repo

Link found for repo: https://www.sparkfun.com/products/12081

Link for repo:
https://github.com/sparkfun/Weather_Shield/blob/master/firmware/Weather_Shield/Weather_Shield.ino

--- FinalProject/FinalProjectSketch/FinalProjectSketch.ino
+++ FinalProject/FinalProjectSketch/FinalProjectSketch.ino
@@ -1,51 +1,432 @@
-
-#include "SparkFunHTU21D.h" //Humidity sensor library
-#include "SparkFunMPL3115A2.h" //Pressure sensor library
-
-
-HTU21D myHumidity;
-MPL3115A2 myPressure;
-
-float humidity;
-float pressure;
-
-void setup() {
-  // put your setup code here, to run once:
-
-
-  //Initiate humidity sensor
+/*
+ Weather Shield Example
+ By: Nathan Seidle
+ SparkFun Electronics
+ Date: November 16th, 2013
+ License: This code is public domain but you buy me a beer if you use this and we meet someday (Beerware license).
+
+ Much of this is based on Mike Grusin's USB Weather Board code: https://www.sparkfun.com/products/10586
+
+ This code reads all the various sensors (wind speed, direction, rain gauge, humidty, pressure, light, batt_lvl)
+ and reports it over the serial comm port. This can be easily routed to an datalogger (such as OpenLog) or
+ a wireless transmitter (such as Electric Imp).
+
+ Measurements are reported once a second but windspeed and rain gauge are tied to interrupts that are
+ calcualted at each report.
+
+ This example code assumes the GPS module is not used.
+
+ */
+
+#include <Wire.h> //I2C needed for sensors
+#include "SparkFunMPL3115A2.h" //Pressure sensor
+#include "SparkFunHTU21D.h" //Humidity sensor
+
+MPL3115A2 myPressure; //Create an instance of the pressure sensor
+HTU21D myHumidity; //Create an instance of the humidity sensor
+
+//Hardware pin definitions
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+// digital I/O pins
+const byte WSPEED = 3;
+const byte RAIN = 2;
+const byte STAT1 = 7;
+const byte STAT2 = 8;
+
+// analog I/O pins
+const byte REFERENCE_3V3 = A3;
+const byte LIGHT = A1;
+const byte BATT = A2;
+const byte WDIR = A0;
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+//Global Variables
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+long lastSecond; //The millis counter to see when a second rolls by
+byte seconds; //When it hits 60, increase the current minute
+byte seconds_2m; //Keeps track of the "wind speed/dir avg" over last 2 minutes array of data
+byte minutes; //Keeps track of where we are in various arrays of data
+byte minutes_10m; //Keeps track of where we are in wind gust/dir over last 10 minutes array of data
+
+long lastWindCheck = 0;
+volatile long lastWindIRQ = 0;
+volatile byte windClicks = 0;
+
+//We need to keep track of the following variables:
+//Wind speed/dir each update (no storage)
+//Wind gust/dir over the day (no storage)
+//Wind speed/dir, avg over 2 minutes (store 1 per second)
+//Wind gust/dir over last 10 minutes (store 1 per minute)
+//Rain over the past hour (store 1 per minute)
+//Total rain over date (store one per day)
+
+byte windspdavg[120]; //120 bytes to keep track of 2 minute average
+
+#define WIND_DIR_AVG_SIZE 120
+int winddiravg[WIND_DIR_AVG_SIZE]; //120 ints to keep track of 2 minute average
+float windgust_10m[10]; //10 floats to keep track of 10 minute max
+int windgustdirection_10m[10]; //10 ints to keep track of 10 minute max
+volatile float rainHour[60]; //60 floating numbers to keep track of 60 minutes of rain
+
+//These are all the weather values that wunderground expects:
+int winddir = 0; // [0-360 instantaneous wind direction]
+float windspeedmph = 0; // [mph instantaneous wind speed]
+float windgustmph = 0; // [mph current wind gust, using software specific time period]
+int windgustdir = 0; // [0-360 using software specific time period]
+float windspdmph_avg2m = 0; // [mph 2 minute average wind speed mph]
+int winddir_avg2m = 0; // [0-360 2 minute average wind direction]
+float windgustmph_10m = 0; // [mph past 10 minutes wind gust mph ]
+int windgustdir_10m = 0; // [0-360 past 10 minutes wind gust direction]
+float humidity = 0; // [%]
+float tempf = 0; // [temperature F]
+float rainin = 0; // [rain inches over the past hour)] -- the accumulated rainfall in the past 60 min
+volatile float dailyrainin = 0; // [rain inches so far today in local time]
+//float baromin = 30.03;// [barom in] - It's hard to calculate baromin locally, do this in the agent
+float pressure = 0;
+//float dewptf; // [dewpoint F] - It's hard to calculate dewpoint locally, do this in the agent
+
+float batt_lvl = 11.8; //[analog value from 0 to 1023]
+float light_lvl = 455; //[analog value from 0 to 1023]
+
+// volatiles are subject to modification by IRQs
+volatile unsigned long raintime, rainlast, raininterval, rain;
+
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+//Interrupt routines (these are called by the hardware interrupts, not by the main code)
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+void rainIRQ()
+// Count rain gauge bucket tips as they occur
+// Activated by the magnet and reed switch in the rain gauge, attached to input D2
+{
+  raintime = millis(); // grab current time
+  raininterval = raintime - rainlast; // calculate interval between this and last event
+
+  if (raininterval > 10) // ignore switch-bounce glitches less than 10mS after initial edge
+  {
+    dailyrainin += 0.011; //Each dump is 0.011" of water
+    rainHour[minutes] += 0.011; //Increase this minute's amount of rain
+
+    rainlast = raintime; // set up for next event
+  }
+}
+
+void wspeedIRQ()
+// Activated by the magnet in the anemometer (2 ticks per rotation), attached to input D3
+{
+  if (millis() - lastWindIRQ > 10) // Ignore switch-bounce glitches less than 10ms (142MPH max reading) after the reed switch closes
+  {
+    lastWindIRQ = millis(); //Grab the current time
+    windClicks++; //There is 1.492MPH for each click per second.
+  }
+}
+
+
+void setup()
+{
+  Serial.begin(9600);
+  Serial.println("Weather Shield Example");
+
+  pinMode(STAT1, OUTPUT); //Status LED Blue
+  pinMode(STAT2, OUTPUT); //Status LED Green
+
+  pinMode(WSPEED, INPUT_PULLUP); // input from wind meters windspeed sensor
+  pinMode(RAIN, INPUT_PULLUP); // input from wind meters rain gauge sensor
+
+  pinMode(REFERENCE_3V3, INPUT);
+  pinMode(LIGHT, INPUT);
+
+  //Configure the pressure sensor
+  myPressure.begin(); // Get sensor online
+  myPressure.setModeBarometer(); // Measure pressure in Pascals from 20 to 110 kPa
+  myPressure.setOversampleRate(7); // Set Oversample to the recommended 128
+  myPressure.enableEventFlags(); // Enable all three pressure and temp event flags
+
+  //Configure the humidity sensor
   myHumidity.begin();
-
-  //Initiate pressure sensor
-  myPressure.begin();
-  myPressure.setModeBarometer();
-  myPressure.setOversampleRate(128);
-  myPressure.enableEventFlags();
-  myPressure.setModeActive();
-
-
-
-
-}
-
-void loop() {
-  // put your main code here, to run repeatedly:
-
-  getWeatherFromSensors();
-  sendWeatherToImp();
-}
-
-void getWeatherFromSensors() {
-
-  //Humidity
+
+  seconds = 0;
+  lastSecond = millis();
+
+  // attach external interrupt pins to IRQ functions
+  attachInterrupt(0, rainIRQ, FALLING);
+  attachInterrupt(1, wspeedIRQ, FALLING);
+
+  // turn on interrupts
+  interrupts();
+
+  Serial.println("Weather Shield online!");
+
+}
+
+void loop()
+{
+  //Keep track of which minute it is
+  if(millis() - lastSecond >= 1000)
+  {
+    digitalWrite(STAT1, HIGH); //Blink stat LED
+
+    lastSecond += 1000;
+
+    //Take a speed and direction reading every second for 2 minute average
+    if(++seconds_2m > 119) seconds_2m = 0;
+
+    //Calc the wind speed and direction every second for 120 second to get 2 minute average
+    float currentSpeed = windspeedmph;
+    //float currentSpeed = random(5); //For testing
+    int currentDirection = get_wind_direction();
+    windspdavg[seconds_2m] = (int)currentSpeed;
+    winddiravg[seconds_2m] = currentDirection;
+    //if(seconds_2m % 10 == 0) displayArrays(); //For testing
+
+    //Check to see if this is a gust for the minute
+    if(currentSpeed > windgust_10m[minutes_10m])
+    {
+      windgust_10m[minutes_10m] = currentSpeed;
+      windgustdirection_10m[minutes_10m] = currentDirection;
+    }
+
+    //Check to see if this is a gust for the day
+    if(currentSpeed > windgustmph)
+    {
+      windgustmph = currentSpeed;
+      windgustdir = currentDirection;
+    }
+
+    if(++seconds > 59)
+    {
+      seconds = 0;
+
+      if(++minutes > 59) minutes = 0;
+      if(++minutes_10m > 9) minutes_10m = 0;
+
+      rainHour[minutes] = 0; //Zero out this minute's rainfall amount
+      windgust_10m[minutes_10m] = 0; //Zero out this minute's gust
+    }
+
+    //Report all readings every second
+    printWeather();
+
+    digitalWrite(STAT1, LOW); //Turn off stat LED
+  }
+
+  delay(100);
+}
+
+//Calculates each of the variables that wunderground is expecting
+void calcWeather()
+{
+  //Calc winddir
+  winddir = get_wind_direction();
+
+  //Calc windspeed
+  windspeedmph = get_wind_speed();
+
+  //Calc windgustmph
+  //Calc windgustdir
+  //These are calculated in the main loop
+
+  //Calc windspdmph_avg2m
+  float temp = 0;
+  for(int i = 0 ; i < 120 ; i++)
+    temp += windspdavg[i];
+  temp /= 120.0;
+  windspdmph_avg2m = temp;
+
+  //Calc winddir_avg2m, Wind Direction
+  //You can't just take the average. Google "mean of circular quantities" for more info
+  //We will use the Mitsuta method because it doesn't require trig functions
+  //And because it sounds cool.
+  //Based on: http://abelian.org/vlf/bearings.html
+  //Based on: http://stackoverflow.com/questions/1813483/averaging-angles-again
+  long sum = winddiravg[0];
+  int D = winddiravg[0];
+  for(int i = 1 ; i < WIND_DIR_AVG_SIZE ; i++)
+  {
+    int delta = winddiravg[i] - D;
+
+    if(delta < -180)
+      D += delta + 360;
+    else if(delta > 180)
+      D += delta - 360;
+    else
+      D += delta;
+
+    sum += D;
+  }
+  winddir_avg2m = sum / WIND_DIR_AVG_SIZE;
+  if(winddir_avg2m >= 360) winddir_avg2m -= 360;
+  if(winddir_avg2m < 0) winddir_avg2m += 360;
+
+  //Calc windgustmph_10m
+  //Calc windgustdir_10m
+  //Find the largest windgust in the last 10 minutes
+  windgustmph_10m = 0;
+  windgustdir_10m = 0;
+  //Step through the 10 minutes
+  for(int i = 0; i < 10 ; i++)
+  {
+    if(windgust_10m[i] > windgustmph_10m)
+    {
+      windgustmph_10m = windgust_10m[i];
+      windgustdir_10m = windgustdirection_10m[i];
+    }
+  }
+
+  //Calc humidity
   humidity = myHumidity.readHumidity();
-
-  //Pressure
+  //float temp_h = myHumidity.readTemperature();
+  //Serial.print(" TempH:");
+  //Serial.print(temp_h, 2);
+
+  //Calc tempf from pressure sensor
+  tempf = myPressure.readTempF();
+  //Serial.print(" TempP:");
+  //Serial.print(tempf, 2);
+
+  //Total rainfall for the day is calculated within the interrupt
+  //Calculate amount of rainfall for the last 60 minutes
+  rainin = 0;
+  for(int i = 0 ; i < 60 ; i++)
+    rainin += rainHour[i];
+
+  //Calc pressure
   pressure = myPressure.readPressure();
-
-}
-
-void sendWeatherToImp() {
-
-}
-
+
+  //Calc dewptf
+
+  //Calc light level
+  light_lvl = get_light_level();
+
+  //Calc battery level
+  batt_lvl = get_battery_level();
+}
+
+//Returns the voltage of the light sensor based on the 3.3V rail
+//This allows us to ignore what VCC might be (an Arduino plugged into USB has VCC of 4.5 to 5.2V)
+float get_light_level()
+{
+  float operatingVoltage = analogRead(REFERENCE_3V3);
+
+  float lightSensor = analogRead(LIGHT);
+
+  operatingVoltage = 3.3 / operatingVoltage; //The reference voltage is 3.3V
+
+  lightSensor = operatingVoltage * lightSensor;
+
+  return(lightSensor);
+}
+
+//Returns the voltage of the raw pin based on the 3.3V rail
+//This allows us to ignore what VCC might be (an Arduino plugged into USB has VCC of 4.5 to 5.2V)
+//Battery level is connected to the RAW pin on Arduino and is fed through two 5% resistors:
+//3.9K on the high side (R1), and 1K on the low side (R2)
+float get_battery_level()
+{
+  float operatingVoltage = analogRead(REFERENCE_3V3);
+
+  float rawVoltage = analogRead(BATT);
+
+  operatingVoltage = 3.30 / operatingVoltage; //The reference voltage is 3.3V
+
+  rawVoltage = operatingVoltage * rawVoltage; //Convert the 0 to 1023 int to actual voltage on BATT pin
+
+  rawVoltage *= 4.90; //(3.9k+1k)/1k - multiple BATT voltage by the voltage divider to get actual system voltage
+
+  return(rawVoltage);
+}
+
+//Returns the instataneous wind speed
+float get_wind_speed()
+{
+  float deltaTime = millis() - lastWindCheck; //750ms
+
+  deltaTime /= 1000.0; //Covert to seconds
+
+  float windSpeed = (float)windClicks / deltaTime; //3 / 0.750s = 4
+
+  windClicks = 0; //Reset and start watching for new wind
+  lastWindCheck = millis();
+
+  windSpeed *= 1.492; //4 * 1.492 = 5.968MPH
+
+  /* Serial.println();
+   Serial.print("Windspeed:");
+   Serial.println(windSpeed);*/
+
+  return(windSpeed);
+}
+
+//Read the wind direction sensor, return heading in degrees
+int get_wind_direction()
+{
+  unsigned int adc;
+
+  adc = analogRead(WDIR); // get the current reading from the sensor
+
+  // The following table is ADC readings for the wind direction sensor output, sorted from low to high.
+  // Each threshold is the midpoint between adjacent headings. The output is degrees for that ADC reading.
+  // Note that these are not in compass degree order! See Weather Meters datasheet for more information.
+
+  if (adc < 380) return (113);
+  if (adc < 393) return (68);
+  if (adc < 414) return (90);
+  if (adc < 456) return (158);
+  if (adc < 508) return (135);
+  if (adc < 551) return (203);
+  if (adc < 615) return (180);
+  if (adc < 680) return (23);
+  if (adc < 746) return (45);
+  if (adc < 801) return (248);
+  if (adc < 833) return (225);
+  if (adc < 878) return (338);
+  if (adc < 913) return (0);
+  if (adc < 940) return (293);
+  if (adc < 967) return (315);
+  if (adc < 990) return (270);
+  return (-1); // error, disconnected?
+}
+
+
+//Prints the various variables directly to the port
+//I don't like the way this function is written but Arduino doesn't support floats under sprintf
+void printWeather()
+{
+  calcWeather(); //Go calc all the various sensors
+
+  Serial.println();
+  Serial.print("$,winddir=");
+  Serial.print(winddir);
+  Serial.print(",windspeedmph=");
+  Serial.print(windspeedmph, 1);
+  Serial.print(",windgustmph=");
+  Serial.print(windgustmph, 1);
+  Serial.print(",windgustdir=");
+  Serial.print(windgustdir);
+  Serial.print(",windspdmph_avg2m=");
+  Serial.print(windspdmph_avg2m, 1);
+  Serial.print(",winddir_avg2m=");
+  Serial.print(winddir_avg2m);
+  Serial.print(",windgustmph_10m=");
+  Serial.print(windgustmph_10m, 1);
+  Serial.print(",windgustdir_10m=");
+  Serial.print(windgustdir_10m);
+  Serial.print(",humidity=");
+  Serial.print(humidity, 1);
+  Serial.print(",tempf=");
+  Serial.print(tempf, 1);
+  Serial.print(",rainin=");
+  Serial.print(rainin, 2);
+  Serial.print(",dailyrainin=");
+  Serial.print(dailyrainin, 2);
+  Serial.print(",pressure=");
+  Serial.print(pressure, 2);
+  Serial.print(",batt_lvl=");
+  Serial.print(batt_lvl, 2);
+  Serial.print(",light_lvl=");
+  Serial.print(light_lvl, 2);
+  Serial.print(",");
+  Serial.println("#");
+
+}
+


[FretBoard] tweaking the build-in-progress indicator


Removed the outdated example

Removed the outdated example

--- IDCF_MQTT_Publisher/IDCF_MQTT_Publisher.ino
+++ IDCF_MQTT_Publisher/IDCF_MQTT_Publisher.ino
@@ -1,164 +0,0 @@
-/*
- * References
- *
- * mqtt_auth by Ian Tester (originally by Nicholas O'Leary)
- * https://github.com/Imroy/pubsubclient/blob/master/examples/mqtt_auth/mqtt_auth.ino
- *
- * bme280_test by Embedded Adventures
- * https://github.com/embeddedadventures/BME280/blob/master/examples/bme280_test/bme280_test.ino
- */
-
-#include <Wire.h>
-
-#include <ESP8266WiFi.h>
-
-// MQTTを扱うためのライブラリ
-// https://github.com/Imroy/pubsubclient
-#include <PubSubClient.h>
-
-// BME280を扱うためのライブラリ
-// https://github.com/embeddedadventures/BME280
-#include <BME280_MOD-1022.h>
-
-#include "config.h"
-
-WiFiClient wclient;
-
-// MQTTクライアント
-PubSubClient client(wclient, server);
-
-// 温度と湿度、気圧を格納する変数
-float temperature = 0.0;
-float humidity = 0.0;
-float pressure = 0.0;
-
-// コールバック関数
-void callback(const MQTT::Publish& pub) {
-  // コールバックで必要な処理があればここで
-}
-
-// JSONフォーマットでペイロードを用意
-String getPayloadInJson() {
-  String json = "{";
-  json +=  "\"devices\":";
-  json += "[\"";
-  json += action_1_uuid;
-  json += "\"";
-  json += ",";
-  json += "\"";
-  json += action_2_uuid;
-  json += "\"";
-  json += "],";
-  json += "\"payload\":";
-  json += "{";
-  json += "\"pressure\":\"";
-  json += pressure;
-  json += "\",";
-  json += "\"humidity\":\"";
-  json += humidity;
-  json += "\",";
-  json += "\"temperature\":\"";
-  json += temperature;
-  json += "\"}";
-  json += "}";
-
-  return json;
-}
-
-// 浮動小数点数を小数点以下2桁でシリアルにプリント
-void printFormattedFloat(float val) {
-  char buffer[10];
-
-  dtostrf(val, 4, 2, buffer);
-  Serial.print(buffer);
-}
-
-void setup() {
-  // I2Cの通信を開始
-  // SDA: DIO4
-  // SCL: DIO14
-  Wire.begin(4, 14);
-
-  // シリアル通信を開始
-  Serial.begin(115200);
-
-  // BME280の補償値を読み取る
-  BME280.readCompensationParams();
-
-  // オーバーサンプリングの回数を設定
-  BME280.writeOversamplingTemperature(os1x);
-  BME280.writeOversamplingHumidity(os1x);
-  BME280.writeOversamplingPressure(os1x);
-}
-
-void loop() {
-  // Wi-Fiアクセスポイントに接続していなければ接続
-  if (WiFi.status() != WL_CONNECTED) {
-    Serial.print("Connecting to ");
-    Serial.print(ssid);
-    Serial.println("...");
-    WiFi.begin(ssid, pass);
-
-    if (WiFi.waitForConnectResult() != WL_CONNECTED) {
-      Serial.println("Failed");
-      return;
-    } else {
-      Serial.println("WiFi connected");
-    }
-  }
-
-  // クライアントがICDF Cloudのサーバに接続されていなければ接続
-  if (!client.connected()) {
-    // トリガー1のUUIDとトークンで認証
-    MQTT::Connect mqttConnect(mqtt_client_id);
-    mqttConnect.set_auth(trigger_1_uuid, trigger_1_token);
-
-    if (client.connect(mqttConnect)) {
-      client.set_callback(callback);
-      Serial.println("Client connected");
-    } else {
-      Serial.println("Client failed to connect");
-    }
-  }
-
-  // クライアントがICDF Cloudのサーバに接続されていたら以下の処理を実行
-  if (client.connected()) {
-    // BME280を1度だけ測定を行うモードに設定し計測が終わるまで待機
-    BME280.writeMode(smForced);
-    while (BME280.isMeasuring()) {
-      delay(1);
-    }
-
-    // BME280から測定値を読み取る
-    BME280.readMeasurements();
-
-    // 温度と湿度、気圧を取得
-    temperature = BME280.getTemperature();
-    humidity = BME280.getHumidity();
-    pressure = BME280.getPressure();
-
-    // 温度と湿度、気圧をシリアルにプリント
-    Serial.print("Temperature: ");
-    printFormattedFloat(temperature);
-    Serial.println("ºC");
-    Serial.print("Humidity   : ");
-    printFormattedFloat(humidity);
-    Serial.println("%");
-    Serial.print("Pressure   : ");
-    printFormattedFloat(pressure);
-    Serial.println("hPa");
-
-    // IDCF CloudにMQTTでデータを送信
-    bool sent = client.publish("message", getPayloadInJson());
-    if (sent) {
-      Serial.println("Sent");
-    } else {
-      Serial.println("Failed to send");
-    }
-
-    Serial.println();
-  }
-
-  delay(10000);
-}
-


Made ConfigBits more universal

Made ConfigBits more universal

--- examples/ConfigBits/ConfigBits.ino
+++ examples/ConfigBits/ConfigBits.ino
@@ -3,11 +3,6 @@
 #include "ConfigBits.h"

 ANSI ansi(Serial);
-
-uint32_t *config0addr = (uint32_t *)0xBFC02FFC;
-uint32_t *config1addr = (uint32_t *)0xBFC02FF8;
-uint32_t *config2addr = (uint32_t *)0xBFC02FF4;
-uint32_t *config3addr = (uint32_t *)0xBFC02FF0;

 struct conf0 config0;
 struct conf1 config1;
@@ -15,18 +10,18 @@
 struct conf3 config3;

 bool confirm() {
-	Serial.print("Are you sure? (y/N): ");
-	while (!Serial.available());
-	char c = Serial.read();
-	if (c >= 'a' && c <= 'z') {
-		c -= 0x20;
-	}
-	if (c == 'Y') {
-		Serial.println("Yes");
-		return true;
-	}
-	Serial.println("No");
-	return false;
+    Serial.print("Are you sure? (y/N): ");
+    while (!Serial.available());
+    char c = Serial.read();
+    if (c >= 'a' && c <= 'z') {
+        c -= 0x20;
+    }
+    if (c == 'Y') {
+        Serial.println("Yes");
+        return true;
+    }
+    Serial.println("No");
+    return false;
 }

 void reboot() {
@@ -47,670 +42,671 @@
 }

 void loadSettings() {
-	config0.raw = *config0addr;
-	config1.raw = *config1addr;
-	config2.raw = *config2addr;
-	config3.raw = *config3addr;
+    config0.raw = DEVCFG0;
+    config1.raw = DEVCFG1;
+    config2.raw = DEVCFG2;
+    config3.raw = DEVCFG3;
 }

 void saveSettings() {
-	Flash.loadPage(config3addr);
-	Flash.writePageWord(config0addr, config0.raw);
-	Flash.writePageWord(config1addr, config1.raw);
-	Flash.writePageWord(config2addr, config2.raw);
-	Flash.writePageWord(config3addr, config3.raw);
-	Flash.savePage();
+    Flash.loadPage((void *)&DEVCFG3);
+    Flash.writePageWord((void *)&DEVCFG0, config0.raw);
+    Flash.writePageWord((void *)&DEVCFG1, config1.raw);
+    Flash.writePageWord((void *)&DEVCFG2, config2.raw);
+    Flash.writePageWord((void *)&DEVCFG3, config3.raw);
+    Flash.savePage();
 }

 const char *ws_ps[32] = {
-	"1ms", "2ms", "4ms", "8ms", "16ms", "32ms", "64ms", "128ms", "256ms", "512ms", "1.024s",
-	"2.048s", "4.096s", "8.192s", "16.384s", "32.768s", "65.536s", "131.072s", "262.144s", "524.288s", "1048.576s", "X", "X", "X", "X",
-	"X", "X", "X", "X", "X", "X", "X"
+    "1ms", "2ms", "4ms", "8ms", "16ms", "32ms", "64ms", "128ms", "256ms", "512ms", "1.024s",
+    "2.048s", "4.096s", "8.192s", "16.384s", "32.768s", "65.536s", "131.072s", "262.144s", "524.288s", "1048.576s", "X", "X", "X", "X",
+    "X", "X", "X", "X", "X", "X", "X"
 };

 void setup() {
-	loadSettings();
-	Serial.begin(115200);
+    loadSettings();
+    Serial.begin(115200);
 }

 void loop() {
-	ansi.cls();
-	ansi.setCursor(0, 0);
-	heading("Main Menu");
-	Serial.println();
-	Serial.println(" D) Debugger");
-	Serial.println(" W) Watchdog");
-	Serial.println(" U) USB");
-	Serial.println(" O) Oscillator");
-	Serial.println(" P) Peripherals");
-	Serial.println();
-	Serial.println(" L) Load settings");
-	Serial.println(" S) Save settings");
-	Serial.println(" R) Reboot");
-	Serial.println();
-	Serial.print("Select an entry: ");
-	char c = getch();
-	switch(c) {
-		case 'L':
-			if (confirm()) {
-				loadSettings();
-				Serial.println("Loaded.");
-			}
-			break;
-		case 'S':
-			if (confirm()) {
-				saveSettings();
-				Serial.println("Saved.");
-			}
-			break;
-		case 'R':
-			if (confirm()) {
-				Serial.println("Rebooting...");
-				Serial.flush();
-				reboot();
-			}
-			break;
-
-		case 'D':
-			debugger();
-			break;
-		case 'W':
-			watchdog();
-			break;
-		case 'U':
-			usb();
-			break;
-		case 'O':
-			oscillator();
-			break;
-		case 'P':
-			peripherals();
-			break;
-	}
+    ansi.cls();
+    ansi.setCursor(0, 0);
+    heading("Main Menu");
+    Serial.println();
+    Serial.println(" D) Debugger");
+    Serial.println(" W) Watchdog");
+    Serial.println(" U) USB");
+    Serial.println(" O) Oscillator");
+    Serial.println(" P) Peripherals");
+    Serial.println();
+    Serial.println(" L) Load settings");
+    Serial.println(" S) Save settings");
+    Serial.println(" R) Reboot");
+    Serial.println();
+    Serial.print("Select an entry: ");
+    char c = getch();
+    switch(c) {
+        case 'L':
+            if (confirm()) {
+                loadSettings();
+                Serial.println("Loaded.");
+            }
+            break;
+        case 'S':
+            if (confirm()) {
+                saveSettings();
+                Serial.println("Saved.");
+            }
+            break;
+        case 'R':
+            if (confirm()) {
+                Serial.println("Rebooting...");
+                Serial.flush();
+                reboot();
+            }
+            break;
+
+        case 'D':
+            debugger();
+            break;
+        case 'W':
+            watchdog();
+            break;
+        case 'U':
+            usb();
+            break;
+        case 'O':
+            oscillator();
+            break;
+        case 'P':
+            peripherals();
+            break;
+    }
 }

 char getch() {
-	while (!Serial.available());
-	char c = Serial.read();
-	if (c >= 'a' && c <= 'z') {
-		c -= 0x20;
-	}
-	return c;
+    while (!Serial.available());
+    char c = Serial.read();
+    if (c >= 'a' && c <= 'z') {
+        c -= 0x20;
+    }
+    return c;
 }

 void subMenuFooter() {
-	Serial.println();
-	Serial.println(" X) Exit to main menu");
-	Serial.println(" L) Load settings");
-	Serial.println(" S) Save settings");
-	Serial.println(" R) Reboot");
-	Serial.println();
-	Serial.print("Select an entry to change: ");
+    Serial.println();
+    Serial.println(" X) Exit to main menu");
+    Serial.println(" L) Load settings");
+    Serial.println(" S) Save settings");
+    Serial.println(" R) Reboot");
+    Serial.println();
+    Serial.print("Select an entry to change: ");
 }

 void heading(const char *t) {
-	int len = strlen(t);
-	for (int x = 0; x < 40 - len / 2; x++) {
-		Serial.write(' ');
-	}
-	Serial.println(t);
-	for (int x = 0; x < 80; x++) {
-		Serial.write("-");
-	}
-	Serial.println();
+    int len = strlen(t);
+    for (int x = 0; x < 40 - len / 2; x++) {
+        Serial.write(' ');
+    }
+    Serial.println(t);
+    for (int x = 0; x < 80; x++) {
+        Serial.write("-");
+    }
+    Serial.println();
 }

 void debugger() {
-	while (1) {
-		ansi.cls();
-		ansi.setCursor(0, 0);
-		heading("Debugger Settings");
-		Serial.println();
-		Serial.print(" D) Debugger .......................... ");
-		switch (config0.debug) {
-			case 0b11: Serial.println("Disabled"); break;
-			default: Serial.println("Enabled"); break;
-		}
-		Serial.print(" I) ICE Pins .......................... ");
-		Serial.println(config0.icesel ? "PGE2" : "PGE1");
-		subMenuFooter();
-		char c = getch();
-		switch(c) {
-			case 'X':
-				return;
-		case 'L':
-			if (confirm()) {
-				loadSettings();
-				Serial.println("Loaded.");
-			}
-			break;
-		case 'S':
-			if (confirm()) {
-				saveSettings();
-				Serial.println("Saved.");
-			}
-			break;
-		case 'R':
-			if (confirm()) {
-				Serial.println("Rebooting...");
-				Serial.flush();
-				reboot();
-			}
-			break;
-		case 'D':
-			if (config0.debug == 0b11) {
-				config0.debug = 0b10;
-			} else {
-				config0.debug = 0b11;
-			}
-			break;
-		case 'I':
-			config0.icesel = 1-config0.icesel;
-			break;
-		}
-	}
+    while (1) {
+        ansi.cls();
+        ansi.setCursor(0, 0);
+        heading("Debugger Settings");
+        Serial.println();
+        Serial.print(" D) Debugger .......................... ");
+        switch (config0.debug) {
+            case 0b11: Serial.println("Disabled"); break;
+            default: Serial.println("Enabled"); break;
+        }
+        Serial.print(" I) ICE Pins .......................... ");
+        Serial.println(config0.icesel ? "PGE2" : "PGE1");
+        subMenuFooter();
+        char c = getch();
+        switch(c) {
+            case 'X':
+                return;
+        case 'L':
+            if (confirm()) {
+                loadSettings();
+                Serial.println("Loaded.");
+            }
+            break;
+        case 'S':
+            if (confirm()) {
+                saveSettings();
+                Serial.println("Saved.");
+            }
+            break;
+        case 'R':
+            if (confirm()) {
+                Serial.println("Rebooting...");
+                Serial.flush();
+                reboot();
+            }
+            break;
+        case 'D':
+            if (config0.debug == 0b11) {
+                config0.debug = 0b10;
+            } else {
+                config0.debug = 0b11;
+            }
+            break;
+        case 'I':
+            config0.icesel = 1-config0.icesel;
+            break;
+        }
+    }
 }

 void watchdog() {
-	while (1) {
-		ansi.cls();
-		ansi.setCursor(0, 0);
-		heading("Watchdog Settings");
-		Serial.println();
-		Serial.print(" W) Watchdog .......................... ");
-		switch (config1.fwdten) {
-			case 0:
-				Serial.println("Software Controlled");
-				break;
-			case 1:
-				Serial.println("Always Enabled");
-				break;
-		}
-		Serial.print(" T) Timeout ........................... ");
-		if (ws_ps[config1.wdtps][0] == 'X') {
-			config1.wdtps = 0b10100;
-		}
-		Serial.println(ws_ps[config1.wdtps]);
-
-		Serial.print(" C) Clock Switching and Monitoring .... ");
-		switch (config1.fcksm) {
-			case 0:
-				Serial.println("Switch enabled, Monitor enabled");
-				break;
-			case 1:
-				Serial.println("Switch enabled, Monitor disabled");
-				break;
-			case 2:
-				Serial.println("Switch disabled, Monitor disabled");
-				break;
-			case 3:
-				Serial.println("Switch disabled, Monitor disabled");
-				break;
-		}
-
-		subMenuFooter();
-		char c = getch();
-		switch(c) {
-			case 'X':
-				return;
-		case 'L':
-			if (confirm()) {
-				loadSettings();
-				Serial.println("Loaded.");
-			}
-			break;
-		case 'S':
-			if (confirm()) {
-				saveSettings();
-				Serial.println("Saved.");
-			}
-			break;
-		case 'R':
-			if (confirm()) {
-				Serial.println("Rebooting...");
-				Serial.flush();
-				reboot();
-			}
-			break;
-		case 'W':
-			config1.fwdten++;
-			break;
-		case 'T':
-			config1.wdtps++;
-			if (config1.wdtps > 0b10100) {
-				config1.wdtps = 0b00000;
-			}
-			break;
-		case 'C':
-			config1.fcksm++;
-			if (config1.fcksm == 3) {
-				config1.fcksm = 0;
-			}
-			break;
-		}
-	}
+    while (1) {
+        ansi.cls();
+        ansi.setCursor(0, 0);
+        heading("Watchdog Settings");
+        Serial.println();
+        Serial.print(" W) Watchdog .......................... ");
+        switch (config1.fwdten) {
+            case 0:
+                Serial.println("Software Controlled");
+                break;
+            case 1:
+                Serial.println("Always Enabled");
+                break;
+        }
+        Serial.print(" T) Timeout ........................... ");
+        if (ws_ps[config1.wdtps][0] == 'X') {
+            config1.wdtps = 0b10100;
+        }
+        Serial.println(ws_ps[config1.wdtps]);
+
+        Serial.print(" C) Clock Switching and Monitoring .... ");
+        switch (config1.fcksm) {
+            case 0:
+                Serial.println("Switch enabled, Monitor enabled");
+                break;
+            case 1:
+                Serial.println("Switch enabled, Monitor disabled");
+                break;
+            case 2:
+                Serial.println("Switch disabled, Monitor disabled");
+                break;
+            case 3:
+                Serial.println("Switch disabled, Monitor disabled");
+                break;
+        }
+
+        subMenuFooter();
+        char c = getch();
+        switch(c) {
+            case 'X':
+                return;
+        case 'L':
+            if (confirm()) {
+                loadSettings();
+                Serial.println("Loaded.");
+            }
+            break;
+        case 'S':
+            if (confirm()) {
+                saveSettings();
+                Serial.println("Saved.");
+            }
+            break;
+        case 'R':
+            if (confirm()) {
+                Serial.println("Rebooting...");
+                Serial.flush();
+                reboot();
+            }
+            break;
+        case 'W':
+            config1.fwdten++;
+            break;
+        case 'T':
+            config1.wdtps++;
+            if (config1.wdtps > 0b10100) {
+                config1.wdtps = 0b00000;
+            }
+            break;
+        case 'C':
+            config1.fcksm++;
+            if (config1.fcksm == 3) {
+                config1.fcksm = 0;
+            }
+            break;
+        }
+    }
 }

 void usb() {
-	while (1) {
-		ansi.cls();
-		ansi.setCursor(0, 0);
-		heading("USB Settings");
-		Serial.println();
-		Serial.print(" P) USB PLL ........................... ");
-		Serial.println(config2.upllen ? "Disabled" : "Enabled");
-		Serial.print(" D) PLL Input Divider ................. ");
-		switch (config2.upllidiv) {
-			case 0:
-				Serial.println("/1");
-				break;
-			case 1:
-				Serial.println("/2");
-				break;
-			case 2:
-				Serial.println("/3");
-				break;
-			case 3:
-				Serial.println("/4");
-				break;
-			case 4:
-				Serial.println("/5");
-				break;
-			case 5:
-				Serial.println("/6");
-				break;
-			case 6:
-				Serial.println("/10");
-				break;
-			case 7:
-				Serial.println("/12");
-				break;
-		}
-
-		Serial.print(" V) VBUSON Pin Control ................ ");
-		Serial.println(config3.fvbusonio ? "Controlled by USB" : "Normal IO Port");
-
-		Serial.print(" I) USBID Pin Control ................. ");
-		Serial.println(config3.fusbidio ? "Controlled by USB" : "Normal IO Port");
-
-		subMenuFooter();
-		char c = getch();
-		switch(c) {
-			case 'X':
-				return;
-		case 'L':
-			if (confirm()) {
-				loadSettings();
-				Serial.println("Loaded.");
-			}
-			break;
-		case 'S':
-			if (confirm()) {
-				saveSettings();
-				Serial.println("Saved.");
-			}
-			break;
-		case 'R':
-			if (confirm()) {
-				Serial.println("Rebooting...");
-				Serial.flush();
-				reboot();
-			}
-			break;
-		case 'P':
-			config2.upllen++;
-			break;
-		case 'D':
-			config2.upllidiv++;
-			break;
-		case 'V':
-			config3.fvbusonio++;
-			break;
-		case 'I':
-			config3.fusbidio++;
-			break;
-		}
-	}
+    while (1) {
+        ansi.cls();
+        ansi.setCursor(0, 0);
+        heading("USB Settings");
+        Serial.println();
+        Serial.print(" P) USB PLL ........................... ");
+        Serial.println(config2.upllen ? "Disabled" : "Enabled");
+        Serial.print(" D) PLL Input Divider ................. ");
+        switch (config2.upllidiv) {
+            case 0:
+                Serial.println("/1");
+                break;
+            case 1:
+                Serial.println("/2");
+                break;
+            case 2:
+                Serial.println("/3");
+                break;
+            case 3:
+                Serial.println("/4");
+                break;
+            case 4:
+                Serial.println("/5");
+                break;
+            case 5:
+                Serial.println("/6");
+                break;
+            case 6:
+                Serial.println("/10");
+                break;
+            case 7:
+                Serial.println("/12");
+                break;
+        }
+
+        Serial.print(" V) VBUSON Pin Control ................ ");
+        Serial.println(config3.fvbusonio ? "Controlled by USB" : "Normal IO Port");
+
+        Serial.print(" I) USBID Pin Control ................. ");
+        Serial.println(config3.fusbidio ? "Controlled by USB" : "Normal IO Port");
+
+        subMenuFooter();
+        char c = getch();
+        switch(c) {
+            case 'X':
+                return;
+        case 'L':
+            if (confirm()) {
+                loadSettings();
+                Serial.println("Loaded.");
+            }
+            break;
+        case 'S':
+            if (confirm()) {
+                saveSettings();
+                Serial.println("Saved.");
+            }
+            break;
+        case 'R':
+            if (confirm()) {
+                Serial.println("Rebooting...");
+                Serial.flush();
+                reboot();
+            }
+            break;
+        case 'P':
+            config2.upllen++;
+            break;
+        case 'D':
+            config2.upllidiv++;
+            break;
+        case 'V':
+            config3.fvbusonio++;
+            break;
+        case 'I':
+            config3.fusbidio++;
+            break;
+        }
+    }
 }

 void oscillator() {
-	while (1) {
-		ansi.cls();
-		ansi.setCursor(0, 0);
-		heading("Oscillator Settings");
-		Serial.println();
-		Serial.print(" O) Oscillator ........................ ");
-
-		switch (config1.fnosc) {
-			case 0:
-				Serial.println("Fast RC");
-				break;
-			case 1:
-				Serial.println("Fast RC with Div-N and PLL");
-				break;
-			case 2:
-				Serial.println("Primary");
-				break;
-			case 3:
-				Serial.println("Primary with PLL");
-				break;
-			case 4:
-				Serial.println("Secondary");
-				break;
-			case 5:
-				Serial.println("Low-Power RC");
-				break;
-			case 6:
-				Serial.println("Fast RC with Div-16");
-				break;
-			case 7:
-				Serial.println("Fast RC with Div-N");
-				break;
-		}
-		Serial.print(" 1) Primary Oscillator Mode ........... ");
-		switch (config1.poscmod) {
-			case 0:
-				Serial.println("External");
-				break;
-			case 1:
-				Serial.println("XT");
-				break;
-			case 2:
-				Serial.println("HS");
-				break;
-			case 3:
-				Serial.println("Disabled");
-				break;
-		}
-		Serial.print(" 2) Secondary Oscillator .............. ");
-		Serial.println(config1.fsoscen ? "Enabled" : "Disabled");
-
-		Serial.print(" I) PLL Input Divider ................. ");
-		switch (config2.fpllidiv) {
-			case 0:
-				Serial.println("/1");
-				break;
-			case 1:
-				Serial.println("/2");
-				break;
-			case 2:
-				Serial.println("/3");
-				break;
-			case 3:
-				Serial.println("/4");
-				break;
-			case 4:
-				Serial.println("/5");
-				break;
-			case 5:
-				Serial.println("/6");
-				break;
-			case 6:
-				Serial.println("/10");
-				break;
-			case 7:
-				Serial.println("/12");
-				break;
-		}
-
-		Serial.print(" M) PLL Multiplier .................... ");
-		switch (config2.fpllmul) {
-			case 0:
-				Serial.println("x15");
-				break;
-			case 1:
-				Serial.println("x16");
-				break;
-			case 2:
-				Serial.println("x17");
-				break;
-			case 3:
-				Serial.println("x18");
-				break;
-			case 4:
-				Serial.println("x19");
-				break;
-			case 5:
-				Serial.println("x20");
-				break;
-			case 6:
-				Serial.println("x21");
-				break;
-			case 7:
-				Serial.println("x24");
-				break;
-		}
-
-		Serial.print(" D) PLL Output Divider ................ ");
-		switch (config2.fpllodiv) {
-			case 0:
-				Serial.println("/1");
-				break;
-			case 1:
-				Serial.println("/2");
-				break;
-			case 2:
-				Serial.println("/3");
-				break;
-			case 3:
-				Serial.println("/4");
-				break;
-			case 4:
-				Serial.println("/5");
-				break;
-			case 5:
-				Serial.println("/6");
-				break;
-			case 6:
-				Serial.println("/10");
-				break;
-			case 7:
-				Serial.println("/12");
-				break;
-		}
-
-		Serial.print(" P) Peripheral Bus Divider ............ /");
-		Serial.println(1 << config1.fpbdiv, DEC);
-
-		Serial.print(" C) Clock Output ...................... ");
-		Serial.println(config1.osciofnc ? "Disabled" : "Enabled");
-
-		Serial.print(" T) Two Speed Startup ................. ");
-		Serial.println(config1.ieso ? "Enabled" : "Disabled");
-
-		subMenuFooter();
-		char c = getch();
-		switch(c) {
-			case 'X':
-				return;
-			case 'L':
-				if (confirm()) {
-					loadSettings();
-					Serial.println("Loaded.");
-				}
-				break;
-			case 'S':
-				if (confirm()) {
-					saveSettings();
-					Serial.println("Saved.");
-				}
-				break;
-			case 'R':
-				if (confirm()) {
-					Serial.println("Rebooting...");
-					Serial.flush();
-					reboot();
-				}
-				break;
-			case 'O':
-				config1.fnosc++;
-				break;
-			case '1':
-				config1.poscmod++;
-				break;
-			case '2':
-				config1.fsoscen++;
-				break;
-			case 'I':
-				config2.fpllidiv++;
-				break;
-			case 'M':
-				config2.fpllmul++;
-				break;
-			case 'D':
-				config2.fpllodiv++;
-				break;
-			case 'P':
-				config1.fpbdiv++;
-				break;
-			case 'C':
-				config1.osciofnc++;
-				break;
-			case 'T':
-				config1.ieso++;
-				break;
-		}
-	}
+    while (1) {
+        ansi.cls();
+        ansi.setCursor(0, 0);
+        heading("Oscillator Settings");
+        Serial.println();
+        Serial.print(" O) Oscillator ........................ ");
+
+        switch (config1.fnosc) {
+            case 0:
+                Serial.println("Fast RC");
+                break;
+            case 1:
+                Serial.println("Fast RC with Div-N and PLL");
+                break;
+            case 2:
+                Serial.println("Primary");
+                break;
+            case 3:
+                Serial.println("Primary with PLL");
+                break;
+            case 4:
+                Serial.println("Secondary");
+                break;
+            case 5:
+                Serial.println("Low-Power RC");
+                break;
+            case 6:
+                Serial.println("Fast RC with Div-16");
+                break;
+            case 7:
+                Serial.println("Fast RC with Div-N");
+                break;
+        }
+        Serial.print(" 1) Primary Oscillator Mode ........... ");
+        switch (config1.poscmod) {
+            case 0:
+                Serial.println("External");
+                break;
+            case 1:
+                Serial.println("XT");
+                break;
+            case 2:
+                Serial.println("HS");
+                break;
+            case 3:
+                Serial.println("Disabled");
+                break;
+        }
+        Serial.print(" 2) Secondary Oscillator .............. ");
+        Serial.println(config1.fsoscen ? "Enabled" : "Disabled");
+
+        Serial.print(" I) PLL Input Divider ................. ");
+        switch (config2.fpllidiv) {
+            case 0:
+                Serial.println("/1");
+                break;
+            case 1:
+                Serial.println("/2");
+                break;
+            case 2:
+                Serial.println("/3");
+                break;
+            case 3:
+                Serial.println("/4");
+                break;
+            case 4:
+                Serial.println("/5");
+                break;
+            case 5:
+                Serial.println("/6");
+                break;
+            case 6:
+                Serial.println("/10");
+                break;
+            case 7:
+                Serial.println("/12");
+                break;
+        }
+
+        Serial.print(" M) PLL Multiplier .................... ");
+        switch (config2.fpllmul) {
+            case 0:
+                Serial.println("x15");
+                break;
+            case 1:
+                Serial.println("x16");
+                break;
+            case 2:
+                Serial.println("x17");
+                break;
+            case 3:
+                Serial.println("x18");
+                break;
+            case 4:
+                Serial.println("x19");
+                break;
+            case 5:
+                Serial.println("x20");
+                break;
+            case 6:
+                Serial.println("x21");
+                break;
+            case 7:
+                Serial.println("x24");
+                break;
+        }
+
+        Serial.print(" D) PLL Output Divider ................ ");
+        switch (config2.fpllodiv) {
+            case 0:
+                Serial.println("/1");
+                break;
+            case 1:
+                Serial.println("/2");
+                break;
+            case 2:
+                Serial.println("/3");
+                break;
+            case 3:
+                Serial.println("/4");
+                break;
+            case 4:
+                Serial.println("/5");
+                break;
+            case 5:
+                Serial.println("/6");
+                break;
+            case 6:
+                Serial.println("/10");
+                break;
+            case 7:
+                Serial.println("/12");
+                break;
+        }
+
+        Serial.print(" P) Peripheral Bus Divider ............ /");
+        Serial.println(1 << config1.fpbdiv, DEC);
+
+        Serial.print(" C) Clock Output ...................... ");
+        Serial.println(config1.osciofnc ? "Disabled" : "Enabled");
+
+        Serial.print(" T) Two Speed Startup ................. ");
+        Serial.println(config1.ieso ? "Enabled" : "Disabled");
+
+        subMenuFooter();
+        char c = getch();
+        switch(c) {
+            case 'X':
+                return;
+            case 'L':
+                if (confirm()) {
+                    loadSettings();
+                    Serial.println("Loaded.");
+                }
+                break;
+            case 'S':
+                if (confirm()) {
+                    saveSettings();
+                    Serial.println("Saved.");
+                }
+                break;
+            case 'R':
+                if (confirm()) {
+                    Serial.println("Rebooting...");
+                    Serial.flush();
+                    reboot();
+                }
+                break;
+            case 'O':
+                config1.fnosc++;
+                break;
+            case '1':
+                config1.poscmod++;
+                break;
+            case '2':
+                config1.fsoscen++;
+                break;
+            case 'I':
+                config2.fpllidiv++;
+                break;
+            case 'M':
+                config2.fpllmul++;
+                break;
+            case 'D':
+                config2.fpllodiv++;
+                break;
+            case 'P':
+                config1.fpbdiv++;
+                break;
+            case 'C':
+                config1.osciofnc++;
+                break;
+            case 'T':
+                config1.ieso++;
+                break;
+        }
+    }
 }

 void peripherals() {
-	while (1) {
-		ansi.cls();
-		ansi.setCursor(0, 0);
-		heading("Peripheral Settings");
-		Serial.println();
-
-		Serial.print(" C) CAN I/O Pins ...................... ");
-		Serial.println(config3.fcanio ? "Default" : "Alternate");
-
-		Serial.print(" E) Ethernet I/O Pins ................. ");
-		Serial.println(config3.fethio ? "Default" : "Alternate");
-
-		Serial.print(" M) Ethernet MII ...................... ");
-		Serial.println(config3.fmiien ? "Enabled" : "Disabled");
-
-		Serial.print(" U) User ID ........................... ");
-		char tmp[10];
-		sprintf(tmp, "0x%04X", config3.userid);
-		Serial.println(tmp);
-
-		subMenuFooter();
-		char c = getch();
-		switch(c) {
-			case 'X':
-				return;
-			case 'L':
-				if (confirm()) {
-					loadSettings();
-					Serial.println("Loaded.");
-				}
-				break;
-			case 'S':
-				if (confirm()) {
-					saveSettings();
-					Serial.println("Saved.");
-				}
-				break;
-			case 'R':
-				if (confirm()) {
-					Serial.println("Rebooting...");
-					Serial.flush();
-					reboot();
-				}
-				break;
-			case 'C':
-				config3.fcanio++;
-				break;
-			case 'E':
-				config3.fethio++;
-				break;
-			case 'M':
-				config3.fmiien++;
-				break;
-			case 'U':
-				config3.userid = inputHex(config3.userid);
-				break;
-		}
-	}
+    while (1) {
+        ansi.cls();
+        ansi.setCursor(0, 0);
+        heading("Peripheral Settings");
+        Serial.println();
+
+        Serial.print(" C) CAN I/O Pins ...................... ");
+        Serial.println(config3.fcanio ? "Default" : "Alternate");
+
+        Serial.print(" E) Ethernet I/O Pins ................. ");
+        Serial.println(config3.fethio ? "Default" : "Alternate");
+
+        Serial.print(" M) Ethernet MII ...................... ");
+        Serial.println(config3.fmiien ? "Enabled" : "Disabled");
+
+        Serial.print(" U) User ID ........................... ");
+        char tmp[10];
+        sprintf(tmp, "0x%04X", config3.userid);
+        Serial.println(tmp);
+
+        subMenuFooter();
+        char c = getch();
+        switch(c) {
+            case 'X':
+                return;
+            case 'L':
+                if (confirm()) {
+                    loadSettings();
+                    Serial.println("Loaded.");
+                }
+                break;
+            case 'S':
+                if (confirm()) {
+                    saveSettings();
+                    Serial.println("Saved.");
+                }
+                break;
+            case 'R':
+                if (confirm()) {
+                    Serial.println("Rebooting...");
+                    Serial.flush();
+                    reboot();
+                }
+                break;
+            case 'C':
+                config3.fcanio++;
+                break;
+            case 'E':
+                config3.fethio++;
+                break;
+            case 'M':
+                config3.fmiien++;
+                break;
+            case 'U':
+                config3.userid = inputHex(config3.userid);
+                break;
+        }
+    }
 }

 int inputHex(int val) {
-	uint16_t hexval = val;
-	char tmp[50];
-	Serial.println();
-
-	while (1) {
-		sprintf(tmp, "\rEnter HEX value: 0x%04X", hexval);
-		Serial.print(tmp);
-		char c = getch();
-		switch (c) {
-			case '0':
-				hexval <<= 4;
-				break;
-			case '1':
-				hexval <<= 4;
-				hexval |= 1;
-				break;
-			case '2':
-				hexval <<= 4;
-				hexval |= 2;
-				break;
-			case '3':
-				hexval <<= 4;
-				hexval |= 3;
-				break;
-			case '4':
-				hexval <<= 4;
-				hexval |= 4;
-				break;
-			case '5':
-				hexval <<= 4;
-				hexval |= 5;
-				break;
-			case '6':
-				hexval <<= 4;
-				hexval |= 6;
-				break;
-			case '7':
-				hexval <<= 4;
-				hexval |= 7;
-				break;
-			case '8':
-				hexval <<= 4;
-				hexval |= 8;
-				break;
-			case '9':
-				hexval <<= 4;
-				hexval |= 9;
-				break;
-			case 'A':
-				hexval <<= 4;
-				hexval |= 10;
-				break;
-			case 'B':
-				hexval <<= 4;
-				hexval |= 11;
-				break;
-			case 'C':
-				hexval <<= 4;
-				hexval |= 12;
-				break;
-			case 'D':
-				hexval <<= 4;
-				hexval |= 13;
-				break;
-			case 'E':
-				hexval <<= 4;
-				hexval |= 14;
-				break;
-			case 'F':
-				hexval <<= 4;
-				hexval |= 15;
-				break;
-			case '\n':
-				return hexval;
-			case '\r':
-				return hexval;
-		}
-	}
-}
+    uint16_t hexval = val;
+    char tmp[50];
+    Serial.println();
+
+    while (1) {
+        sprintf(tmp, "\rEnter HEX value: 0x%04X", hexval);
+        Serial.print(tmp);
+        char c = getch();
+        switch (c) {
+            case '0':
+                hexval <<= 4;
+                break;
+            case '1':
+                hexval <<= 4;
+                hexval |= 1;
+                break;
+            case '2':
+                hexval <<= 4;
+                hexval |= 2;
+                break;
+            case '3':
+                hexval <<= 4;
+                hexval |= 3;
+                break;
+            case '4':
+                hexval <<= 4;
+                hexval |= 4;
+                break;
+            case '5':
+                hexval <<= 4;
+                hexval |= 5;
+                break;
+            case '6':
+                hexval <<= 4;
+                hexval |= 6;
+                break;
+            case '7':
+                hexval <<= 4;
+                hexval |= 7;
+                break;
+            case '8':
+                hexval <<= 4;
+                hexval |= 8;
+                break;
+            case '9':
+                hexval <<= 4;
+                hexval |= 9;
+                break;
+            case 'A':
+                hexval <<= 4;
+                hexval |= 10;
+                break;
+            case 'B':
+                hexval <<= 4;
+                hexval |= 11;
+                break;
+            case 'C':
+                hexval <<= 4;
+                hexval |= 12;
+                break;
+            case 'D':
+                hexval <<= 4;
+                hexval |= 13;
+                break;
+            case 'E':
+                hexval <<= 4;
+                hexval |= 14;
+                break;
+            case 'F':
+                hexval <<= 4;
+                hexval |= 15;
+                break;
+            case '\n':
+                return hexval;
+            case '\r':
+                return hexval;
+        }
+    }
+}
+


Adds comment for mains power and battery usage

--- examples/GPRSLinkit/GPRSLinkit.ino
+++ examples/GPRSLinkit/GPRSLinkit.ino
@@ -54,7 +54,9 @@
 void setup()
 {
   Serial.begin(115200);
-  while(!Serial);                                                       //for the linkit, we need to wait until the serial monitor is initialized correclty, if we don't do this, we don't get to see the logging.
+  while(!Serial);                                                       //for the linkit, we need to wait until the serial monitor is initialized correctly, if we don't do this, we don't get to see the logging.
+                                                                        //Warning for battery and mains power usage, comment out the above line, otherwise the setup() will continue to wait for the Serial to become available
+
   Serial.println("starting");
   pinMode(a1, OUTPUT);


fix a_omlink.ino

fix a_omlink.ino

--- arduino/opencr_arduino/opencr/libraries/OpenManipulator/example/Arduino/Link/a_open_manipulator_link/a_open_manipulator_link.ino
+++ arduino/opencr_arduino/opencr/libraries/OpenManipulator/example/Arduino/Link/a_open_manipulator_link/a_open_manipulator_link.ino
@@ -17,7 +17,6 @@
 /* Authors: Hye-Jong KIM */

 #include "OMLink.h"
-#include "RemoteController.h"
 //#include "Processing.h"

 float present_time = 0.0;
@@ -47,7 +46,6 @@
   ac_angle_max.push_back(-90.0*DEG2RAD);

   OM_PROCESSING::initProcessing(12);
-  connectRC100();
   initOMLink();

   ///////////////first move//////////////////////


Update readTag to fetch just the payload from the messages on the tag

--- firmware/examples/readTag/readtag.ino
+++ firmware/examples/readTag/readtag.ino
@@ -19,8 +19,13 @@
         //tag.print();
         if(tag.hasNdefMessage()){
                 NdefMessage tagMessage = tag.getNdefMessage();
-
-        }
+                int i;
+                for (i = 0; i < tagMessage.getRecordCount()   ; i++)  {
+                         //
+                         NdefRecord tagRecord = tagMessage.getRecord(i);
+                         tagRecord.print();
+
+                }
         }
     }
     delay(5000);


Update uint8 to uint16 so that we don't overflow on the for loop. Access the PROGMEM using the memcpy rather than direct access

--- projects/arduino/led_matrix_256/led_matrix_256.ino
+++ projects/arduino/led_matrix_256/led_matrix_256.ino
@@ -113,16 +113,23 @@
     delay(200);
 }

-void renderFrame( uint8_t frameNumber ) {
+void renderFrame( uint16_t frameNumber ) {
+
   // Ensure that there is a valid frame, otherwise we will walk off the memory allocated and then bad things happen
   if (frameNumber >= 0 && frameNumber < MAX_FRAME) {
-
-    COLOR pixel = {0, 0, 0};
+    static COLOR pixel = {0, 0, 0};

     // Setup every pixels
-    for(uint8_t i = 0; i < strip.numPixels(); i++) {
-        pixel = frames[frameNumber][i];
-        strip.setPixelColor(i, pixel.red, pixel.green, pixel.blue);
+    for(uint16_t i = 0; i < NUM_OF_PIXELS; i++) {
+
+      // Copy from the program memory to the local variable pixel
+      memcpy_P ((void *)&pixel, &frames[frameNumber][i], sizeof(COLOR));
+      /*  Serial.print("Pixel: "); Serial.println(i);
+        Serial.print("R: "); Serial.println(pixel.red);
+        Serial.print("G: "); Serial.println(pixel.green);
+        Serial.print("B: "); Serial.println(pixel.blue);
+        delay(1000);*/
+      strip.setPixelColor(i, pixel.red, pixel.green, pixel.blue);
     }

     // Render the frame
@@ -130,8 +137,8 @@
   }
 }

-uint8_t myRemoteRead() {
-    uint8_t remoteFrame = MAX_FRAME; // Start off with an invalid frame to ease debugging
+uint16_t myRemoteRead() {
+    uint16_t remoteFrame = MAX_FRAME; // Start off with an invalid frame to ease debugging
     uint32_t remoteValue = 0;

     if (irrecv.decode(&results))  {  // have we received an IR signal?


Time spacing defined to 10 seconds until launch day

--- hispatracker/hispatracker.ino
+++ hispatracker/hispatracker.ino
@@ -29,7 +29,7 @@
 static uint8_t next_aprs = 0;

 //Sends an APRS packet every...
-#define SEND_TIME_SPACING 60
+#define SEND_TIME_SPACING 10
 static APRSPacket packet;

@@ -47,7 +47,7 @@
 #endif

 void setup()
-{
+{
   #ifdef LOAD_EEPROM
       loadEEPROM();
   #endif
@@ -175,4 +175,4 @@
     }
     next_aprs++;
   }
-}+}


more complete graph (still need to load edges)

--- hb.ino
+++ hb.ino
@@ -1,22 +1,25 @@
 #define HB_VERSION "HoneyBee Arduino interpreter version 0.0.1"
-/*
-outline of HoneyBee UltraMini TransmitionFormat version 0.0.1
-1_hbumtf_v0
-nodes:
+// outline of HoneyBee UltraMini TransmitionFormat version 0.0.1
+#define START_HBG "1_hbumtf_v0"
+#define NODES_HBG "nodes:"
+/*
   0|env|||
   1|high||1|
-  2|led|13||
-edges:
+  2|led|13|| */
+#define EDGES_HBG "edges:"
+/*
   0|1|msg|graph_init|
-  1|2|set||
-0_hbumtf
-
+  1|2|set|| */
+#define END_HBG "0_hbumtf"
+/*
 nodes follow this sequence
   id|name|io|value|process
 edges follow this sequence
   from|to|type|name|alias/guard

 */
+
+//#define DUBUG_BUILD true
 #define UNDEF_INT -32768
 #define NAME_SIZE  12
 #define PROCESS_SIZE  12
@@ -28,6 +31,15 @@
   int value;
   char process[PROCESS_SIZE];
 } Node;
+
+typedef struct
+{
+  int from;
+  int to;
+  char type[4];
+  char name[NAME_SIZE];
+  char guard[PROCESS_SIZE];
+} Edge;

 // Pin 13 has an LED connected on most Arduino boards.
 // give it a name:
@@ -38,6 +50,8 @@
 boolean intComplete = false;
 int node_index = 0;
 Node nodes[10];
+int edge_index = 0;
+Edge edges[10];

 // hbumtf parser vars.
 // state 0=outside_cmd, 1=loading, 2=nodes, 3=edges
@@ -71,7 +85,9 @@
     // so the main loop can do something about it:
     if (inChar == '\n') {
       stringComplete = true;
+      #ifdef DUBUG_BUILD
       debug("raw|"+inputString+"|state|"+state);
+      #endif
     }
    else {
       // add it to the inputString:
@@ -79,37 +95,40 @@
    }
   }
   if (!stringComplete) {return;}
-  if (state == 0 && inputString == "1_hbumtf_v0") {
+  if (state == 0 && inputString == START_HBG) {
     next_state = 1;
+    #ifdef DUBUG_BUILD
     debug("load|"+inputString);
+    #endif
   }
   else if (state == 0) {
-    debug("outside_cmd|"+inputString);
+    #ifdef DUBUG_BUILD
+    debug("outside_com|"+inputString);
+    #endif
     if (inputString == "rfi") {
-      Serial.println(HB_VERSION);
-      Serial.println(state);
-      debugAllNodes();
-    }
-  }
-  if (state == 1 && inputString == "nodes:") {
+      com_rfi();
+    }
+  }
+  if (state == 1 && inputString == NODES_HBG) {
     node_i = 0;
     next_state = 2;
     state = -1;
-    //debug("state from|" + state + "|to|" + next_state);
-  }
-  if (state == 2 && inputString == "edges:") {
+  }
+  if (state == 2 && inputString == EDGES_HBG) {
     edge_i = 0;
     next_state = 3;
     state = -1;
   }
-  if (state == 3 && inputString == "0_hbumtf") {
+  if (state == 3 && inputString == END_HBG) {
     next_state = 0;
     state = -1;
-    debugAllNodes();
+    com_graph();
   }
   // processing for states 2 and 3
   if (state == 2) {
+    #ifdef DUBUG_BUILD
     debug("parsing node|"+inputString);
+    #endif
     int i = 0;
     char temp[10];
     i = crawlStr(temp, i, inputString, '|');
@@ -125,9 +144,11 @@
     else {
       nodes[node_i].io = atoi(temp);
     }
+    #ifdef DUBUG_BUILD
     Serial.print("io = ");
     Serial.print(nodes[node_i].io, DEC);
     Serial.print("|");
+    #endif

     temp[0] = '\0';
     i = crawlStr(temp, i, inputString, '|');
@@ -137,16 +158,18 @@
     else {
       nodes[node_i].value = atoi(temp);
     }
+    #ifdef DUBUG_BUILD
     Serial.print("value = ");
     Serial.print(nodes[node_i].value, DEC);
     Serial.println("|");
+    #endif

     i = crawlStr(nodes[node_i].process, i, inputString, '|');
-
-    //debug("process = " + nodes[node_i].process);
   }
   if (state == 3) {
+    #ifdef DUBUG_BUILD
     debug("edge|"+inputString);
+    #endif
   }
   if (next_state >= 0) {
     state = next_state;
@@ -157,8 +180,6 @@
 int crawlStr(char *result, int i, String inputString, char stopChar) {
   const unsigned int len = inputString.length();
   int j = 0;
-  //Serial.println(len, DEC);
-  //Serial.println(i, DEC);
   while (i < len) {
     if (inputString[i] == stopChar) {
       result[j] = '\0';
@@ -170,13 +191,24 @@
   }
 }

+#ifdef DUBUG_BUILD
 void debug(String out) {
+  Serial.print("Debug: ");
   Serial.println(out);
 }
-
-void debugAllNodes() {
+#endif
+
+void com_rfi() {
+  Serial.println(HB_VERSION);
+  Serial.print("Serial state: ");
+  Serial.println(state);
+  com_graph();
+}
+
+void com_graph() {
   int i;
-  Serial.println("all nodes:");
+  Serial.println(START_HBG);
+  Serial.println(NODES_HBG);
   for (i = 0; i < 10; i++) {
     if (nodes[i].name[0]) {
       Serial.print(i);
@@ -189,6 +221,22 @@
       Serial.println("");
     }
   }
-
-
-}
+  Serial.println(EDGES_HBG);
+  for (i = 0; i < 10; i++) {
+    if (edges[i].type[0]) {
+      Serial.print(i);
+      Serial.print("|");
+      Serial.print(edges[i].from);
+      Serial.print("|");
+      Serial.print(edges[i].to);
+      Serial.print("|");
+      Serial.print(edges[i].type);
+      Serial.print("|");
+      Serial.print(edges[i].name);
+      Serial.print("|");
+      Serial.print(edges[i].guard);
+      Serial.println("");
+    }
+  }
+  Serial.println(END_HBG);
+}


get rid of these spaces

get rid of these spaces

--- sketches/gear_indicator/gear_indicator.ino
+++ sketches/gear_indicator/gear_indicator.ino
@@ -124,13 +124,13 @@

 void saveValues(int rpm, int wheel, int gear) {
   i2c_values[0] = rpm &0xFF;
-  i2c_values[1] = (rpm >> 8) &0xFF;
+  i2c_values[1] = (rpm >> 8) &0xFF;

   i2c_values[2] = wheel &0xFF;
-  i2c_values[3] = (wheel >> 8) &0xFF;
+  i2c_values[3] = (wheel >> 8) &0xFF;

   i2c_values[4] = gear &0xFF;
-  i2c_values[5] = (gear >> 8) &0xFF;
+  i2c_values[5] = (gear >> 8) &0xFF;
 }

 void writeToFile(char* data) {


Rewrite to make it possible to calibrate each joint position

--- otto/otto.ino
+++ otto/otto.ino
@@ -1,49 +1,84 @@
 #include <Servo.h>

-#define RIGHT_ANKLE_PIN 5
-#define LEFT_ANKLE_PIN  4
-#define RIGHT_HIP_PIN   3
-#define LEFT_HIP_PIN    2
+#define DELAY               3

-#define RIGHT_ANKLE_MIDDLE  1500
-#define LEFT_ANKLE_MIDDLE   1500
-#define RIGHT_HIP_MIDDLE    1300
-#define LEFT_HIP_MIDDLE     1500
-#define MOVE                350
-#define FACTOR              2
-#define DELAY               2
+struct Joint
+{
+    const unsigned int pin;
+    const unsigned int posMin;
+    const unsigned int posMiddle;
+    const unsigned int posMax;
+    const unsigned int distMinToMiddle;
+    const unsigned int distMaxToMiddle;
+    Servo servo;

-Servo rightAnkle;
-Servo leftAnkle;
-Servo rightHip;
-Servo leftHip;
+    unsigned int currentPos;
+
+    Joint(
+        const unsigned int pin,
+        const unsigned int posMin,
+        const unsigned int posMiddle,
+        const unsigned int posMax) :
+        pin(pin),
+        posMin(posMin),
+        posMiddle(posMiddle),
+        posMax(posMax),
+        distMinToMiddle(posMiddle-posMin),
+        distMaxToMiddle(posMax-posMiddle),
+        currentPos(0)
+    {
+    }
+
+    void init()
+    {
+        this->servo.attach(this->pin);
+        this->servo.writeMicroseconds(this->posMiddle);
+        this->currentPos = this->posMiddle;
+    }
+
+    void dec(unsigned int steps = 1)
+    {
+        this->currentPos -= steps;
+        this->servo.writeMicroseconds(this->currentPos);
+    }
+
+    void inc(unsigned int steps = 1)
+    {
+        this->currentPos += steps;
+        this->servo.writeMicroseconds(this->currentPos);
+    }
+};
+
+Joint rightAnkle(5, 810, 1510, 1860);
+Joint leftAnkle(4, 1140, 1490, 2190);
+Joint rightHip(3, 950, 1300, 1650);
+Joint leftHip(2, 1150, 1500, 1850);

 void stepForward();

 void setup() {
-    rightAnkle.attach(RIGHT_ANKLE_PIN);
-    leftAnkle.attach(LEFT_ANKLE_PIN);
-    rightHip.attach(RIGHT_HIP_PIN);
-    leftHip.attach(LEFT_HIP_PIN);
-
-    rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE);
-    leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE);
-    rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE);
-    leftHip.writeMicroseconds(LEFT_HIP_MIDDLE);
+    rightAnkle.init();
+    leftAnkle.init();
+    rightHip.init();
+    leftHip.init();
 }

 bool running = false;

-void loop() {
+void loop()
+{
     int i = 0;
+    int j = 0;

-    if (!running) {
+    if (!running)
+    {
         delay(5000);

-        // lean left
-        for (i = 0; i < MOVE; ++i) {
-            rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE-i*FACTOR);
-            leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE-i);
+        for (i = 0; i < leftAnkle.distMinToMiddle; ++i)
+        {
+            rightAnkle.dec(2);
+            leftAnkle.dec();
+
             delay(DELAY);
         }

@@ -55,50 +90,60 @@

 void stepForward() {
     int i = 0;
+    int j = 0;

-    // rotate left
-    for (i = 0; i < MOVE; ++i) {
-        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE + i);
-        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE + i);
-        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE - MOVE * FACTOR + i * FACTOR);
-        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE - MOVE + i);
+    // left step
+    for (i = 0; i < leftAnkle.distMinToMiddle; ++i)
+    {
+        rightAnkle.inc(2);
+        leftAnkle.inc();
+        rightHip.inc();
+        leftHip.inc();
+
         delay(DELAY);
     }

     // lean right
-    for (i = 0; i < MOVE; ++i) {
-        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE + i);
-        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE + i * FACTOR);
+    for (i = 0; i < rightAnkle.distMaxToMiddle; ++i)
+    {
+        rightAnkle.inc();
+        leftAnkle.inc(2);
+
         delay(DELAY);
     }

-    // rotate to center
-    for (i = 0; i < MOVE; ++i) {
-        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE + MOVE - i);
-        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE + MOVE - i);
+    // rotate from left to center
+    for (i = 0; i < rightHip.distMaxToMiddle; ++i)
+    {
+        rightHip.dec();
+        leftHip.dec();
+
         delay(DELAY);
     }

-    // rotate right
-    for (i = 0; i < MOVE; ++i) {
-        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE - i);
-        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE - i);
-        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE + MOVE - i);
-        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE + MOVE * FACTOR - i * FACTOR);
+    // right step
+    for (i = 0; i < rightAnkle.distMaxToMiddle; ++i) {
+        rightAnkle.dec();
+        leftAnkle.dec(2);
+        rightHip.dec();
+        leftHip.dec();
+
         delay(DELAY);
     }

     // lean left
-    for (i = 0; i < MOVE; ++i) {
-        rightAnkle.writeMicroseconds(RIGHT_ANKLE_MIDDLE - i * FACTOR);
-        leftAnkle.writeMicroseconds(LEFT_ANKLE_MIDDLE - i);
+    for (i = 0; i < leftAnkle.distMinToMiddle; ++i) {
+        rightAnkle.dec(2);
+        leftAnkle.dec();
+
         delay(DELAY);
     }

-    // rotate to center
-    for (i = 0; i < MOVE; ++i) {
-        rightHip.writeMicroseconds(RIGHT_HIP_MIDDLE - MOVE + i);
-        leftHip.writeMicroseconds(LEFT_HIP_MIDDLE - MOVE + i);
+    // rotate from right to center
+    for (i = 0; i < rightHip.distMinToMiddle; ++i) {
+        rightHip.inc();
+        leftHip.inc();
+
         delay(DELAY);
     }
 }


Many fixes + last working version before interrupts

- code optimizations
- clean up style
- adjustments to account for neopixels

--- jacksclock12/jacksclock12.ino
+++ jacksclock12/jacksclock12.ino
@@ -1,11 +1,9 @@
 /* ================================================================================== //
 //
-//    Jack's 420 Clock
-//
-//    *** TO DO ***
-//    * Clean up both switch functions
-//    * Auto Dim: Debounce / Smoothing
-//    * Fix RGB LED
+//    Jack's 420 Clock - 2014
+//    Written for Arduino Uno Rev. 3
+//    Adafruit Hardware: Real Time Clock: DS1307, Neopixel (40 RGB-LED) Shield,
+//    7-Segment Display, 14-Segment Aphanumeric Display, Backlight Module
 //
 // ================================================================================== */

@@ -18,41 +16,37 @@
 #include <Adafruit_NeoPixel.h>

 // Input/Output Pins
-int photoCellIn = A1;         // Auto Dimming
-int nightLightIn = A2;        // Backlight
-int clockLightIn = A3;        // 7-Sebment
-int NeoPixel = 6;             // RGB-LED: Green
-int uvLED = 7;                // LEDs: UV
-int reminderSwitchIn = 8;     // Reminder Switch *** NOT WORKING ***
-int fourTwentyLED = 9;        // LED: Green
-int piezoOut = 10;            // Speaker
-int nightLightOut = 11;       // Backlight
-int brightSwitchIn = 12;      // Auto Brightness
-int dstSwitchIn = 13;         // Savings Time Switch
-
+int photoCellIn =       A1;      // Auto Dimming
+int nightLightIn =      A2;      // Backlight
+int clockLightIn =      A3;      // 7-Sebment
+int NeoPixel =          6;       // RGB-LED: Green
+int uvLED =             7;       // LEDs: UV
+int reminderSwitchIn =  8;       // Reminder Switch *** NOT WORKING ***
+int fourTwentyLED =     9;       // LED: Green
+int piezoOut =          10;      // Speaker
+int nightLightOut =     11;      // Backlight
+int brightSwitchIn =    12;      // Auto Brightness
+int dstSwitchIn =       13;      // Savings Time Switch

 // Variables
-int clockKnob;                // Potentiometer 1
-int lightKnob;                // Potentiometer 2
-int clockBrightness;          // 7-Segment & Alphanumeric
-int lightBrightness;          // Backlight
-int dstState;                 // DST
-int reminderState;            // Switch (Reminder)
-int autoBrightState;          // Switch (Auto-Dimmer)
-int photoCellRead;            // Photo Cell
-int autoBrightAverage;        // Photo Cell
-long previousMillis;          // For counting of xfade timer
-int fourTwentyBright = 0;     // 420 LED
-int fadeAmount = 2;           // 420 LED
-boolean running = false;      // Colon On/Off
-int counter = 0;              // Counts notes played
-int numReadings = 25;         // Smoothing function: # of Readings
+int dstState;                    // DST
+int reminderState;               // Switch (Reminder)
+int autoBrightState;             // Switch (Auto-Dimmer)
+int photoCellRead;               // Photo Cell
+int autoBrightAverage;           // Photo Cell
+long previousMillis;             // For counting of xfade timer
+int fadeAmount = 2;              // 420 LED
+int counter;                     // Counts notes played
+int numReadings = 25;            // Smoothing function: # of Readings
+int neoBrightness = 100;         // Neopixel Shield
+boolean running = false;         // Colon On/Off

 // Setup Components
 RTC_DS1307 RTC;
 Adafruit_7segment disp = Adafruit_7segment();
 Adafruit_AlphaNum4 alpha4 = Adafruit_AlphaNum4();
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, NeoPixel, NEO_GRB + NEO_KHZ800);
+

 // ================================================================================== //
 //                                  *** SETUP ***
@@ -78,6 +72,7 @@
   strip.show();                                           // Initialize all pixels to 'off'
 }

+
 // ================================================================================== //
 //                                  *** LOOP ***
 // ================================================================================== //
@@ -89,7 +84,8 @@
   blinkColon();                          // Blink Colon
   adjustBrightness();                    // Check Switch & Adjust brightness
   fourTwentyCheck();                     // Check if 4:20pm & Run Alarm
-  reminderSwitch();                      // LED / Reminder
+  reminderSwitch();                      // LED / Reminder
+  if (reminderState == 0) strip.show();  // Turn pixels off
 }

 // ================================================================================== //
@@ -218,15 +214,10 @@
 void reminderSwitch()                                   // Checks Switch & Activates LED
 {
   Serial.println(reminderState);                        // Turn back on when ready to test this function
+  disp.drawColon(true);
   reminderState = digitalRead(reminderSwitchIn);        // Check Reminder Switch
-  if (reminderState == 1)                               // If On: Run Crossfade Part 1 / 3
-  {
-  rainbowCycle(1);
-  }
-  else
-  {
-  strip.show();                                           // Initialize all pixels to 'off'
-  }
+  if (reminderState == HIGH) rainbowCycle(35);             // If On: Run Rainbow Crossfade
+  if (reminderState == LOW) strip.show();                 // Turn pixels off
 }

@@ -245,8 +236,7 @@
     total = total + readings[index];                    // add the reading to the total
     index = index + 1;                                  // advance to next position in array

-    if (index >= numReadings)                           // if we're at the end of the array...
-      index = 0;
+    if (index >= numReadings) index = 0;                           // if we're at the end of the array...

     average = total / numReadings;
     autoBrightAverage = average;
@@ -265,7 +255,7 @@
     previousMillis = currentMillis;

     tone(piezoOut, note, duration);                          //Play tone on buzzerPin
-    if (counter % 2 == 0)
+    if (counter % 2 == 0)                                    // Alternate Green then UV LED's
     {
       digitalWrite(fourTwentyLED, HIGH);
       delay(duration);
@@ -278,17 +268,16 @@
       digitalWrite(uvLED, LOW);
     }
     noTone(piezoOut);
-
-    counter++;    //Increment counter
-  }
-}
-
-
-void rainbowCycle(uint8_t wait)                                                               // Makes the rainbow equally distributed throughout
-{
+    counter++;
+  }
+}
+
+
+void rainbowCycle(uint8_t wait)                                                            // Runs rainbow led setup
+{
   uint16_t i, j;
-  for (j = 0; j < 256 * 5; j++)                                                               // 5 cycles of all colors on wheel
-  {
+  for (j = 0; j < 256 ; j++)                                                               // *1 cycles of all colors on wheel
+  {
     for (i = 0; i < strip.numPixels(); i++)
     {
       strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
@@ -299,8 +288,7 @@
 }

-// The colours are a transition r - g - b - r - g.... ||  Input value 0 - 255 to get a color value.
-uint32_t Wheel(byte WheelPos)
+uint32_t Wheel(byte WheelPos)                                      // The colours are a transition r - g - b - r - g.... & Input value 0 - 255 to get a color value.
 {
   if (WheelPos < 85)
   {
@@ -327,13 +315,16 @@
 void adjustBrightness()                                          // Brightness Check & Adjust
 {
   smooth();                                                      // Averages photocell readings
-  clockKnob = analogRead(clockLightIn);                          // Check & Map Potentiometers/Photocell
-  clockBrightness = map(clockKnob, 0, 1023, 2, 15);
-  lightKnob = analogRead(nightLightIn);
-  lightBrightness = map(lightKnob, 0, 1023, 50, 255);
+  int clockKnob = analogRead(clockLightIn);                      // Check & Map Potentiometers/Photocell
+  int clockBrightness = map(clockKnob, 0, 1023, 2, 15);
+  int lightKnob = analogRead(nightLightIn);
+  int lightBrightness = map(lightKnob, 0, 1023, 50, 255);        // Backlight
+  int neoBrightness = map(lightKnob, 0, 1023, 1, 200);
   int autoBright1 = map(autoBrightAverage, 1, 1023, 2, 15);
   int autoBright2 = map(autoBrightAverage, 1, 1023, 50, 255);
-
+
+  strip.setBrightness(neoBrightness);                            // Set Neopixel Brightness
+
   autoBrightState = digitalRead(brightSwitchIn);                 // Adjust Brightness (if Auto Switch On)
   if (autoBrightState == 1)
   {
@@ -346,9 +337,9 @@
     disp.setBrightness(clockBrightness);                          // Use Potentiometers to Set Brightness
     alpha4.setBrightness(clockBrightness);
     analogWrite(nightLightOut, lightBrightness);
-    strip.setBrightness(lightBrightness);
-  }
-}
+  }
+}
+

 void themeMusic()
 {
@@ -365,11 +356,11 @@
     beep(NOTE_C4, 500);
     beep(NOTE_E4, 250);
     beep(NOTE_F4, 250);
-  }
-  beep(NOTE_G4, 500);
-  beep(NOTE_C4, 250);
-  beep(NOTE_E4, 250);
-  beep(NOTE_F4, 250);
+    beep(NOTE_G4, 500);
+    beep(NOTE_C4, 250);
+    beep(NOTE_E4, 250);
+    beep(NOTE_F4, 250);
+  }
   for (int i = 0; i < 3; i++)
   {
     beep(NOTE_G3, 500);


Implemented three buzzers

Implemented three buzzers

All three buzzers now loop through a c-scale, each buzzer a 3rd above the last. Resting does not work, and so work will have to be done to fix that.

--- ArduMusic/ArduMusic.ino
+++ ArduMusic/ArduMusic.ino
@@ -1,21 +1,56 @@
 #include <Tone.h>
 #include "Notes.cpp"
+
+

 // Create three tone controllers
 Tone buzzer[3];

-Note Music[9] = {
-  { NOTE_C4, 10 },
-  { NOTE_D4, 10 },
-  { NOTE_E4, 10 },
-  { NOTE_F4, 10 },
-  { NOTE_G4, 10 },
-  { NOTE_A4, 10 },
-  { NOTE_B4, 10 },
-  { NOTE_C5, 20 },
-  { NOTE_RST, 100 }
+// The "cursor" for each of the buzzers
+unsigned int music_pos[3] = { 0, 0, 0 };
+// Holds the length of the music
+unsigned int music_length = 9;
+
+
+// Defines the music
+Note Music[3][9] = {
+  {
+    { NOTE_C4, 10 },
+    { NOTE_D4, 10 },
+    { NOTE_E4, 10 },
+    { NOTE_F4, 10 },
+    { NOTE_G4, 10 },
+    { NOTE_A4, 10 },
+    { NOTE_B4, 10 },
+    { NOTE_C5, 20 },
+    { NOTE_RST, 10 }
+  },
+  {
+    { NOTE_E4, 10 },
+    { NOTE_F4, 10 },
+    { NOTE_G4, 10 },
+    { NOTE_A4, 10 },
+    { NOTE_B4, 10 },
+    { NOTE_C5, 10 },
+    { NOTE_D5, 10 },
+    { NOTE_E5, 20 },
+    { NOTE_RST, 10 }
+  },
+  {
+    { NOTE_G4, 10 },
+    { NOTE_A4, 10 },
+    { NOTE_B4, 10 },
+    { NOTE_C5, 10 },
+    { NOTE_D5, 10 },
+    { NOTE_E5, 10 },
+    { NOTE_F5, 10 },
+    { NOTE_G5, 20 },
+    { NOTE_RST, 10 }
+  }
 };
+
+

 void setup()
 {
@@ -26,22 +61,24 @@

   // Creates a Serial connection
   Serial.begin(9600);
-  Serial.print("Program Begin \n");
-  Serial.print("Note size:");
-  Serial.println(sizeof(Note));
 }
+
+

 void loop()
 {
-  for (unsigned int i = 0; i < 9; i++)
+  for (unsigned int i = 0; i < 3; i++)
   {
-    // Play or stop the music
-    buzzer[0].play(
-      pgm_read_word(Frequency + Music[i].pitch),
-      Music[i].duration * 20);
-
-    // Wait until the next note
-    while (buzzer[0].isPlaying());
+    // If the buzzer is not playing
+    if (!buzzer[i].isPlaying())
+    {
+      // Play the next note, advance the cursor
+      buzzer[i].play(
+        pgm_read_word(Frequency + Music[i][music_pos[i]++].pitch),
+        Music[i][music_pos[i]].duration * 20);
+
+      // Wrap the cursor if necessary
+      if (music_pos[i] >= music_length) music_pos[i] = 0;
+    }
   }
 }
-


Fixing Blink to be bare bones blink.

Fixing Blink to be bare bones blink.

--- Arduino/Blink/Blink.ino
+++ Arduino/Blink/Blink.ino
@@ -13,89 +13,17 @@
   by Scott Fitzgerald
  */

-#include <SPI.h>
-#include "nRF24L01.h"
-#include "RF24.h"
-#include "printf.h"
-
-const int pressureSensor = A0;
-const int lightSensor = A1;
-
-const int W1_9 = 3;
-const int W1_10 = 4;
-const int W1_11 = 5;
-const int W1_12 = 6;
-const int W1_13 = 7;
-
-const int W2_9 = 9;
-const int W2_10 = 10;
-const int W2_11 = 11;
-const int W2_12 = 12;
-const int W2_13 = 13;
-
-int sensorReading = 0;
-
-RF24 radio1(W1_9, W1_10);
-RF24 radio2(W2_9, W2_10);
-
-byte message[4] = {1,2,3,4};
-byte data[4] = {0,0,0,0};

 // the setup function runs once when you press reset or power the board
 void setup() {
   // initialize digital pin 13 as an output.
   pinMode(13, OUTPUT);
-  Serial.begin(9600);
-
-Serial.println("Configure Radio 1");
-   radio1.begin();
-   radio1.setChannel(2);
-   radio1.setPayloadSize(4);
-   radio1.setAutoAck(false);
-   radio1.setCRCLength(RF24_CRC_8);
-
-Serial.println("Configure Radio 2");
-
-   radio2.setChannel(2);
-   radio2.setPayloadSize(4);
-   radio2.setAutoAck(false);
-   radio2.setCRCLength(RF24_CRC_8);
-
-Serial.println("Open Read");
-
-   radio2.openReadingPipe(1,0xE7E7E7E7E7LL);
-   radio2.startListening();
-
-Serial.println("Open Write");
-
-   radio1.openWritingPipe(0xE7E7E7E7E7LL);
-
 }

 // the loop function runs over and over again forever
 void loop() {
-
-  //sensorReading = analogRead(pressureSensor);
-  //Serial.print("Pressure: ");
-  //Serial.println(sensorReading);
-
-  //sensorReading = analogRead(lightSensor);
-  //Serial.print("Light: ");
-  //Serial.println(sensorReading);
-
-Serial.println("Sending Message");
-  radio1.write(message, sizeof(message));
-
-Serial.println("Reading");
-  if(radio2.available())
-  {
-     radio2.read(&data,sizeof(data));
-
-     Serial.println(data[0]);
-  }
-
-
-  delay(100);
-
-
+  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
 }


Add screen mirror support

Add screen mirror support

A couple months ago, someone made an app that lets you mirror the Arduboy screen, provided you add a bit of code to it, which this commit adds.

--- pong/pong.ino
+++ pong/pong.ino
@@ -8,6 +8,7 @@
 void
 setup()
 {
+	Serial.begin(9600);
 	arduboy.begin();
 	arduboy.setFrameRate(30);
 	arduboy.setTextSize(2);
@@ -23,5 +24,6 @@
 	}
 	arduboy.pollButtons();
 	tick();
+	Serial.write(arduboy.getBuffer(), 128 * 64 / 8);
 	arduboy.display(CLEAR_BUFFER);
 }


Helpful link added

Helpful link added

--- sketches/gear_indicator/gear_indicator.ino
+++ sketches/gear_indicator/gear_indicator.ino
@@ -4,7 +4,8 @@
 * Some information about interrupts:
 * - http://arduino.cc/en/Reference/attachInterrupt
 * About I2C:
-$ - WSWireLib: https://github.com/steamfire/WSWireLib
+* - WSWireLib: https://github.com/steamfire/WSWireLib
+* - http://stackoverflow.com/questions/21073085/how-to-send-4-pot-values-via-i2c-from-arduino-to-arduino-how-to-differentiate-t
 * About SD Cards:
 * - https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/format
 * Some useful information about Aprilia RSV/SL bikes work: (See: http://www.aprilia-v60.com/index.php?topic=262315)


First pass at performance layer

First pass at performance layer


Better millis() practice

Better millis() practice

Updated the timer to implement good millis() practice, as suggested by rsocol.

--- examples/SevSeg_Counter/SevSeg_Counter.ino
+++ examples/SevSeg_Counter/SevSeg_Counter.ino
@@ -38,9 +38,10 @@
   static unsigned long timer = millis();
   static int deciSeconds = 0;

-  if (millis() >= timer) {
+  if (millis() - timer >= 100) {
+    timer += 100;
     deciSeconds++; // 100 milliSeconds is equal to 1 deciSecond
-    timer += 100;
+
     if (deciSeconds == 10000) { // Reset to 0 after counting for 1000 seconds.
       deciSeconds=0;
     }


sending MIDI out of pin 11 using SoftwareSerial library using ifdef for debug now that default Serial can be devoted to debug messages

--- whammy_seq.ino
+++ whammy_seq.ino
@@ -1,6 +1,4 @@
-/* TODO better debugging method (need to send MIDI out of a different pin,
-so it's not tying up the default serial interface) */
-#define DEBUG false
+#include <SoftwareSerial.h>

 enum Modes {
   PLAY, // play current sequence
@@ -21,6 +19,8 @@
 int current_step = 0;
 long seq_speed = 150; // milliseconds per step
 long last_seq_step_time = 0;
+
+SoftwareSerial midi_serial(10, 11); // RX, TX

 ////////////////////////////////////////////////////////////////////////////////
 ////////////////////////////////////////////////////////////////////////////////
@@ -81,12 +81,12 @@

 // the setup function runs once when you press reset or power the board
 void setup() {
-  if (DEBUG) {
-    Serial.begin(9600);
-  } else {
-    //  Set MIDI baud rate:
-    Serial.begin(31250);
-  }
+  #ifdef DEBUG
+  Serial.begin(9600);
+  #endif
+
+  //  Set MIDI baud rate:
+  midi_serial.begin(31250);

   start_button.init();
 }
@@ -117,9 +117,6 @@
       break;
   }

-  if (DEBUG) {
-    delay(500);
-  }
 }

 void play_loop() {
@@ -128,7 +125,6 @@

     send_whammy_position((byte) sequence[current_step]);

-    // next step
     current_step += 1;
     current_step = current_step % (sizeof(sequence) / sizeof(sequence[0]));
   }
@@ -139,14 +135,14 @@
 }

 void send_whammy_position(byte value) {
-  if (DEBUG) {
-    Serial.print("set position:");
-    Serial.print(value);
-    Serial.print("\n");
-  } else {
-    Serial.write((byte) 176); // CC on Channel 1 (10110000)
-    Serial.write((byte) 11); // Controller 11
-    Serial.write(value); // value
-  }
+  #ifdef DEBUG
+  Serial.print("set position:");
+  Serial.print(value);
+  Serial.print("\n");
+  #endif
+
+  midi_serial.write((byte) 176); // CC on Channel 1 (10110000)
+  midi_serial.write((byte) 11); // Controller 11
+  midi_serial.write(value);
 }


fix typo

fix typo

* fix typo assignment and comparison

--- Arduino/McLighting/McLighting.ino
+++ Arduino/McLighting/McLighting.ino
@@ -937,7 +937,7 @@
   if (mode == BRIGHTNESS) {
     strip.setBrightness(brightness);
     strip.trigger();
-    if (prevmode == SET_MODE) prevmode == HOLD;
+    if (prevmode == SET_MODE) prevmode = HOLD;
     mode = HOLD;
   }
   #ifdef ENABLE_LEGACY_ANIMATIONS


Added checksum for IR

Added checksum for IR

--- Arduino/_firmware3/_firmware3.ino
+++ Arduino/_firmware3/_firmware3.ino
@@ -289,11 +289,24 @@
 }

 void shaft_temp(){
+    int i;
+    unsigned long time_check=millis();
+
     int data_buf[5] = {0};
     int tempData = 0;
-    data_read(data_buf);
+    do
+    {
+      data_read(data_buf);
+      delay(1);
+      if ((millis() - time_check) >= 2000){//Haha, let's NOT get stuck if the thing is unplugged
+        break;
+        }
+
+    }while(((data_buf[0] + data_buf[1] + data_buf[2])& 0xff) != data_buf[3]);
+
     tempData = data_buf[1]*256 + data_buf[2];
     shaftTemp = (float)tempData/16-273.15;
+
 }


Inclusão do código do giroscópio.

Inclusão do código do giroscópio.

--- quad/quad.ino
+++ quad/quad.ino
@@ -1,5 +1,12 @@
 #include <Servo.h>
 #include <PID_v1.h>
+#include "I2Cdev.h"
+#include "MPU6050_6Axis_MotionApps20.h"
+#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
+#include "Wire.h"
+#endif
+
+MPU6050 mpu;

 void telemetry();
 void readRC();
@@ -17,8 +24,34 @@
 long tmInterval;
 #endif

+#define LED_PIN 13
+bool blinkState = false;
+
+// MPU control/status vars
+bool dmpReady = false;  // set true if DMP init was successful
+uint8_t mpuIntStatus;   // holds actual interrupt status byte from MPU
+uint8_t devStatus;      // return status after each device operation (0 = success, !0 = error)
+uint16_t packetSize;    // expected DMP packet size (default is 42 bytes)
+uint16_t fifoCount;     // count of all bytes currently in FIFO
+uint8_t fifoBuffer[64]; // FIFO storage buffer
+
+// orientation/motion vars
+Quaternion q;           // [w, x, y, z]         quaternion container
+VectorFloat gravity;    // [x, y, z]            gravity vector
+float ypr[3];           // [yaw, pitch, roll]   yaw/pitch/roll container and gravity vector
+
+// ================================================================
+// ===               INTERRUPT DETECTION ROUTINE                ===
+// ================================================================
+
+volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
+void dmpDataReady() {
+  mpuInterrupt = true;
+}
+
+
 /* Definição dos canais de entrada. */
-const int CH1 = 2; /* Roll (horizontal da direita) */
+const int CH1 = 8; /* Roll (horizontal da direita) */
 const int CH2 = 3; /* Pitch (vertical da direita) */
 const int CH3 = 4; /* Throttle (vertical da esquerda) */
 const int CH4 = 5; /* Yaw (horizontal da esquerda */
@@ -55,15 +88,14 @@
 const int MOTOR_BL = 10; /* To-do test this pin */
 const int MOTOR_BR = 11; /* To-do test this pin */
 unsigned long val; /* Debug - To-do: retirar */
-
+
 /* Parâmetros do PID. */
 double setpoint, input, output;

 PID myPID(&input, &output, &setpoint,1,2,3, DIRECT);

 /* Inicialização do Arduino. */
-void setup()
-{
+void setup() {
   pinMode(CH1, INPUT);
   pinMode(CH2, INPUT);
   pinMode(CH3, INPUT);
@@ -81,26 +113,86 @@
   motorBL.attach(MOTOR_BL);
   motorBR.attach(MOTOR_BR);

-  Serial.begin(57600);
+  // join I2C bus (I2Cdev library doesn't do this automatically)
+#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
+  Wire.begin();
+  TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz)
+#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
+  Fastwire::setup(400, true);
+#endif
+
+  Serial.begin(115200);
+  while (Serial.available() && Serial.read()); // empty buffer
+
+  mpu.initialize();
+  Serial.println(F("Initializing DMP..."));
+  devStatus = mpu.dmpInitialize();
+
+  mpu.setXAccelOffset(616);
+  mpu.setYAccelOffset(2244);
+  mpu.setZAccelOffset(300);
+  mpu.setXGyroOffset(83);
+  mpu.setYGyroOffset(-25);
+  mpu.setZGyroOffset(44);
+
+  // make sure it worked (returns 0 if so)
+  if (devStatus == 0) {
+    // turn on the DMP, now that it's ready
+    mpu.setDMPEnabled(true);
+
+    // enable Arduino interrupt detection
+    Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
+    attachInterrupt(0, dmpDataReady, RISING);
+    mpuIntStatus = mpu.getIntStatus();
+
+    // set our DMP Ready flag so the main loop() function knows it's okay to use it
+    Serial.println(F("DMP ready! Waiting for first interrupt..."));
+    dmpReady = true;
+
+    // get expected DMP packet size for later comparison
+    packetSize = mpu.dmpGetFIFOPacketSize();
+  }
+  else {
+    // ERROR!
+    // 1 = initial memory load failed
+    // 2 = DMP configuration updates failed
+    // (if it's going to break, usually the code will be 1)
+    Serial.print(F("DMP Initialization failed (code "));
+    Serial.print(devStatus);
+    Serial.println(F(")"));
+  }
+
+  // configure LED for output
+  pinMode(LED_PIN, OUTPUT);
 }

 /* Loop infinito do Arduino. */
-void loop()
-{
+void loop() {
+  // if DMP programming failed, don't try to do anything
+
+  if (!dmpReady) {
+    return;
+  }
+
+  readOrientation();
+
   readRC();

   //  input = ch1v;
   // myPID.Compute();
   // ch1v += (int)output;
-
+
   writeMotor();
-
-  D(telemetry());
+
+  // D(telemetry());
+
+  // blink LED to indicate activity
+  blinkState = !blinkState;
+  digitalWrite(LED_PIN, blinkState);
 }

 /* Efetua a leitura dos canais dos controles. */
-void readRC()
-{
+void readRC() {
   channels[0] = pulseIn(CH1, HIGH);
   channels[1] = pulseIn(CH2, HIGH);
   channels[2] = pulseIn(CH3, HIGH);
@@ -112,8 +204,7 @@
 }

 /* Normaliza os valores do controle para ranges pré definidos. */
-void normalizeRC()
-{
+void normalizeRC() {
   rcThrottle = channels[2];
   rcYaw      = map(channels[3], MIN_CH4, MAX_CH4, -150, 150);
   rcPitch    = map(channels[1], MIN_CH2, MAX_CH2, 45, -45);
@@ -122,8 +213,8 @@
   rcDimmer   = map(channels[5], MIN_CH6, MAX_CH6, 0, 1000);
 }

-void writeMotor()
-{
+/* Efetua a escrita da potência dos motores entre 1 e 2ms */
+void writeMotor() {
   val = map(rcThrottle, MIN_CH1, MAX_CH1, 1000, 2000);
   motorFL.writeMicroseconds(val);
   motorFR.writeMicroseconds(val);
@@ -131,6 +222,48 @@
   motorBR.writeMicroseconds(val);
 }

+void readOrientation() {
+  if (mpuInterrupt) {
+    // reset interrupt flag and get INT_STATUS byte
+    mpuInterrupt = false;
+    mpuIntStatus = mpu.getIntStatus();
+
+    // get current FIFO count
+    fifoCount = mpu.getFIFOCount();
+
+    // check for overflow (this should never happen unless our code is too inefficient)
+    if ((mpuIntStatus & 0x10) || fifoCount == 1024) {
+      // reset so we can continue cleanly
+      mpu.resetFIFO();
+      //Serial.println(F("FIFO overflow!"));
+
+      // otherwise, check for DMP data ready interrupt (this should happen frequently)
+      //}
+    }
+    else if (mpuIntStatus & 0x02) {
+      //if (mpuIntStatus & 0x02) {
+      // wait for correct available data length, should be a VERY short wait
+      while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();
+
+      // read a packet from FIFO
+      mpu.getFIFOBytes(fifoBuffer, packetSize);
+      // track FIFO count here in case there is > 1 packet available
+      // (this lets us immediately read more without waiting for an interrupt)
+      fifoCount -= packetSize;
+
+      // display Euler angles in degrees
+      mpu.dmpGetQuaternion(&q, fifoBuffer);
+      mpu.dmpGetGravity(&gravity, &q);
+      mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
+      Serial.print("ypr\t");
+      Serial.print(ypr[0] * 180/M_PI);
+      Serial.print("\t");
+      Serial.print(ypr[1] * 180/M_PI);
+      Serial.print("\t");
+      Serial.println(ypr[2] * 180/M_PI);
+    }
+  }
+}
 /*
  * Efetua a telemetria dos dados do quadricoptero na seguinte ordem, separados por ';':
  * - rcThrottle (em us - entre ~1000 a ~2000)
@@ -147,12 +280,11 @@
  * - Canal 5 (em us - entre ~1000 a ~2000)
  * - Canal 6 (em us - entre ~1000 a ~2000)
  */
-void telemetry()
-{
+void telemetry() {
   /* Calcula a frequência do loop */
   tmInterval = micros() - tmCheckpoint;
   tmCheckpoint = micros();
-
+
   String tmValues;
   tmValues += String(rcThrottle) + ";";
   tmValues += String(rcYaw) + ";";
@@ -174,3 +306,7 @@

+
+
+
+


Add drawRectangle

Add drawRectangle

--- dee-oh-tee.ino
+++ dee-oh-tee.ino
@@ -101,6 +101,20 @@
   }
 }

+void drawRectangle(int startX, int startY, int width, int height, int xDegreesPerCycle) {
+  if (startX + width > USABLE_DEGREES || startY + height > USABLE_DEGREES) {
+    Serial.print("The requested rectangle goes beyond the servo's usable range");
+    Serial.println();
+    return;
+  }
+
+  moveToPoint(startX, startY, xDegreesPerCycle);
+  moveToPoint(startX + width, startY, xDegreesPerCycle);
+  moveToPoint(startX + width, startY + height, xDegreesPerCycle);
+  moveToPoint(startX, startY + height, xDegreesPerCycle);
+  moveToPoint(startX, startY, xDegreesPerCycle);
+}
+
 void performRangeTest() {
   moveToPoint(0, 0, 50);
   moveToPoint(-90, 90, 50);


More tweaks

More tweaks

--- Pan_Tilt_laser/Pan_Tilt_laser.ino
+++ Pan_Tilt_laser/Pan_Tilt_laser.ino
@@ -198,7 +198,7 @@

   if(val < 35){
-    return random(1000, 1500);
+    return random(1000, 2000);
   }
   else if(val < 80){
     return random(750, 1000);


deleted:    arduino_new/arduino_new.ino

deleted:    arduino_new/arduino_new.ino

--- libraries/esp8266/examples/arduino_new/arduino_new.ino
+++ libraries/esp8266/examples/arduino_new/arduino_new.ino
@@ -1,159 +0,0 @@
-
-// show arduino_new benefits
-// released to public domain
-// result is below
-
-class SomeClass {
-  public:
-    SomeClass(const String& s1 = emptyString, const String& s2 = emptyString) {
-      Serial.printf("SomeClass@%p(%s)(%s)\n", this, s1.c_str(), s2.c_str());
-    }
-
-    ~SomeClass() {
-      Serial.printf("~ SomeClass @%p\n", this);
-    }
-};
-
-class oom {
-  private:
-    char large [65000];
-  public:
-    oom() {
-      Serial.printf("this constructor should not be called\n");
-    }
-};
-
-void setup() {
-
-  Serial.begin(115200);
-  Serial.printf("\n\narduino_new benefits\n\n");
-  delay(5000); // avoid too frequent bootloop
-
-  // arduino_new / arduino_newarray api
-
-  Serial.printf("\n----- arduino_new:\n");
-  auto an = arduino_new(SomeClass);
-  delete an;
-
-  Serial.printf("\n----- arduino_new with oom:\n");
-  auto anoom = arduino_new(oom);
-  Serial.printf("nullptr: %p\n", anoom);
-  delete anoom;
-
-  Serial.printf("\n----- arduino_new with constructor parameters:\n");
-  auto ancp = arduino_new(SomeClass, "param1", "param2");
-  delete ancp;
-
-  Serial.printf("\n----- arduino_newarray[2]\n");
-  auto ana2 = arduino_newarray(SomeClass, 2);
-  Serial.printf("@:%p s=%zd s(2)=%zd\n", ana2, sizeof(SomeClass), sizeof(SomeClass[2]));
-  Serial.printf("0: %p\n", &ana2[0]);
-  Serial.printf("1: %p\n", &ana2[1]);
-  delete [] ana2;
-
-  Serial.printf("\n----- arduino_newarray[2] (with constructor parameters)\n");
-  auto ana2cp = arduino_newarray(SomeClass, 2, "param1");
-  Serial.printf("@:%p s=%zd s(2)=%zd\n", ana2cp, sizeof(SomeClass), sizeof(SomeClass[2]));
-  Serial.printf("0: %p\n", &ana2cp[0]);
-  Serial.printf("1: %p\n", &ana2cp[1]);
-  delete [] ana2cp;
-
-  Serial.printf("\n----- arduino_newarray[100000]\n");
-  auto anaX = arduino_newarray(SomeClass, 100000);
-  Serial.printf("@:%p\n", anaX);
-
-  // standard c++ api for new and new[]
-
-  Serial.printf("\n----- new\n");
-  auto sn = new SomeClass;
-  delete sn;
-
-  Serial.printf("\n----- new with oom: (abort() with option 'Exceptions: Disabled (new can abort)'\n");
-  auto snoom = new oom;
-  Serial.printf("nullptr: %p\n", snoom);
-  delete snoom;
-
-  Serial.printf("\n----- new[2]\n");
-  auto sna2 = new SomeClass[2];
-  Serial.printf("@:%p s=%zd s(2)=%zd\n", sna2, sizeof(SomeClass), sizeof(SomeClass[2]));
-  Serial.printf("0: %p\n", &sna2[0]);
-  Serial.printf("1: %p\n", &sna2[1]);
-  delete [] sna2;
-
-  Serial.printf("\n----- new[10000] (badly fails with 'Exceptions: Legacy' or '...Disabled'\n");
-  auto snaX = new SomeClass[100000];
-  Serial.printf("@:%p\n", snaX);
-}
-
-void loop() {
-}
-
-//////////////////////////////
-/*
-
-  Result with:
-  Exceptions: Legacy(new can return nullptr)
-
-  //////////////////////////////
-
-  arduino_new benefits
-
-  ----- arduino_new:
-  SomeClass@0x3fff1864()()
-  ~ SomeClass @0x3fff1864
-
-  ----- arduino_new with oom:
-  nullptr: 0
-
-  ----- arduino_new with constructor parameters:
-  SomeClass@0x3fff1864(param1)(param2)
-  ~ SomeClass @0x3fff1864
-
-  ----- arduino_newarray[2]
-  SomeClass@0x3fff1868()()
-  SomeClass@0x3fff1869()()
-  @: 0x3fff1868 s = 1 s(2) = 2
-  0: 0x3fff1868
-  1: 0x3fff1869
-  ~ SomeClass @0x3fff1869
-  ~ SomeClass @0x3fff1868
-
-  ----- arduino_newarray[2](with constructor parameters)
-  SomeClass@0x3fff1868(param1)()
-  SomeClass@0x3fff1869(param1)()
-  @: 0x3fff1868 s = 1 s(2) = 2
-  0: 0x3fff1868
-  1: 0x3fff1869
-  ~ SomeClass @0x3fff1869
-  ~ SomeClass @0x3fff1868
-
-  ----- arduino_newarray[100000]
-  @: 0
-
-  ----- new
-  SomeClass@0x3fff1864()()
-  ~ SomeClass @0x3fff1864
-
-  ----- new with oom: (abort() with option 'Exceptions: Disabled (new can abort)'
-  this constructor should not be called
-  nullptr: 0
-
-  ----- new[2]
-  SomeClass@0x3fff1868()()
-  SomeClass@0x3fff1869()()
-  @:0x3fff1868 s = 1 s(2) = 2
-  0: 0x3fff1868
-  1: 0x3fff1869
-  ~ SomeClass @0x3fff1869
-  ~ SomeClass @0x3fff1868
-
-  ----- new[10000](badly fails with 'Exceptions: Legacy' or '...Disabled'
-
-  Exception(29):
-  epc1 = 0x402013de epc2 = 0x00000000 epc3 = 0x00000000 excvaddr = 0x00000000 depc = 0x00000000
-
-  >>> stack >>>
-  ...
-
-*/
-/////////////////////////////


add the software power off example

add the software power off example

--- examples/Basics/PowerOFF/PowerOFF.ino
+++ examples/Basics/PowerOFF/PowerOFF.ino
@@ -18,7 +18,6 @@
 void loop() {

   if(M5.BtnA.wasPressed()) {
-
     M5.powerOFF();
   }