Delete OTTO_ultrasound.ino

Delete OTTO_ultrasound.ino

--- OTTO_ultrasound.ino
+++ OTTO_ultrasound.ino
@@ -1,831 +0,0 @@
-//----------------------------------------------------------------
-//-- Zowi basic firmware v2 adapted to Otto
-//-- (c) BQ. Released under a GPL licencse
-//-- 04 December 2015
-//-- Authors:  Anita de Prado: ana.deprado@bq.com
-//--           Jose Alberca:   jose.alberca@bq.com
-//--           Javier Isabel:  javier.isabel@bq.com
-//--           Juan Gonzalez (obijuan): juan.gonzalez@bq.com
-//--           Irene Sanz : irene.sanz@bq.com
-//-----------------------------------------------------------------
-//-- Experiment with all the features that Otto has thanks to Zowi!
-//-----------------------------------------------------------------
-
-#include <Servo.h>
-#include <Oscillator.h>
-#include <EEPROM.h>
-#include <BatReader.h>
-#include <US.h>
-#include <LedMatrix.h>
-#include <EnableInterrupt.h>
-#include <OttoSerialCommand.h>
-OttoSerialCommand SCmd;  //The SerialCommand object
-//-- Otto Library
-#include <Otto.h>
-Otto Otto;  //This is Otto!
-//---------------------------------------------------------
-//-- First step: Configure the pins where the servos are attached
-/*
-         ---------------
-        |     O   O     |
-        |---------------|
-YR 3==> |               | <== YL 2
-         ---------------
-            ||     ||
-            ||     ||
-RR 5==>   -----   ------  <== RL 4
-         |-----   ------|
-*/
-
-  #define PIN_YL 2 //servo[0]
-  #define PIN_YR 3 //servo[1]
-  #define PIN_RL 4 //servo[2]
-  #define PIN_RR 5 //servo[3]
-
-//---Otto Buttons
-#define PIN_SecondButton 6
-#define PIN_ThirdButton 7
-
-///////////////////////////////////////////////////////////////////
-//-- Global Variables -------------------------------------------//
-///////////////////////////////////////////////////////////////////
-
-const char programID[]="Otto_todo"; //Each program will have a ID
-
-const char name_fac='$'; //Factory name
-const char name_fir='#'; //First name
-
-//-- Movement parameters
-int T=1000;              //Initial duration of movement
-int moveId=0;            //Number of movement
-int moveSize=15;         //Asociated with the height of some movements
-
-//---------------------------------------------------------
-//-- Otto has 5 modes:
-//--    * MODE = 0: Otto is awaiting
-//--    * MODE = 1: Dancing mode!
-//--    * MODE = 2: Obstacle detector mode
-//--    * MODE = 3: Noise detector mode
-//--    * MODE = 4: OttoPAD or any Teleoperation mode (listening SerialPort).
-//---------------------------------------------------------
-volatile int MODE=0; //State of Otto in the principal state machine.
-
-volatile bool buttonPushed=false;  //Variable to remember when a button has been pushed
-volatile bool buttonAPushed=false; //Variable to remember when A button has been pushed
-volatile bool buttonBPushed=false; //Variable to remember when B button has been pushed
-
-unsigned long previousMillis=0;
-
-int randomDance=0;
-int randomSteps=0;
-
-bool obstacleDetected = false;
-
-///////////////////////////////////////////////////////////////////
-//-- Setup ------------------------------------------------------//
-///////////////////////////////////////////////////////////////////
-void setup(){
-
-  //Serial communication initialization
-  Serial.begin(115200);
-
-  pinMode(PIN_SecondButton,INPUT);
-  pinMode(PIN_ThirdButton,INPUT);
-
-  //Set the servo pins
-  Otto.init(PIN_YL,PIN_YR,PIN_RL,PIN_RR,true);
-
-  //Uncomment this to set the servo trims manually and save on EEPROM
-    //Otto.setTrims(TRIM_YL, TRIM_YR, TRIM_RL, TRIM_RR);
-    //Otto.saveTrimsOnEEPROM(); //Uncomment this only for one upload when you finaly set the trims.
-
-  //Set a random seed
-  randomSeed(analogRead(A6));
-
-  //Interrumptions
-  enableInterrupt(PIN_SecondButton, secondButtonPushed, RISING);
-  enableInterrupt(PIN_ThirdButton, thirdButtonPushed, RISING);
-
-  //Setup callbacks for SerialCommand commands
-  SCmd.addCommand("S", receiveStop);      //  sendAck & sendFinalAck
-  SCmd.addCommand("L", receiveLED);       //  sendAck & sendFinalAck
-  SCmd.addCommand("T", recieveBuzzer);    //  sendAck & sendFinalAck
-  SCmd.addCommand("M", receiveMovement);  //  sendAck & sendFinalAck
-  SCmd.addCommand("H", receiveGesture);   //  sendAck & sendFinalAck
-  SCmd.addCommand("K", receiveSing);      //  sendAck & sendFinalAck
-  SCmd.addCommand("C", receiveTrims);     //  sendAck & sendFinalAck
-  SCmd.addCommand("G", receiveServo);     //  sendAck & sendFinalAck
-  SCmd.addCommand("D", requestDistance);
-  SCmd.addCommand("N", requestNoise);
-  SCmd.addCommand("B", requestBattery);
-  SCmd.addCommand("I", requestProgramId);
-  SCmd.addDefaultHandler(receiveStop);
-
-  //Otto wake up!
-  Otto.sing(S_connection);
-  Otto.home();
-
-  delay(50);
-  requestBattery();
-
-  //Checking battery
-  OttoLowBatteryAlarm();
-
- // Animation Uuuuuh - A little moment of initial surprise
- //-----
-  for(int i=0; i<2; i++){
-      for (int i=0;i<8;i++){
-        if(buttonPushed){break;}
-        Otto.putAnimationMouth(littleUuh,i);
-        delay(150);
-      }
-  }
- //-----
-
-
-  //Smile for a happy Otto :)
-  if(!buttonPushed){
-    Otto.putMouth(smile);
-    Otto.sing(S_happy);
-    delay(200);
-  }
-
-
-  //If Otto's name is '#' means that Otto hasn't been baptized
-  //In this case, Otto does a longer greeting
-  //5 = EEPROM address that contains first name character
-  if (EEPROM.read(5)==name_fir){
-
-    if(!buttonPushed){
-        Otto.jump(1,700);
-        delay(200);
-    }
-
-    if(!buttonPushed){
-        Otto.shakeLeg(1,T,1);
-    }
-
-    if(!buttonPushed){
-        Otto.putMouth(smallSurprise);
-        Otto.swing(2,800,20);
-        Otto.home();
-    }
-  }
-
-
-  if(!buttonPushed){
-    Otto.putMouth(happyOpen);
-  }
-
-  previousMillis = millis();
-
-}
-
-///////////////////////////////////////////////////////////////////
-//-- Principal Loop ---------------------------------------------//
-///////////////////////////////////////////////////////////////////
-void loop() {
-
-      //-- MODE 2 - Obstacle detector mode
-       if(obstacleDetected){
-              Otto.jump(1,700);
-              Otto.sing(S_superHappy);
-              Otto.walk(1,1300,-1);
-
-
-            delay(100);
-            obstacleDetector();
-            delay(100);
-        }else{
-            Otto.home();
-            obstacleDetector();
-        }
-  }
-
-///////////////////////////////////////////////////////////////////
-//-- Functions --------------------------------------------------//
-///////////////////////////////////////////////////////////////////
-
-//-- Function executed when second button is pushed
-void secondButtonPushed(){
-
-    buttonAPushed=true;
-
-    if(!buttonPushed){
-        buttonPushed=true;
-        Otto.putMouth(smallSurprise);
-    }
-}
-
-//-- Function executed when third button is pushed
-void thirdButtonPushed(){
-
-    buttonBPushed=true;
-
-    if(!buttonPushed){
-        buttonPushed=true;
-        Otto.putMouth(smallSurprise);
-    }
-}
-
-
-//-- Function to read distance sensor & to actualize obstacleDetected variable
-void obstacleDetector(){
-
-   int distance = Otto.getDistance();
-
-        if(distance<15){
-          obstacleDetected = true;
-        }else{
-          obstacleDetected = false;
-        }
-}
-
-
-//-- Function to receive Stop command.
-void receiveStop(){
-
-    sendAck();
-    Otto.home();
-    sendFinalAck();
-
-}
-
-
-//-- Function to receive LED commands
-void receiveLED(){
-
-    //sendAck & stop if necessary
-    sendAck();
-    Otto.home();
-
-    //Examples of receiveLED Bluetooth commands
-    //L 000000001000010100100011000000000
-    //L 001111111111111111111111111111111 (todos los LED encendidos)
-    unsigned long int matrix;
-    char *arg;
-    char *endstr;
-    arg=SCmd.next();
-    //Serial.println (arg);
-    if (arg != NULL) {
-      matrix=strtoul(arg,&endstr,2);    // Converts a char string to unsigned long integer
-      Otto.putMouth(matrix,false);
-    }else{
-      Otto.putMouth(xMouth);
-      delay(2000);
-      Otto.clearMouth();
-    }
-
-    sendFinalAck();
-
-}
-
-
-//-- Function to receive buzzer commands
-void recieveBuzzer(){
-
-    //sendAck & stop if necessary
-    sendAck();
-    Otto.home();
-
-    bool error = false;
-    int frec;
-    int duration;
-    char *arg;
-
-    arg = SCmd.next();
-    if (arg != NULL) { frec=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    arg = SCmd.next();
-    if (arg != NULL) { duration=atoi(arg); } // Converts a char string to an integer
-    else {error=true;}
-
-    if(error==true){
-
-      Otto.putMouth(xMouth);
-      delay(2000);
-      Otto.clearMouth();
-
-    }else{
-
-      Otto._tone(frec, duration, 1);
-    }
-
-    sendFinalAck();
-
-}
-
-
-//-- Function to receive TRims commands
-void receiveTrims(){
-
-    //sendAck & stop if necessary
-    sendAck();
-    Otto.home();
-
-    int trim_YL,trim_YR,trim_RL,trim_RR;
-
-    //Definition of Servo Bluetooth command
-    //C trim_YL trim_YR trim_RL trim_RR
-    //Examples of receiveTrims Bluetooth commands
-    //C 20 0 -8 3
-    bool error = false;
-    char *arg;
-    arg=SCmd.next();
-    if (arg != NULL) { trim_YL=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    arg = SCmd.next();
-    if (arg != NULL) { trim_YR=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    arg = SCmd.next();
-    if (arg != NULL) { trim_RL=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    arg = SCmd.next();
-    if (arg != NULL) { trim_RR=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    if(error==true){
-
-      Otto.putMouth(xMouth);
-      delay(2000);
-      Otto.clearMouth();
-
-    }else{ //Save it on EEPROM
-      Otto.setTrims(trim_YL, trim_YR, trim_RL, trim_RR);
-      Otto.saveTrimsOnEEPROM(); //Uncomment this only for one upload when you finaly set the trims.
-    }
-
-    sendFinalAck();
-
-}
-
-
-//-- Function to receive Servo commands
-void receiveServo(){
-
-    sendAck();
-    moveId = 30;
-
-    //Definition of Servo Bluetooth command
-    //G  servo_YL servo_YR servo_RL servo_RR
-    //Example of receiveServo Bluetooth commands
-    //G 90 85 96 78
-    bool error = false;
-    char *arg;
-    int servo_YL,servo_YR,servo_RL,servo_RR;
-
-    arg=SCmd.next();
-    if (arg != NULL) { servo_YL=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    arg = SCmd.next();
-    if (arg != NULL) { servo_YR=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    arg = SCmd.next();
-    if (arg != NULL) { servo_RL=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    arg = SCmd.next();
-    if (arg != NULL) { servo_RR=atoi(arg); }    // Converts a char string to an integer
-    else {error=true;}
-
-    if(error==true){
-
-      Otto.putMouth(xMouth);
-      delay(2000);
-      Otto.clearMouth();
-
-    }else{ //Update Servo:
-
-      int servoPos[4]={servo_YL, servo_YR, servo_RL, servo_RR};
-      Otto._moveServos(200, servoPos);   //Move 200ms
-
-    }
-
-    sendFinalAck();
-
-}
-
-
-//-- Function to receive movement commands
-void receiveMovement(){
-
-    sendAck();
-
-    if (Otto.getRestState()==true){
-        Otto.setRestState(false);
-    }
-
-    //Definition of Movement Bluetooth commands
-    //M  MoveID  T   MoveSize
-    char *arg;
-    arg = SCmd.next();
-    if (arg != NULL) {moveId=atoi(arg);}
-    else{
-      Otto.putMouth(xMouth);
-      delay(2000);
-      Otto.clearMouth();
-      moveId=0; //stop
-    }
-
-    arg = SCmd.next();
-    if (arg != NULL) {T=atoi(arg);}
-    else{
-      T=1000;
-    }
-
-    arg = SCmd.next();
-    if (arg != NULL) {moveSize=atoi(arg);}
-    else{
-      moveSize =15;
-    }
-}
-
-
-//-- Function to execute the right movement according the movement command received.
-void move(int moveId){
-
-  bool manualMode = false;
-
-  switch (moveId) {
-    case 0:
-      Otto.home();
-      break;
-    case 1: //M 1 1000
-      Otto.walk(1,T,1);
-      break;
-    case 2: //M 2 1000
-      Otto.walk(1,T,-1);
-      break;
-    case 3: //M 3 1000
-      Otto.turn(1,T,1);
-      break;
-    case 4: //M 4 1000
-      Otto.turn(1,T,-1);
-      break;
-    case 5: //M 5 1000 30
-      Otto.updown(1,T,moveSize);
-      break;
-    case 6: //M 6 1000 30
-      Otto.moonwalker(1,T,moveSize,1);
-      break;
-    case 7: //M 7 1000 30
-      Otto.moonwalker(1,T,moveSize,-1);
-      break;
-    case 8: //M 8 1000 30
-      Otto.swing(1,T,moveSize);
-      break;
-    case 9: //M 9 1000 30
-      Otto.crusaito(1,T,moveSize,1);
-      break;
-    case 10: //M 10 1000 30
-      Otto.crusaito(1,T,moveSize,-1);
-      break;
-    case 11: //M 11 1000
-      Otto.jump(1,T);
-      break;
-    case 12: //M 12 1000 30
-      Otto.flapping(1,T,moveSize,1);
-      break;
-    case 13: //M 13 1000 30
-      Otto.flapping(1,T,moveSize,-1);
-      break;
-    case 14: //M 14 1000 20
-      Otto.tiptoeSwing(1,T,moveSize);
-      break;
-    case 15: //M 15 500
-      Otto.bend(1,T,1);
-      break;
-    case 16: //M 16 500
-      Otto.bend(1,T,-1);
-      break;
-    case 17: //M 17 500
-      Otto.shakeLeg(1,T,1);
-      break;
-    case 18: //M 18 500
-      Otto.shakeLeg(1,T,-1);
-      break;
-    case 19: //M 19 500 20
-      Otto.jitter(1,T,moveSize);
-      break;
-    case 20: //M 20 500 15
-      Otto.ascendingTurn(1,T,moveSize);
-      break;
-    default:
-        manualMode = true;
-      break;
-  }
-
-  if(!manualMode){
-    sendFinalAck();
-  }
-
-}
-
-
-//-- Function to receive gesture commands
-void receiveGesture(){
-
-    //sendAck & stop if necessary
-    sendAck();
-    Otto.home();
-
-    //Definition of Gesture Bluetooth commands
-    //H  GestureID
-    int gesture = 0;
-    char *arg;
-    arg = SCmd.next();
-    if (arg != NULL) {gesture=atoi(arg);}
-    else
-    {
-      Otto.putMouth(xMouth);
-      delay(2000);
-      Otto.clearMouth();
-    }
-
-    switch (gesture) {
-      case 1: //H 1
-        Otto.playGesture(OttoHappy);
-        break;
-      case 2: //H 2
-        Otto.playGesture(OttoSuperHappy);
-        break;
-      case 3: //H 3
-        Otto.playGesture(OttoSad);
-        break;
-      case 4: //H 4
-        Otto.playGesture(OttoSleeping);
-        break;
-      case 5: //H 5
-        Otto.playGesture(OttoFart);
-        break;
-      case 6: //H 6
-        Otto.playGesture(OttoConfused);
-        break;
-      case 7: //H 7
-        Otto.playGesture(OttoLove);
-        break;
-      case 8: //H 8
-        Otto.playGesture(OttoAngry);
-        break;
-      case 9: //H 9
-        Otto.playGesture(OttoFretful);
-        break;
-      case 10: //H 10
-        Otto.playGesture(OttoMagic);
-        break;
-      case 11: //H 11
-        Otto.playGesture(OttoWave);
-        break;
-      case 12: //H 12
-        Otto.playGesture(OttoVictory);
-        break;
-      case 13: //H 13
-        Otto.playGesture(OttoFail);
-        break;
-      default:
-        break;
-    }
-
-    sendFinalAck();
-}
-
-//-- Function to receive sing commands
-void receiveSing(){
-
-    //sendAck & stop if necessary
-    sendAck();
-    Otto.home();
-
-    //Definition of Sing Bluetooth commands
-    //K  SingID
-    int sing = 0;
-    char *arg;
-    arg = SCmd.next();
-    if (arg != NULL) {sing=atoi(arg);}
-    else
-    {
-      Otto.putMouth(xMouth);
-      delay(2000);
-      Otto.clearMouth();
-    }
-
-    switch (sing) {
-      case 1: //K 1
-        Otto.sing(S_connection);
-        break;
-      case 2: //K 2
-        Otto.sing(S_disconnection);
-        break;
-      case 3: //K 3
-        Otto.sing(S_surprise);
-        break;
-      case 4: //K 4
-        Otto.sing(S_OhOoh);
-        break;
-      case 5: //K 5
-        Otto.sing(S_OhOoh2);
-        break;
-      case 6: //K 6
-        Otto.sing(S_cuddly);
-        break;
-      case 7: //K 7
-        Otto.sing(S_sleeping);
-        break;
-      case 8: //K 8
-        Otto.sing(S_happy);
-        break;
-      case 9: //K 9
-        Otto.sing(S_superHappy);
-        break;
-      case 10: //K 10
-        Otto.sing(S_happy_short);
-        break;
-      case 11: //K 11
-        Otto.sing(S_sad);
-        break;
-      case 12: //K 12
-        Otto.sing(S_confused);
-        break;
-      case 13: //K 13
-        Otto.sing(S_fart1);
-        break;
-      case 14: //K 14
-        Otto.sing(S_fart2);
-        break;
-      case 15: //K 15
-        Otto.sing(S_fart3);
-        break;
-      case 16: //K 16
-        Otto.sing(S_mode1);
-        break;
-      case 17: //K 17
-        Otto.sing(S_mode2);
-        break;
-      case 18: //K 18
-        Otto.sing(S_mode3);
-        break;
-      case 19: //K 19
-        Otto.sing(S_buttonPushed);
-        break;
-      default:
-        break;
-    }
-
-    sendFinalAck();
-}
-
-//-- Function to send ultrasonic sensor measure (distance in "cm")
-void requestDistance(){
-
-    Otto.home();  //stop if necessary
-
-    int distance = Otto.getDistance();
-    Serial.print(F("&&"));
-    Serial.print(F("D "));
-    Serial.print(distance);
-    Serial.println(F("%%"));
-    Serial.flush();
-}
-
-
-//-- Function to send noise sensor measure
-void requestNoise(){
-
-    Otto.home();  //stop if necessary
-
-    int microphone= Otto.getNoise(); //analogRead(PIN_NoiseSensor);
-    Serial.print(F("&&"));
-    Serial.print(F("N "));
-    Serial.print(microphone);
-    Serial.println(F("%%"));
-    Serial.flush();
-}
-
-
-//-- Function to send battery voltage percent
-void requestBattery(){
-
-    Otto.home();  //stop if necessary
-
-    //The first read of the batery is often a wrong reading, so we will discard this value.
-    double batteryLevel = Otto.getBatteryLevel();
-
-    Serial.print(F("&&"));
-    Serial.print(F("B "));
-    Serial.print(batteryLevel);
-    Serial.println(F("%%"));
-    Serial.flush();
-}
-
-
-//-- Function to send program ID
-void requestProgramId(){
-
-    Otto.home();   //stop if necessary
-
-    Serial.print(F("&&"));
-    Serial.print(F("I "));
-    Serial.print(programID);
-    Serial.println(F("%%"));
-    Serial.flush();
-}
-
-
-//-- Function to send Ack comand (A)
-void sendAck(){
-
-  delay(30);
-
-  Serial.print(F("&&"));
-  Serial.print(F("A"));
-  Serial.println(F("%%"));
-  Serial.flush();
-}
-
-
-//-- Function to send final Ack comand (F)
-void sendFinalAck(){
-
-  delay(30);
-
-  Serial.print(F("&&"));
-  Serial.print(F("F"));
-  Serial.println(F("%%"));
-  Serial.flush();
-}
-
-
-
-//-- Functions with animatics
-//--------------------------------------------------------
-
-void OttoLowBatteryAlarm(){
-
-    double batteryLevel = Otto.getBatteryLevel();
-
-    if(batteryLevel<45){
-
-      while(!buttonPushed){
-
-          Otto.putMouth(thunder);
-          Otto.bendTones (880, 2000, 1.04, 8, 3);  //A5 = 880
-
-          delay(30);
-
-          Otto.bendTones (2000, 880, 1.02, 8, 3);  //A5 = 880
-          Otto.clearMouth();
-          delay(500);
-      }
-    }
-}
-
-void OttoSleeping_withInterrupts(){
-
-  int bedPos_0[4]={100, 80, 60, 120};
-
-  if(!buttonPushed){
-    Otto._moveServos(700, bedPos_0);
-  }
-
-  for(int i=0; i<4;i++){
-
-    if(buttonPushed){break;}
-      Otto.putAnimationMouth(dreamMouth,0);
-      Otto.bendTones (100, 200, 1.04, 10, 10);
-
-    if(buttonPushed){break;}
-      Otto.putAnimationMouth(dreamMouth,1);
-      Otto.bendTones (200, 300, 1.04, 10, 10);
-
-    if(buttonPushed){break;}
-      Otto.putAnimationMouth(dreamMouth,2);
-      Otto.bendTones (300, 500, 1.04, 10, 10);
-
-    delay(500);
-
-    if(buttonPushed){break;}
-      Otto.putAnimationMouth(dreamMouth,1);
-      Otto.bendTones (400, 250, 1.04, 10, 1);
-
-    if(buttonPushed){break;}
-      Otto.putAnimationMouth(dreamMouth,0);
-      Otto.bendTones (250, 100, 1.04, 10, 1);
-
-    delay(500);
-  }
-
-  if(!buttonPushed){
-    Otto.putMouth(lineMouth);
-    Otto.sing(S_cuddly);
-  }
-
-  Otto.home();
-  if(!buttonPushed){Otto.putMouth(happyOpen);}
-
-}


Add all devices

Add all devices

--- Photon/IoTlib/examples/everything/everything.ino
+++ Photon/IoTlib/examples/everything/everything.ino
@@ -1,17 +1,99 @@
-// Example usage for IoT library by Ron Lisle.
+/*******************************************************
+Everything ParticleIoT Example
+
+This example contains one of each IoT device type
+supported by ParticleIoT. This include the following:
+
+ * 4 LED Lights (Red, Green)
+ * 4 Switches   (left, right)
+ * DHT11 Temperature & Humidity sensor
+ * HC-SR04 Ultrasonic Proximity Sensor
+ * Photoresistor light level sensor
+ * Servo Motor   (TODO:)
+ * Stepper Motor (TODO:)
+
+http://www.github.com/rlisle/ParticleIoT
+
+Written by Ron Lisle
+
+BSD license, check LICENSE for more information.
+All text above must be included in any redistribution.
+
+Changelog:
+2017-03-07: Initial creation
+********************************************************/

 #include <IoT.h>

-// Include the IoT functionality in your sketch.
+/*****************/
+/*** CONSTANTS ***/
+/*****************/
+// DHT11 or DHT22 Humidity & Temperature Sensor
+#define kDhtType        DHT22
+#define kDhtPin         A2      // pin 10
+
+// HD-SR04 Ultrasonic Proximity Sensor
+#define kTriggerPin     A1      // pin 11
+#define kEchoPin        A0      // pin 12
+
+// Display LEDs
+#define kLed1Pin        A3      // pin 9
+#define kLed2Pin        RX      // pin 4
+#define kLed3Pin        TX      // pin 3
+#define kLed4Pin        WKP     // pin 5
+
+// Switch inputs
+#define kSwitch1Pin     D4      // pin 17
+#define kSwitch2Pin     D5      // pin 18
+#define kSwitch3Pin     D6      // pin 19
+#define kSwitch4Pin     D7      // pin 20
+
+// Photoresistor ambient light level sensor
+#define kPhotoPin       A4      // pin 8
+
+// Servo Motor
+//TBD
+
+// Stepper motor
+#define kStepperPin1    D0      // pin 13
+#define kStepperPin2    D1      // pin 14
+#define kStepperPin3    D2      // pin 15
+#define kStepperPin4    D3      // pin 16
+
+/*****************/
+/*** VARIABLES ***/
+/*****************/
 IoT *iot;

+
+/*************/
+/*** SETUP ***/
+/*************/
 void setup() {
     iot = IoT::getInstance();
     iot->setControllerName("lislerv");
     iot->setPublishName("RonTest");
     iot->begin();
+
+    iot->addLight(kLed2Pin, kMicrowaveSpots);   // RX
+    iot->addLight(kLed3Pin, kMicrowaveCabinet); // TX
+
+    iot->addSwitch(kSwitch4Pin,"computer"); // Right-most switch
+    iot->addSwitch(kSwitch3Pin,"booth");
+    iot->addSwitch(kSwitch2Pin,"downstairs");
+    iot->addSwitch(kSwitch1Pin,"outside");    // Left-most switch
+
+    iot->monitorPresence(kTriggerPin, kEchoPin, 3, 36, "kitchen");  // A1, A0
+    iot->monitorTemperature(kDhtPin, kDhtType, "kitchen", 5000);    // A2
+
+    iot->exposeControllers();
+    iot->exposeActivities();
 }

+
+/************/
+/*** LOOP ***/
+/************/
 void loop() {
     long currentMillis = millis();
     iot->loop(currentMillis);


Update FirebaseStream_ESP8266.ino

Update FirebaseStream_ESP8266.ino

OLED_RESET should be at "3" otherwise example does not work. Pulled this directly from adafruit's own example: https://learn.adafruit.com/digital-display-badge/code

--- examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
+++ examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
@@ -22,7 +22,7 @@
 #include <Adafruit_SSD1306.h>
 #include <ArduinoJson.h>

-#define OLED_RESET 10
+#define OLED_RESET 3
 Adafruit_SSD1306 display(OLED_RESET);

 Firebase fbase("publicdata-cryptocurrency.firebaseio.com");


pushbutton interrupt sample updated

pushbutton interrupt sample updated

--- code/arduino/sample/sketch_pushbutton/sketch_pushbutton.ino
+++ code/arduino/sample/sketch_pushbutton/sketch_pushbutton.ino
@@ -1 +1,38 @@
+/*
+ * pushbutton sample with a debouncer circuit
+ * and interrupts to write *click* to serial when
+ * pushbutton is pressed.
+ *
+ * Arduino UNO has two external interrupts
+ * int.0 on pin2 and int.1 on pin3
+ *
+ *
+ *
+ */

+int ledPin = 13;
+volatile int state = LOW;
+volatile int counter = 0 ;
+
+void setup()
+{
+    pinMode(ledPin, OUTPUT);
+    // watch pin2
+    attachInterrupt(0,isr_pin2,RISING);
+}
+
+void loop()
+{
+    digitalWrite(ledPin, state);
+    delay(1000);
+
+}
+
+void isr_pin2()
+{
+    state = !state ;
+    counter++ ;
+    Serial.print("pin2 interrupted: ");
+    Serial.print("counter: ");
+    Serial.println(counter);
+}


LED strip added

LED strip added

--- module/module.ino
+++ module/module.ino
@@ -1,10 +1,14 @@
 #include <SoftwareSerial.h>
+#include <LPD8806.h>
 #include "RFID.h"

 #define MODULE

 SoftwareSerial WIFI(WIFI_RX, WIFI_TX);
 SoftwareSerial RFID(RFID_RX, RFID_TX);
+LPD8806 LED = LPD8806(4, 11, 12);
+
+int j = 0;

 void setup() {
 	// Set up pins
@@ -18,6 +22,7 @@

 	// Start with support systems off
 	digitalWrite(supportPin, LOW);
+	LED.begin();

 	// Set up serial communication
 	Serial.begin(monitorBaud);
@@ -50,6 +55,7 @@
 		sendCommand(CMD_GET_SNR, blockID, machineID, NULL);
 		delay(waitforSerialResponse);
 		isValidResponse = getResponse(readData);
+		rainbowCycle();
 	}
 	// ----------------------------------------------------------------------
 	// RFID tag detected, get user ID and authorization for this machine
@@ -68,6 +74,7 @@
 	// -----------------------------------------------------------------------
 	// Analyze response packet and data
 	if (!isValidResponse) {
+		red();
 		playDeath();
 		getStringFromMem(readUnsuccessful);
 	}
@@ -77,11 +84,13 @@
 		existingTime = getTime(readData, numTimeBytes, timeOffset);
 		// Check if the user has taken the class, skip if staff member
 		if ( !isAuthorized && !isStaff ) {
+			red();
 			playDeath();
 			getStringFromMem(notAuthorized);
 		}
 		// Check if the user has reached the 60 min quota, skip if staff member
 		else if ( (existingTime >= quota) && !isStaff ) {
+			red();
 			playDeath();
 			getStringFromMem(quotaMet);
 		}
@@ -89,6 +98,7 @@
 		// --------------------------------------------------------------------
 		else {
 			// Sound and text feedback
+			green();
 			playCoinSound();
 			getStringFromMem(displayUsedTime);
 			Serial.println(existingTime);
@@ -267,6 +277,57 @@
 	}
 }

+void red() {
+	LED.setPixelColor(0, LED.Color(68, 0, 5));
+	LED.setPixelColor(1, LED.Color(127, 16, 25));
+	LED.setPixelColor(2, LED.Color(127, 0, 0));
+	LED.setPixelColor(3, LED.Color(84, 20, 15));
+	LED.show();
+}
+
+void rainbowCycle() {
+	j == 384 * 5 ? j = 0 : j++;
+	for (int i = 0; i < LED.numPixels(); i++) {
+		// tricky math! we use each pixel as a fraction of the full 384-color wheel
+		// (thats the i / strip.numPixels() part)
+		// Then add in j which makes the colors go around per pixel
+		// the % 384 is to make the wheel cycle around
+		LED.setPixelColor(i, Wheel( ((i * 384 / LED.numPixels()) + j) % 384) );
+	}
+	LED.show();   // write all the pixels out
+}
+
+void green() {
+	LED.setPixelColor(0, LED.Color(5, 0, 68));
+	LED.setPixelColor(1, LED.Color(25, 16, 127));
+	LED.setPixelColor(2, LED.Color(10, 0, 127));
+	LED.setPixelColor(3, LED.Color(20, 14, 84));
+	LED.show();
+}
+
+uint32_t Wheel(uint16_t WheelPos)
+{
+  byte r, g, b;
+  switch(WheelPos / 128)
+  {
+    case 0:
+      r = 127 - WheelPos % 128;   //Red down
+      g = WheelPos % 128;      // Green up
+      b = 0;                  //blue off
+      break;
+    case 1:
+      g = 127 - WheelPos % 128;  //green down
+      b = WheelPos % 128;      //blue up
+      r = 0;                  //red off
+      break;
+    case 2:
+      b = 127 - WheelPos % 128;  //blue down
+      r = WheelPos % 128;      //red up
+      g = 0;                  //green off
+      break;
+  }
+  return(LED.Color(r,g,b));
+}
 void playCoinSound() {
 	int coinNotes[] = { 988, 1319 };
 	int coinNoteDurations[] = { 125, 400 };
@@ -306,4 +367,4 @@
 			digitalWrite(supportPin, LOW);
 		}
 	}
-}
+}


Moved to this folder.

Moved to this folder.


Fixed the copyright date for sketch.

Fixed the copyright date for sketch.

--- src/LearningRemote.ino
+++ src/LearningRemote.ino
@@ -1,7 +1,7 @@
 // -*- c -*-
 // LearningRemote Arduino sketch
 //
-// Copyright (c) 2013 Dave Sieh
+// Copyright (c) 2013,2014 Dave Sieh
 // See LICENSE.txt for details.

 #include <IRremote.h>       // IR remote control library


Remove compiler warning.

Remove compiler warning.

--- examples/Benchmarks/CosaBenchmarkPins/CosaBenchmarkPins.ino
+++ examples/Benchmarks/CosaBenchmarkPins/CosaBenchmarkPins.ino
@@ -494,6 +494,7 @@

   MEASURE_US("var = analogPin") {
     uint16_t var = analogPin;
+    UNUSED(var);
   }

   MEASURE_US("AnalogPin::sample(A0)") {


SetTime: adjusted some observations in comments


Update ADXL362_SimpleRead.ino

Update ADXL362_SimpleRead.ino

--- firmware/examples/ADXL362_SimpleRead/ADXL362_SimpleRead.ino
+++ firmware/examples/ADXL362_SimpleRead/ADXL362_SimpleRead.ino
@@ -20,6 +20,7 @@

 */

+#include "application.h"
 #include "adxl362/adxl362.h"

 ADXL362 xl;


finalizado PWM, resolves #6

finalizado PWM, resolves #6

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -17,9 +17,9 @@
     const byte pot_solda_horizontal = A1; // Potenciômetro da Solda Vertical
     const byte pot_solda_datador = A2; // Potenciômetro da Solda Vertical
   // Saídas
-    const byte led_geral = 23; // Saída Geral
-    const byte led_dosador = 25; // Saída do Dosador
-    const byte led_datador = 27; // Saída do Datador
+    const byte geral = 23; // Saída Geral
+    const byte dosador = 25; // Saída do Dosador
+    const byte datador = 27; // Saída do Datador
     const byte solda_vertical = 33; // Saída da Solda Vertical
     const byte solda_horizontal = 35; // Saída da Solda Horizontal
     const byte solda_datador = 37; // Saída da Solda do Datador
@@ -86,14 +86,17 @@
   pinMode(sensor_maquina, ModoBotoes);

-  pinMode(led_geral, ModoLeds);
-  pinMode(led_dosador, ModoLeds);
-  pinMode(led_datador, ModoLeds);
+  pinMode(geral, ModoLeds);
+  pinMode(dosador, ModoLeds);
+  pinMode(datador, ModoLeds);

   // Define estado inicial das saídas
-  digitalWrite(led_geral, DESLIGA);
-  digitalWrite(led_dosador, DESLIGA);
-  digitalWrite(led_datador, DESLIGA);
+  digitalWrite(geral, DESLIGA);
+  digitalWrite(dosador, DESLIGA);
+  digitalWrite(datador, DESLIGA);
+  digitalWrite(solda_vertical, DESLIGA);
+  digitalWrite(solda_horizontal, DESLIGA);
+  digitalWrite(solda_datador, DESLIGA);
 }

@@ -110,10 +113,8 @@
   unsigned long inativo = ciclo_PWM - ativo;
   if (millis() > *inicio && millis() <= (*inicio + ativo)){
     liga(saida, nome);
-    // digitalWrite(led, HIGH);
   } else if (millis() > (*inicio + ativo) && millis() < (*inicio + ciclo_PWM)){
     desliga(saida, nome);
-    // digitalWrite(led, LOW);
   } else if (millis() >= (*inicio + ciclo_PWM)) {
     *inicio = millis();
   }
@@ -251,26 +252,26 @@
   dosador_ligado = FALSO;
   datador_ligado = FALSO;

-  desliga(led_geral, NomeGeral);
-  desliga(led_dosador, NomeDosador);
-  desliga(led_datador, NomeDatador);
+  desliga(geral, NomeGeral);
+  desliga(dosador, NomeDosador);
+  desliga(datador, NomeDatador);
 }

 void modoTeste(){
   if (maquina_ligada){
-    liga(led_geral, NomeGeral);
-  } else {
-    desliga(led_geral, NomeGeral);
+    liga(geral, NomeGeral);
+  } else {
+    desliga(geral, NomeGeral);
   }
   if (dosador_ligado){
-    liga(led_dosador, NomeDosador);
-  } else {
-    desliga(led_dosador, NomeDosador);
+    liga(dosador, NomeDosador);
+  } else {
+    desliga(dosador, NomeDosador);
   }
   if (datador_ligado){
-    liga(led_datador, NomeDatador);
-  } else {
-    desliga(led_datador, NomeDatador);
-  }
-}
+    liga(datador, NomeDatador);
+  } else {
+    desliga(datador, NomeDatador);
+  }
+}


add comment

add comment

--- gestureDetection/gestureDetection.ino
+++ gestureDetection/gestureDetection.ino
@@ -74,7 +74,7 @@
   pinMode(7,OUTPUT);
   pinMode(13, OUTPUT);
   digitalWrite(13,LOW);
-  attachInterrupt(0,ISR_interrupt,FALLING);
+  attachInterrupt(0,ISR_interrupt,FALLING); // Used 0 here because digitalPinToInterrupt(2) returns 0
   Serial.begin(9600);
 }
 void loop(){


backed out mac hacks

backed out mac hacks

--- src/resource/Arduino/MRLComm/MRLComm.ino
+++ src/resource/Arduino/MRLComm/MRLComm.ino
@@ -51,97 +51,7 @@

 // Included as a 3rd party arduino library from here: https://github.com/ivanseidel/LinkedList/
 #include "LinkedList.h"
-#include <Servo.h> // mac needs this removed? because it causes error on upload in Mac
 #include "MrlComm.h"
-
-
-#ifndef MrlServo_h
-#define MrlServo_h
-
-#include <Servo.h>
-#include "Device.h"
-#include "MrlMsg.h"
-
-// servo event types
-// ===== published sub-types based on device type begin ===
-#define  SERVO_EVENT_STOPPED          1
-#define  SERVO_EVENT_POSITION_UPDATE  2
-// ===== published sub-types based on device type begin ===
-
-/**
- * Servo Device
- */
-class MrlServo : public Device {
-  private:
-    Servo* servo; // servo pointer - in case our device is a servo
-    int pin;
-    bool isMoving;
-    bool isSweeping;
-    int targetPos;
-    float currentPos;
-    int speed; // servos have a "speed" associated with them that's not part of the base servo driver
-    bool eventsEnabled;
-    float step;
-    int min;
-    int max;
-    unsigned long lastUpdate;
-  public:
-    MrlServo();
-    ~MrlServo();
-    bool deviceAttach(unsigned char config[], int configSize);
-    void attach(int pin);
-    void detach();
-    void update();
-    void publishServoEvent(int eventType);
-    void servoWrite(int position);
-    void servoEventEnabled(int value);
-    void servoWriteMicroseconds(int position);
-    void setSpeed(int speed);
-    void startSweep(int min, int max, int step);
-    void stopSweep();
-};
-
-#endif
-
-
-#ifndef MrlI2cBus_h
-#define MrlI2cBus_h
-
-#include "Device.h"
-#include "MrlMsg.h"
-
-#define WIRE Wire
-#include <Wire.h>
-
-/**
- * I2C bus
- * TODO:KW? don't allow this class to write directly to the global serial port
- * device classes shouldn't have a direct handle to the serial port, rather have
- * a mrlmessage class that it returns.
- * TODO: Mats
- * The I2CBus device represents one I2C bus.
- * It's the SDA (data line) and SCL pins (clock line) that is used to
- * communicate with any device that uses the i2c protocol on that bus.
- * It is NOT a representation of the addressable i2c devices, just the bus
- * On Arduino Uno that's pins A4 and A5, Mega 20 and 21, Leonardo 2 and 3,
- * The pin assignment is defined in Wire.h so it will change to the correct
- * pins at compile time. We don't have to worry here.
- * However some other i2c implementations exist's so that more pins can be used
- * for i2c communication. That is not supported here yet.
- *
- */
-class MrlI2CBus : public Device {
-  private:
-  public:
-    MrlI2CBus();
-    void i2cRead(unsigned char* ioCmd);
-    void i2cWrite(unsigned char* ioCmd);
-    void i2cWriteRead(unsigned char* ioCmd);
-    void update();
-};
-
-#endif
-

 /***********************************************************************


Renamed variables more relevant.

Renamed variables more relevant.

--- tfttask.ino
+++ tfttask.ino
@@ -151,7 +151,7 @@

 static inline __attribute__((always_inline)) void showMenu()
 {
-  static lightStatus_t lastLightStatus;
+  static lightStatus_t displayedLightStatus;

   if ( tftClearScreen )
   {
@@ -164,7 +164,7 @@

     snprintf( versionString.text, sizeof( versionString.text ), sketchVersion );
     button.updateText( versionString );
-    lastLightStatus = lightStatus;
+    displayedLightStatus = lightStatus;
     ledcWrite( TFT_BACKLIGHT_CHANNEL, map( tftBrightness, 0, 100, 0, backlightMaxvalue ) );
     tftClearScreen = false;
   }
@@ -177,10 +177,10 @@
   }

   /* check if light status has changed */
-  if ( lastLightStatus != lightStatus )
+  if ( displayedLightStatus != lightStatus )
   {
     drawMenuButtons();
-    lastLightStatus = lightStatus;
+    displayedLightStatus = lightStatus;
   }

   if ( touch.tirqTouched() )
@@ -228,8 +228,8 @@
   const uint16_t BARS_WIDTH       = 210 / 5; /* note: total width is 210 px */
   const float    HEIGHT_FACTOR    = BARS_HEIGHT / 100.0;

-  static wl_status_t   lastWiFiStatus;
-  static lightStatus_t lastLightStatus;
+  static wl_status_t   displayedWiFiStatus;
+  static lightStatus_t displayedLightStatus;

   uint16_t channelColor565[NUMBER_OF_CHANNELS];

@@ -240,7 +240,7 @@
     button.draw( MENU_BUTTON );

     showIPAddress(  );
-    lastWiFiStatus = WiFi.status();
+    displayedWiFiStatus = WiFi.status();

     tft.setTextSize( 0 );
     for ( uint8_t thisSensor = 0; thisSensor < numberOfFoundSensors; thisSensor++ )
@@ -273,7 +273,7 @@

         button.updateSensorLabel( tempArea[thisSensor], sensor[thisSensor].name );

-        strncpy( savedSensor[thisSensor].name, sensor[thisSensor].name, sizeof( savedSensor[thisSensor].name ) );
+        strncpy( savedSensor[thisSensor].name, sensor[thisSensor].name, sizeof( sensor->name ) );
       }
     }
   }
@@ -393,10 +393,10 @@
     oldtimeinfo = timeinfo.tm_sec;
   }

-  if ( lastWiFiStatus != WiFi.status() )
+  if ( displayedWiFiStatus != WiFi.status() )
   {
     showIPAddress( );
-    lastWiFiStatus = WiFi.status();
+    displayedWiFiStatus = WiFi.status();
   }

   if ( touch.tirqTouched() )
@@ -504,6 +504,7 @@
         if ( sensor[ thisSensor ].tempCelcius < -55 || sensor[ thisSensor ].tempCelcius > 125 )    /* temp is outside DS18B20 specs */
         {
           tempArea[thisSensor].labelcolor = ILI9341_RED;                                           /* show temp as in error */
+          ESP_LOGE( TAG, "Out of range temperature." );
           sensor[ thisSensor ].tempCelcius = currentTemp[ thisSensor ];                            /* show previous temp */
         }
         snprintf( tempArea[thisSensor].text, sizeof( tempArea[thisSensor].text ), "%.1f%c", sensor[thisSensor].tempCelcius, char(247) );


center "save settings" menu title.

center "save settings" menu title.

--- src/rx5808-pro-diversity-oled/rx5808-pro-diversity-oled.ino
+++ src/rx5808-pro-diversity-oled/rx5808-pro-diversity-oled.ino
@@ -598,7 +598,7 @@
                 display.fillRect(0, 0, display.width(), 11, WHITE);
                 display.drawLine(0, 10, display.width(), 10, WHITE);
                 display.setTextColor(BLACK);
-                display.setCursor(35,2);
+                display.setCursor(25,2);
                 display.print("SAVE SETTINGS");
                 display.setTextColor(WHITE);
                 display.setCursor(5,8*1+4);


indoor firmware

indoor firmware

--- indoor-firm/indoor-firm.ino
+++ indoor-firm/indoor-firm.ino
@@ -17,7 +17,6 @@

 void setup()
 {
-
   Serial.begin(9600);
   BTSerial.begin(38400);
 }


Check refactoring of String/IOStream.

Check refactoring of String/IOStream.

--- examples/Sandbox/CosaString/CosaString.ino
+++ examples/Sandbox/CosaString/CosaString.ino
@@ -23,10 +23,10 @@
  * This file is part of the Arduino Che Cosa project.
  */

-#include "Cosa/String.hh"
 #include "Cosa/Memory.h"
 #include "Cosa/Watchdog.hh"
 #include "Cosa/Trace.hh"
+#include "Cosa/String.hh"
 #include "Cosa/IOStream/Driver/UART.hh"

 void setup()


turnstyle seems to be working

turnstyle seems to be working

--- Turnstyle/Turnstyle.ino
+++ Turnstyle/Turnstyle.ino
@@ -13,6 +13,10 @@
 #define DETECTION_THRESH 50 // Distance cutoff for passing
 #define MAX_DISTANCE 200 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

+// USE THIS INSTEAD TO REVERSE THE DOOR DIRECTION
+// NewPing sonar_1(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE); // NewPing setup of closer sensor.
+// NewPing sonar_2(TRIGGER_PIN_1, ECHO_PIN_1, MAX_DISTANCE); // NewPing setup of farther sensor.
+
 NewPing sonar_1(TRIGGER_PIN_1, ECHO_PIN_1, MAX_DISTANCE); // NewPing setup of closer sensor.
 NewPing sonar_2(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE); // NewPing setup of farther sensor.

@@ -25,7 +29,7 @@
 float accelScale, gyroScale;

 // THRESHOLDS
-const int thresh = 60;       // < 60 cm to sensor is considered passing through.
+const int thresh = 25;       // < 60 cm to sensor is considered passing through.
 const float openAngle = 20;  // door is considered open at 20 degrees.
 boolean doorOpen = false;


deleting useless empty lines

deleting useless empty lines

--- examples/basic_bt_movement/basic_bt_movement.ino
+++ examples/basic_bt_movement/basic_bt_movement.ino
@@ -47,9 +47,3 @@
     }
   }
 }
-
-
-
-
-
-


Fix logging during setup() not working

Fix logging during setup() not working

--- examples/cymatic-triangles/cymatic-triangles.ino
+++ examples/cymatic-triangles/cymatic-triangles.ino
@@ -9,7 +9,7 @@
   int _write(){return -1;}
 }

-#define LOGLEVEL LOG_LEVEL_INFOS
+#define LOGLEVEL LOG_LEVEL_DEBUG

 using namespace pixelmap;

@@ -22,8 +22,10 @@

 void setup() {
   Log.Init(LOGLEVEL, 9600);
-  Log.Info("Starting setup()\n");
-  delay(100);
+  delay(1000);
+  Log.Debug("Starting setup()\n");
+  Serial.flush();
+  delay(1000);

   input = new MSGEQ7Input(
     1,    // left pin


Updated setSelectionOfAnchors in tut 2 with remote ID

--- examples/ready_to_localize/ready_to_localize.ino
+++ examples/ready_to_localize/ready_to_localize.ino
@@ -193,6 +193,6 @@
     Pozyx.addDevice(anchor, remote_id);
   }
   if (num_anchors > 4){
-    Pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, num_anchors);
+    Pozyx.setSelectionOfAnchors(POZYX_ANCHOR_SEL_AUTO, num_anchors, remote_id);
   }
 }


give all pubs a common root; closes #30

give all pubs a common root; closes #30

--- brew-buddy-firmware/src/brew-buddy-firmware.ino
+++ brew-buddy-firmware/src/brew-buddy-firmware.ino
@@ -87,6 +87,8 @@
 float fermentationRate = 0; // knocks per ms
 unsigned long lastKnock;

+String messageBase = "bb/";
+
 String brewStage;
 String brewId;

@@ -153,7 +155,7 @@
         displayFermentationModeDelta();

         waitUntil(Particle.connected);
-        Particle.publish("fermentation/state", "start");
+        Particle.publish(messageBase + "ferment/state", "start");
       }
       else
       {
@@ -373,13 +375,13 @@
 void postTemp(float temp)
 {
   String payload = "{ \"temperature\":" + String(temp, 2) + ", \"time\": \"" + millis() + "\" }";
-  Particle.publish("brewing/temp", payload);
+  Particle.publish(messageBase + "brew/temp", payload);
 }

 void postFermentationRate()
 {
   String payload = "{ \"current_rate\":" + String(fermentationRate, 2) + ", \"time\": \"" + millis() + "\" }";
-  Particle.publish("fermentation/rate", payload);
+  Particle.publish(messageBase + "ferment/rate", payload);
 }

 void printReading(float reading)


Added left ultrasonic sensor and removed initial movement code

I added the pins and setup for the left ultrasonic sensor that was added to the robot. I also removed the initial example movement code we put in our loop on the first day.

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -9,12 +9,15 @@

 #define FRONT_US_ECHO   2
 #define FRONT_US_TRIG   3
+#define LEFT_US_ECHO   18
+#define LEFT_US_TRIG   19

 Servo leftServo;
 Servo rightServo;
 Servo extinguisher;

 Ultrasonic frontUltrasonic(FRONT_US_ECHO, FRONT_US_TRIG, true);
+Ultrasonic leftUltrasonic(LEFT_US_ECHO, LEFT_US_TRIG, true);

 void moveForward() {
   leftServo.write(180);
@@ -84,13 +87,7 @@
 }

 void loop() {
-  // put your main code here, to run repeatedly:
-
-//  if (frontUltrasonic.getDistance() > 3) {
-//    moveForward();
-//  } else {
-//    moveBackward();
-//  }
+// put your main code here, to run repeatedly:

   extinguishFire();


Add serialEvent function to unfill buffer and avoid stopping program

--- Arduino/MPU9150_AHRS/MPU9150_AHRS.ino
+++ Arduino/MPU9150_AHRS/MPU9150_AHRS.ino
@@ -162,6 +162,18 @@
   mpu.setFullScaleAccelRange(0); // set accelerometer to 2 g range

   mpu.setIntDataReadyEnabled(true); // enable data ready interrupt
+}
+/*
+  SerialEvent occurs whenever a new data comes in the
+ hardware serial RX.  This routine is run between each
+ time loop() runs, so using delay inside loop can delay
+ response.  Multiple bytes of data may be available.
+ */
+void serialEvent() {
+  while (Serial.available()) {
+    // get the new byte:
+    char inChar = (char)Serial.read();
+  }
 }

 void loop()
@@ -196,7 +208,7 @@
          }

   now = micros();
-  time_boot_ms = now/1000;
+  time_boot_ms = millis();
   deltat = ((now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
   lastUpdate = now;
   // Sensors x (y)-axis of the accelerometer is aligned with the y (x)-axis of the magnetometer;
@@ -206,7 +218,7 @@
   // in the LSM9DS0 sensor. This rotation can be modified to allow any convenient orientation convention.
   // This is ok by aircraft orientation standards!
   // Pass gyro rate as rad/s
-   MadgwickQuaternionUpdate(ax_g, ay_g, az_g, gx_degps*PI/180.0f, gy_degps*PI/180.0f, gz_degps*PI/180.0f,  my,  mx, mz);
+   MadgwickQuaternionUpdate(ax_g, ay_g, az_g, gx_degps*PI/180.0f, gy_degps*PI/180.0f, gz_degps*PI/180.0f, my, mx, mz);
 // MahonyQuaternionUpdate(ax_g, ay, az, gx_degps*PI/180.0f, gy_degps*PI/180.0f, gz_degps*PI/180.0f, my, mx, mz);

     // Serial print and/or display at 0.05 s rate independent of data rates
@@ -239,11 +251,11 @@
       // uint32_t time_boot_ms, int16_t xacc, int16_t yacc, int16_t zacc, int16_t xgyro, int16_t ygyro, int16_t zgyro, int16_t xmag, int16_t ymag, int16_t zmag)
       mavlink_msg_raw_imu_pack(system_id, component_id, &msg, time_boot_ms, a1, a2, a3, g1, g2, g3, m1, m2, m3);
       len = mavlink_msg_to_send_buffer(buf, &msg);
-      Serial.write(buf, len);
+      //Serial.write(buf, len);

       mavlink_msg_scaled_imu_pack(system_id, component_id, &msg, time_boot_ms, ax_g*1000, ay_g*1000, az_g*1000, gx_degps*PI/180.0f*1000, gy_degps*PI/180.0f*1000, gz_degps*PI/180.0f*1000, mx, my, mz);
       len = mavlink_msg_to_send_buffer(buf, &msg);
-      Serial.write(buf, len);
+      //Serial.write(buf, len);
       //static inline uint16_t mavlink_msg_attitude_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
       //  uint32_t time_boot_ms, float roll, float pitch, float yaw, float rollspeed, float pitchspeed, float yawspeed)
       mavlink_msg_attitude_pack(system_id, component_id, &msg, time_boot_ms, roll, pitch, yaw, gx_degps*PI/180.0f, gy_degps*PI/180.0f, gz_degps*PI/180.0f);


add 60 sec delay to ignore following cmds

--- _86-meross-garage-to-remote/meross-to-remote.ino
+++ _86-meross-garage-to-remote/meross-to-remote.ino
@@ -27,7 +27,8 @@
 }

 void loop() {
-  DURATION = pulseIn(HKIT_CMD_PIN, LOW, 1000000000);
+  Serial.println("working....");
+  DURATION = pulseIn(HKIT_CMD_PIN, LOW, 6000000);
   if ( DURATION > 10 ) {
     AWNING_REEDS_STATUS = digitalRead(REED_SENSOR_PIN);
     if(AWNING_REEDS_STATUS) { // CLOSED STATUS --> OPEN
@@ -41,5 +42,7 @@
       digitalWrite(AWNING_CLOSE_CMD_PIN, LOW);
       Serial.println("CMD IN, CLOSING AWNING");
     }
+   Serial.println("delay 60 secs");
+   delay(60000);
   }
 }


Updates reference file.

Updates reference file.

--- njmakerday_20160318/zz_references.ino
+++ njmakerday_20160318/zz_references.ino
@@ -2,5 +2,7 @@
  * Home Automation in the Cloud with the ESP8266 & Adafruit IO => https://learn.adafruit.com/home-automation-in-the-cloud-with-the-esp8266-and-adafruit-io/programming-the-modules
  *  Github => https://github.com/openhomeautomation/adafruit-io-esp8266/blob/master/esp8266_sensor_module/esp8266_sensor_module.ino
  * Many, many Google searches.
-
+ * jQuery => http://jquery.com
+ * Humidity Information => https://en.wikipedia.org/wiki/Humidity
+ * Temperature Information => https://en.wikipedia.org/wiki/Category:Units_of_temperature
  */


Update AT.ino

Update AT.ino

--- examples/Modules/SIM800L/ATCOM/AT/AT.ino
+++ examples/Modules/SIM800L/ATCOM/AT/AT.ino
@@ -23,7 +23,6 @@
   M5.Lcd.setTextColor(TFT_WHITE, TFT_BLACK);
   M5.Lcd.drawString("Please use serial port to Test AT command.",0, 35, 2);
   // Host serial communication
-  Serial.begin(115200);

   // SIM800L serial communication
   Serial2.begin(115200, SERIAL_8N1, RX_PIN, TX_PIN);


Changed servo control to use writeMicroseconds in Servo library

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -2,6 +2,7 @@

 #include <SPI.h>
 #include <Elcano_Serial.h>
+#include <Servo.h>

 //#include <SoftwareSerial.h>
 // On Mega, TX must use d10-15, d50-53, or a8-a15 (62-69)
@@ -9,6 +10,8 @@
 const int softwareRx = 7;   // not used
 //SoftwareSerial s7s(softwareRx, softwareTx);
 #define s7s Serial2
+Servo STEER_SERVO, BRAKE_SERVO;
+

 #define LOOP_TIME_MS 400
 #define ERROR_HISTORY 20
@@ -67,7 +70,6 @@
 volatile unsigned long RC_elapsed[7];
 volatile boolean synced = false;
 volatile unsigned long last_fallingedge_time = 4294967295; // max long
-unsigned long local_results[7] = {0,0,0,0,0,0,0};
 volatile bool RC_Done[7] = {0,0,0,0,0,0,0};

 // interrupt number handling a function depends on the RC controller.
@@ -84,7 +86,10 @@
 //THESE MAY NEED TO BE ADJUSTED
 int DEAD_ZONE = 75;
 int MIDDLE = 1480;  // was 1322; new stable value = 1510
+int MIDDLE_GO = 1152;
 // extremes of RC pulse width
+int MIN_GO = 896;
+int MAX_GO = 1560;
 int MIN_RC = 1090;  // was 911;
 int MAX_RC = 1930; // was 1730;
 #endif
@@ -203,24 +208,25 @@

 void ISR_SWITCH_rise() {
   noInterrupts();
-  RC_elapsed[RC_RDR] = HIGH;
+  ProcessRiseOfINT(RC_RDR);
   attachInterrupt(digitalPinToInterrupt(IRPT_SWITCH), ISR_SWITCH_fall, FALLING);
-  RC_Done[RC_RDR] = 1;
+  //RC_Done[RC_RDR] = 1;
   interrupts();
 }

 void ISR_SWITCH_fall() {
   noInterrupts();
-  RC_elapsed[RC_RDR] = LOW;
+  ProcessFallOfINT(RC_RDR);
+  RC_Done[RC_RDR] = 1;
   attachInterrupt(digitalPinToInterrupt(IRPT_SWITCH), ISR_SWITCH_rise, RISING);
-  RC_Done[RC_RDR] = 1;
   interrupts();
 }
 //----------------------------------------------------------------------------
 void setup()
 { //Set up pins
-      pinMode(BRAKE_OUT_PIN, OUTPUT);
-      pinMode(STEER_OUT_PIN, OUTPUT);
+      STEER_SERVO.attach(STEER_OUT_PIN);
+      BRAKE_SERVO.attach(BRAKE_OUT_PIN);
+
       // SPI: set the slaveSelectPin as an output:
       pinMode (SelectAB, OUTPUT);
       pinMode (SelectCD, OUTPUT);
@@ -241,7 +247,7 @@
       moveVehicle(MIN_ACC_OUT);
       //setup7seg();    // Initialize 7 segment display for speedometer
       delay(500);   // let vehicle stabilize
-
+      //brake(MAX_BRAKE_OUT);
       Serial.begin(9600);
       rc_index = 0;
       for (int i = 0; i < 8; i++)
@@ -257,15 +263,16 @@
       CalibrateTurnAngle(32, 20);
       calibrationTime_ms = millis();
       attachInterrupt(digitalPinToInterrupt(IRPT_TURN), ISR_TURN_rise,  RISING);
-      attachInterrupt(digitalPinToInterrupt(IRPT_RDR), ISR_RDR_rise,   RISING);
+      //attachInterrupt(digitalPinToInterrupt(IRPT_RDR), ISR_RDR_rise,   RISING);
       attachInterrupt(digitalPinToInterrupt(IRPT_GO), ISR_GO_rise,    RISING);
       attachInterrupt(digitalPinToInterrupt(IRPT_ESTOP), ISR_ESTOP_rise, RISING);
-      attachInterrupt(digitalPinToInterrupt(IRPT_RVS), ISR_RVS_rise,   RISING);
+      //attachInterrupt(digitalPinToInterrupt(IRPT_RVS), ISR_RVS_rise,   RISING);
       attachInterrupt(digitalPinToInterrupt(IRPT_SWITCH), ISR_SWITCH_rise,   RISING);
       //calibrateRC(micros());

 //      Print7headers(false);
       //PrintHeaders();
+      //circleRoutine(10);
 }

 void loop() {
@@ -279,11 +286,11 @@

     startCapturingRCState();// I don't like this structure. It should know that RC has been processed as it comes.

-
+    unsigned long local_results[7];
     //PrintDone();

   while (micros() < nextTime &&
-    ~((RC_Done[RC_ESTP] == 1) && (RC_Done[RC_GO] == 1) && (RC_Done[RC_TURN] == 1) ))
+    ~((RC_Done[RC_ESTP] == 1) && (RC_Done[RC_GO] == 1) && (RC_Done[RC_TURN] == 1) && (RC_Done[RC_RDR])))
     ;  //wait

     // got data;
@@ -312,10 +319,10 @@
     stoppedTime_ms = (throttle_control == MIN_ACC_OUT)? stoppedTime_ms + LOOP_TIME_MS: 0;
     if (calibrationTime_ms > 40000 && straightTime_ms > 3000 && stoppedTime_ms > 3000)
     {
-         int oldBrake = brake_control;
-         brake(MAX_BRAKE_OUT);  // put on brakes
+//         int oldBrake = brake_control;
+//         brake(MAX_BRAKE_OUT);  // put on brakes
          CalibrateTurnAngle(16, 10);  // WARNING: No response to controls while calibrating
-         brake(oldBrake);       // restore brake state
+    //     brake(oldBrake);       // restore brake state
          calibrationTime_ms = 0;
     }

@@ -340,7 +347,7 @@
 }

 void circleRoutine(unsigned long seconds){
-  steer(128);
+  steer(LEFT_TURN_OUT);
   delay(1000);
   seconds = seconds * 1000;
   unsigned long loopTime = millis();
@@ -376,18 +383,25 @@
 void Print7 (bool processed, unsigned long results[7])
 {
     if(processed){
-      Serial.print("processed data \t");
+      Serial.println("processed data \t");
     }
     else {
-      Serial.print("received dataaa \t");
-    }
-    Serial.print(results[0]);     Serial.print("\t");
+      Serial.println("received data \t");
+    }
+
+    Serial.print("Turn");     Serial.print("\t");
+    Serial.print("Go");     Serial.print("\t");
+    Serial.print("EStop");     Serial.print("\t");
+    Serial.print("Switch");   Serial.print("\t");
+    Serial.println();
+
+//    Serial.print(results[0]);     Serial.print("\t");
     Serial.print(results[1]);     Serial.print("\t");
-    Serial.print(results[2]);     Serial.print("\t");
+    //Serial.print(results[2]);     Serial.print("\t");
     Serial.print(results[3]);     Serial.print("\t");
     Serial.print(results[4]);     Serial.print("\t");
     Serial.print(results[5]);     Serial.print("\t");
-    Serial.println(results[6]);
+    Serial.println();//Serial.println(results[6]);
 }
 void LogData(unsigned long commands[7], SerialData *sensors)  // data for spreadsheet
 {
@@ -474,7 +488,7 @@
 {
     // 1st pulse is aileron (position 5 on receiver; controlled by Right left/right joystick on transmitter)
     //     used for Steering
-    int aileron = results[RC_TURN];
+    unsigned long aileron = results[RC_TURN];
 //    Serial.print("\tTurn input "); Serial.print(aileron);
     results[RC_TURN] = convertTurn(aileron);
 //    Serial.print("\tTurn Cmd "); Serial.println(results[RC_TURN]);
@@ -493,7 +507,7 @@
     {
         E_Stop();  // already done at interrupt level
         if ((results[RC_AUTO] == LOW)  && (NUMBER_CHANNELS > 5)) // under RC control
-            steer(results[RC_TURN]);
+            ;//steer(results[RC_TURN]);
         Serial.println("Exiting processRC due to E-stop.");
         return;
     }
@@ -509,7 +523,7 @@
     /*  6th pulse is marked throttle (position 6 on receiver; controlled by Left up/down joystick on transmitter).
     It will be used for shifting from Drive to Reverse . D40
     */
-    results[RC_RVS] = (results[RC_RVS] > MIDDLE? HIGH: LOW);
+   // results[RC_RVS] = (results[RC_RVS] > MIDDLE? HIGH: LOW);

 // TO DO: Select Forward / reverse based on results[RC_RVS]

@@ -517,41 +531,43 @@
        will be used for throttle/brake: RC_Throttle
     */
     // Braking or Throttle
-    if (liveBrake(results[RC_GO]))
-         convertBrake (&(results[RC_GO]));
-
+    if (liveBrake(results[RC_GO])){
+         Serial.println("Breaking");
+         convertBrake ((results[RC_GO]));
+    }
     //Accelerating
-    else if(liveThrottle(results[RC_GO]))
+    if(liveThrottle(results[RC_RDR]))
     {
-        results[RC_GO] = convertThrottle(results[RC_GO]);
-        moveVehicle(results[RC_GO]);
+        int going = convertThrottle(results[RC_RDR]);
+        //results[RC_GO] = convertThrottle(results[RC_GO]);
+        moveVehicle(going);
     }
     else
-        //moveVehicle(MIN_ACC_OUT);
+        moveVehicle(MIN_ACC_OUT);

     steer(results[RC_TURN]);

     /* 5th pulse is rudder (position 3 on receiver; controlled by Left left/right joystick on transmitter)
     Not used */
 //    results[RC_RDR] = (results[RC_RDR] > MIDDLE? HIGH: LOW);  // could be analog
-    Serial.println(results[RC_RDR]);
-    if (results[RC_RDR] >= HubAtZero)
-        HubSpeed_kmPh = 0;
-    else
-        HubSpeed_kmPh = HubSpeed2kmPh / results[RC_RDR];
-
-  Serial.println("");  // New line
+//    Serial.println(results[RC_RDR]);
+//    if (results[RC_RDR] >= HubAtZero)
+//        HubSpeed_kmPh = 0;
+//    else
+//        HubSpeed_kmPh = HubSpeed2kmPh / results[RC_RDR];
+//
+//  Serial.println("");  // New line

 }

 //Converts RC values to corresponding values for the PWM output
-int convertTurn(int input)
-{
-     long int steerRange, rcRange;
-     long output;
-     int trueOut;
+unsigned long convertTurn(unsigned long input)
+{
+     unsigned long steerRange, rcRange;
+     unsigned long output;
+     unsigned long trueOut;
 //     Serial.print("\tconvertTurn: input = \t"); Serial.print(input);
      //  Check if Input is in steer dead zone
      if ((input <= MIDDLE + DEAD_ZONE) && (input >= MIDDLE - DEAD_ZONE))
@@ -559,38 +575,41 @@
        // On SPEKTRUM, MIN_RC = 1 msec = stick right; MAX_RC = 2 msec = stick left
        // On HI_TEC, MIN_RC = 1 msec = stick left; MAX_RC = 2 msec = stick right
       // LEFT_TURN_OUT > RIGHT_TURN_OUT
+
+      else
+        return input;
 #ifdef RC_HITEC
   input = MAX_RC - (input - MIN_RC);
 #endif

-      if (input > MIDDLE + DEAD_ZONE)
-      {  // left turn
-         steerRange = LEFT_TURN_OUT - STRAIGHT_TURN_OUT;
-         rcRange = MAX_RC - (MIDDLE + DEAD_ZONE);
-        input = input - MIDDLE - DEAD_ZONE; // originally input = middle + dead_zone
-        output = STRAIGHT_TURN_OUT + input * steerRange / rcRange;
-        //set max and min values if out of range
-        trueOut = (int)output;
-        if(trueOut > LEFT_TURN_OUT)
-            trueOut = LEFT_TURN_OUT;
-        if(trueOut < STRAIGHT_TURN_OUT)
-            trueOut = STRAIGHT_TURN_OUT;
-        return trueOut;
-    }
-      if (input < MIDDLE - DEAD_ZONE)
-      {  // right turn
-         steerRange = STRAIGHT_TURN_OUT - RIGHT_TURN_OUT;
-         rcRange = MIDDLE - DEAD_ZONE - MIN_RC;
-        input = input - DEAD_ZONE - MIDDLE;  // input is negative
-        output = STRAIGHT_TURN_OUT + input * steerRange / rcRange;
-        //set max and min values if out of range
-        trueOut = (int)output;
-        if(trueOut < RIGHT_TURN_OUT)
-            trueOut = RIGHT_TURN_OUT;
-        if(trueOut > STRAIGHT_TURN_OUT)
-            trueOut = STRAIGHT_TURN_OUT;
-        return trueOut;
-    }
+//      if (input > MIDDLE + DEAD_ZONE)
+//      {  // left turn
+//         steerRange = LEFT_TURN_OUT - STRAIGHT_TURN_OUT;
+//         rcRange = MAX_RC - (MIDDLE + DEAD_ZONE);
+//        input = input - MIDDLE - DEAD_ZONE; // originally input = middle + dead_zone
+//        output = STRAIGHT_TURN_OUT + input * steerRange / rcRange;
+//        //set max and min values if out of range
+//        trueOut = (int)output;
+//        if(trueOut > LEFT_TURN_OUT)
+//            trueOut = LEFT_TURN_OUT;
+//        if(trueOut < STRAIGHT_TURN_OUT)
+//            trueOut = STRAIGHT_TURN_OUT;
+//        return trueOut;
+//    }
+//      if (input < MIDDLE - DEAD_ZONE)
+//      {  // right turn
+//         steerRange = STRAIGHT_TURN_OUT - RIGHT_TURN_OUT;
+//         rcRange = MIDDLE - DEAD_ZONE - MIN_RC;
+//        input = input - DEAD_ZONE - MIDDLE;  // input is negative
+//        output = STRAIGHT_TURN_OUT + input * steerRange / rcRange;
+//        //set max and min values if out of range
+//        trueOut = (int)output;
+//        if(trueOut < RIGHT_TURN_OUT)
+//            trueOut = RIGHT_TURN_OUT;
+//        if(trueOut > STRAIGHT_TURN_OUT)
+//            trueOut = STRAIGHT_TURN_OUT;
+//        return trueOut;
+//    }
 }

 int convertThrottle(int input)
@@ -619,38 +638,56 @@
 // Input is not in brake dead zone
 boolean liveBrake(int brake)
 {
-      return (brake < MIDDLE - DEAD_ZONE);
+      return (brake < MIDDLE_GO - DEAD_ZONE);
 }

 // Emergency stop
 void E_Stop()
 {
     brake(MAX_BRAKE_OUT);
+    steer(STRAIGHT_TURN_OUT);
     moveVehicle(MIN_ACC_OUT);
+
     delay (2000);   // inhibit output
     // TO DO: disable 36V power
 }

 //Send values to output pin
-void steer(int pos)
-{
-      analogWrite(STEER_OUT_PIN, pos);
+void steer(unsigned long pos)
+{
+      STEER_SERVO.writeMicroseconds(pos);
 //      Serial.print("\tSteering to: \t"); Serial.print(pos);
      steer_control = pos;
 }
-void convertBrake(long unsigned *amount)
-{
-      if (*amount < (MIDDLE + MIN_RC)/2)
-          *amount = MAX_BRAKE_OUT;
-      else
-           *amount = MIN_BRAKE_OUT;
-      brake (*amount);
-}
-void brake (int amount)
-{
-      analogWrite(BRAKE_OUT_PIN, amount);
- //     Serial.print("\tBraking to: \t"); Serial.print(*amount);
-      brake_control = amount;
+void convertBrake(unsigned long amount)
+{
+      // (MIDDLE + MIN_RC)/2 is currently 1360
+//      if (amount < (MIDDLE + MIN_RC)/2)
+//          amount = MAX_BRAKE_OUT;
+//      else
+//          amount = MIN_BRAKE_OUT;
+      //*amount = *amount + (MAX_BRAKE_OUT - MIDDLE);
+//      Serial.print("Breaking ");
+//      Serial.println(*amount);
+  if(amount > 800 && amount < 1000){
+          brake (amount + 300);
+  }
+  else ;
+      //brake(MIN_BRAKE_OUT);
+}
+void brake (unsigned long amount)
+{
+    STEER_SERVO.writeMicroseconds(STRAIGHT_TURN_OUT);
+    STEER_SERVO.detach();
+    //BRAKE_SERVO.attach(BRAKE_OUT_PIN);
+    if(amount > 1000)
+      BRAKE_SERVO.write(20);
+    else
+      BRAKE_SERVO.write(160);
+      //BRAKE_SERVO.writeMicroseconds(amount);
+      Serial.print("\tBraking to: \t"); Serial.println(amount);
+    STEER_SERVO.attach(STEER_OUT_PIN);
+      //brake_control = amount;
 }
 /*---------------------------------------------------------------------------------------*/
 /* DAC_Write applies value to address, producing an analog voltage.


Remove compiler warning on program memory.

--- examples/Pins/CosaAnalogPins/CosaAnalogPins.ino
+++ examples/Pins/CosaAnalogPins/CosaAnalogPins.ino
@@ -34,7 +34,7 @@
 #include "Cosa/Memory.h"

 // Analog pin vector for pin set. Note: use program memory
-const PROGMEM Board::AnalogPin pins[] = {
+const Board::AnalogPin pins[] __PROGMEM = {
   Board::A0,
   Board::A1,
   Board::A2,


changed to globals

changed to globals

--- T3/src/AFE-MQTT-API-listener.ino
+++ T3/src/AFE-MQTT-API-listener.ino
@@ -22,7 +22,7 @@
                          }
                      */

-    for (uint8_t i = 0; i < 4; i++) {
+    for (uint8_t i = 0; i < sizeof(Device.configuration.isRelay); i++) {
       if (Device.configuration.isRelay[i]) {
         sprintf(_mqttTopic, "%scmd", Relay[i].getMQTTTopic());

@@ -43,7 +43,7 @@
       }
     }

-    for (uint8_t i = 0; i < 4; i++) {
+    for (uint8_t i = 0; i < sizeof(Device.configuration.isPIR); i++) {
       if (Device.configuration.isPIR[i]) {
         sprintf(_mqttTopic, "%scmd", Pir[i].getMQTTTopic());


Testing DriveMode_One and _Two. DigiPot broken?

--- motion/motion-control.ino
+++ motion/motion-control.ino
@@ -49,6 +49,14 @@
         xpos = 0;
         ypos = 0;
     }
+
+    UART_string((char*)"setJoy(");
+    UART_signed(xpos,10);
+    UART_string((char*)",");
+    UART_signed(ypos,10);
+    UART_string((char*)")");
+    UART_crlf();
+
     // -xpos is left, +xpos is right
     state.joyx = JOY_STOP + xpos;
     // flip sign of fwd/bkw signal
@@ -147,6 +155,9 @@
     //
     // set angle / push to 0's initially
     setAnglePush(0, 0);
+    // long pause to allow interrupt routine
+    // to update hardware
+    delay(1000);
 }

 // Interrupt ticks at 1024Hz
@@ -252,25 +263,15 @@

     // initial state setup
     initDefaultState();
+
+    // initial start delay
+    delay(3000);
 }

 void loop()
 {
-    static bool led = true;
     setDrivemode(DRIVEMODE_ONE);
-    delay(3000);
-    setDrivemode(DRIVEMODE_OFF);
+    setJoy(0,0);
     while (1) {
-        while (UART_available()) {
-            UART_char(' ');
-            uint8_t in = UART_getchar();
-            UART_signed(in, 16);
-            UART_char(' ');
-        }
-        UART_char(led + 48);
-        UART_char(8);
-        setLED(led ? LED0 | LED1 : LED1);
-        led = !led;
-        delay(2000);
-    }
-}
+    }
+}


removed code not being used

removed code not being used

--- arducode/arducode.ino
+++ arducode/arducode.ino
@@ -68,23 +68,6 @@
 int numpix=0;
 int integerValue=0;
 char incomingByte;
-void center_vis(int integerValue, Adafruit_NeoPixel strip, int** ciroc) {
-  int center_val = 36;
-  int move = integerValue/2;
-    for(int i=center_val; i >= center_val-move && i>0; i--){ //select lights from center towards pos 0
-      strip.setPixelColor(i,ciroc[i][0],ciroc[i][1],ciroc[i][2]);
-    }
-    for(int i=0; i<center_val-move; i++){ //set remaining lights from left end to black
-      strip.setPixelColor(i,0,0,0);
-    }
-    // for(int i=center_val; i<= (center_val+move) && i<strip.numPixels(); i++){ //select lights from center towards numPixels()
-    //   strip.setPixelColor(i,ciroc[i][0],ciroc[i][1],ciroc[i][2]);
-    // }
-    // for(int i=center_val + move; i<strip.numPixels(); i++){ //set lights up to numPixels() to black
-    //   strip.setPixelColor(i,0,0,0);
-    // }
-    strip.show();
-}

 int gabe = 0;
 void loop() {
@@ -266,4 +249,4 @@
   }
   WheelPos -= 170;
   return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
-}+}


Change battery full/empty levels

Change battery full/empty levels

Now that I know how to disable BOD, the sensor can go as low as
2.43V.

2xAA full battery deliver 3.143V according to my measurements.

--- arduino-plantmoisture.ino
+++ arduino-plantmoisture.ino
@@ -9,8 +9,8 @@
 #define SLEEP_TIME 1800000 // Sleep time between reads (in milliseconds)
 #define THRESHOLD 1.1 // Only make a new reading with reverse polarity if the change is larger than 10%.
 #define STABILIZATION_TIME 1000 // Let the sensor stabilize before reading
-#define BATTERY_FULL 3000 // 3,000 millivolts for 2xAA
-#define BATTERY_ZERO 2800 // 1,900 millivolts (1.9V, limit for nrf24l01 without step-up. 2.8V limit for Atmega328 without BOD disabled))
+#define BATTERY_FULL 3143 // 2xAA usually give 3.143V when full
+#define BATTERY_ZERO 2340 // 2.43V limit for 328p at 8MHz. 1.9V, limit for nrf24l01 without step-up. 2.8V limit for Atmega328 with default BOD settings.
 const int SENSOR_ANALOG_PINS[] = {A0, A1}; // Sensor is connected to these two pins. Avoid A3 if using ATSHA204. A6 and A7 cannot be used because they don't have pullups.

 MySensor gw;


Update revbits function

Update revbits function


updated twitter client for Ethernet

updated twitter client for Ethernet

--- libraries/Ethernet/examples/TwitterClient/TwitterClient.ino
+++ libraries/Ethernet/examples/TwitterClient/TwitterClient.ino
@@ -121,4 +121,4 @@
   }
   // note the time of this connect attempt:
   lastAttemptTime = millis();
-}
+}


Added getWeather example

Added getWeather example

Get up-to-date weather information by performing HTTP GET requests to
openweathermap.org. The example parses the XML to get temperature,
humidity, pressure & timestamp data.

www.openweathermap.org/api

Users can modify the code easily to add the appropriate WiFi SSID,
password & desired location.


Trying to use ArduinoJson

Trying to use ArduinoJson

--- ESP8266HueEmulator/ESP8266HueEmulator.ino
+++ ESP8266HueEmulator/ESP8266HueEmulator.ino
@@ -21,13 +21,13 @@
 // Settings for the NeoPixels
 #define pixelCount 30 // Strip has 30 NeoPixels
 #define pixelPin 2 // Strip is attached to GPIO2 on ESP-01
-#define colorSaturation 128
+#define colorSaturation 254
 RgbColor red = RgbColor(colorSaturation, 0, 0);
 RgbColor green = RgbColor(0, colorSaturation, 0);
 RgbColor blue = RgbColor(0, 0, colorSaturation);
 RgbColor white = RgbColor(colorSaturation);
 RgbColor black = RgbColor(0);
-unsigned int transitionTime = 400; // by default there is a transition time to the new state of 400 milliseconds
+unsigned int transitionTime = 800; // by default there is a transition time to the new state of 400 milliseconds

 NeoPixelBus strip = NeoPixelBus(pixelCount, pixelPin);
 NeoPixelAnimator animator(&strip); // NeoPixel animation management object
@@ -48,7 +48,7 @@

 ESP8266WebServer HTTP(80);

-String client = "e7x4kuCaC8h885jo"; // "UjBZ0nvTLu7aMdOe"; // The client string that the client app sends. Need to enter here what the app sends.
+String client = "e7x4kuCaC8h885jo"; // The client name that the sketch gives to the app
 // FIXME: Parse this out of what is being sent by the app.

 void handleAllOthers() {
@@ -59,49 +59,41 @@

   if ( requestedUri.endsWith("/config") )
   {
-    // Using a library like in the following is probably the way to do; we can even do entirely without using String, saving memory.
-    // However, it is not entirely clear to me how to use it, see https://github.com/bblanchon/ArduinoJson/issues/85
-    StaticJsonBuffer<200> jsonBuffer;
+
+    StaticJsonBuffer<1024> jsonBuffer;
     JsonObject& root = jsonBuffer.createObject();
-    root["name"] = "Philips hue";
-    root["zigbeechannel"] = "0"; // As per spec, 0 is allowed
-    root["mac"] = macString.c_str();
-    root["dhcp"] = "true";
-    root["ipaddress"] = ipString.c_str();
-    root["netmask"] = "255.255.255.0"; // TODO: FIXME
-    root["gateway"] = "192.168.0.1"; // TODO: FIXME
-    root["proxyaddress"] = "none";
-    root["proxyport"] = "0";
-    //JsonObject& whitelist = root.createNestedObject();
-    //whitelist["name"] = "XXXXXXX";
-    //JsonObject& clientobj = whitelist.createNestedObject();
-    //char buffer[256];
-    //root.prettyPrintTo(buffer, sizeof(buffer));
-    //HTTP.send(200, "text/plain", "[" + String(buffer) + "]");
-    //Serial.println("[" + String(buffer) + "]");
-
-    String longstr = "{\"portalservices\":false,\"gateway\":\"192.168.2.1\",\"mac\":\"" + macString + "\",\"swversion\":\"01005215\",\"linkbutton\":false,\"ipaddress\":\"" + ipString + "\",\"proxyport\":0,\"swupdate\":{\"text\":\"\",\"notify\":false,\"updatestate\":0,\"url\":\"\"},\"netmask\":\"255.255.255.0\",\"name\":\"Philips hue\",\"dhcp\":true,\"proxyaddress\":\"\",\"whitelist\":{\"newdeveloper\":{\"name\":\"test user\",\"last use date\":\"2012-10-29T12:00:00\",\"create date\":\"2012-10-29T12:00:00\"},\"e7x4kuCaC8h885jo\":{\"name\":\"appname#devicename\",\"last use date\":\"2015-07-05T17:07:39\",\"create date\":\"2015-07-05T16:58:10\"}},\"UTC\":\"2012-10-29T12:05:00\"}";
-
-    HTTP.send(200, "text/plain", longstr);
-    Serial.println(longstr);
-  }
-
-  else if (requestedUri.endsWith(client))
-  {
-    String longstr = "{\"lights\":{\"1\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":4444,\"sat\":254,\"xy\":[0.0,0.0],\"ct\":0,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 1\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}},\"2\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":23536,\"sat\":144,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 2\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}},\"3\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":65136,\"sat\":254,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 3\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}}},\"schedules\":{\"1\":{\"time\":\"2012-10-29T12:00:00\",\"description\":\"\",\"name\":\"schedule\",\"command\":{\"body\":{\"on\":true,\"xy\":null,\"bri\":null,\"transitiontime\":null},\"address\":\"/api/newdeveloper/groups/0/action\",\"method\":\"PUT\"}}},\"config\":{\"portalservices\":false,\"gateway\":\"192.168.2.1\",\"mac\":\"" + macString + "\",\"swversion\":\"01005215\",\"linkbutton\":false,\"ipaddress\":\"" + ipString + "\",\"proxyport\":0,\"swupdate\":{\"text\":\"\",\"notify\":false,\"updatestate\":0,\"url\":\"\"},\"netmask\":\"255.255.255.0\",\"name\":\"Philips hue\",\"dhcp\":true,\"proxyaddress\":\"\",\"whitelist\":{\"newdeveloper\":{\"name\":\"test user\",\"last use date\":\"2012-10-29T12:00:00\",\"create date\":\"2012-10-29T12:00:00\"},\"e7x4kuCaC8h885jo\":{\"name\":\"appname#devicename\",\"last use date\":\"2015-07-05T17:18:04\",\"create date\":\"2015-07-05T16:58:10\"}},\"UTC\":\"2012-10-29T12:05:00\"},\"groups\":{\"1\":{\"name\":\"Group 1\",\"action\":{\"on\":true,\"bri\":254,\"hue\":33536,\"sat\":144,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":null,\"effect\":\"none\",\"colormode\":\"xy\",\"reachable\":null},\"lights\":[\"1\",\"2\"]}},\"scenes\":{}}";
-
-    HTTP.send(200, "text/plain", longstr);
-    Serial.println(longstr);
-    Serial.println("Responded with complete json as in https://github.com/probonopd/ESP8266HueEmulator/wiki/Hue-API#get-all-information-about-the-bridge");
-  }
-
-  else if (requestedUri.endsWith("UjBZ0nvTLu7aMdOe")) // FIXME: remove this!!! This is the same as above, but for same strange reason the Chroma app is using a different username!
-  {
-    String longstr = "{\"lights\":{\"1\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":4444,\"sat\":254,\"xy\":[0.0,0.0],\"ct\":0,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 1\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}},\"2\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":23536,\"sat\":144,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 2\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}},\"3\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":65136,\"sat\":254,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 3\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}}},\"schedules\":{\"1\":{\"time\":\"2012-10-29T12:00:00\",\"description\":\"\",\"name\":\"schedule\",\"command\":{\"body\":{\"on\":true,\"xy\":null,\"bri\":null,\"transitiontime\":null},\"address\":\"/api/newdeveloper/groups/0/action\",\"method\":\"PUT\"}}},\"config\":{\"portalservices\":false,\"gateway\":\"192.168.2.1\",\"mac\":\"" + macString + "\",\"swversion\":\"01005215\",\"linkbutton\":false,\"ipaddress\":\"" + ipString + "\",\"proxyport\":0,\"swupdate\":{\"text\":\"\",\"notify\":false,\"updatestate\":0,\"url\":\"\"},\"netmask\":\"255.255.255.0\",\"name\":\"Philips hue\",\"dhcp\":true,\"proxyaddress\":\"\",\"whitelist\":{\"newdeveloper\":{\"name\":\"test user\",\"last use date\":\"2012-10-29T12:00:00\",\"create date\":\"2012-10-29T12:00:00\"},\"e7x4kuCaC8h885jo\":{\"name\":\"appname#devicename\",\"last use date\":\"2015-07-05T17:18:04\",\"create date\":\"2015-07-05T16:58:10\"}},\"UTC\":\"2012-10-29T12:05:00\"},\"groups\":{\"1\":{\"name\":\"Group 1\",\"action\":{\"on\":true,\"bri\":254,\"hue\":33536,\"sat\":144,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":null,\"effect\":\"none\",\"colormode\":\"xy\",\"reachable\":null},\"lights\":[\"1\",\"2\"]}},\"scenes\":{}}";
-
-    HTTP.send(200, "text/plain", longstr);
-    Serial.println(longstr);
-    Serial.println("Responded with complete json as in https://github.com/probonopd/ESP8266HueEmulator/wiki/Hue-API#get-all-information-about-the-bridge");
+    addConfigJson(root);
+    char buffer[1024];
+    root.printTo(buffer, sizeof(buffer));
+    HTTP.send(200, "text/plain", buffer);
+    // root.prettyPrintTo(Serial);
+  }
+
+  else if ((requestedUri.startsWith("/api") and (requestedUri.lastIndexOf("/") == 4 )))
+  {
+//    String longstr = "{\"lights\":{\"1\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":4444,\"sat\":254,\"xy\":[0.0,0.0],\"ct\":0,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 1\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}},\"2\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":23536,\"sat\":144,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 2\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}},\"3\":{\"state\":{\"on\":true,\"bri\":254,\"hue\":65136,\"sat\":254,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":\"none\",\"effect\":\"none\",\"colormode\":\"hs\",\"reachable\":true},\"type\":\"Extended color light\",\"name\":\"Hue Lamp 3\",\"modelid\":\"LCT001\",\"swversion\":\"65003148\",\"pointsymbol\":{\"1\":\"none\",\"2\":\"none\",\"3\":\"none\",\"4\":\"none\",\"5\":\"none\",\"6\":\"none\",\"7\":\"none\",\"8\":\"none\"}}},\"schedules\":{\"1\":{\"time\":\"2012-10-29T12:00:00\",\"description\":\"\",\"name\":\"schedule\",\"command\":{\"body\":{\"on\":true,\"xy\":null,\"bri\":null,\"transitiontime\":null},\"address\":\"/api/newdeveloper/groups/0/action\",\"method\":\"PUT\"}}},\"config\":{\"portalservices\":false,\"gateway\":\"192.168.2.1\",\"mac\":\"" + macString + "\",\"swversion\":\"01005215\",\"linkbutton\":false,\"ipaddress\":\"" + ipString + "\",\"proxyport\":0,\"swupdate\":{\"text\":\"\",\"notify\":false,\"updatestate\":0,\"url\":\"\"},\"netmask\":\"255.255.255.0\",\"name\":\"Philips hue\",\"dhcp\":true,\"proxyaddress\":\"\",\"whitelist\":{\"newdeveloper\":{\"name\":\"test user\",\"last use date\":\"2012-10-29T12:00:00\",\"create date\":\"2012-10-29T12:00:00\"},\"e7x4kuCaC8h885jo\":{\"name\":\"appname#devicename\",\"last use date\":\"2015-07-05T17:18:04\",\"create date\":\"2015-07-05T16:58:10\"}},\"UTC\":\"2012-10-29T12:05:00\"},\"groups\":{\"1\":{\"name\":\"Group 1\",\"action\":{\"on\":true,\"bri\":254,\"hue\":33536,\"sat\":144,\"xy\":[0.346,0.3568],\"ct\":201,\"alert\":null,\"effect\":\"none\",\"colormode\":\"xy\",\"reachable\":null},\"lights\":[\"1\",\"2\"]}},\"scenes\":{}}";
+
+//    HTTP.send(200, "text/plain", longstr);
+//    Serial.println(longstr);
+      Serial.println("Respond with complete json as in https://github.com/probonopd/ESP8266HueEmulator/wiki/Hue-API#get-all-information-about-the-bridge");
+
+    StaticJsonBuffer<1024> jsonBuffer;
+    JsonObject& root = jsonBuffer.createObject();
+    JsonObject& groups = root.createNestedObject("groups");
+    JsonObject& scenes = root.createNestedObject("scenes");
+    JsonObject& config = root.createNestedObject("config");
+    addConfigJson(config);
+    JsonObject& lights = root.createNestedObject("lights");
+    //addLightJson(lights, 1); // This crashes (FIXME)
+    JsonObject& schedules = root.createNestedObject("schedules");
+//    for (int i = 1; i < 2; i++)
+//    {
+//      addLightJson(root, i); // This crashes when i>1; see https://github.com/bblanchon/ArduinoJson/issues/87
+//    }
+    char buffer[1024];
+    root.printTo(buffer, sizeof(buffer));
+    HTTP.send(200, "text/plain", buffer);
+    root.prettyPrintTo(Serial);
   }

   else if (requestedUri.endsWith("/api"))
@@ -116,9 +108,6 @@

   else if (requestedUri.endsWith("/state"))
   {
-    String str = "{ \"state\": { \"hue\": 50000, \"on\": true, \"effect\": \"none\", \"alert\": \"none\", \"bri\": 200, \"sat\": 200, \"ct\": 500, \"xy\": [0.5, 0.5], \"reachable\": true, \"colormode\": \"hs\" }, \"type\": \"Living Colors\", \"name\": \"LC 1\", \"modelid\": \"LC0015\", \"swversion\": \"1.0.3\", \"pointsymbol\": { \"1\": \"none\", \"2\": \"none\", \"3\": \"none\", \"4\": \"none\", \"5\": \"none\", \"6\": \"none\", \"7\": \"none\", \"8\": \"none\" } }";
-    HTTP.send(200, "text/plain", str);
-    Serial.println(str);
     // For this to work we need a patched version of esp8266/libraries/ESP8266WebServer/src/Parsing.cpp which hopefully lands in the official channel soon
     // https://github.com/me-no-dev/Arduino/blob/d4894b115e3bbe753a47b1645a55cab7c62d04e2/hardware/esp8266com/esp8266/libraries/ESP8266WebServer/src/Parsing.cpp
     Serial.println(HTTP.arg("plain"));
@@ -159,6 +148,13 @@
       animator.StartAnimation(numberOfTheLight, transitionTime, animUpdate);
     }

+    JsonObject& lightJson = jsonBuffer.createObject();
+    addLightJson(lightJson, numberOfTheLight);
+    // lightJson.printTo(HTTP.client()); // FIXME: Why is this not working? Gives "no matching function for call to 'ArduinoJson::JsonObject::printTo(WiFiClient)'"
+    char buffer[256];
+    lightJson.printTo(buffer, sizeof(buffer));
+    HTTP.send(200, "text/plain", buffer);
+    Serial.println(buffer);
   }

   else if (requestedUri == "/description.xml")
@@ -263,6 +259,8 @@
   float y = Y / (X + Y + Z);
 }

+// See https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/commit/00187a3db88dedd640f5ddfa8a474458dff4e1db for more needed color conversions
+
 void infoLight(RgbColor color) {
   // Flash the strip in the selected color. White = booted, green = WLAN connected, red = WLAN could not connect
   for (int i = 0; i < pixelCount; i++)
@@ -295,9 +293,68 @@
   String LocalIP = "";
   IPAddress myaddr = WiFi.localIP();
   for (int i = 0; i < 4; i++)
-  {
-  LocalIP += String(myaddr[i]);
-  if (i < 3) LocalIP += ".";
-  }
-  return LocalIP;
-}
+  {
+    LocalIP += String(myaddr[i]);
+    if (i < 3) LocalIP += ".";
+  }
+  return LocalIP;
+}
+
+void addConfigJson(JsonObject& root)
+{
+  root["name"] = "Philips hue";
+  root["swversion"] = "01005215";
+  root["portalservices"] = false;
+  root["zigbeechannel"] = "0"; // As per spec, 0 is allowed
+  root["mac"] = macString.c_str();
+  root["dhcp"] = "true";
+  root["ipaddress"] = ipString.c_str();
+  root["netmask"] = "255.255.255.0"; // TODO: FIXME
+  root["gateway"] = "192.168.0.1"; // TODO: FIXME
+  root["proxyaddress"] = "";
+  root["proxyport"] = 0;
+  root["UTC"] = "2012-10-29T12:05:00";
+  JsonObject& whitelist = root.createNestedObject("whitelist");
+  JsonObject& whitelistFirstEntry = whitelist.createNestedObject("e7x4kuCaC8h885jo"); // FIXME: Do not hardcode e7x4kuCaC8h885jo
+  whitelistFirstEntry["name"] = "clientname#devicename";
+  whitelistFirstEntry["last use date"] = "2015-07-05T16:48:18";
+  whitelistFirstEntry["create date"] = "2015-07-05T16:48:17";
+  JsonObject& swupdate = root.createNestedObject("swupdate");
+  swupdate["text"] = "";
+  swupdate["notify"] = false;
+  swupdate["updatestate"] = 0;
+  swupdate["url"] = "";
+}
+
+void addLightJson(JsonObject& root, int numberOfTheLight)
+{
+  String lightName = "" + (String) numberOfTheLight;
+  JsonObject& light = root.createNestedObject(lightName.c_str());
+  light["type"] = "Extended color light";
+  light["name"] =  ("Hue Lamp " + (String) numberOfTheLight).c_str();
+  light["modelid"] = "LCT001";
+  JsonObject& state = light.createNestedObject("state");
+  unsigned int brightness = strip.GetPixelColor(numberOfTheLight - 1).CalculateBrightness();
+  if (brightness == 0)
+  {
+    state["on"] = false;
+  }
+  else
+  {
+    state["on"] = true;
+  }
+  state["bri"] = 254; // Can be 0-255 but should be 1-254 according to Philips API (why?)
+  state["hue"] = 0; // Should between 0 and 65535. Both 0 and 65535 are red, 25500 is green and 46920 is blue.
+  state["sat"] = 0;
+  JsonArray& array = state.createNestedArray("xy");
+  array.add(0.0);
+  array.add(0.0);
+  state["alert"] = "none";
+  state["effect"] = "none";
+  state["colormode"] = "hs";
+  state["reachable"] = true;
+
+}
+
+
+


Add ESP8266 branding

Add ESP8266 branding

--- KugelmatikFirmware/KugelmatikFirmware.ino
+++ KugelmatikFirmware/KugelmatikFirmware.ino
@@ -1,10 +1,10 @@
-// Kugelmatik V3.1 (ESP32)
+// Kugelmatik V3.1 (ESP8266)
 // Firmware
 //  Henrik Kunzelmann 2016 - 2017
 //  Rainer Wieland

 // Hardware
-//  ESP32
+//  ESP8266
 //  MCP23S17
 //  L293DNE

@@ -30,14 +30,15 @@
 	disable_wdt();

 	serialBegin();
-	serialPrintF("Kugelmatik Firmware (ESP32) booting up, version: ");
+	serialPrintF("Kugelmatik Firmware (ESP8266) booting up, version: ");
 	serialPrintln(BUILD_VERSION);

 	serialPrintlnF("Wire.begin()");
-	Wire.begin(SDA, SCL, 400000);
+	Wire.begin(SDA, SCL);
+	Wire.setClock(400000);

 	initEEPROM();
-	writeEEPROM("Kugelmatik32");
+	writeEEPROM("Kugelmatik8266");

 	setupLeds();
 	turnGreenLedOn();


Update voteino.ino

Update voteino.ino

added comment

--- voteino.ino
+++ voteino.ino
@@ -39,7 +39,7 @@
 uint8_t server_id = 0xB0;
 uint8_t client_id = 0xC0;
 uint8_t client_all_id = 0xAA;
-/* The role of the current running sketch */
+/* The role of the current running sketch ( server_id or client_id )*/
 uint8_t role_id = server_id;

 /* VOTING RESULTS */


minor cleanup and rename of variables

minor cleanup and rename of variables

--- TemperatureDisplay/TemperatureDisplay.ino
+++ TemperatureDisplay/TemperatureDisplay.ino
@@ -39,7 +39,7 @@

 AsyncTemperatureSensor sensor(temperatureSensorPin);

-unsigned long lastIncrement = 0;
+unsigned long lastUpdate = 0;

 int digitValues[] =
 {
@@ -83,9 +83,6 @@
   writeValue(0, valueToDisplay, false);
 }

-bool toggle = false;
-unsigned long lastToggle = 0;
-
 void loop()
 {
   float place = calculatePlace(3 - segmentIndex, decimals);
@@ -99,10 +96,10 @@
   valueToDisplay = temperatureInF;

   unsigned long now = millis();
-  if (now > lastIncrement + 100)
+  if (now > lastUpdate + 100)
   {
     sensor.update();
-    lastIncrement = now;
+    lastUpdate = now;
   }

   digitalWrite(ledPin, (now % 200 == 0) ? HIGH : LOW);
@@ -120,6 +117,7 @@
     case 1: return 10;
     case 2: return 100;
     case 3: return 1000;
+    default: assert(false);
   }
 }


read temperature async

read temperature async

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -50,7 +50,8 @@

 #define BACKLIGHT_BLINK_RATE 200

-#define DALLAS_RESOLUTION 9 //This will give faster read at 0.5C precision.
+#define DALLAS_RESOLUTION 11 //This will give 0.125C precision
+#define DALLAS_READING_DELAY 750/ (1 << (12-DALLAS_RESOLUTION))

 typedef enum {
   STATE_MCB_TRIPPED, STATE_WINDOW_BEFORE, STATE_WINDOW_WITHIN, STATE_WINDOW_EXITED, STATE_TEMP_MAX
@@ -100,6 +101,7 @@
   dallasTemp.begin();
   dallasTemp.getAddress(tempDeviceAddress, 0);
   dallasTemp.setResolution(tempDeviceAddress, DALLAS_RESOLUTION);
+  dallasTemp.setWaitForConversion(false); //I'll read temperatures asynchronously

   unsigned long initialTime = millis();
   unsigned long timeElapsedSinceStart;
@@ -565,10 +567,21 @@
 }

 float getTemperature(){
-  //There is only one sensor on the bus so just use the first one
-  dallasTemp.requestTemperaturesByIndex(0);
-  float temperature = dallasTemp.getTempCByIndex(0);
-  return temperature;
+
+  static float previousTemperature = -273.15;
+  static unsigned long previousReadingTime = 0;
+
+  unsigned long currentTime = millis();
+
+  if((currentTime - previousReadingTime) > DALLAS_READING_DELAY){
+    previousTemperature = dallasTemp.getTempCByIndex(0);
+    previousReadingTime = currentTime;
+    dallasTemp.requestTemperaturesByIndex(0);
+  }
+
+  return previousTemperature;
+
+
 }

 bool isTopButtonPressed(){


Print a newline properly.

Print a newline properly.

--- libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino
+++ libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino
@@ -30,12 +30,11 @@
     Serial.println("Start");
   });
   ArduinoOTA.onEnd([]() {
-    Serial.println("End");
+    Serial.println("\nEnd");
   });
   ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
     Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
   });
-  Serial.println("")
   ArduinoOTA.onError([](ota_error_t error) {
     Serial.printf("Error[%u]: ", error);
     if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");


Shrink buffer.

Shrink buffer.

--- ntptask.ino
+++ ntptask.ino
@@ -20,7 +20,7 @@

   /* save reset reason */
   if ( preferences.getString("bootlog").equalsIgnoreCase("on") ) {
-    char content[100];
+    char content[60];
     snprintf( content, sizeof( content ), " %s,%s", resetString( 0 ), resetString( 1 ) );
     logger.appendToFile( "/reset_reasons.txt", HUMAN_TIME, content );
   }


Comentarios

Comentarios

--- 01-persiana/sketch/persiana.ino
+++ 01-persiana/sketch/persiana.ino
@@ -4,6 +4,10 @@
 // Saber de dónde viene la orden: LOW = botón, HIGH = mqtt
 int mqtt_control = LOW;

+
+// ==========
+// SUBIMOS PERSIANA
+// ==========
 void up() {
   digitalWrite(DOWN_PIN, LOW);
   delay(SECURITY_DELAY);
@@ -17,6 +21,9 @@

 }

+// ==========
+// BAJAMOS PERSIANA
+// ==========
 void down() {
   digitalWrite(UP_PIN, LOW);
   delay(SECURITY_DELAY);
@@ -29,24 +36,38 @@
   #endif
 }

+// ==========
+// PARAMOS PERSIANA
+// ==========
 void stop_all() {
   // mqtt_client.publish("/DOMUS/OFFICE/PERSIANA", "STOP", true);
   digitalWrite(UP_PIN, LOW);
   digitalWrite(DOWN_PIN, LOW);
 }

+
+
+// ==========
+// RECIBIMOS "SUBIR" por MQTT
+// ==========
 void up_mqtt() {
   mqtt_control = HIGH;
   up_state = LOW;
   down_state = HIGH;
 }

+// ==========
+// RECIBIMOS "BAJAR" por MQTT
+// ==========
 void down_mqtt() {
   mqtt_control = HIGH;
   up_state = HIGH;
   down_state = LOW;
 }

+// ==========
+// RECIBIMOS "STOP" por MQTT
+// ==========
 void stop_mqtt() {
   stop_all();
   mqtt_control = LOW;


Declare screens as an array rather than #defines

--- moros/moros.ino
+++ moros/moros.ino
@@ -1,12 +1,3 @@
-// For the breakout, you can use any (4 or) 5 pins
-
-#define cs_1   4
-#define dc_1   5
-#define rst_1  6
-#define cs_2   7
-#define dc_2   8
-#define rst_2  9
-
 #include <SPI.h>
 #include <TFT.h>

@@ -52,6 +43,25 @@
 };

 typedef struct {
+  unsigned int cs_pin;
+  unsigned int dc_pin;
+  unsigned int rst_pin;
+} screen;
+
+screen screens[2] = {
+  {
+    cs_pin: 4,
+    dc_pin: 5,
+    rst_pin: 6
+  },
+  {
+    cs_pin: 7,
+    dc_pin: 8,
+    rst_pin: 9
+  }
+};
+
+typedef struct {
   long time_remaining_ms;
   long last_update_ms;
   TFT tft;
@@ -65,7 +75,7 @@
   {
     INITIAL_TIME_MS,
     0,
-    TFT(cs_1, dc_1, rst_1),
+    TFT(screens[0].cs_pin, screens[0].dc_pin, screens[0].rst_pin),
     "",
     0,
     buttons[0].interrupt_number,
@@ -74,7 +84,7 @@
   {
     INITIAL_TIME_MS,
     0,
-    TFT(cs_2, dc_2, rst_2),
+    TFT(screens[1].cs_pin, screens[1].dc_pin, screens[1].rst_pin),
     "",
     0,
     buttons[1].interrupt_number,


115200 serial monitor at runtime too, whee

--- moros/moros.ino
+++ moros/moros.ino
@@ -73,8 +73,8 @@
 // does the SPI library allow selecting of which SS to issue the command on?

 void setup(void) {
-  Serial.begin(9600);
-  Serial.println("hello!");
+  Serial.begin(115200);
+  Serial.println("Initializing...");

   char timea[12];
   for(int i = 0; i < sizeof(players) / sizeof(players[0]); i++) {
@@ -87,13 +87,10 @@
     ltoa(players[i].time_remaining_ms/100, timea, 10);
     strncpy(players[i].display_time, timea, 12);
     players[i].tft.text(timea, 0, 20);
-    Serial.println("handle button press:");
-    Serial.println((int)players[i].handle_button_press);
-    Serial.println(players[i].interrupt_number);
     attachInterrupt(players[i].interrupt_number, players[i].handle_button_press, RISING);
   }

-  Serial.println("init");
+  Serial.println("done.");
   //delay(100);
   //exit(1);
 }


Commit Stage 4

Commit Stage 4

--- compet/stage4/stage4.ino
+++ compet/stage4/stage4.ino
@@ -85,7 +85,6 @@
     Position0 += QEM [Old0 * 4 + New0];

     myRobot->setPositionRight(Position0);
-
 }

 void setup() {
@@ -111,24 +110,38 @@

     attachInterrupt(digitalPinToInterrupt(encoderPinA), isr, CHANGE);    //init the interrupt mode for the digital pin 2
     attachInterrupt(digitalPinToInterrupt(encoderPinB), isr, CHANGE);   //init the interrupt mode for the digital pin 3
-
-
 }

 void loop() {
   // forwardAt
   delay(10000);
-  myRobot->forwardAtDistance(100, 60);
-  // forwardAtDifferentSpeed
+  myRobot->forwardAtDistance(100, 10);
+
+  myRobot->turnLeftAtDegre(150, 20);
+
+  myRobot->forwardAtDistance(100, 15);
+
+  myRobot->turnLeftAtDegre(150, 20);
+
+  myRobot->forwardAtDistance(100, 15);
+
+  myRobot->turnLeftAtDegre(150, 20);
+
+  myRobot->forwardAtDistance(100, 15);
+
+  myRobot->turnLeftAtDegre(150, 20);
+
+  myRobot->forwardAtDistance(100, 15);
+
+  myRobot->turnLeftAtDegre(150, 10 );
+
+  myRobot->forwardAtDistance(100, 155);
+
   myRobot->forwardDifferentSpeed(150,100);
-  // forwardAt
-  myRobot->forwardAtDistance(100, 155);
-  // forwardAtDifferentSpeed
-  myRobot->forwardDifferentSpeed(150,100);
-  // forwardAt
+
   myRobot->forwardAtDistance(100, 50);
-  //end
+
 }


JSON outputs

JSON outputs

--- ppt/ppt.ino
+++ ppt/ppt.ino
@@ -217,6 +217,40 @@
   Serial.print("  ");

   Serial.print("\n\r");
+}
+
+void print_data_json(void) {
+  Serial.print("{\"time\": ");
+  Serial.print(seconds, DEC);
+
+  Serial.print(", \"state\": ");
+  if (power_status.mode == off)              Serial.print("\"off\",  ");
+  else if (power_status.mode == mppt_on)     Serial.print("\"mppt\",   ");
+  else if (power_status.mode == auto_off)    Serial.print("\"autooff\",");
+  else if (power_status.mode == bulk)        Serial.print("\"bulk\", ");
+  else if (power_status.mode == bat_float)   Serial.print("\"float\",");
+  else if (power_status.mode == const_volt)  Serial.print("\"volt\", ");
+  else if (power_status.mode == const_power) Serial.print("\"watt\", ");
+
+  Serial.print(" \"target\": ");
+  print_int100_dec2(power_status.target);
+
+  Serial.print(", \"pwm\": ");
+  print_int100_dec2((long)power_status.pwm_duty * 10000 / (PWM_FULL - 1));
+
+  Serial.print(", \"volts_in\": ");
+  print_int100_dec2(power_status.sol_volts);
+
+  Serial.print(", \"volts_out\": ");
+  print_int100_dec2(power_status.bat_volts);
+
+  Serial.print(", \"amps_in\": ");
+  print_int100_dec2(power_status.sol_amps);
+
+  Serial.print(", \"watts_in\": ");
+  print_int100_dec2(power_status.sol_watts);
+
+  Serial.println("}");
 }
 //------------------------------------------------------------------------------------------------------
 // This routine reads all the analog input values for the system. Then it multiplies them by the scale


Enable debug by default.

Enable debug by default.

It's just more convenient right now.

--- printer.ino
+++ printer.ino
@@ -35,7 +35,7 @@
 const byte buttonPin = 3;      // the print button
 const byte SD_Pin = 4;         // the SD Card SPI pin

-// #define DEBUG // When debug is enabled, log a bunch of stuff to the hardware Serial
+#define DEBUG // When debug is enabled, log a bunch of stuff to the hardware Serial

 // -- Everything below here can be left alone


Add bluetooth code in

Add bluetooth code in

--- Caravan_Thermostat_TX/Caravan_Thermostat_TX.ino
+++ Caravan_Thermostat_TX/Caravan_Thermostat_TX.ino
@@ -23,11 +23,11 @@
 #define rst  8

 // DHT11
-#define DHT11PIN 2
+#define DHT11PIN 4

 // BLE
-#define BLERXPIN 3
-#define BLETXPIN 4
+#define BLERXPIN 2
+#define BLETXPIN 3

 // IR Receiver
 #define IRPIN 5
@@ -37,7 +37,7 @@
 dht DHT;
 IRrecv irrecv(IRPIN);
 decode_results results;
-SoftwareSerial BT(BLERXPIN, BLETXPIN); // RX, TX
+SoftwareSerial BTserial(BLERXPIN, BLETXPIN); // RX, TX

 // Define Global Variables

@@ -55,8 +55,10 @@
 int ReqTempStartPointY = TFTscreen.height() - 32;
 int PreviousHour = 0;
 int PreviousMinute = 0;
+int BTCheckLoop = 0;
 String PreviousDate = "";
 uint32_t IRCheckTime = 0;
+uint32_t BTCheckTime = 0;

 char *MessageOfTheDay[] =
 {
@@ -85,19 +87,55 @@
 #include "CampFireGFX.h"

 void setup() {
-  Serial.begin(115200);
+  Serial.begin(9600);
   setSyncProvider(RTC.get);
   SetupDisplayLayout();
   irrecv.enableIRIn();
+  Serial.println("Enter AT commands:");
+  BTserial.begin(9600);
+  //at("AT+NAMECaravanTX");
+  //at("AT+ROLE1");
+  //at("AT+RESET");
+  delay(1000); // wait a bit, NECESSARY!!
+  at("AT+INQ");
+  // Master Address 00:15:83:00:84:F7
+  // Slave Address 00:15:83:00:83:EE
+  //at("Hello World!!");
 }

 void loop() {
   // Read the Temperature
   ReadTemperature();
   ReadTime();
-  CheckIR(); // This has the delay of 2000ms
-}
-
+  //CheckIR(); // This has the delay of 2000ms
+  CheckBT(); // This has a delay of 2000ms
+
+}
+
+void CheckBT()
+{
+  BTCheckLoop++;
+  if (BTCheckLoop == 5)
+  {
+    Serial.println("Trying To Pair");
+    at("AT+CONN1");
+    Serial.println("Paired");
+  }
+  BTCheckTime = millis() + 2000;
+  while (BTCheckTime > millis())
+  {
+    if (BTserial.available())
+    {
+      Serial.write(BTserial.read());
+    }
+
+    // Keep reading from Arduino Serial Monitor and send to HC-06
+    if (Serial.available())
+    {
+      BTserial.write(Serial.read());
+    }
+  }
+}
 void CheckIR()
 {
   IRCheckTime = millis() + 2000;
@@ -165,9 +203,11 @@
         // Do we need to turn the heating on?
         if (sensorVal < ReqTemp - 1)  {
           HeatingOn = true;
+              at("*HEAT*");
         }
         if (sensorVal >= ReqTemp) {
           HeatingOn = false;
+              at("*COOL*");
         }
         DrawFire(HeatingOn);
       }
@@ -267,7 +307,6 @@
   {
     TFTscreen.drawBitmap(TFTscreen.width() - 45, 36, CampFireFlames, 40, 44, Black);
   }
-
   TFTscreen.drawBitmap(TFTscreen.width() - 45, 80, CampFireLogs, 40, 12, Brown);
 }

@@ -288,5 +327,12 @@
   memcpy(PreviousTemperature, CurrentTemperature, 2);
 }

-
-
+void at(char* cmd) {
+  BTserial.write(cmd);
+  BTserial.write("\r\n");
+  Serial.print(cmd);
+  //while (!BTserial.find("OK") || !BTserial.find("Connected")) Serial.print(".");
+
+  Serial.println(" .. OK");
+}
+