Delete game_snake.ino

Delete game_snake.ino

--- examples/game_snake/game_snake.ino
+++ examples/game_snake/game_snake.ino
@@ -1,250 +0,0 @@
-#include <Servo.h>
-#include <InkyBoard.h>
-#include <Display.h>
-
-InkyBoard B; // definieer B als InkyBoard
-
-// structure for holding coordinates
-struct snakePart{
-  int x;
-  int y;
-};
-
-unsigned long snakeRefreshRate; // refreshrate of snake (higher means longer to refresh = slower snake)
-volatile snakePart parts[64]; // array to hold snakeparts, max 64 => no more dots on screen
-int snakeLength; // length of the snake
-int p_parts; // pointer for snake array
-int snakeDirection; // direction of this snake
-snakePart apple; // location of the apple
-boolean appleEaten; //
-boolean ghost; // in ghost mode, snake can go through walls
-
-int highScore = 0;
-
-const static byte PRIZE [] = {B01111110,B10111101,B10111101,B01111110,B00111100,B00011000,B00011000,B00111100};
-
-void setup() {
-  B.init();
-  B.display.wakeup();
-
-  snakeStart(); // initialize the snake
-
-  Serial.begin(9600);
-}
-
-void loop() {
-  snake(); // run the snake code
-}
-
-/**
- * Initialize the snake
- */
-void snakeStart(){
-  snakeLength = 5; // startup length of the snake
-  parts[0].x = 0; // starting x position
-  parts[0].y = 0; // starting y position
-  snakeDirection = 1; // starting direction
-  snakeRefreshRate = 100; // starting speed
-  ghost = true; // gost mode
-
-  randomSeed(analogRead(B.pLight)); // make sure the random function is random
-  random(1000); // start up the random function (weird arduino stuff)
-
-  // make sure the tail is not on the screen on startup
-  for(int i=(65-snakeLength); i< 64; i++){
-    parts[i].x = -1;
-    parts[i].y = -1;
-  }
-
-  p_parts = 1; // reset the pointer to 1
-  appleEaten = true; // make sure a new apple is created
-}
-
-/**
- * Main snake function
- */
-void snake(){
-  static unsigned long snakeTimer = millis(); // start the snake timer
-
-  checkSnakeDirection(); // check direction change (and do this every loop!)
-
-  if((millis() - snakeTimer) > snakeRefreshRate){ // check if
-    snakeTimer = millis();
-
-    checkSnakeSpeed(); // check speed change
-    moveSnake(); // move snake 1 step in direction
-    drawSnake(); // draw new snake
-    makeApple(); // make and draw an apple
-  }
-}
-
-/**
- * Check if button is pressed and change direction accordingly
- */
-void checkSnakeDirection(){
-  for(int i = 0; i < 4; i++){ // check all 4 buttons
-    if(digitalRead(B.apButton[i])){ // if button is high
-      if(i != (snakeDirection + 2) && i != (snakeDirection -2)){ // only change direction if the snake won't turn backwards
-        snakeDirection = i; // change direction
-      }
-    }
-    else{
-      digitalWrite(B.apLed[i], LOW); // LED's off
-    }
-  }
-  digitalWrite(B.apLed[snakeDirection], HIGH); // Direction LED on
-}
-
-/**
- * Check and changes snakespeed (or actualy refresh rate)
- */
-void checkSnakeSpeed(){
-  snakeRefreshRate = map(B.getPot(),0,1023,300,50); // get pot value and use it to set snake speed (lower is faster)
-  B.setServo(B.getPot(true)); // show speed with the servo
-}
-
-/**
- * Draw the snake
- */
-void drawSnake(){
-  B.display.clear();  // clear display
-
-  int pos;
-  int headPos = p_parts - 1; // get position of the head in the array with snake parts
-  if(headPos >= 64) pos = 0; // array is only 64 items big
-
-  boolean collision = false;
-
-  snakePart head = {parts[headPos].x, parts[headPos].y}; // the head of the snake
-
-  for(int i = 0; i < snakeLength; i++){ // go through every snake part
-    pos = p_parts - snakeLength + i; // this is the position in the array
-    if(pos < 0) pos = 64 + pos; // cant be smaller than 0
-    else if(pos >= 64) pos = pos - 64; // and bigger than 63
-
-    if(parts[pos].x == head.x && parts[pos].y == head.y && headPos != pos){ // check if the x and y of this part is not the same as the head
-      collision = true; // if they are the same: collision with itself!
-    }
-
-    B.display.pixel(parts[pos].x, parts[pos].y); // display snake part
-  }
-
-  if(collision){
-    snakeRestart(); // the snake is dead, so restart
-  }
-}
-
-/**
- * Move the snake (remove tail and make new head)
- */
-void moveSnake(){
-  boolean collision = false;
-
-  int pos = p_parts -1; // current array position
-  if(pos < 0) pos = 64 + pos; // smaller than 0 is not possible
-  else if(pos >= 64) pos = pos - 64; // bigger than 63 neither
-
-  snakePart p = {parts[pos].x, parts[pos].y}; // current head
-  switch(snakeDirection){
-    case 0:
-      p.y--; // up (y starts at the top with 0 so up is a number closer to zero
-      break;
-    case 1:
-      p.x++; // right
-      break;
-    case 2:
-      p.y++; // left
-      break;
-    case 3:
-      p.x--; // down
-      break;
-  }
-
-
-  if(p.x >= 8){ // collision with the wall
-    collision = true;
-    p.x=0;
-  }
-  else if(p.x < 0){ // collision with the wall
-    collision = true;
-    p.x=7;
-  }
-  if(p.y >= 8){ // collision with the wall
-    collision = true;
-    p.y=0;
-  }
-  else if(p.y < 0){ // collision with the wall
-    collision = true;
-    p.y=7;
-  }
-  if(!ghost && collision == true){ // only restart if there is a collision with the wall and ghost-mode is off
-    snakeRestart();
-    return;
-  }
-
-  if(p.x == apple.x && p.y == apple.y){ // if the new head position is same as apple position
-    snakeLength++; // increase lenght of the snake
-    appleEaten = true; // the snake at an apple
-  }
-
-  parts[p_parts].x = p.x; // add new head to the array (x)
-  parts[p_parts].y = p.y; // add new head to the array (y)
-  p_parts++; // increase array pointer
-  if(p_parts >= 64) p_parts = 0; // pointer can't be bigger than 63
-}
-
-/**
- * create a new apple (if nessesary)
- */
-void makeApple(){
-  if(appleEaten){ // only make a new one if the current apple is eaten
-    apple.x = random(0,8); // new random position (x)
-    apple.y = random(0,8); // new random position (y)
-
-    appleEaten = false; // this apple is not eaten yet
-  }
-  B.display.pixel(apple.x, apple.y); // display the apple
-}
-
-/**
- * game over, restart the game
- */
-void snakeRestart(){
-  for(int i=7; i>=0; i--){ // decrease the intensity of the screen
-    B.display.intensity(i);
-    delay(100);
-  }
-
-  B.display.clear(); // clear screen
-  B.display.intensity(8); // set intensity back to default
-
-  delay(300);
-
-  showScore(); // show score
-
-  snakeStart(); // start a new game
-
-  delay(200);
-}
-
-/**
- * show the score
- */
-void showScore(){
-  if(snakeLength > highScore){ // if this score is better than highscore
-    highScore = snakeLength; // score is the new highscore
-
-    for(int i = 0; i < 2; i++){ // display score + prize 2 times
-      B.display.number(snakeLength); // display score
-      delay(1000);
-      B.display.image(PRIZE); // display prize
-      delay(1000);
-    }
-
-  }
-  else{ // no highscore
-    B.display.number(snakeLength); // display score
-    delay(2000);
-  }
-}
-


Ajout de #include "application.h"

Ajout de #include "application.h"

--- firmware/examples/TeleInfo_exemple.ino
+++ firmware/examples/TeleInfo_exemple.ino
@@ -7,6 +7,7 @@

 #include "teleinfo/TeleInfo.h"
+#include "application.h"

 // ======== MAIN ============


Screen Brightness Function

Screen Brightness Function

The code controlling the screen brightness within Setup and the loop were both moved to a function to clean up the code within setup and loop.

--- WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
+++ WVO_Controller_0.6.3/WVO_Controller_0.6.3.ino
@@ -142,9 +142,7 @@

 void setup()
 {
-  dayLightVal = analogRead(A10);
-  backlightValue = 0.2138*dayLightVal + 20.5;
-  analogWrite(backlightPin, backlightValue);
+  screen_brightness();

   Tft.TFTinit();                                        // init TFT library

@@ -197,17 +195,6 @@
   Point p = ts.getPoint();
   p.x = map(p.x, TS_MINX, TS_MAXX, 0, 240);
   p.y = map(p.y, TS_MINY, TS_MAXY, 0, 320);
-
-  dayLightVal = analogRead(A10);
-  //Serial.println(dayLightVal);
-  //backlightPerc = (0.0000003*(dayLightVal*dayLightVal*dayLightVal))-(0.0006*(dayLightVal*dayLightVal))+(0.397*dayLightVal);
-  //Serial.println(backlightPerc);
-  backlightValue = 0.2138*dayLightVal + 20.5;
-  //Serial.println(backlightValue);
-  //backlightValue = ((backlightPercent*backlightPercent*backlightPercent)/3937) + 1.5;
-  //backlightValue = (127 * backlightPercent) / 50 + 1;
-  analogWrite(backlightPin, backlightValue);
-  //Serial.println(backlightValue);

   int sensorValue = analogRead(A11);
   float voltage = sensorValue * (5.0 / 1023.0);
@@ -233,8 +220,9 @@
     index = 0;                                  // calculate the average:
   average = total / numReadings;

-fuelGage();
-fuelPressure();
+  screen_brightness();
+  fuelGage();
+  fuelPressure();

   if (page == 0 && purgeState == 0)
@@ -1119,6 +1107,25 @@
   pressure = sumP / numReadings;
 }

+void screen_brightness()
+{
+  /*
+   * Below is old code for the backlight brightness when the manual setting was still used, before upgrading to the auto brightness
+   * function with the photo-diode
+  Serial.println(dayLightVal);
+  backlightPerc = (0.0000003*(dayLightVal*dayLightVal*dayLightVal))-(0.0006*(dayLightVal*dayLightVal))+(0.397*dayLightVal);
+  Serial.println(backlightPerc);
+  Serial.println(backlightValue);
+  backlightValue = ((backlightPercent*backlightPercent*backlightPercent)/3937) + 1.5;
+  backlightValue = (127 * backlightPercent) / 50 + 1;
+  analogWrite(backlightPin, backlightValue);
+  */
+
+  dayLightVal = analogRead(A10);
+  backlightValue = 0.2138*dayLightVal + 20.5;
+  analogWrite(backlightPin, backlightValue);
+}
+

 //float getVoltage(int pin)				        // function that reads the value of the temperature pin and returns it
 // to be converted into a temperature value.


Changed the writing of data files to use a 32 byte buffer intead of writing 1 byte at a time. This significantly speeds up the data transfer.

--- SuperGraphingDataLogger/SuperGraphingDataLogger.ino
+++ SuperGraphingDataLogger/SuperGraphingDataLogger.ino
@@ -146,7 +146,7 @@

   // The SD card is working, start the server and ethernet related stuff!
   if (Ethernet.begin(mac) == 0) {
-    //Serial.println("Failed to configure DHCP");
+    //Serial.println("Failed to configure Ethernet using DHCP");
     // don't do anything more:
     return;
   }
@@ -395,11 +395,12 @@

             HtmlHeaderOK(client);

-            int16_t c;
-            while ((c = file.read()) > 0) {
-                // uncomment the serial to debug (slow!)
-                //Serial.print((char)c);
-                client.print((char)c);
+            while(file.available()) {
+              int num_bytes_read;
+              uint8_t byte_buffer[32];
+
+              num_bytes_read=file.read(byte_buffer,32);
+              client.write(byte_buffer,num_bytes_read);
             }
             file.close();
           }


Update BasicUltrasonic test to be a bit more useful

--- ARTF_Sensors/examples/BasicUltrasonic/BasicUltrasonic.ino
+++ ARTF_Sensors/examples/BasicUltrasonic/BasicUltrasonic.ino
@@ -1,21 +1,70 @@
 /*
   Test Ultrasonic sensor readings

+  This sketch takes 5 readings and averages them to
+  help verify similar calcuations used in BridgeSensorGSM
+  sketch.
+
   Created 2 7 2014
-  Modified 2 7 2014
+  Modified 10 7 2014
 */
+

 // Ultrasonic sensor settings
 const byte ULTRASONIC_PIN = A6;
+const int DISTANCE_INCREMENT = 5;
+const int NUM_READINGS = 5;
+

 void setup()
 {
   Serial.begin(9600);
 }

-
+int count = 1;
 void loop()
 {
-  Serial.println(analogRead(ULTRASONIC_PIN));
-  delay(1000);
+  Serial.print("Trial ");
+  Serial.println(count);
+  Serial.println("-------------------");
+
+  // Take X readings
+  int distanceReadings[NUM_READINGS];
+  for (int i = 0; i < NUM_READINGS; ++i)
+  {
+    int reading = analogRead(ULTRASONIC_PIN);
+    distanceReadings[i] = reading * DISTANCE_INCREMENT;
+
+    Serial.print(i);
+    Serial.print(". Analog:");
+    Serial.print(reading);
+    Serial.print("; Calculated:");
+    Serial.print(reading * DISTANCE_INCREMENT);
+
+    delay(300);
+  }
+
+  // Average the readings
+  double sumDistance = 0.0;
+  for (int i = 0; i < NUM_READINGS; ++i)
+  {
+    sumDistance += distanceReadings[i];
+  }
+  double avgDistance = sumDistance / NUM_READINGS;
+
+  // Rounded measurements
+  int roundedDistance = round(avgDistance);
+
+
+  Serial.print("Sum:");
+  Serial.println(sumDistance);
+
+  Serial.print("Avg:");
+  Serial.println(avgDistance);
+
+  Serial.print("Rounded:");
+  Serial.println(roundedDistance);
+
+  delay(500);
+  count += 1;
 }


Moved to examples folder

Moved to examples folder


Mise à jour du nombre de modules lors d'un MAJ et ordonnancement des modules selon leur ordre d'allumage

--- src/deplacement/deplacement.ino
+++ src/deplacement/deplacement.ino
@@ -15,12 +15,12 @@
   backTime = 0;
   bras.attach(3);
   bras.write(90);
+  nbModules = 0;
+  posX = 1;
   Serial1.begin(9600);
   Serial1.write("NEW");
   reset();
   noRecv = 0;
-  nbModules = 1;
-  posX = 3;
 }

 void loop() {
@@ -58,11 +58,15 @@
     {
         reset();
         nbModules++;
+        Serial1.write("MAJ");
+        Serial1.write(nbModules);
+
     }
     else if(recv[0] == 'M' && recv[1] == 'A' && recv[2] == 'J')
     {
        char nbModulesRecv = Serial1.read();
        nbModules = nbModulesRecv;
+       posX = nbModules;
     }
     noRecv = 0;
   }


adding range repetitions

adding range repetitions

--- firmware/SVPA-FloodSensor-2016.ino
+++ firmware/SVPA-FloodSensor-2016.ino
@@ -63,6 +63,7 @@
 #define ChangeAddressCommand2 byte(0xA5)

 int rangValue = 0;
+int rangeRep = 30; // Number of range readings to take and average.

 int led2 = D7; // Instead of writing D7 over and over again, we'll write led2

@@ -257,6 +258,58 @@
   altf = weatherShield.readAltitudeFt();
 }

+void getRange() {
+
+    int rangeReadingIndex;
+    int rangeReading[rangeRep];
+    uint16_t range;
+    int rangeSum = 0;
+    int rangeCount,rangeMax;
+    float rangeAvg;
+    for (int i=0; i<=rangeRep; i++){
+      //currentReport.readings[i] =  getLastReading(i);
+
+      takeRangeReading();
+      //Tell the sensor to perform a ranging cycle
+      delay(100);
+      //Wait for sensor to finish
+      range = requestRange();
+      //Get the range from the sensor
+
+      rangeReading[i] = range;
+
+      // @TODO Add debugging feedback. LEDs?
+      Serial.print("Range String - ");
+      Serial.println(String(i));
+      Serial.print(": ");
+      Serial.println(String(rangeReading[i]));
+      //Print to the user
+
+      delay(500);
+    }
+
+    // @TODO Screen for outliers and compute the average range.
+
+    rangeMax = 0;
+    rangeSum = 0;
+    for (int i=0; i<=rangeRep; i++){
+      rangeSum = rangeSum + rangeReading[i];
+      if (range > rangeMax) {rangeMax = rangeReading[i];};
+
+
+    }
+    rangeAvg = rangeSum / rangeRep;  //update the online range varable
+
+    Serial.print("Range Average: "); Serial.println(String(rangeAvg));
+    //Print to the user
+    Serial.print("Range Max: "); Serial.println(String(rangeMax));
+    //Print to the user
+
+    //rangValue = (int) rangeAvg;
+    rangValue = rangeMax;
+
+}
+
 void takeRangeReading(){
     Wire.beginTransmission(SensorAddress);
     //Start addressing
@@ -264,24 +317,6 @@
     //send range command
     Wire.endTransmission();
     //Stop and do something else now
-}
-
-void getRange() {
-
-
-    takeRangeReading();
-    //Tell the sensor to perform a ranging cycle
-    delay(100);
-    //Wait for sensor to finish
-    uint16_t range = requestRange();
-    //Get the range from the sensor
-
-
-    rangValue = range;  //update the online range varable
-
-    Serial.print("Range String: "); Serial.println(String(rangValue));
-    //Print to the user
-
 }


modes

modes

--- main/main.ino
+++ main/main.ino
@@ -127,6 +127,14 @@

 // MODE VARIABLES ////////////////////////////////////

+enum Mode {
+  dual,
+  quad,
+  octo,
+  diag
+};
+Mode currentMode;
+
 bool dualModeReady = false;
 bool quadModeReady = false;
 bool octoModeReady = false;
@@ -140,6 +148,8 @@
 MCP_CAN CAN(SPI_CS_PIN);

 void setup() {
+
+  currentMode = octo;

   pinMode(LED_PIN, OUTPUT);
   pinMode(MODE_PIN, INPUT_PULLUP);
@@ -209,9 +219,16 @@
   currentMillis = millis();
   if(currentMillis - lastDisplayMillis >= displayInterval && currentMillis > 500) {
     lastDisplayMillis = currentMillis;
-      //draw_octo_gauges();
-      //draw_dual_gauges();
-      draw_quad_gauges();
+
+      if(currentMode == dual) {
+        draw_dual_gauges();
+      }
+      else if(currentMode == quad) {
+        draw_quad_gauges();
+      }
+      else if(currentMode == octo) {
+        draw_octo_gauges();
+      }
   }

   if(currentMillis - lastDiagnosticMillis >= diagnosticInterval && currentMillis > 500) {
@@ -228,6 +245,18 @@

 }

+void next_mode() {
+  if(currentMode == dual) {
+    currentMode = quad;
+  }
+  else if(currentMode == quad) {
+    currentMode = octo;
+  }
+  else if(currentMode = octo) {
+    currentMode = dual;
+  }
+  //diag mode is not implemented yet
+}

 void clear_mode() {
   dualModeReady = false;


Better turnmark output.

Better turnmark output.

--- brotherKH930_arduino.ino
+++ brotherKH930_arduino.ino
@@ -46,9 +46,9 @@
     else Serial.print("_");
     Serial.print("\t");

-    if (brother.isAtLeftMark()) Serial.print(" at L");
-    else if (brother.isAtRightMark()) Serial.print(" at R");
-    else Serial.print("     ");
+    if (brother.isAtLeftMark()) Serial.print("at L");
+    else if (brother.isAtRightMark()) Serial.print("at R");
+    else Serial.print("    ");
     Serial.println();
     Serial.flush();
   }


firmware: command sonar works now

firmware: command sonar works now


fixed non-changed color after tuning

fixed non-changed color after tuning

--- hal100/hal100.ino
+++ hal100/hal100.ino
@@ -71,7 +71,6 @@
 float valueRotateC2 = -1;
 float valueRotateL = -1;
 float valueSWR;
-float stepsToMhFloat;

 boolean presentValue = false;

@@ -129,8 +128,8 @@
         boolean bsy = payload->status.flags & (1 << 3);
         if (isBusy != bsy) {
           isBusy = bsy;
-          displayRefreshFlags |= DISPLAY_REFRESH_BSY;
-        }
+          displayRefreshFlags |= (DISPLAY_REFRESH_BSY | DISPLAY_REFRESH_C1 | DISPLAY_REFRESH_C2 | DISPLAY_REFRESH_L);
+        }
         break;
       }
     case cmdDebug: {
@@ -231,13 +230,13 @@

 void displayValueLuH() {                                         // display L values in uH
   dtostrf(stepsToUH(valueRotateL), 4, 3, DisplayValueL1uH);
-  if (isBusy) {
-    tft.setTextColor(TFT_YELLOW);
+  tft.setTextSize(1);
+  tft.drawString(DisplayValueL1uH, 50, 42, 4);
+  if (isBusy) {
+    tft.setTextColor(TFT_YELLOW, TFT_BLACK);
   } else {
-    tft.setTextColor(TFT_GREEN);
-  }
-  tft.setTextSize(1);
-  tft.drawString(DisplayValueL1uH, 50, 42, 4);
+    tft.setTextColor(TFT_GREEN, TFT_BLACK);
+  }
 }

 void ErasDisplayValueLuH() {                                   // erase display L values in uH
@@ -346,13 +345,15 @@

 void displayValueC2pF() {                                           // display C2 values in pF
   dtostrf(stepsC2topF(valueRotateC2), 4, 1, DisplayValueC2pF);
-  if (isBusy) {
-    tft.setTextColor(TFT_YELLOW);
-  } else {
-    tft.setTextColor(TFT_GREEN);
-  }
-  tft.setTextSize(1);
-  tft.drawString(DisplayValueC2pF, 50, 107, 4);
+   tft.setTextSize(1);
+   tft.drawString(DisplayValueC2pF, 50, 107, 4);
+
+  if (isBusy) {
+     tft.setTextColor(TFT_YELLOW, TFT_BLACK);
+   } else {
+    tft.setTextColor(TFT_GREEN, TFT_BLACK);
+  }
+
 }

 void ErasDisplayValueC2pF() {                                       // erase display C1 values in pF
@@ -484,7 +485,7 @@
     }
     if ((displayRefreshFlags & DISPLAY_REFRESH_BSY) != 0) {
       if (!isBusy) {
-        tft.setTextColor(TFT_YELLOW);
+        tft.setTextColor(TFT_YELLOW, TFT_BLACK);
         digitalWrite(40, LOW);
       } else {
         tft.setTextColor(TFT_BLACK);


Added forgotten click type

Added forgotten click type

--- src/cyclop_plus/cyclop_plus.ino
+++ src/cyclop_plus/cyclop_plus.ino
@@ -330,7 +330,7 @@
   if (saveScreenActive) {
     saveScreenActive = 0;
     while (digitalRead(buttonPin) == BUTTON_PRESSED) ;
-    return ( NO_CLICK );
+    return ( WAKEUP_CLICK );
   }

   while (digitalRead(buttonPin) == BUTTON_PRESSED) {


Use new button class

Use new button class

--- midicontroller.ino
+++ midicontroller.ino
@@ -1,14 +1,12 @@
-#include <Bounce2.h>
+#include "Button.h"
+#include "base64/Base64.h"

 #include <Adafruit_GFX.h>
-
 #include <SPI.h>
-
 #include <Wire.h>
-
 #include <Adafruit_SSD1306.h>

-#include "base64/Base64.h"
+

 byte counter;
 const byte CLOCK = 248;
@@ -17,17 +15,19 @@
 const byte STOP = 252;
 const int ledPin = 13;

+const byte bpmLed = 22;
+
 const byte channelButtonStart = 0;
 const byte numberOfChannelButtons = 2;
 const byte ledPins[] = {/*10, 11, 12,*/ 14, 15, 16};
-Bounce channelButtons[numberOfChannelButtons];
+Button channelButtons[numberOfChannelButtons];
 boolean channelButtonStates[numberOfChannelButtons];
 boolean channelButtonDown[numberOfChannelButtons];

 const byte bankDownPin = 6;
 const byte bankUpPin = 7;
-Bounce bankDownButton = Bounce();
-Bounce bankUpButton = Bounce();
+Button bankDownButton = Button();
+Button bankUpButton = Button();
 boolean bankDownState;
 boolean bankDownDown;
 boolean bankUpState;
@@ -35,8 +35,8 @@

 const byte stopPin = 8;
 const byte playPin = 9;
-Bounce stopButton = Bounce();
-Bounce playButton = Bounce();
+Button stopButton = Button();
+Button playButton = Button();
 boolean stopState;
 boolean stopDown;
 boolean playState;
@@ -47,8 +47,7 @@

 byte bank = 0;

-const byte bpmLed = 22;
-
+boolean initMode = false;

 void OnNoteOn(byte channel, byte note, byte velocity)
 {
@@ -76,12 +75,13 @@

 void setupButtons() {
   for (byte i = 0; i < numberOfChannelButtons; i++) {
-    initButton(channelButtonStart + i, &channelButtons[i], &channelButtonStates[i], &channelButtonDown[i]);
-  }
-  initButton(bankDownPin, &bankDownButton, &bankDownState, &bankDownDown);
-  initButton(bankUpPin, &bankUpButton, &bankUpState, &bankUpDown);
-  initButton(stopPin, &stopButton, &stopState, &stopDown);
-  initButton(playPin, &playButton, &playState, &playDown);
+    //initButton(channelButtonStart + i, &channelButtons[i], &channelButtonStates[i], &channelButtonDown[i]);
+    channelButtons[i].init(channelButtonStart + i);
+  }
+  bankDownButton.init(bankDownPin);
+  bankUpButton.init(bankUpPin);
+  stopButton.init(stopPin);
+  playButton.init(playPin);
 }

 void initButton(byte pin, Bounce *button, boolean *state, boolean *down) {
@@ -133,30 +133,34 @@
   delay(200);
 }

+void debugButton(Button *button) {
+  Serial.print("Button: ");
+  Serial.print((*button).getPin());
+  Serial.print(" Just pressed: ");
+  Serial.print((*button).isJustPressed());
+  Serial.print(" Pressed: ");
+  Serial.print((*button).isPressed());
+  Serial.print(" Just released : ");
+  Serial.println((*button).isJustReleased());
+}
+
 void updateButtons() {
   for (byte i = 0; i < numberOfChannelButtons; i++) {
-    updateButtonState(channelButtonStart + i, &channelButtons[i], &channelButtonStates[i], &channelButtonDown[i]);
-  }
-  updateButtonState(bankDownPin, &bankDownButton, &bankDownState, &bankDownDown);
-  updateButtonState(bankUpPin, &bankUpButton, &bankUpState, &bankUpDown);
-  updateButtonState(stopPin, &stopButton, &stopState, &stopDown);
-  updateButtonState(playPin, &playButton, &playState, &playDown);
-}
-
-void updateButtonState(byte pin, Bounce *button, boolean *state, boolean *down) {
-  if ((*button).update()) {
-    if ((*button).read() == LOW) {
-      *down = true;
-      Serial.print("Button ");
-      Serial.print(pin);
-      Serial.println(" down");
-    } else if (*down) {
-      Serial.print("Button ");
-      Serial.print(pin);
-      Serial.println(" up");
-      *state = 1 - *state;
-      *down = false;
-    }
+    if (channelButtons[i].update()) {
+      debugButton(&channelButtons[i]);
+    }
+  }
+  if (bankDownButton.update()) {
+    debugButton(&bankDownButton);
+  }
+  if (bankUpButton.update()) {
+    debugButton(&bankUpButton);
+  }
+  if (stopButton.update()) {
+    debugButton(&stopButton);
+  }
+  if (playButton.update()) {
+    debugButton(&playButton);
   }
 }

@@ -166,21 +170,39 @@

   updateButtons();

-  updateState();
+  changeBank();
+
+  changeMode();

   updateLeds();

-
-}
-
-void updateState() {
+}
+
+boolean bothBanksDownLastState = false;
+
+void changeMode() {
+  /*if (bankDownDown && bankUpDown) {
+    if (!previousBothBanksDown) {
+      initMode = 1 - initMode;
+      previousBothBanksDown = true;
+      if (initMode) {
+        Serial.println("Init mode");
+      } else {
+        Serial.println("Normal mode");
+      }
+    } else {
+      previousBothBanksDown = false;
+    }
+    }*/
+
+}
+
+void changeBank() {
   boolean update = false;
-  if (bankDownState != bankDownLastState) {
-    bankDownLastState = bankDownState;
+  if (bankDownButton.isJustReleased()) {
     bank--;
     update = true;
-  } else if (bankUpState != bankUpLastState) {
-    bankUpLastState = bankUpState;
+  } else if (bankUpButton.isJustReleased()) {
     bank++;
     update = true;
   }


Simplify example

Simplify example

--- examples/Boards_BLE/Serial_HM10_HC08/Serial_HM10_HC08.ino
+++ examples/Boards_BLE/Serial_HM10_HC08/Serial_HM10_HC08.ino
@@ -21,26 +21,26 @@
  *
  **************************************************************/

-//#define BLYNK_DEBUG
-#define BLYNK_PRINT Serial
+// You could use a spare Hardware Serial on boards that have it (like Mega)
+#include <SoftwareSerial.h>
+SoftwareSerial DebugSerial(2, 3); // RX, TX

+#define BLYNK_PRINT DebugSerial
 #define BLYNK_USE_DIRECT_CONNECT
-
 #include <BlynkSimpleSerialBLE.h>

 // You should get Auth Token in the Blynk App.
 // Go to the Project Settings (nut icon).
 char auth[] = "YourAuthToken";

-#define SerialBLE  Serial1      // Set Serial object
-
 void setup()
 {
-  // This is for debug prints
+  // Debug console
+  DebugSerial.begin(9600);
+
+  // Blynk will work through Serial
   Serial.begin(9600);
-
-  SerialBLE.begin(9600);        // Set Serial baud rate
-  Blynk.begin(auth, SerialBLE);
+  Blynk.begin(auth, Serial);
 }

 void loop()


création d'une classe Kinto

création d'une classe Kinto


move radio power up/down

move radio power up/down

--- _41-promini-nrf24-ads1115/_41-promini-nrf24-ads1115.ino
+++ _41-promini-nrf24-ads1115/_41-promini-nrf24-ads1115.ino
@@ -73,9 +73,11 @@
   counterForloop_old = counterForloop;
   checkRangenow = true;
   detachInterrupt(digitalPinToInterrupt(2));
+  radio.powerUp();
 }

 void sleepNow() {
+  radio.powerDown();
   digitalWrite(ledPin, LOW);
   attachInterrupt(digitalPinToInterrupt(2), wakeUp, FALLING);
   LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);
@@ -176,9 +178,9 @@
   Serial.println(payload.data2);

   if ( rangeStatus == 1 || rangeStatus == 3 || rangeStatus == 2 ) {
-    radio.powerUp();
+    //radio.powerUp();
     radio.write(&payload , sizeof(payload));
-    radio.powerDown();
+    //radio.powerDown();
   }

   digitalWrite(ledPin, LOW);


Move interrupt handlers more into the controller rather than Button

--- moros/moros.ino
+++ moros/moros.ino
@@ -31,13 +31,6 @@
   static inline void handle_button_interrupt(int button);
 };

-void handle_button_interrupt_0() {
-  Button::handle_button_interrupt(0);
-}
-void handle_button_interrupt_1() {
-  Button::handle_button_interrupt(1);
-}
-
 class Screen {
 private:
   char prev_text[12];
@@ -136,19 +129,22 @@
   }
 };

+void handle_interrupt_0();
+void handle_interrupt_1();
+
 class Controller {
 public:
   Player *players[2];
   static int active_player;
-  static int interrupt_fired;
+  volatile static int interrupt_fired;

   Controller() {
     players[0] = new Player(
-     new Button(0, handle_button_interrupt_0),
+     new Button(0, handle_interrupt_0),
      new Screen(4,5,6)
     );
     players[1] = new Player(
-     new Button(1, handle_button_interrupt_1),
+     new Button(1, handle_interrupt_1),
       new Screen(7,8,9)
     );

@@ -163,7 +159,7 @@
   };

   // called from the actual interrupt handler. be quick.
-  void handle_button_interrupt(int interrupt_number) {
+  static void handle_interrupt(int interrupt_number) {
     interrupt_fired = interrupt_number;
   };

@@ -215,13 +211,16 @@
   }
 };
 int Controller::active_player = NONE;
-int Controller::interrupt_fired = NONE;
+volatile int Controller::interrupt_fired = NONE;

 Controller controller;

-void Button::handle_button_interrupt(int button) {
-  controller.handle_button_interrupt(button);
-};
+void handle_interrupt_0() {
+  Controller::handle_interrupt(0);
+}
+void handle_interrupt_1() {
+  Controller::handle_interrupt(1);
+}

 void setup(void) {
   Serial.begin(115200);


Update RedBear Duo BLE example [ci skip]

--- examples/Boards_BLE/RedBear_Duo_BLE/RedBear_Duo_BLE.ino
+++ examples/Boards_BLE/RedBear_Duo_BLE/RedBear_Duo_BLE.ino
@@ -14,10 +14,8 @@
  *
  **************************************************************
  *
- * This example shows how to use Arduino 101 CurieBLE
+ * This example shows how to use RedBear Duo BLE
  * to connect your project to Blynk.
- *
- * For this example you need CurieBLE library from http://librarymanager
  *
  * NOTE: BLE support is in beta!
  *
@@ -53,6 +51,8 @@
   Blynk.run();
 }

+// Next functions are optional.
+// Add ZeRGBa Widget on V0 to control onboard LED.
 BLYNK_CONNECTED() {
   RGB.control(true);
 }


Added library hint

Added library hint

--- ReaperRemote.ino
+++ ReaperRemote.ino
@@ -1,3 +1,10 @@
+/**
+ * Author: Leonid Lezner
+ * License: MIT
+ *
+ * Required libraries: Adafruit_BluefruitLE_nRF51, Button
+ */
+
 #include <Arduino.h>
 #include "Feather.h"
 #include <SPI.h>


Sketch updated with improved button decoder

Signed-off-by: jmhrvy <6a3cd8a1b2d47d05877db3d1fefa06cbe0a9a3f0@epbfi.com>

--- CNCSpindleSpeedControl/CNCSpindleSpeedControl.ino
+++ CNCSpindleSpeedControl/CNCSpindleSpeedControl.ino
@@ -662,44 +662,41 @@
     }
     else return;
   }
-
-
-  int buttonPressed = Keypad.button();
-  if (buttonPressed==KEYPAD_NONE){
+  int buttons = DecodeButton();
+  if (buttons == -1){
     NuInput = true;
      return;
   }
+  int NubtnVal = buttons; //remember previous button reading
+  int i = 0;
+  // Button debounce code to help ensure a true button reading
+  while(i<200 ){
+    buttons = DecodeButton();
+    if (NubtnVal == buttons) i++;
+    else {// doesn't match; Reset & Start over
+      NubtnVal = buttons;
+      i= 0;
+    }
+  }
+  if (buttons > 0 ){
+    chkBtns = false;// lock out new button scan for another delay interval (original wait period was250 ms)
+    QrtrSecTimeOut = millis(); // reset delay interval timer
+    UpDateSettings(buttons, Mode);
+  }
+
+  return;
+}
+
+int DecodeButton(){
   int buttons = 0;
-  int NubtnVal = 0;
+  int buttonPressed = Keypad.button();
+  if (buttonPressed==KEYPAD_NONE)return -1;
   if (buttonPressed==KEYPAD_UP) buttons += 1;
   if (buttonPressed==KEYPAD_DOWN) buttons += 2;
   if (buttonPressed==KEYPAD_LEFT) buttons += 4;
   if (buttonPressed==KEYPAD_RIGHT) buttons += 8;
   if (buttonPressed==KEYPAD_SELECT) buttons += 16;
-  //bool Same = true;
-  int i = 0;
-  NubtnVal = buttons; //remember previous button reading
-  // Switch debounce code to help ensure a true button reading
-  while(i<6 ){
-    buttonPressed = Keypad.button();
-    buttons = 0;
-    if (buttonPressed==KEYPAD_UP) buttons += 1;
-    if (buttonPressed==KEYPAD_DOWN) buttons += 2;
-    if (buttonPressed==KEYPAD_LEFT) buttons += 4;
-    if (buttonPressed==KEYPAD_RIGHT) buttons += 8;
-    if (buttonPressed==KEYPAD_SELECT) buttons += 16;
-    if (NubtnVal == buttons) i++;
-    else {// doesn't match; Rest & Start over
-      NubtnVal = buttons;
-      i= 0;
-    }
-  }
-  if (buttons > 0 ){
-    chkBtns = false;// lock out new button scan for another delay interval (original wait period was250 ms)
-    QrtrSecTimeOut = millis(); // reset 1/4 second timer
-  }
-  UpDateSettings(buttons, Mode);
-  return;
+  return buttons;
 }

 void UpDateSettings(int UsrInput, int mode)
@@ -777,7 +774,8 @@
   SpndlPWM = 15;
   SetPoint = 2000;
   ITerm = 0.0; //kill any residual Integral component that might be left over from a previous run
-  lastTime = millis();// reset/establish time mark for initial PID calculation
+  lastTime = millis();// reset/establish time mark for initial PID calculation
+  attachInterrupt(InterruptId, SpindleTachInterrupt, FALLING); //UNO digital pin 3;
   analogWrite(PWMpin, SpndlPWM); //start the PWM output
 }
 // -------------------------------------------------------------------------


Debugged angle detection; set up right values for #2. Eliminated SoftwareSerial, since it keeps things from running. Used code to gather data.

--- Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
+++ Elcano_C2_LowLevel/Elcano_C2_LowLevel.ino
@@ -2,11 +2,12 @@
 #include <SPI.h>
 #include <Elcano_Serial.h>

-#include <SoftwareSerial.h>
+//#include <SoftwareSerial.h>
 // On Mega, TX must use d10-15, d50-53, or a8-a15 (62-69)
 const int softwareTx = 10;  // to 7 segment LED display
 const int softwareRx = 7;   // not used
-SoftwareSerial s7s(softwareRx, softwareTx);
+//SoftwareSerial s7s(softwareRx, softwareTx);
+#define s7s Serial3

 #define LOOP_TIME_MS 400
 #define ERROR_HISTORY 20
@@ -48,9 +49,9 @@
 #define MAX_ACC_OUT 227
 #define MIN_BRAKE_OUT 210
 #define MAX_BRAKE_OUT 254
-#define RIGHT_TURN_OUT 146 // Original value 146
-#define LEFT_TURN_OUT 223 // Original value 230
-#define STRAIGHT_TURN_OUT 182 // Original value 187
+#define RIGHT_TURN_OUT 160
+#define LEFT_TURN_OUT 254
+#define STRAIGHT_TURN_OUT 192
 // Turn sensors are believed if they are in this range while wheels are straight
 #define RIGHT_MIN_COUNT 725
 #define RIGHT_MAX_COUNT 785
@@ -63,23 +64,23 @@
 #endif

 /*================ReadTurnAngle ================*/
-// Value measured at analog input A3 from right steering column when wheels pointed straight ahead.
+// Value measured at analog input A2 from right steering column when wheels pointed straight ahead.
 // An analog voltage can be 0 to 5V, which correspond to angles from 0 to 360 degrees.
 // Analog input reads this as a value form 0 to 1024.
 // We may want to mount the sensors so that straight is close to 500.
 // This number is not critical, since actual wheel turn range is much less than 360
-int RightStraight_A3 = 914; // Original value 181
-// Value measured at analog input A2 from left steering column when wheels pointed straight ahead.
-int LeftStraight_A2  = 750; // Original value 181
+int RightStraight_A2 = 750; // Original value 181
+// Value measured at analog input A3 from left steering column when wheels pointed straight ahead.
+int LeftStraight_A3  = 914; // Original value 181
 // Calibration constants
-// Aangle (degrees) = (Value - RightStraight_A3) * RIGHT_DEGx1000pCOUNT / 1000
-#define RIGHT_DEGx1000pCOUNT  3333
-#define LEFT_DEGx1000pCOUNT  3333
+// Aangle (degrees) = (Value - RightStraight_A2) * RIGHT_DEGx1000pCOUNT / 1000
+#define RIGHT_DEGx1000pCOUNT  333
+#define LEFT_DEGx1000pCOUNT  333
 // A correct sensor will produce a reading between these values
-int Right_Min_Count = 850; // Real values are in setup().
-int Right_Max_Count = 980;
-int Left_Min_Count = 698;
-int Left_Max_Count = 808;
+int Left_Min_Count = 850; // Real values are in setup().
+int Left_Max_Count = 980;
+int Right_Min_Count = 698;
+int Right_Max_Count = 808;

 // Channel order differs for differernt vehicles
 // Indices for information stored in arrays RC_rise, RC_elapsed, local_results,...
@@ -103,12 +104,6 @@
 #define ProcessFallOfINT(Index)  RC_elapsed[Index]=(micros()-RC_rise[Index])
 #define ProcessRiseOfINT(Index) RC_rise[Index]=micros()

-//RC input values - pulse widths in microseconds
-const int DEAD_ZONE = 75;
-const int MIDDLE = 1500;  // was 1322; new stable value = 1510
-// extremes of RC pulse width
-const int MIN_RC = 1090;  // was 911;
-const int MAX_RC = 1930; // was 1730;

 const int SelectCD = 49; // Select IC 3 DAC (channels C and D)
 const int SelectAB = 53; // Select IC 2 DAC (channels A and B)
@@ -129,6 +124,12 @@
 const int IRPT_GO = 3;   //  D20 = Int 3
 const int IRPT_RDR = 4;   // D19 = Int 4
 const int IRPT_ESTOP = 5; // D18 = Int 5
+//RC input values - pulse widths in microseconds
+const int DEAD_ZONE = 75;
+const int MIDDLE = 1500;  // was 1322; new stable value = 1510
+// extremes of RC pulse width
+const int MIN_RC = 1090;  // was 911;
+const int MAX_RC = 1930; // was 1730;
 #endif

 #ifdef RC_HITEC
@@ -137,6 +138,12 @@
 const int IRPT_GO = 3;   //  D20 = Int 3
 const int IRPT_RDR = 5;   // D18 = Int 5
 const int IRPT_ESTOP = 4; // D19 = Int 4
+//RC input values - pulse widths in microseconds
+const int DEAD_ZONE = 75;
+const int MIDDLE = 1380;
+// extremes of RC pulse width
+const int MIN_RC = 960;
+const int MAX_RC = 1800;
 #endif
 //  D3 = Int 1  Wheel Click

@@ -212,8 +219,8 @@
   noInterrupts();
   ProcessFallOfINT(RC_ESTP);
   RC_Done[RC_ESTP] = 1;
-  if (RC_elapsed[RC_ESTP] > MIDDLE)
-      E_Stop();
+//  if (RC_elapsed[RC_ESTP] > MIDDLE)
+//     E_Stop();
   attachInterrupt(IRPT_ESTOP, ISR_ESTOP_rise, RISING);
   interrupts();
 }
@@ -282,7 +289,7 @@
     startCapturingRCState();

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

   while (micros() < nextTime &&
     ~((RC_Done[RC_ESTP] == 1) && (RC_Done[RC_GO] == 1) && (RC_Done[RC_TURN] == 1) && (RC_Done[RC_RDR] == 1)))
@@ -291,7 +298,7 @@
     // got data;
     for (int i = 0; i < 8; i++)
         local_results[i] = RC_elapsed[i];
-//    Print7( false, local_results);
+//  Print7( false, local_results);
     processRC(local_results);
 //    Print7( true, local_results);

@@ -313,10 +320,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;
     }

@@ -400,8 +407,9 @@
     // 1st pulse is aileron (position 5 on receiver; controlled by Right left/right joystick on transmitter)
     //     used for Steering
     int 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]);
     /* 2nd pulse is aux (position 1 on receiver; controlled by flap/gyro toggle on transmitter)
        will be used for selecting remote control or autonomous control. */
 //    Serial.print("In processRC, received results[RC_AUTO] = "); Serial.println(results[RC_AUTO]);
@@ -539,6 +547,7 @@
 {
     brake(MAX_BRAKE_OUT);
     moveVehicle(MIN_ACC_OUT);
+    delay (2000);   // inhibit output
     // TO DO: disable 36V power
 }
 //Send values to output pin
@@ -914,8 +923,8 @@
     int i, left, right;
     for (i = 0; i < count; i++)
     {
-          totalRight += analogRead(A3);
-          totalLeft += analogRead(A2);
+          totalRight += analogRead(A2);
+          totalLeft += analogRead(A3);
           delay(pause);
     }
     right = totalRight / count;
@@ -924,29 +933,30 @@
     // Do not make garbage readings the new normal.
     if(RIGHT_MIN_COUNT <= right && right <= RIGHT_MAX_COUNT)
     {
-         RightStraight_A3 = right;
-         Right_Min_Count = RightStraight_A3 - 60;   // 60 counts is 20 degrees
-         Right_Max_Count = RightStraight_A3 + 60;
+         RightStraight_A2 = right;
+         Right_Min_Count = RightStraight_A2 - 60;   // 60 counts is 20 degrees
+         Right_Max_Count = RightStraight_A2 + 60;
      }
     else
     {
-         RightStraight_A3 = (RIGHT_MAX_COUNT - RIGHT_MIN_COUNT)/2 ;
+         RightStraight_A2 = RIGHT_MIN_COUNT + (RIGHT_MAX_COUNT - RIGHT_MIN_COUNT)/2 ;
          Right_Min_Count = RIGHT_MIN_COUNT;
          Right_Max_Count = RIGHT_MAX_COUNT;
     }
     if  (LEFT_MIN_COUNT  <= left  && left  <= LEFT_MAX_COUNT)
     {
-        LeftStraight_A2  = left;
-        Left_Min_Count  = LeftStraight_A2  - 60;
-        Left_Max_Count  = LeftStraight_A2  + 60;
+        LeftStraight_A3  = left;
+        Left_Min_Count  = LeftStraight_A3  - 60;
+        Left_Max_Count  = LeftStraight_A3  + 60;
     }
     else
     {
-        LeftStraight_A2  = (LEFT_MAX_COUNT - LEFT_MIN_COUNT)/2 ;
+        LeftStraight_A3  = LEFT_MIN_COUNT + (LEFT_MAX_COUNT - LEFT_MIN_COUNT)/2 ;
         Left_Min_Count = LEFT_MIN_COUNT;
         Left_Max_Count = LEFT_MAX_COUNT;
     }
-
+    Serial.print("CALIBRATE: Left Straight = "); Serial.print(LeftStraight_A3);
+     Serial.print("\tRight Straight = "); Serial.print(RightStraight_A2);
     old_turn_degx1000 = 0; // straight
 }
 /*======================ReadTurnAngle======================*/
@@ -958,16 +968,20 @@
     long min_ang, max_ang;
     bool OK_right = false;
     bool OK_left = false;
-    int right = analogRead(A3);
-    int left = analogRead(A2);
-    //Serial.print("Left"); Serial.print("\t"); Serial.println(left);
-    //Serial.print("Right"); Serial.print("\t"); Serial.println(right);
+    int right = analogRead(A2);
+    int left = analogRead(A3);
+//    Serial.print("Left"); Serial.print("\t"); Serial.print(left);
+//    Serial.print("\tRight"); Serial.print("\t"); Serial.print(right);
+//    Serial.print("LeftStraight_A3"); Serial.print("\t"); Serial.print(LeftStraight_A3);
+//    Serial.print("\tRightStraight_A2"); Serial.print("\t"); Serial.print(RightStraight_A2);
     if ((Right_Min_Count <= right) && (right <= Right_Max_Count))
        OK_right = true;
     if ((Left_Min_Count <= left) && (left <= Left_Max_Count))
        OK_left = true;
-    long right_degx1000 = (right - RightStraight_A3) * RIGHT_DEGx1000pCOUNT;
-    long left_degx1000  = (left -  LeftStraight_A2) *  LEFT_DEGx1000pCOUNT;
+    long right_degx1000 = (right - RightStraight_A2) * RIGHT_DEGx1000pCOUNT;
+    long left_degx1000  = (left -  LeftStraight_A3) *  LEFT_DEGx1000pCOUNT;
+//    Serial.print("Left"); Serial.print("\t"); Serial.print(left_degx1000);
+//    Serial.print("\tRight"); Serial.print("\t"); Serial.print(right_degx1000);

     expected_turn_degx1000 = old_turn_degx1000;
     if (OK_left && OK_right)
@@ -1003,6 +1017,7 @@
     }
     new_turn_degx10 = (int) (new_turn_degx1000 / 100);
     old_turn_degx1000 = new_turn_degx1000;
+//  Serial.print("\tnew_turn_degx10"); Serial.print("\t"); Serial.println(new_turn_degx10);
     return new_turn_degx10;
 }
 /*---------------------------------------------------------------------------------------*/
@@ -1130,11 +1145,11 @@
 {
   char tempString[10];  // Will be used with sprintf to create strings
   // convert mm/s to km/h
-  int speed_kmPhx10 = (speed_mmPs*36)/10;
+  int speed_kmPhx10 = (speed_mmPs*.036);
   // Magical sprintf creates a string for us to send to the s7s.
   //  The %4d option creates a 4-digit integer.
   sprintf(tempString, "%4d", speed_kmPhx10);
-
+//  Serial.println(tempString);
   // This will output the tempString to the S7S
   s7s.print(tempString);
   setDecimals(0b00000100);  // Sets digit 3 decimal on


Revert "Revert "Revert "add batt readings"""

This reverts commit c52cc3b7ff764c1c1837b84c5e691d25f891088b.

--- Micro_Temp/Micro_Temp.ino
+++ Micro_Temp/Micro_Temp.ino
@@ -26,10 +26,8 @@

 #define UPDATE_FREQUENCY 300 // Time to sleep (in seconds)
 #define DHTTYPE DHT11        // DHT 11
-#define BATT_CAL 0.34        // Offset for internal vcc readings
 const int DHTPin = 2;        // Should be D4 on the Wemos D1 Mini
 bool fahrenheit = true;      // Yes, report fahrenheit
-ADC_MODE(ADC_VCC);           // Allows for reading VCC via internal vreg
 DHT dht(DHTPin, DHTTYPE);

 //Wifi settings
@@ -42,7 +40,7 @@
   Serial.begin(9600);
   while(!Serial) { }         // Wait for serial to initialize.
   Serial.println("I AM WOKE.");
-
+
   dht.begin();
   connectWifi();
   yield();
@@ -110,12 +108,8 @@
   char humid[8];
   dtostrf(getHumidity(), -6, 2, humid);

-  char batt[8];
-  dtostrf((((float)ESP.getVcc()/1024.0)+BATT_CAL), -6, 2, batt);
-
   Serial.println(temp);
   Serial.println(humid);
   MQTT_Helper.publishMQTT("home/living/micro/temp",  temp,  false);
   MQTT_Helper.publishMQTT("home/living/micro/humid", humid, false);
-  MQTT_Helper.publishMQTT("home/living/micro/batt",  batt, false);
 }


GPS feature added

GPS feature added

--- Arduino/Tracky/Tracky.ino
+++ Arduino/Tracky/Tracky.ino
@@ -1,98 +1,177 @@
-#include "CurieIMU.h"
-
-int avgX = 0;
-int avgY = 0;
-int avgZ = 0;
-//int count = 0;
-
-boolean alert = 0;
-boolean theft = 0;
-// Functions
-void setReference();
-/*************************************************************
-  Setup Function
-*************************************************************/
-void setup() {
-  Serial.begin(9600); // initialize Serial communication
-  Serial1.begin(9600); // initialize serial communication for BT
-
-  // initialize device
-  Serial1.println("Initializing IMU device...");
-  CurieIMU.begin();
-
-  // Set the accelerometer range to 3G
-  CurieIMU.setAccelerometerRange(3);
-  delay(1000);
-}
-/*************************************************************
-  Loop Function
-*************************************************************/
-void loop() {
-  if (Serial1.available() > 0) {
-    char ch = Serial1.read();
-    if (ch == '1' && alert == 0) {
-      // Calculate reference
-      setReference();
-      alert = 1;
-    } else if (ch == '0') {
-      alert = 0;
-      theft = 0;
-      Serial1.println("Reseting. . .");
-    }
-  }
-
-  if (alert == 1) {
-    int x = abs(abs(CurieIMU.readAccelerometer(X_AXIS)) - avgX);
-    int y = abs(abs(CurieIMU.readAccelerometer(Y_AXIS)) - avgY);
-    int z = abs(abs(CurieIMU.readAccelerometer(Z_AXIS)) - avgZ);
-    int s = (x + y + z) / 3;
-    Serial1.print("Curret position: ");
-    Serial1.print("\t");
-    Serial1.println(s);
-    if (s > 1000) {
-      theft = 1;
-      Serial1.println("ALERT");
-      Serial1.println();
-    }
-  }
-
-  while(theft) {
-    digitalWrite(13, HIGH);
-    if (Serial1.available() > 0 && Serial1.read() == '0') {
-      alert = 0;
-      theft = 0;
-      Serial1.println("Reseting. . .");
-    }
-  }
-  digitalWrite(13, LOW);
-  delay(50);
-}
-/*************************************************************
-  setReference Function
-*************************************************************/
-void setReference() {
-  long sumX = 0;
-  long sumY = 0;
-  long sumZ = 0;
-  // Calculate reference position
-  for (int i = 0; i < 1000; i++) {
-    int x = abs(CurieIMU.readAccelerometer(X_AXIS));
-    int y = abs(CurieIMU.readAccelerometer(Y_AXIS));
-    int z = abs(CurieIMU.readAccelerometer(Z_AXIS));
-    sumX += x;
-    sumY += y;
-    sumZ += z;
-  }
-  avgX = sumX / 1000;
-  avgY = sumY / 1000;
-  avgZ = sumZ / 1000;
-  Serial1.print("Reference position: ");
-  Serial1.print("\t");
-  Serial1.print(avgX);
-  Serial1.print("\t");
-  Serial1.print(avgY);
-  Serial1.print("\t");
-  Serial1.println(avgZ);
-  Serial1.println();
-}
+#include <SoftwareSerial.h>
+#include "CurieIMU.h"

+SoftwareSerial GPS(2, 3); // Rx, Tx
+//SoftwareSerial GSMmodule(4, 5); // Rx, Tx
+
+int Gpsdata;             // for incoming serial data
+unsigned int finish = 0; // indicate end of message
+unsigned int pos_cnt = 0; // position counter
+unsigned int lat_cnt = 0; // latitude data counter
+unsigned int log_cnt = 0; // longitude data counter
+unsigned int flg = 0;    // GPS flag
+unsigned int com_cnt = 0; // comma counter
+char lt[20];            // latitude array
+char lg[20];             // longitude array
+
+int avgX = 0;
+int avgY = 0;
+int avgZ = 0;
+//int count = 0;
+
+boolean alert = 0;
+boolean theft = 0;
+
+// Functions
+void setReference();
+void GPSData();
+//void ring();
+/*******************************************************************************************
+Function Name: Setup
+*******************************************************************************************/
+void setup() {
+  Serial1.begin(9600); // initialize serial communication for BT
+  GPS.begin(9600); // initialize serial communication for GPS
+  //GSMmodule.begin(9600); // initialize serial communication for GSM
+
+  // initialize device
+  Serial1.println("Initializing IMU device...");
+  CurieIMU.begin();
+
+  // Set the accelerometer range to 3G
+  CurieIMU.setAccelerometerRange(3);
+  delay(1000);
+}
+/*******************************************************************************************
+Function Name: Loop
+*******************************************************************************************/
+void loop() {
+  //ring();
+  if (Serial1.available() > 0) {
+    char ch = Serial1.read();
+    if (ch == '1' && alert == 0) {
+      // Calculate reference
+      setReference();
+      alert = 1;
+    } else if (ch == '0') {
+      alert = 0;
+      theft = 0;
+      Serial1.println("Reseting. . .");
+    } else if (ch == '2') {
+      Serial1.println("GPS");
+      GPSData();
+    }
+  }
+
+  if (alert == 1) {
+    int x = abs(abs(CurieIMU.readAccelerometer(X_AXIS)) - avgX);
+    int y = abs(abs(CurieIMU.readAccelerometer(Y_AXIS)) - avgY);
+    int z = abs(abs(CurieIMU.readAccelerometer(Z_AXIS)) - avgZ);
+    int s = (x + y + z) / 3;
+    Serial1.print("Curret position: ");
+    Serial1.print("\t");
+    Serial1.println(s);
+    if (s > 1000) {
+      theft = 1;
+      Serial1.println("ALERT");
+      Serial1.println();
+    }
+  }
+
+  //long long lastMillis = 0;
+  while (theft) {
+    digitalWrite(13, HIGH);
+    if (Serial1.available() > 0 && Serial1.read() == '0') {
+      alert = 0;
+      theft = 0;
+      Serial1.println("Reseting. . .");
+    }
+  }
+  digitalWrite(13, LOW);
+  pos_cnt = 0; finish = 0;
+  delay(50);
+}
+/*******************************************************************************************
+Function Name: setReference
+*******************************************************************************************/
+void setReference() {
+  long sumX = 0;
+  long sumY = 0;
+  long sumZ = 0;
+  // Calculate reference position
+  for (int i = 0; i < 1000; i++) {
+    int x = abs(CurieIMU.readAccelerometer(X_AXIS));
+    int y = abs(CurieIMU.readAccelerometer(Y_AXIS));
+    int z = abs(CurieIMU.readAccelerometer(Z_AXIS));
+    sumX += x;
+    sumY += y;
+    sumZ += z;
+  }
+  avgX = sumX / 1000;
+  avgY = sumY / 1000;
+  avgZ = sumZ / 1000;
+  Serial1.print("Reference position: ");
+  Serial1.print("\t");
+  Serial1.print(avgX);
+  Serial1.print("\t");
+  Serial1.print(avgY);
+  Serial1.print("\t");
+  Serial1.println(avgZ);
+  Serial1.println();
+}
+/*******************************************************************************************
+Function Name: GPSData
+*******************************************************************************************/
+void GPSData() {
+  while (!finish) {
+  Serial1.println(GPS.available());
+    while (GPS.available() > 0) {       // Check GPS data
+      Gpsdata = GPS.read();
+      //Serial1.write(Gpsdata);
+      //Serial1.println("looping");
+      flg = 1;
+      if ( Gpsdata == '$' && pos_cnt == 0) // finding GPRMC header
+        pos_cnt = 1;
+      if ( Gpsdata == 'G' && pos_cnt == 1)
+        pos_cnt = 2;
+      if ( Gpsdata == 'P' && pos_cnt == 2)
+        pos_cnt = 3;
+      if ( Gpsdata == 'R' && pos_cnt == 3)
+        pos_cnt = 4;
+      if ( Gpsdata == 'M' && pos_cnt == 4)
+        pos_cnt = 5;
+      if ( Gpsdata == 'C' && pos_cnt == 5 )
+        pos_cnt = 6;
+      if (pos_cnt == 6 &&  Gpsdata == ',') { // count commas in message
+        com_cnt++;
+        flg = 0;
+      } if (com_cnt == 3 && flg == 1) {
+        lt[lat_cnt++] =  Gpsdata;         // latitude
+        flg = 0;
+      } if (com_cnt == 5 && flg == 1) {
+        lg[log_cnt++] =  Gpsdata;         // Longitude
+        flg = 0;
+      } if ( Gpsdata == '*' && com_cnt >= 5) {
+        com_cnt = 0;                      // end of GPRMC message
+        lat_cnt = 0;
+        log_cnt = 0;
+        flg     = 0;
+        finish  = 1;
+      }
+    }
+  }
+}
+
+/*
+void ring()
+{
+  tone(8, 2000);
+  delay(100);
+  noTone(8);
+  delay(100);
+  tone(8, 1000);
+  delay(100);
+  noTone(8);
+  delay(100);
+}*/
+


Removed unused (commented) code for start/stop recording and USB mode

--- c_I2C.ino
+++ c_I2C.ino
@@ -520,77 +520,6 @@
 #endif
 }

-/* HGM: these functions still in development */
-/* void My_startRecording() */
-/* { */
-/*     buf[0] = 3; buf[1] = 'S'; buf[2] = 'Y'; buf[3] = 0x01; */
-/*     SendBufToCamera(); */
-
-/* #ifdef USE_GENLOCK */
-/*     if (1) { // send to Dongle */
-/*       Serial.println(""); */
-/*       Serial.println(F("SH01")); */
-/*       Serial.flush(); */
-/*     } */
-/* #endif */
-
-/* } */
-
-/* void My_stopRecording() */
-/* { */
-/*     buf[0] = 3; buf[1] = 'S'; buf[2] = 'Y'; buf[3] = 0x00; */
-/*     SendBufToCamera(); */
-
-/* #ifdef USE_GENLOCK */
-/*     if (1) { // send to Dongle */
-/*       Serial.println(""); */
-/*       Serial.println(F("SH00")); */
-/*       Serial.flush(); */
-/*     } */
-/* #endif */
-
-/* } */
-
-/* void My_USBMode() */
-/* { */
-/*     //power off camera */
-/*     buf[0] = 3; buf[1] = 'P'; buf[2] = 'W'; buf[3] = 0x00; */
-/*     SendBufToCamera(); */
-/*     tdDone = false; */
-
-/*     //wait for some time */
-/*     delay(5000); */
-
-/*     //power on camera */
-/*     pinMode(PWRBTN, OUTPUT); */
-/*     digitalWrite(PWRBTN, LOW); */
-/*     delay(1000); */
-/*     tdDone = false;     //maybe comment this later */
-/*     pinMode(PWRBTN, INPUT); */
-
-/*     //detach Mewpro */
-/*     pinMode(BPRDY, INPUT); */
-/*     delay(1000); */
-
-/* //DO NOT UNCOMMENT codes below (not tested yet) */
-/* /\* */
-/* #ifdef USE_GENLOCK */
-/*     if (1) { // send to Dongle */
-/*       Serial.println(""); */
-/*       Serial.println("^")); */
-/*       Serial.flush(); */
-/*     } */
-/* #endif */
-/* *\/ */
-
-/*     noInterrupts(); //mask all interrupts so that no more SMARTY commands will be sent */
-/*     __debug(F("Plug in USB cable now")); */
-/*     Serial.flush(); */
-/*     while(1);       //dead loop to make sure Mewpro won't interfere USB transmission */
-
-/* } */
-
-
 void checkCameraCommands()
 { // CameraCommands come via the Serial communication.  They may be from
   // the GenlockDongle, from a computer connected via the Arduino Serial
@@ -602,11 +531,10 @@
                               // single data value (example: characters
                               // '0b' convert to value 11)
     byte c = myRead();
-    /* hgm: not sure this works, need to find a way to view the queue */
-    /* if(debug) { */
-    /*   Serial.print("myRead()="); */
-    /*   Serial.println((char)c); */
-    /* } */
+    // hgm: don't think this works, but we need to find a way to view the
+    //      queue when in debug mode
+    // if(debug) { Serial.print("myRead()=");
+    // Serial.println((char)c); }
     switch (c) {
     case ' ': // Ignore spaces
       continue;
@@ -618,44 +546,6 @@
         SendBufToCamera();
       }
       return;
-
-      /* //\***********************Adding our unique commands******************** */
-
-      /*       case '$': */
-      /*         bufp = 1; */
-      /*         __debug(F("Start Recording!")); */
-      /*         My_startRecording(); */
-      /*         while (inputAvailable()) { */
-      /*           if (myRead() == '\n') { */
-      /*             return; */
-      /*           } */
-      /*         } */
-      /*         return; */
-
-      /*       case '%': */
-      /*         bufp = 1; */
-      /*         __debug(F("Stop Recording!")); */
-      /*         My_stopRecording(); */
-      /*         while (inputAvailable()) { */
-      /*           if (myRead() == '\n') { */
-      /*             return; */
-      /*           } */
-      /*         } */
-      /*         return; */
-
-      /*         case '^': */
-      /*         bufp = 1; */
-      /*         __debug(F("Getting into USB Mode")); */
-      /*         My_USBMode(); */
-      /*         while (inputAvailable()) { */
-      /*           if (myRead() == '\n') { */
-      /*             return; */
-      /*           } */
-      /*         } */
-      /*         return; */
-
-      /* //\*************************End of custom commands*********************************** */
-
     case '&': // toggle debug mode
       bufp = 1;
       debug = !debug;
@@ -719,7 +609,7 @@
       }
       if (bufp < 4) { // processing [length] or [cmd], not [dataX]
         // always reset shiftable to true before processing [dataX]
-        shiftable = true;
+        shiftable = true;
         buf[bufp++] = c; // add to buffer
       } else {
         if (shiftable) {


Using more structs and functions

Using more structs and functions

--- DiplayTemp/DiplayTemp.ino
+++ DiplayTemp/DiplayTemp.ino
@@ -46,49 +46,88 @@
 #define MAIN_SENSOR_UPDATE 60000

 // LCD
-LiquidCrystal_I2C _lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
+//LiquidCrystal_I2C _lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

 // Touched
 CapacitiveSensor _touch = CapacitiveSensor(touchCommonPin,touchSensPin);

 // Athmospheric Sensor
-Adafruit_BMP085 _bmp = Adafruit_BMP085(1234);
+Adafruit_BMP085 _mainSensor = Adafruit_BMP085(0);
+
+// Sensor Defintion
+typedef struct SensorStruct {
+  char * name;
+  uint8_t id; // Sensor ID
+  float value;
+  char * unit; // Unit
+} SensorDefinition;
+
+// Rendering
+typedef struct RenderStruct {
+  LiquidCrystal_I2C lcd; // LCD
+  SensorDefinition * sensor; // Sensor to display
+  byte tick; // Used for transition
+} RenderDefinition;

 // Sensor RX Data
-typedef struct sensorData_t{
+typedef struct RxSensorDataStruct {
   byte id; // size 1
   float value; // size 4
+} RxSensorDataDefinition;
+
+typedef union RxSensorRawDataStruc{
+  RxSensorDataDefinition decoded;
+  uint8_t raw[5]; // total size of 5 bytes
+} RxSensorRawDataDefinition;
+
+// RX Message
+typedef struct ReceiverStruct {
+  uint8_t stream[VW_MAX_MESSAGE_LEN]; // Raw Rx Stream
+  RxSensorRawDataDefinition value; // Decoded Value
+} ReceiverDefinition;
+
+// Main Application Structure
+typedef struct ApplicationStruct {
+  byte nbrSensor;
+  SensorDefinition sensors[2]; // Sensors Definition
+  RenderDefinition render; // LCD rendering
+  ReceiverDefinition rx; // RX receiver
+  unsigned long lastTouched; // Last Touched time
+} ApplicationDefinition;
+
+// Static Definition
+ApplicationDefinition _app = {
+  2, // Total number of sensors
+  // Sensors
+  {
+    // Sensor #1
+    {
+      "Inside Temp",
+      0, // Sensor ID
+      -99.0, // Initial Value
+      "°C"
+    },
+    // Sensor #2
+    {
+      "Outside Temp",
+      42, // Sensor ID
+      -99.0, // Initial Value
+      "°C"
+    }
+  },
+    // Render
+  {
+    LiquidCrystal_I2C(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin)
+    // Init other field with 0
+  },
+
+  // RX Reveiver
+  {
+    // Init array with 0
+  },
+  0 // last touched
 };

-typedef union sensorData_union_t{
-  sensorData_t data;
-  uint8_t raw[5]; // total size of 5 bytes
-};
-
-// Main Sensor Definition
-typedef struct mainSensorDef_t {
-  float pressure;
-  float temp;
-};
-
-// Remote Sensor Defintion
-typedef struct remoteSensorDef_t {
-  char * name;
-  uint8_t id;
-  float temp;
-};
-
-// RX message
-uint8_t _message[VW_MAX_MESSAGE_LEN];
-
-// LCD State
-State _lcdHome = State(updateSensor);
-
-// Remote Sensors
-remoteSensorDef_t * _remoteSensors;
-
-// Last Touched
-unsigned long _lastTouch;

 void setup() {
   // Led Setup
@@ -103,30 +142,21 @@
   vw_setup(2000);

   // Set Up LCD
-  _lcd.begin (16,2); // 16x2 LCD
-  _lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
-  _lcd.setBacklight(HIGH);
-  _lcd.home();
-  _lcd.print("--- Welcome ---");
+  _app.render.lcd.begin (16,2); // 16x2 LCD
+  _app.render.lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
+  _app.render.lcd.setBacklight(HIGH);
+  _app.render.lcd.home();
+  _app.render.lcd.print("--- Welcome ---");

   // Start the receiver
   vw_rx_start();

   // Initialise
-  if(!_bmp.begin())
+  if(!_mainSensor.begin())
   {
     /* There was a problem detecting the BMP085 ... check your connections */
     Serial.print("Ooops, no BMP085 detected ...");
   }
-
-  // Remote sensore Static Def
-  _remoteSensors = new remoteSensorDef_t[2];
-
-  _remoteSensors[0].name="Sonde 1";
-  _remoteSensors[0].id=42;
-
-  _remoteSensors[0].name="Sonde 2";
-  _remoteSensors[0].id=69;
 }

 void loop() {
@@ -140,27 +170,65 @@
   {
     Serial.print("Touch ");
     Serial.println(touched);
-    _lcd.setBacklight(HIGH); // Backlight on
-    _lastTouch = currentTime;
-  }
-  else if( currentTime - _lastTouch > BACKLIGHT_DURATION)
-  {
-    _lcd.setBacklight(LOW); // Backlight off
-  }
-
-
-  updateSensor();
+    _app.render.lcd.setBacklight(HIGH); // Backlight on
+    _app.lastTouched = currentTime;
+  }
+  else if( currentTime - _app.lastTouched > BACKLIGHT_DURATION)
+  {
+    _app.render.lcd.setBacklight(LOW); // Backlight off
+  }
+
+  // Check RX
+  checkIncomingData();
+
+  // Paint
+  render();

   // Wait some time
   delay(20);
 }

-/*
- * Update all sensors
- *
- */
-void  updateSensor()
+
+//
+// LCD Render function
+//
+void render()
+{
+  // TODO annimation ?
+
+
+  // Display Sensor
+  if(_app.render.sensor!=NULL)
+  {
+    _app.render.lcd.home();
+    _app.render.lcd.print(_app.render.sensor->name);
+    _app.render.lcd.setCursor (0,1); // go to start of 2nd line
+    _app.render.lcd.print(_app.render.sensor->value);
+    _app.render.lcd.print(' ');
+    _app.render.lcd.print(_app.render.sensor->unit);
+
+
+    _app.render.sensor = NULL;
+  }
+
+}
+
+
+
+//
+// Diplay the Next Sensor
+//
+void selectNextSensor()
+{
+
+}
+
+
+//
+// Check if we have a unread message in the air
+//
+void checkIncomingData()
 {
   // Message Received ?
   if( vw_have_message())
@@ -168,7 +236,7 @@
     // max message size
     uint8_t messageLen = VW_MAX_MESSAGE_LEN;

-    if (vw_get_message(_message, &messageLen)) // Read message
+    if (vw_get_message(_app.rx.stream, &messageLen)) // Read message
     {
       digitalWrite(rxLed, HIGH);

@@ -180,7 +248,7 @@
         // HEX DUMP
         for (int i = 0; i < messageLen; i++)
         {
-          Serial.print(_message[i], HEX);
+          Serial.print(_app.rx.stream[i], HEX);
         }
         Serial.println("");
       }
@@ -189,21 +257,15 @@
       if(messageLen>4)
       {
         // Convert Byte to Sensor Data
-        sensorData_union_t sensor;
+        //RxSensorRawDataDefinition sensor;

         for (int k=0; k < 5; k++)
         {
-          sensor.raw[k] = _message[k];
+          _app.rx.value.raw[k] = _app.rx.stream[k];
         }
-
-        Serial.print("Sensor=");
-        Serial.print(sensor.data.id);
-        Serial.print(", Temp=");
-        Serial.println(sensor.data.value);
-
-        // LCD
-        _lcd.setCursor (0,1); // go to start of 2nd line
-        _lcd.print(sensor.data.value);
+
+        // Fire this new value
+        fireNewSensorValue(_app.rx.value.decoded.id, _app.rx.value.decoded.value);
       }
       else
       {
@@ -218,10 +280,45 @@
     }
   }

-
-}
-
-
-
-
-
+}
+
+
+void fireNewSensorValue(byte sensorID, float newValue)
+{
+  Serial.print("Sensor=");
+  Serial.print(_app.rx.value.decoded.id);
+  Serial.print(", Value=");
+  Serial.println(_app.rx.value.decoded.value);
+
+
+  // Find in the sensor the SensorDefinition
+  for (int i = 0; i < (_app.nbrSensor); ++i)
+  {
+    if(_app.sensors[i].id==sensorID)
+    {
+      // Update value
+      _app.sensors[i].value = newValue;
+
+      // Render
+      _app.render.sensor = &_app.sensors[i];
+
+      // TODO Ethernet
+
+      break; // Exit loop
+    }
+  }
+}
+
+
+//
+// Update Local sensors
+//
+void updateLocalSensors()
+{
+
+  // Read Pression sensor
+
+  // Read Temp sensor
+
+}
+


+added power_node_v1.1.ino (okay na pero di pa natetest kung nakakapag-usap talaga siya with Custom Due. Hardware issues.)

--- power_node_v1.1/power_node_v1.1/power_node_v1.1.ino
+++ power_node_v1.1/power_node_v1.1/power_node_v1.1.ino
@@ -133,6 +133,7 @@
   // put your setup code here, to run once:
   Serial.begin(BAUD);
   customDue.begin(BAUD);
+  //customDue.begin(C
   altserial.begin(9600);
   xbee.begin(altserial);

@@ -566,21 +567,27 @@
   //sendMessage("testing xbee-power module code");
   //Serial.println("Sending this message: testing xbee-power module code");
   digitalWrite(trigForDue, HIGH);
-  ReadTimeDate(&lastSec, &lastMin, &lastHr);
+  timestamp= ReadTimeDate(&lastSec, &lastMin, &lastHr);
   customDue.print(command);
   customDue.print("/");
   customDue.println(timestamp);
+  Serial.print(command);
+  Serial.print(F("/"));
+  Serial.println(timestamp);
   delay(5000); //di pa sure

   //timestart= millis();
-/*
+
   while ( globalChecker == 0 ) {
     t.update();
+    Serial.println(F("Inside globalchecker"));
     if (customDue.available()){
+      Serial.println(F("CD is available"));
       customDue.readBytesUntil('\n',streamBuffer,250);
-    }
-
-    Serial.println(streamBuffer);
+
+    }
+
+    //Serial.println(streamBuffer);

     //if (Serial.available()) {
       //Serial.readBytesUntil('\n', streamBuffer, 250);
@@ -665,7 +672,7 @@
   }

   Serial.println(F("TIME OUT"));
-*/
+
 }

 void printna() {
@@ -675,6 +682,7 @@
   sprintf(dataXB,"No data from Senslope",sizeof("No data from Senslope"));
   sendMessage();
   //sendMessage("No data from Senslope");
+  digitalWrite(trigForDue, LOW);
   t.stop(x);
   globalChecker = 1;
   breaker = 1;


Final push for WWW

Final push for WWW

--- proj/hypercube/HCS/Animations.ino
+++ proj/hypercube/HCS/Animations.ino
@@ -491,7 +491,7 @@
     in_pal_index +=  12;
     if(!iAnimSwitch) {
       while(is_black(ColorFromPalette(iPalette, in_pal_index, gBrightness, gBlending))) {
-        out_pal_index += 1;
+        in_pal_index += 1;
       }
     }
   }


Fix compile

Fix compile

facepalm

--- wled00/wled07_notify.ino
+++ wled00/wled07_notify.ino
@@ -48,10 +48,10 @@
   udpOut[18] = (transitionDelay >> 8) & 0xFF;
   udpOut[19] = effectPalette;
   uint32_t colTer = strip.getSegment(strip.getMainSegmentId()).colors[2];
-  udpOut[20] = (t >> 16) & 0xFF;
-  udpOut[21] = (t >>  8) & 0xFF;
-  udpOut[22] = (t >>  0) & 0xFF;
-  udpOut[23] = (t >> 24) & 0xFF;
+  udpOut[20] = (colTer >> 16) & 0xFF;
+  udpOut[21] = (colTer >>  8) & 0xFF;
+  udpOut[22] = (colTer >>  0) & 0xFF;
+  udpOut[23] = (colTer >> 24) & 0xFF;

   udpOut[24] = followUp;
   uint32_t t = millis() + strip.timebase;


Revert "Fixed gate logic."

Revert "Fixed gate logic."

This reverts commit 7980d5f881e6f9b8e400c62691a1a17cd3ad781b.

--- res/Examples/MIDI_SimpleSynth/MIDI_SimpleSynth.ino
+++ res/Examples/MIDI_SimpleSynth/MIDI_SimpleSynth.ino
@@ -18,12 +18,12 @@

 // -----------------------------------------------------------------------------

-inline void handleGateChanged(bool inGateActive)
+void handleGateChanged(bool inGateActive)
 {
     digitalWrite(sGatePin, inGateActive ? HIGH : LOW);
 }

-inline void pulseGate()
+void pulseGate()
 {
     handleGateChanged(false);
     delay(1);
@@ -32,40 +32,41 @@

 // -----------------------------------------------------------------------------

-void handleNoteOn(byte inChannel, byte inNote, byte inVelocity)
+void handleNotesChanged()
 {
-    const bool firstNote = midiNotes.empty();
-    midiNotes.add(MidiNote(inNote, inVelocity));
-
-    // Possible playing modes:
-    // Mono Low:  use midiNotes.getLow
-    // Mono High: use midiNotes.getHigh
-    // Mono Last: use midiNotes.getLast
+    if (midiNotes.empty())
+    {
+        handleGateChanged(false);
+        noTone(sAudioOutPin);
+    }
+    else
+    {
+        // Possible playing modes:
+        // Mono Low:  use midiNotes.getLow
+        // Mono High: use midiNotes.getHigh
+        // Mono Last: use midiNotes.getLast

-    byte currentNote = 0;
-    if (midiNotes.getLast(currentNote))
-    {
-        tone(sAudioOutPin, sNotePitches[currentNote]);
-
-        if (firstNote)
+        byte currentNote = 0;
+        if (midiNotes.getLast(currentNote))
         {
-            handleGateChanged(true);
-        }
-        else
-        {
+            tone(sAudioOutPin, sNotePitches[currentNote]);
             pulseGate(); // Retrigger envelopes. Remove for legato effect.
         }
     }
 }

+// -----------------------------------------------------------------------------
+
+void handleNoteOn(byte inChannel, byte inNote, byte inVelocity)
+{
+    midiNotes.add(MidiNote(inNote, inVelocity));
+    handleNotesChanged();
+}
+
 void handleNoteOff(byte inChannel, byte inNote, byte inVelocity)
 {
     midiNotes.remove(inNote);
-    if (midiNotes.empty())
-    {
-        handleGateChanged(false);
-        noTone(sAudioOutPin);
-    }
+    handleNotesChanged();
 }

 // -----------------------------------------------------------------------------


Updated to actually include caliper reading code

--- ReFilament/ReFilament.ino
+++ ReFilament/ReFilament.ino
@@ -152,6 +152,43 @@
   }
 }

+void decode(){
+   unsigned char dataIn;
+   dataIn = digitalRead(dataPin);
+
+   now = millis();
+
+   if((now - lastInterrupt) > cycleTime)
+   {
+     finalValue = (-1 *(value * sign) / 100.00);
+     currentBit = 0;
+     value = 0;
+     sign = 1;
+     newValue = 1;
+   }
+   else if (currentBit < 16 )
+   {
+
+     if (dataIn == 0)
+     {
+       if (currentBit < 16) {
+          value |= 1 << currentBit;
+       }
+       else if (currentBit == 20) {
+          sign = -1;
+       }
+
+     }
+
+     currentBit++;
+
+   }
+
+   lastInterrupt = now;
+
+}
+
+
 void clockISR(){
  clockFlag = 1;
 }


Added an EEPROM write protect, and implemented a heartbeat function (partially, still need to program the responses the program makes to the various heartbeat returns).

--- Alarm_Tone/Alarm_Tone.ino
+++ Alarm_Tone/Alarm_Tone.ino
@@ -31,6 +31,7 @@
 enum mode {sensor, alarm};
 unsigned long time = millis();
 const unsigned int eepromModeAddress = 0;
+const bool eepromWriteProtect = true;
 mode opMode = sensor;
 bool reconfiguration();

@@ -68,6 +69,10 @@
 const int delayTillAlarm = 100;
 void waterReadings();

+//Heartbeat global variables
+const unsigned int heartbeatTimeout = 5000;
+int heartbeat(bool sent = false);
+
 void setup() {

   //Setup LED
@@ -78,7 +83,7 @@
   digitalWrite(sensorPin, HIGH); //Sets the pullup resistor

   //Speaker is already set up by default as output
-
+
   //Read in mode from EEPROM
   int storedMode = EEPROM.read(eepromModeAddress);
   if (storedMode == 0) {
@@ -90,7 +95,9 @@
     blinkRate = alarmBlinkRate;
   }
   else {
-    EEPROM.write(eepromModeAddress, opMode);
+    if (!eepromWriteProtect) {
+      EEPROM.write(eepromModeAddress, opMode);
+    }
   }

   //Setup Bluetooth/serial
@@ -98,6 +105,9 @@
   //mode can be changed on-the-fly at runtime
   bluetooth.begin(btBaud);
   Serial.begin(serialBaud);
+
+  //Seed randomness
+  randomSeed(analogRead(0));
 }

 void loop() {
@@ -109,11 +119,14 @@
   //Todo: heartbeat communications
   //Todo: communications on the serial interfaces may have varying length. Account for it
   //DONE Todo: slow down bluetooth send rate. It's too fast and will leave an alarm on forever.
-
+
   if (opMode == sensor) {
     waterReadings();
   }
-
+  if (opMode == alarm) {
+    heartbeat();
+  }
+
   if (Serial.available()) { //DO NOT allow mode reconfiguration via bluetooth. Security hazard.

     if (opMode == alarm) { //What if the Serial command was triggered to reconfigure? (CHECK WITH EUGEN THAT POWER AND USB COMBINED WON'T FRY THE BOARD!)
@@ -122,6 +135,9 @@
       if (input == '5') {
         reconfiguration(); //Start reconfiguration code
       }
+      else if (input == '2') { //a heartbeat came in, respond
+        heartbeat(true);
+      }
       else if (input == '1') { //alarm has been rung
         speaker(alarmTone, sizeof(alarmTone));
       }
@@ -132,6 +148,9 @@

       if (input == '5') { //order of these conditions is important so compiler checks available first!
         reconfiguration(); //Start reconfiguration code
+      }
+      else if (input == '2') { //a heartbeat came in, respond
+        heartbeat(true);
       }

     }
@@ -140,7 +159,7 @@
       blinkRate = 0;
     }
   }
-
+
   //oscillate light
   if (millis() - time >= blinkRate) {
     statePin = !statePin;
@@ -155,74 +174,151 @@
   static unsigned int timeSinceLastHigh = 0; //time since the last high reading
   static bool activated = false; //has the high readings been around long enough that it warranted an alarm
   static unsigned long lastSignal = 0; //time the last warning signal was sent
-
+
   // if a water reading is made
   if (digitalRead (sensorPin) == LOW) {
     timeSinceLastHigh = millis(); //a high water reading was made, reset the counter
-
+
     //if there has been one seen previously
     if (noticed) {
-
+
       //and it's been around for a while without getting turned off, activate
       if (millis() - timeNoticed >= delayTillAlarm && activated == false) {
         bluetooth.write('1');
         activated = true;
         lastSignal = millis();
       }
-
+
       //if the alarm has already been activated, wait for the first alarm to play so you don't flood the alarm beacon
       if (activated && millis() - lastSignal >= 1200) {
         bluetooth.write('1');
         lastSignal = millis();
       }
-
+
     }
     else { //this is the first time it's been seen, make note of it
       noticed = true;
       timeNoticed = millis();
     }
-
+
   }
   else { //there is no more high water readings
-
+
     //if the high water readings have been away for a while, kill the alarm
     if (noticed && millis() - timeSinceLastHigh > timeTillOff) {
       noticed = false;
       activated = false;
     }
-
-  }
+
+  }
+}
+
+//Return codes: 0=response ok, 1=waiting for a response, 2=heartbeat sent, 3=incorrect response, 4=lost communications
+//42=lost communications, sent a new one, 41=lost comms, waiting for a response to new heartbeat, 43=lost communications, incorrect response
+//The sensor only returns 2
+int heartbeat(bool sent) {
+  static unsigned long timeSent = millis();
+  static unsigned int checkValue = 0;
+  static bool signalSent = false;
+  static bool lostComms = false;
+
+  //if a heartbeat hasn't been sent, or one has had a successful validation and enough time has passed to send a new one
+  if (!signalSent && opMode == alarm && millis() - timeSent >= heartbeatTimeout) {
+    checkValue = random(0, 53);
+    timeSent = millis();
+    Serial.print(200 + checkValue);
+    signalSent = true;
+    if (lostComms) {
+      return 42;
+    }
+    else {
+      return 2;
+    }
+  }
+  //if a heartbeat came in
+  else if (sent) {
+    delay(10); //this is needed
+
+    //Assemble the returned value
+    char num = Serial.read();
+    int checkReturned = atoi((const char *) &num) * 10;
+    num = Serial.read();
+    checkReturned += atoi((const char *) &num);
+
+    if (opMode == alarm) {
+
+      //validate the returned value, return result
+      if (checkValue + 1 == checkReturned) {
+        signalSent = false;
+        lostComms = false;
+        Serial.println("Validated successfully");
+        return 0;
+      }
+      else {
+        //signalSent = false; //don't kill the signalSent, the real one may be on the way
+        Serial.println ("No validation");
+
+        if (lostComms) {
+          return 43;
+        }
+        else {
+          return 3;
+        }
+
+      }
+
+    }
+    else if (opMode == sensor) {
+      //increment the return value by one, and send back
+      bluetooth.print(200 + checkReturned + 1);
+      return 2;
+    }
+
+  }
+
+  //If the heartbeat hasn't arrived yet
+  if (millis() - timeSent >= heartbeatTimeout && opMode == alarm) {
+    signalSent = false;
+    lostComms = true;
+    Serial.println ("Lost communications");
+    return 4;
+  }
+
 }

 bool reconfiguration() {
   Serial.println ("Starting reconfiguration...");
   bool retVal = false;
   unsigned int counter = 0;
-
+
   delay(10); //Necessary to make this work
-
+
   while (Serial.available() && counter < 2) {
     char input = Serial.read();
-
+
     if (input == ' ' && counter == 0) {
       //NULL, keep going
     }
     else if (input == '0' && counter == 1) {
       opMode = sensor;
       blinkRate = sensorBlinkRate;
-      EEPROM.write(eepromModeAddress, 0);
+      if (!eepromWriteProtect) {
+        EEPROM.write(eepromModeAddress, 0);
+      }
       retVal = true;
       Serial.println("Now a sensor. Reconfiguration successful.");
     }
     else if (input == '1' && counter == 1) {
       opMode = alarm;
       blinkRate = alarmBlinkRate;
-      EEPROM.write(eepromModeAddress, 1);
+      if (!eepromWriteProtect) {
+        EEPROM.write(eepromModeAddress, 1);
+      }
       retVal = true;
       Serial.println("Now an alarm. Reconfiguration successful.");
     }
     else if (input == '2' && counter == 1) {
-
+
       if (opMode == sensor) {
         Serial.println("I'm a sensor.");
         retVal = true;
@@ -231,7 +327,7 @@
         Serial.println ("I'm an alarm.");
         retVal = true;
       }
-
+
     }
     else {
       retVal = false;
@@ -276,4 +372,4 @@
   alarmSounding = false;
 }

-//Base code from http://www.arduino.cc/en/Tutorial/PlayMelody
+//Base speaker code from http://www.arduino.cc/en/Tutorial/PlayMelody


Changed MAC address of lan arduino

Changed MAC address of lan arduino

--- Arduino/MQTTRF/MQTTRF.ino
+++ Arduino/MQTTRF/MQTTRF.ino
@@ -20,7 +20,7 @@
 #define STR_L1_BRIGHTNESS "home/light/1/status/brightness"

 // Update these with values suitable for your network.
-byte mac[]    = { 0x11, 0x11, 0x11, 0x66, 0x66, 0x66 };
+byte mac[]    = { 0x00, 0x00, 0x10, 0x66, 0x66, 0x66 };
 byte server[] = { 192, 168, 0, 175 };
 byte ip[]     = { 192, 168, 0, 20 };


Fixing Merge Conflicts

Fixing Merge Conflicts

--- TemperatureMonitor/TemperatureMonitor.ino
+++ TemperatureMonitor/TemperatureMonitor.ino
@@ -1,6 +1,7 @@
 #include "DHT.h"

 int sampleRate = 2500; //Milliseconds between sampling
+float tCorrection = -9.4;

 #define DHTPWR 7 //Power
 #define DHTGND 4 //Ground
@@ -53,6 +54,9 @@
   float tC = dht.readTemperature(); //Read Temperature (in Celsius) from DHT22
   float tF = (lm34/1024.0) * (readVcc() - 500) / 10; //Convert the LM34 analog value to a temperature
   float l = 0; //Light Sensor, future use
+
+  float tArduino = readTemp()/1000.0 + tCorrection;
+  float vArduino = readVcc()/1000.0;

   // check if returns are valid, if they are NaN (not a number) then something went wrong!
   if (isnan(tC) || isnan(h)) {
@@ -79,11 +83,28 @@
     Serial.print("|");
     Serial.print(l);
     Serial.print("|");
-    Serial.print("(Celsius,Fahrenheit,% Humidity,Light)");
+    Serial.print(vArduino);
+    Serial.print("|");
+    Serial.print(tArduino);
+    Serial.print("|");
+    Serial.print("(C,F,%,lm,Vcc,Ci)");
     Serial.println();
   }

   delay(sampleRate);
+}
+
+long readTemp() {
+  long result;
+  // Read temperature sensor against 1.1V reference
+  ADMUX = _BV(REFS1) | _BV(REFS0) | _BV(MUX3);
+  delay(2); // Wait for Vref to settle
+  ADCSRA |= _BV(ADSC); // Convert
+  while (bit_is_set(ADCSRA,ADSC));
+  result = ADCL;
+  result |= ADCH<<8;
+  result = (result - 125) * 1075;
+  return result;
 }

 long readVcc() {


Added RF command pathway to turn on LED.

--- testmote_v0_1/testmote_v0_1.ino
+++ testmote_v0_1/testmote_v0_1.ino
@@ -169,6 +169,7 @@
   // recevie rf messages
   noInterrupts();
   if (radio.receiveDone()) {
+      Serial.println("received rf message");
       if (radio.DATALEN != sizeof(Message)) {
           Serial.print("Invalid payload received, not matching Payload struct!");
       } else {
@@ -188,8 +189,9 @@
 //
 void consumeRf() {
   if ((inbound.msg.type == MSG_COMMAND) && (inbound.msg.destination == NODEID)) {
-    Serial.print("switch = ");
+    Serial.print("light = ");
     Serial.println(inbound.msg.data[0]);
+    digitalWrite(DPIN_LIGHT, inbound.msg.data[0]);
   }
 }


Add comment to main sketch to warn about the need for setup

--- solarbit/solarbit.ino
+++ solarbit/solarbit.ino
@@ -1,5 +1,6 @@
 // Solar Mining Module Prototype A
 // https://www.solarbit.cc
+// NOTE: Run solarbit_setup first to configure EEPROM parameters!

 #include <EEPROM.h>
 #include <WiFi101.h>


No suffix

No suffix

--- Vsens/src/sketch.ino
+++ Vsens/src/sketch.ino
@@ -55,7 +55,7 @@
   voltage *= scaleRaw2Volts;      // Scale avg raw value to source voltage.

   Serial.print(voltage);
-  Serial.println (" V");
+  //Serial.println (" V");
   digitalWrite(activityLED, LOW);
   elapsedTime = millis() - startTime;


Adding macros

Adding macros

--- module/module.ino
+++ module/module.ino
@@ -1,5 +1,8 @@
 #include <SoftwareSerial.h>
 #include "RFID.h"
+
+#define isRange(x, y) (x + y) < maximumValue ? 1 : 0
+#define calcTime(x) (millis() - x)/1000

 SoftwareSerial WIFI(WIFI_RX, WIFI_TX);
 SoftwareSerial RFID(RFID_RX, RFID_TX);
@@ -200,7 +203,7 @@

 		// if periodX and periodY IS a valid pair
 		if ( signals[i] == 1 ) {
-			// a job is detected when we get 3 valid signals in a row
+			// a job is detected when we get 5 valid signals in a row
 			// begin stopwatch
 			if (checkHistory(signals) == flag.detectedJobStart) {
 				if (startTime == 0) {
@@ -235,7 +238,7 @@
     	else {
       		i += 1;
     	}
-
+
     	digitalWrite(interlock, HIGH);
 		delay(pollInterval);
 	}


Added OLED code.

Added OLED code.

OLED now shows LED output as bargraph.
Shows ip adress / hostname every 5 seconds.
Shows system time.

--- aquacontrol2.ino
+++ aquacontrol2.ino
@@ -153,6 +153,14 @@
 void loop() {
   webServer.handleClient();

+  if ( programOverride ) {
+    OLED.invertDisplay();
+  }
+  else {
+    OLED.normalDisplay();
+  }
+  updateOLEDbar();
+
   if ( memoryLogging ) {
     //show mem usage
     int nowFreeRAM = ESP.getFreeHeap();


Bunch more bugs

Bunch more bugs

--- tpsu1.ino
+++ tpsu1.ino
@@ -59,9 +59,9 @@

 void readEEPROM() {
   stateOEP = readAddress(0);
-  digitalWrite(OE_P, stateOEP);
+  digitalWrite(OE_P, !stateOEP);
   stateOEN = readAddress(1);
-  digitalWrite(OE_N, stateOEN);
+  digitalWrite(OE_N, !stateOEN);
   stateITE = readAddress(2);
   digitalWrite(ITE, stateITE);
   stateAC1 = readAddress(3);
@@ -230,6 +230,14 @@
           // Diagnostic function - set DAC2
           NegDac.output(param);
           break;
+        case 22:
+          // Diagnostic function - raw ADC values
+          int vsp = analogRead(Vsense_P);
+          int vsn = analogRead(Vsense_N);
+          int asp = analogRead(Asense_P);
+          int asn = analogRead(Asense_N);
+          Serial.println(String("ADC:") + vsp + ", " + vsn + ", " + asp + ", " + asn);
+          break;
       }
     }
   }
@@ -280,13 +288,13 @@
   }
   if (!limitingN) {
     // Adjust voltage within 10mv
-    if (vSenseN > (setVP + 10)) {
-      dacValP++;
-      PosDac.output(dacValP);
-    }
-    if (vSenseP < (setVP - 10)) {
-      dacValP--;
-      PosDac.output(dacValP);
+    if (vSenseN > (setVN + 10)) {
+      dacValN++;
+      NegDac.output(dacValN);
+    }
+    if (vSenseN < (setVN - 10)) {
+      dacValN--;
+      NegDac.output(dacValN);
     }
   }
 }


non-working controller without interrupt

--- beanWheelwriterControl/beanWheelwriterControl.ino
+++ beanWheelwriterControl/beanWheelwriterControl.ino
@@ -22,10 +22,6 @@
 #define CHAR_DELAY 150

 QueueArray<int> q; // holds the bytes we will send to the bus
-int pinChangeCount = 0; // how many times the bus has changed.
-                        // Used to determine if we've received
-                        // a response of zero on the bus
-bool nextCharOkay = true; // flag indicating okay to send a follow-on byte

 int asciiTrans[128] =
 //col: 0     1     2     3     4     5     6     7     8     9     a     b     c     d     e     f     row:
@@ -52,7 +48,7 @@
 //     p     q     r     s     t     u     v     w     x     y     z     {     |     }     ~    DEL
      0x5c, 0x52, 0x03, 0x06, 0x5e, 0x5b, 0x53, 0x55, 0x51, 0x58, 0x54, 0x00, 0x00, 0x00, 0x00, 0x00}; // 7

-     void setup()
+void setup()
 {
   // initialize serial communication at 57600 bits per second:
   Serial.begin(57600);
@@ -67,13 +63,10 @@
   //PORTD |= 0b00000100;

   pinMode(d2, INPUT); // listening pin
-  PCintPort::attachInterrupt(d2, pinChanged, CHANGE);
-
-  // start the pin low
+
+  // start the input pin off (meaning the bus is high, normal state)
   PORTD &= 0b11111011;
-  //SET(PORTD,d7);
-  //digitalWrite(d7,1);
-  pinMode(d1, INPUT_PULLUP);
+  pinMode(d1, INPUT_PULLUP);
 }

 // the loop routine runs over and over again forever:
@@ -254,25 +247,19 @@
     // make sure we aren't still pulling down
     PORTD &= 0b11111011;

-    delayMicroseconds(6 ); // wait for pin to go high before we re-enable interrupts
     // re-enable interrupts
     interrupts();

 }

 void send_letter(int letter) {
-    while (!nextCharOkay) {
-      // busy
-    }
     q.enqueue(0b100100001);
     q.enqueue(0b000001011);
     q.enqueue(0b100100001);
     q.enqueue(0b000000011);
     q.enqueue(letter);
     q.enqueue(0b000001010);
-    pinChangeCount = 1; // pretend we've seen a change on the bus
-    nextCharOkay = false;
-    pinChanged();
+    sendBytes();

     //delay(LETTER_DELAY); // before next character
 }
@@ -387,18 +374,15 @@

 }

-void pinChanged() {
-    if (pinChangeCount == 0) {
-        // first change should be high to low,
-        // second change should be low to high (for a zero)
-        pinChangeCount++;
-    } else {
-        if (!q.isEmpty()) {
-            pinChangeCount = 0;
-            sendByteOnPin(q.dequeue());
+void sendBytes() {
+    while (!q.isEmpty()) {
+        sendByteOnPin(q.dequeue());
+        // wait for low then high (for a zero)
+        while (digitalRead(d2) == 1) {
+          // busy
         }
-        else {
-          nextCharOkay = true;
+        while (digitalRead(d2) == 0) {
+          // busy
         }
     }
 }


decrease threshold

decrease threshold

--- sensor_clock_2.ino
+++ sensor_clock_2.ino
@@ -25,7 +25,7 @@
 #define SLEEP_INTERVAL 250 //0.25s
 #define SLEEP_LONG_INTERVAL 45000 //45s

-#define LIGHT_THRESHOLD 90
+#define LIGHT_THRESHOLD 70

 #define OFF_HOUR 00
 #define OFF_MIN 00


Fix reading failure.

Fix reading failure.

Checking read after write works, but not reading alone.

We have to reset the internal address counter to 000H by bringing RST from “L” to “H”.

Closes #22


test

test

cause I felt like it

--- embedded/Crossfire_Program_V01/Crossfire_Program_V01.ino
+++ embedded/Crossfire_Program_V01/Crossfire_Program_V01.ino
@@ -2,6 +2,7 @@
 //2013

 //Written by Dean Reading
+


Update comments

Update comments

--- examples/Export_Demo/Template_ESP8266/Template_ESP8266.ino
+++ examples/Export_Demo/Template_ESP8266/Template_ESP8266.ino
@@ -3,14 +3,14 @@
  * You should open Setting.h and modify General options.
  *
  * If you would like to add these features to your product,
- * please contact Blynk for Business:
+ * please contact Blynk for Businesses:
  *
  *                  http://www.blynk.io/
  *
  **************************************************************/

-#define USE_SPARKFUN_BLYNK_BOARD
-//#define USE_NODE_MCU_BOARD
+#define USE_SPARKFUN_BLYNK_BOARD  // Uncomment the board you are using
+//#define USE_NODE_MCU_BOARD      // Comment out the boards you are not using
 //#define USE_WITTY_CLOUD_BOARD

 #define DEBUG        // Comment this out to disable debug prints


Time v2 - small changes

Time v2 - small changes

--- time2/time2.ino
+++ time2/time2.ino
@@ -46,9 +46,13 @@
 #include <Time.h>
 #include <DS1302RTC.h>
 // Set pins:  CE, IO,CLK
-DS1302RTC RTC(13, 12, 11);
+DS1302RTC RTC(12, 11, 10);
+
+const uint8_t pin = 13;

 void setup() {
+  pinMode(pin, OUTPUT);
+
   lcd = new CyrI2c(0x27, 16, 2);
   lcd->backlight();

@@ -77,10 +81,15 @@
   while(prevtime == RTC.get()){
     char keypressed = myKeypad.getKey();
     if (keypressed != NO_KEY){
-      if (keypressed != 'A') {
-        hello(tm.Hour);
-        break;
+      digitalWrite(pin, HIGH);
+      switch (keypressed) {
+        case 'A':
+          hello(tm.Hour);
+          break;
+        default:
+          delay(200);
       }
+      digitalWrite(pin, LOW);
     }
   }
 }
@@ -88,9 +97,9 @@
 void hello(uint8_t hour){
   lcd->clear();
   lcd->init(F("Доброї ночі!\rДоброго ранку!\rДоброго дня!\rДоброго вечора!\rЯ годинник :)"));
-  lcd->printn((hour - 1) / 6, 0, 0);
+  lcd->printn((hour + 1) / 6, 0, 0);
   lcd->printn(4, 3, 1);
-  delay(3000);
+  delay(2000);
   lcd->clear();
 }


Some workarounds for ESP32 memory usage

Some workarounds for ESP32 memory usage

--- AnimatedGIFs.ino
+++ AnimatedGIFs.ino
@@ -158,6 +158,8 @@
     randomSeed(analogRead(14));

     Serial.begin(115200);
+    Serial.println("Starting AnimatedGIFs Sketch");
+

     // Initialize matrix
     matrix.addLayer(&backgroundLayer);
@@ -166,22 +168,39 @@
 #endif

     matrix.setBrightness(defaultBrightness);
+
+    // for large panels, set the refresh rate lower to leave more CPU time to decoding GIFs (needed if GIFs are playing back slowly)
+    //matrix.setRefreshRate(90);
+
+    // for large panels on ESP32, set the calculation refresh rate divider lower to leave more CPU time to decoding GIFs (needed if GIFs are playing back slowly)
+    //matrix.setCalcRefreshRateDivider(4);
+
+#if !defined(ESP32)
     matrix.begin();
-
-    //matrix.setRefreshRate(90);
-    // for large panels, set the refresh rate lower to leave more CPU time to decoding GIFs (needed if GIFs are playing back slowly)
+#endif

     // Clear screen
     backgroundLayer.fillScreen(COLOR_BLACK);
-    backgroundLayer.swapBuffers();
+    backgroundLayer.swapBuffers(false);

     if(initSdCard(SD_CS) < 0) {
 #if ENABLE_SCROLLING == 1
         scrollingLayer.start("No SD card", -1);
 #endif
         Serial.println("No SD card");
+        // for ESP32 we need to allocate SmartMatrix DMA buffers after we (in this case fail to) initialize the SD card to avoid using up too much memory
+#if defined(ESP32)
+        matrix.begin();
+#endif
         while(1);
     }
+
+    // for ESP32 we need to allocate SmartMatrix DMA buffers after initializing the SD card to avoid using up too much memory
+#if defined(ESP32)
+    matrix.begin();
+    // If you don't see this message, SmartMatrix Library is likely using up too much CPU, lower the refresh rate or increase the calc refresh rate divider
+    Serial.println("matrix.begin() returned");
+#endif

     // Determine how many animated GIF files exist
     num_files = enumerateGIFFiles(GIF_DIRECTORY, false);