Delete rx8_display_beta_2.0.ino

Delete rx8_display_beta_2.0.ino

--- rx8_display_beta_2.0.ino
+++ rx8_display_beta_2.0.ino
@@ -1,1242 +0,0 @@
-/*****************************************************
-*
-*  S1-RX8-AC-Display-controller
-*  Copyright (c) 2017 TonyChatfield
-*  for Arduino Mega 2560
-*
-******************************************************/
-
-#include <SPI.h>
-#include <Time.h>
-#include <Wire.h>
-//#include "DS3231.h"
-#include "RTClib.h"
-
-RTC_DS1307 rtc;
-//RTC_DS3231 rtc;
-
-#define acAmpTX 8
-#define acAmpRX 12
-
-//PORTA Inputs
-#define matrixRow2 22
-#define matrixRow4 23
-#define matrixRow1 24
-#define matrixRow3 25
-#define rearDemistLED 26
-#define AirConLED 27
-#define reCircLED 28
-#define matrixColB 29
-
-//PORTB
-#define DATAOUT 51 // MOSI
-#define SPICLOCK  52 //sck
-#define ssPin 53 // PB0
-
-//PORTC Outputs
-#define freshAirLED 30
-#define matrixColA 31
-#define frontDemistLED 32
-#define fanInOne 33
-#define autoLED 34
-#define tempInTwo 35
-#define fanInTwo 36
-#define tempInOne 37
-
-//PORT L
-#define mode0 49
-#define mode1 48
-
-//acAmpTX
-int acAmpDataOut[5];
-int acAmpDataDefault[5] = {0x104, 0x180, 0x180, 0x180, 0x0FC}; //Default data for the A\C amplifier TX; basicly it means I am here and no buttons have been pressed.
-unsigned long acAmpTxBetweenTime;
-unsigned long acAmpTxWaitTime = 18; //Control the cycle time otherwise we have a continuous data stream allowing for processing time this equates to 6-7 ms (most of the time).
-
-// Push button matrix stuff
-byte buttonCount = 0;
-byte pushedButtonOld = 0;
-byte pushedButtonCurrent = 0;
-byte longPushButton = 0;
-byte shortPushButton = 0;
-long buttonPushed = 0;
-byte buttonDebounce = 50;
-bool buttonCycle = false;
-byte buttonControl = 15; //Control the point where shortPushButton becomes longPushButton
-
-// Rotary switches
-bool aFanOld = 0;
-bool bFanOld = 0;
-bool aTempOld = 0;
-bool bTempOld = 0;
-
-// Menu
-byte menuIndexMin = 0;
-byte menuIndexMax = 255;
-byte menuIndex = 0;
-byte menuValueMin = 0;
-byte menuValueMax = 255;
-byte menuValue = 0;
-bool menuStartValue = false;
-bool setHourFirst = true;
-bool inMenu = false;
-
-
-//RX data stuff
-byte acAmpIndex = 0;
-unsigned int acAmpNewByte;
-unsigned int acAmpRxData[6]; //Where we keep our inbound data.
-unsigned long acAmpReceivedTime;
-unsigned long acAmpCycleTime;
-bool acAmpOn = false;
-bool acAmpRunning = false;
-bool acAmpRxChanged = true;
-bool acAmpMessageToProcess = false;
-bool acAmpDisplayClear = false;
-
-//Data processing
-byte currentTemp;
-byte currentHour;
-byte currentMinute;
-byte previousMinute;
-unsigned long nowTimeCycle;
-byte nowHour = 0;
-byte nowMinute = 0;
-bool minuteChange = false;
-bool acAmpCentigrade = true;
-bool clock24Hour = true; //false = 12 hour clock
-bool acAmpAmbient = false;
-bool confMode = false;
-
-// iconArray for display icons 90-9D, first 5 LSB, calculated via addition. iconArray[0] = current, iconArray[1] = LCD display registry values.
-byte iconArray[2][14] = {0};
-byte sevenSegmentArray[1][7] = {0};
-
-
-/**********************************************
-// User configurable
-**********************************************/
-String welcome = "Test Beta2.0"; // populate something into the text display - 12 Char max anything else is truncated.
-
-
-void setup() {
-  // we use iconArray[1] to define the registers we write too with the data thats populated into iconArray[0]
-  iconArray[1][0] = 0x90; iconArray[1][1] = 0x91; iconArray[1][2] = 0x92; iconArray[1][3] = 0x93; iconArray[1][4] = 0x94; iconArray[1][5] = 0x95; iconArray[1][6] = 0x96;
-  iconArray[1][7] = 0x97; iconArray[1][8] = 0x98; iconArray[1][9] = 0x99; iconArray[1][10] = 0x9A; iconArray[1][11] = 0x9B; iconArray[1][12] = 0x9C; iconArray[1][13] = 0x9D;
-
-  // Control pins for the display SPI
-  pinMode(mode0, OUTPUT);
-  pinMode(mode1, OUTPUT);
-  pinMode(ssPin, OUTPUT);
-
-  //Push buttons and rotary switches
-  pinMode(matrixColA, OUTPUT);
-  pinMode(matrixColB, OUTPUT);
-  pinMode(matrixRow1, INPUT_PULLUP);
-  pinMode(matrixRow2, INPUT_PULLUP);
-  pinMode(matrixRow3, INPUT_PULLUP);
-  pinMode(matrixRow4, INPUT_PULLUP);
-  pinMode(fanInOne, INPUT_PULLUP);
-  pinMode(fanInTwo, INPUT_PULLUP);
-  pinMode(tempInOne, INPUT_PULLUP);
-  pinMode(tempInTwo, INPUT_PULLUP);
-
-  //Control panel LED's
-  pinMode(rearDemistLED, OUTPUT);
-  pinMode(frontDemistLED, OUTPUT);
-  pinMode(freshAirLED, OUTPUT);
-  pinMode(autoLED, OUTPUT);
-  pinMode(AirConLED, OUTPUT);
-
-  // Real time clock
-  rtc.begin();
-  //rtc.adjust(DateTime(2014, 1, 21, 4, 33, 0)); //a fixed time
-  // rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // your PC's time. ***** You may need to comment out after 1 upload to set the time - see wiki*******
-  DateTime now = rtc.now();
-  nowHour = now.hour();
-  nowMinute = now.minute();
-
-
-  SPI.begin();
-  SPI.beginTransaction(SPISettings(10000000, MSBFIRST, SPI_MODE3)); //I couldn't see a defined max speed in the NJU6623 datasheet, 10Meg is quite an increase on the original 9600, so need to monitor incase this is not stable.
-  Serial.begin (115200, SERIAL_8N1, true); // 9 bit mode
-  Serial2.begin (4800, SERIAL_8N1, true);// 9 bit mode
-
-  delay(300);
-  lcdDisplayStartUp(); // run the LCD default settings and clear the display icons
-
-}
-
-void loop()
-{
-  checkAndSendHardwareControl();
-  calculateTime();
-
-  if (!confMode)
-  {
-    acAmpGetSerialData();
-
-    if (millis() - acAmpCycleTime >= 200) // we force the state of acAmpRxChanged if there has been no recent data update, this way we minimise unnecessary processing but at acAmp power off our icons clear more\less instantly (to the human eye).
-    {
-      acAmpRxChanged = true;
-      // Enabling these would give us a timed refresh regardless of change, this may be needed if we encounter issues\interference
-      // acAmpMessageToProcess = true;
-      // acAmpCycleTime = millis();
-    }
-
-    if (acAmpMessageToProcess && acAmpRxChanged || minuteChange)
-    {
-      acAmpLedFuntions(acAmpOn);
-      if (acAmpOn)
-      {
-        acAmpRecievedStatus();
-
-        acAmpProcessAC();
-        acAmpProcessFan();
-        acAmpProcessTemp();
-        acAmpProcessModeControls();
-      }
-
-      iconArrayCheckThenSet();
-      sevenSegmentCheckThenSet();
-      populateFixedLcdDisplay(welcome);
-      minuteChange = false;
-      acAmpRxChanged = false;
-      acAmpMessageToProcess = false;
-    }
-  }
-  else
-  {
-    acAmpOn = false;
-    //This will be confMode
-    confMenu();
-    sevenSegmentCheckThenSet();
-    iconArrayCheckThenSet();
-  }
-}
-
-
-/*****************************************************************
-// acAmp inbound
-*****************************************************************/
-
-void acAmpRecievedStatus() // Based on the first byte of our inbound message we have 3 main data states from AC Amplifier. Off, Normal control and Ambient
-{
-  if (acAmpRxData[0] == 0x00F) // we are off apart from showing Mode settings
-  {
-    acAmpRunning = false;
-  }
-
-  acAmpAmbient = (acAmpRxData[0] == 0x10E) ? true : false; // 10D Normal || 10E Ambient
-
-}
-
-
-
-void acAmpProcessModeControls() // acAmp control settings. Mode 1 = feet, 2 = feet\demist, 3 = face, 4 = face\feet
-{ byte acAmpMode;
-
-  if (bitRead(acAmpRxData[4], 0) && bitRead(acAmpRxData[4], 1))
-  {
-    acAmpMode = 1;
-  }
-  else if (bitRead(acAmpRxData[4], 0) && !bitRead(acAmpRxData[4], 1))
-  {
-    acAmpMode = 2;
-  }
-  else if (!bitRead(acAmpRxData[4], 0) && !bitRead(acAmpRxData[4], 1))
-  {
-    acAmpMode = 3;
-  }
-  else if (!bitRead(acAmpRxData[4], 0) && bitRead(acAmpRxData[4], 1))
-  {
-    acAmpMode = 4;
-  }
-  iconCalculateMode(acAmpMode);
-}
-
-
-
-void acAmpProcessFan() // Find the current fan speed
-{ byte acAmpFanSpeed = 0;
-  bitWrite(acAmpFanSpeed, 2, bitRead(acAmpRxData[2], 6));
-  bitWrite(acAmpFanSpeed, 1, bitRead(acAmpRxData[2], 5));
-  bitWrite(acAmpFanSpeed, 0, bitRead(acAmpRxData[2], 4));
-
-  acAmpFanSpeed = (acAmpFanSpeed <= 6) ? ++acAmpFanSpeed : 0;
-  acAmpRunning = (acAmpFanSpeed) ? true : false;
-  iconCalculateFan(acAmpFanSpeed);
-}
-
-
-
-void acAmpProcessAC() //The 3 A/C States
-{
-  if (!bitRead(acAmpRxData[3], 6)) // Auto
-  {
-    iconArray[0][7] += 0x10;
-  }
-  if (!bitRead(acAmpRxData[3], 5)) // A/C
-  {
-    iconArray[0][8] += 0x08;
-  }
-  if (!bitRead(acAmpRxData[3], 4)) // ECO
-  {
-    iconArray[0][8] += 0x10;
-  }
-}
-
-
-
-// Need to set leds based on acAmp button state, we are directly manipulating the ports.
-void acAmpLedFuntions(bool _acAmpOn)
-{
-  if (_acAmpOn)
-  {
-    PORTC = (!bitRead(acAmpRxData[4], 6)) ? PORTC |= (1 << PC5) : PORTC &= ~(1 << PC5); // FrontDemist
-    PORTA = (!bitRead(acAmpRxData[4], 5)) ? PORTA |= (1 << PA4) : PORTA &= ~(1 << PA4); // RearDemist
-    PORTC = (bitRead(acAmpRxData[4], 3)) ? PORTC &= ~(1 << PC7) : PORTC |= (1 << PC7); // Fresh
-    PORTA = (bitRead(acAmpRxData[4], 3)) ? PORTA |= (1 << PA6) : PORTA &= ~(1 << PA6); // Recirc
-    PORTC = (!bitRead(acAmpRxData[3], 6)) ? PORTC |= (1 << PC3) : PORTC &= ~(1 << PC3); // Auto
-    PORTA = (!bitRead(acAmpRxData[3], 5)) ? PORTA |= (1 << PA5) : PORTA &= ~(1 << PA5); // A/C
-  }
-  else // When the acAmp is off, We turn off all the LED's.
-  {
-    PORTC &= ~(1 << PC5);
-    PORTA &= ~(1 << PA4);
-    PORTC &= ~(1 << PC7);
-    PORTA &= ~(1 << PA6);
-    PORTC &= ~(1 << PC3);
-    PORTA &= ~(1 << PA5);
-  }
-}
-
-
-
-// Get data from the acAmplifier - it's 9N1 and inverted. Note we don't sit and wait around for a full payload.
-void acAmpGetSerialData()
-{
-  if (Serial2.available() > 0)
-  { //acAmpOn = true;
-    acAmpReceivedTime = millis();
-    acAmpNewByte = Serial2.read();
-    acAmpDisplayClear = false;
-
-    if (acAmpNewByte == 0x00F || acAmpNewByte == 0x10D || acAmpNewByte == 0x10E) // We don't know the last byte but we know the first byte will be one of these
-    {
-      acAmpIndex = 0;
-      if (acAmpNewByte != acAmpRxData[acAmpIndex])
-      {
-        acAmpRxData[acAmpIndex] = acAmpNewByte;
-        acAmpRxChanged = true;
-      }
-    }
-    else
-    {
-      acAmpIndex++;
-      if (acAmpNewByte != acAmpRxData[acAmpIndex])
-      {
-        acAmpRxData[acAmpIndex] = acAmpNewByte;
-        acAmpRxChanged = true;
-
-        if (acAmpIndex == 5) //we know the length of the data transfer. If we knew how to calculate the checksum we could validate received data but for now we assume it's correct.
-        {
-          acAmpOn = (acAmpRxData[4] != 0xFF) ? true : false ; // Stops icon flicker at startup
-          acAmpMessageToProcess = true;
-          acAmpIndex = 0;
-          acAmpCycleTime = millis();
-        }
-      }
-    }
-  }
-  else
-  {
-    if (millis() - acAmpReceivedTime > 30 && !acAmpDisplayClear) // If there is no data we assume the A\C amplifier is off and we run 1 cycle to clear the display. This is easier than having to monitor assorted vehicle power states.
-    {
-      acAmpOn = false;
-      acAmpMessageToProcess = true;
-      acAmpDisplayClear = true;
-    }
-  }
-}
-
-
-
-/*****************************************************************
-  // Icon display
-  // For the icon displays we calculate a binary value for the 5 seperate registers with simple addition in hex
-  //                      Position\Register 0x01,0x02,0x04,0x08,0x10
-  // int icon90 = [00]; mM R/H lower, mM lower, fullstop between Minutes, Mm R/H lower, Mn lower
-  // int icon91 - [01]; mM L/H upper, mM Upper, mM R/H upper, mM centre, L/H vertical divider
-  // int icon92 = [02]; Mm L/H upper, Mn upper, Mm R/H upper, Mm centre, mM L/H lower
-  // int icon93 = [03]; not used, not used, HH:MM Divider, Mm L/H lower, CD IN
-  // int icon94 = [04]; not used, not used, not used, not used, MD IN
-  // int icon95 = [05]; Dolby Logo, not used, not used, not used, ST
-  // int icon96 = [06]; AF, AMB, Thermo symbol, degF, degC
-  // int icon97 = [07]; Car logo (aircon), PTY, fresh air Arrow, recirculate Arrow, AUTO
-  // int icon98 = [08]; fan4, RPT, fan5, A\C, ECO
-  // int icon99 = [09]; not used, Fan base, fan1, fan2, fan3
-  // int icon9A = [10]; Auto-M, TP, TA, RDM, Full Stop between DDRAM #10 & #11
-  // int icon9B = [11]; not used, fan7, not used, R/H vertical divider, Full Stop between DDRAM #11 & #12
-  // int icon9C = [12]; Seated Man, Front Demist, Down\Feet Arrow, not used, not used
-  // int icon9D = [13]; not used, Temp Decimal, Face Arrow, fan6, mid display colon,
-*****************************************************************/
-
-void iconCalculateMode(byte _modeSet) // Mode 1 = feet, 2 = feet\demist, 3 = face, 4 = face\feet
-{
-  switch (_modeSet)
-  {
-    case 1: iconArray[0][12] += 0x04;
-      break;
-    case 2: if (!bitRead(acAmpRxData[4], 2) && bitRead(acAmpRxData[4], 6)) // feet/demist has dependancies on addition demist related bytes
-      {
-        iconArray[0][12] += 0x02;
-        iconArray[0][12] += 0x04;
-      }
-      else if (bitRead(acAmpRxData[4], 2))
-      {
-        iconArray[0][12] += 0x02;
-      }
-      break;
-    case 3: iconArray[0][13] += 0x04;
-      break;
-    case 4: iconArray[0][12] += 0x04; iconArray[0][13] += 0x04;
-      break;
-  }
-}
-
-
-
-// Set fan speed icons including the base outline
-void iconCalculateFan(byte _fanSpeed)
-{
-  switch (_fanSpeed)
-  {
-    case 1: iconArray[0][9] += 0x06;
-      break;
-    case 2: iconArray[0][9] += 0x0E;
-      break;
-    case 3: iconArray[0][9] += 0x1E;
-      break;
-    case 4: iconArray[0][8] += 0x01; iconArray[0][9] += 0x1E;
-      break;
-    case 5: iconArray[0][8] += 0x05; iconArray[0][9] += 0x1E;
-      break;
-    case 6: iconArray[0][8] += 0x05; iconArray[0][9] += 0x1E; iconArray[0][13] += 0x08;
-      break;
-    case 7: iconArray[0][8] += 0x05; iconArray[0][9] += 0x1E; iconArray[0][13] += 0x08; iconArray[0][11] += 0x02;
-      break;
-  }
-}
-
-
-
-//Calculate the seven segment display values that are generated via the icon matrix, Mm and mM
-void iconCalculateMinute(byte _digit, byte _value)
-{
-  if (_digit == 1) //Mm
-  {
-    switch (_value)
-    {
-      case 0: iconArray[0][0] += 0x18; iconArray[0][2] += 0x07; iconArray[0][3] += 0x08;
-        break;
-      case 1: iconArray[0][0] += 0x08; iconArray[0][2] += 0x04; iconArray[0][3] += 0x00;
-        break;
-      case 2: iconArray[0][0] += 0x10; iconArray[0][2] += 0x0E; iconArray[0][3] += 0x08;
-        break;
-      case 3: iconArray[0][0] += 0x18; iconArray[0][2] += 0x0E; iconArray[0][3] += 0x00;
-        break;
-      case 4: iconArray[0][0] += 0x08; iconArray[0][2] += 0x0D; iconArray[0][3] += 0x00;
-        break;
-      case 5: iconArray[0][0] += 0x18; iconArray[0][2] += 0x0B; iconArray[0][3] += 0x00;
-        break;
-        // we should never see these for Mm minute, but just incase someone wants them for an alternate purpose.
-        // case 6: iconArray[0][0] += 0x18; iconArray[0][2] +=0x0B; iconArray[0][3] += 0x08;
-        // break;
-        // case 7: iconArray[0][0] += 0x08; iconArray[0][2] +=0x06; iconArray[0][3] += 0x00;
-        // break;
-        // case 8: iconArray[0][0] += 0x18; iconArray[0][2] +=0x0F; iconArray[0][3] += 0x08;
-        // break;
-        // case 9: iconArray[0][0] += 0x08; iconArray[0][2] +=0x0F; iconArray[0][3] += 0x00;
-        // break;
-    }
-  }
-  else if (_digit == 2) //mM
-  {
-    switch (_value)
-    {
-      case 0: iconArray[0][0] += 0x03; iconArray[0][1] += 0x07; iconArray[0][2] += 0x10;
-        break;
-      case 1: iconArray[0][0] += 0x01; iconArray[0][1] += 0x04; iconArray[0][2] += 0x00;
-        break;
-      case 2: iconArray[0][0] += 0x02; iconArray[0][1] += 0x0E; iconArray[0][2] += 0x10;
-        break;
-      case 3: iconArray[0][0] += 0x03; iconArray[0][1] += 0x0E; iconArray[0][2] += 0x00;
-        break;
-      case 4: iconArray[0][0] += 0x01; iconArray[0][1] += 0x0D; iconArray[0][2] += 0x00;
-        break;
-      case 5: iconArray[0][0] += 0x03; iconArray[0][1] += 0x0B; iconArray[0][2] += 0x00;
-        break;
-      case 6: iconArray[0][0] += 0x03; iconArray[0][1] += 0x0B; iconArray[0][2] += 0x10;
-        break;
-      case 7: iconArray[0][0] += 0x01; iconArray[0][1] += 0x06; iconArray[0][2] += 0x00;
-        break;
-      case 8: iconArray[0][0] += 0x03; iconArray[0][1] += 0x0F; iconArray[0][2] += 0x10;
-        break;
-      case 9: iconArray[0][0] += 0x03; iconArray[0][1] += 0x0F; iconArray[0][2] += 0x00;
-        break;
-    }
-  }
-}
-
-
-
-// Default values for iconArray [0][1] vertical divider, [0][3] HH:MM divider, [0][11] vertical divider, iconArray[1][x] = hex mapping for display address.
-void iconDefaultDisplayValues()
-{
-  iconArray[0][1] += 0x10; // Vertical divider R/H
-  iconArray[0][11] += 0x08; // Vertical divider L/H
-  iconArray[0][3] += 0x04; // HH:MM Divider
-
-  if (acAmpOn)
-  {
-    iconArray[0][12] += 0x01; // The seated man
-    iconArray[0][7] = (bitRead(acAmpRxData[4], 3)) ? iconArray[0][7] += 0x09 : iconArray[0][7] += 0x05; //airSource
-    if (acAmpAmbient)
-    {
-      iconArray[0][6] += 0x02; // AMB
-      iconArray[0][6] = (acAmpCentigrade) ? iconArray[0][6] += 0x10 : iconArray[0][6] += 0x08; // C or F
-    }
-    if (acAmpRunning && !acAmpAmbient)
-    {
-      iconArray[0][13] += 0x02; // decimal place in TMP
-      iconArray[0][6] += 0x04; // Thermo symbol
-    }
-  }
-}
-
-
-
-void iconArrayCheckThenSet()
-{
-  minuteCalculate(currentMinute); //Must be recalculated every time we update Icons regardless of change.
-  iconDefaultDisplayValues();     //Must be recalculated every time we update Icons regardless of change.
-  for (int i = 0; i < 14; i++)
-  {
-    lcdDisplaySetIconDisplay(iconArray[1][i], iconArray[0][i]);
-    iconArray[0][i] = 0;
-  }
-}
-
-
-/*****************************************************************
-  // SevenSegment Display
-  // Calculate the seven segmeent display values that are generated via CGRam for Hh, hH, Tmp, tMp, tmP
-  // Parameters; the HEX value for the bit mapped to column (0x10 = 8C Hh, 0x08 = 8C hH, 0x01 = 8D Tmp, 0x04 = 8D tMp, 0x02 = 8C tmP)
-*****************************************************************/
-
-void sevenSegmentCalculate(byte _column, byte _value)
-{
-  switch (_value)
-  {
-    case 0: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][1] += _column; sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][4] += _column; sevenSegmentArray[0][5] += _column; sevenSegmentArray[0][6] += _column;
-      break;
-    case 1: sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][5] += _column;
-      break;
-    case 2: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][3] += _column; sevenSegmentArray[0][4] += _column; sevenSegmentArray[0][6] += _column;
-      break;
-    case 3: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][3] += _column; sevenSegmentArray[0][5] += _column; sevenSegmentArray[0][6] += _column;
-      break;
-    case 4: sevenSegmentArray[0][1] += _column; sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][3] += _column; sevenSegmentArray[0][5] += _column;
-      break;
-    case 5: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][1] += _column; sevenSegmentArray[0][3] += _column; sevenSegmentArray[0][5] += _column; sevenSegmentArray[0][6] += _column;
-      break;
-    case 6: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][1] += _column; sevenSegmentArray[0][3] += _column; sevenSegmentArray[0][4] += _column; sevenSegmentArray[0][5] += _column; sevenSegmentArray[0][6] += _column;
-      break;
-    case 7: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][5] += _column;
-      break;
-    case 8: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][1] += _column; sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][3] += _column; sevenSegmentArray[0][4] += _column; sevenSegmentArray[0][5] += _column; sevenSegmentArray[0][6] += _column;
-      break;
-    case 9: sevenSegmentArray[0][0] += _column; sevenSegmentArray[0][1] += _column; sevenSegmentArray[0][2] += _column; sevenSegmentArray[0][3] += _column; sevenSegmentArray[0][5] += _column;
-      break;
-  }
-}
-
-
-
-void sevenSegmentCheckThenSet()
-{
-  hourCalculate(currentHour); //we include this here as must be reclaculated everytime we update regardless of change.
-  lcdDisplayPopulateCgramAddress(0x00);
-}
-
-
-/*****************************************************************
-  // Time and temp
-*****************************************************************/
-
-void calculateTime()
-{
-  if (millis() - nowTimeCycle >= 10000 || confMode) // 'DateTime now' takes over 1 milliSecond to return a result, so we don't run it every cycle.
-  {
-    DateTime now = rtc.now();
-    nowTimeCycle = millis();
-    nowHour = now.hour();
-    nowMinute = now.minute();
-  }
-
-  if (!clock24Hour && nowHour > 12) // 12 or 24 hour, for now set in main controls via clock24Hour
-  {
-    currentHour = nowHour - 12;
-  }
-  else
-  {
-    currentHour = nowHour;
-  }
-
-  currentMinute = nowMinute;
-
-
-
-  //If the hour or minute are continually updating the other icons flicker\vanish as they are not set constantly, so we flag a minute change to manage display updates.
-  minuteChange = (previousMinute != currentMinute) ? true : false;
-  previousMinute = currentMinute;
-}
-
-
-
-//Process Hour as 2 separate digits
-void hourCalculate(byte _currentHour)
-{
-  byte theHourHh = _currentHour / 10;
-  sevenSegmentCalculate(0x10, theHourHh); //wirte to the sevenSegment array
-
-  byte theHourhH = _currentHour % 10;
-  sevenSegmentCalculate(0x08, theHourhH); //wirte to the sevenSegment array
-}
-
-
-
-// Process Minute as 2 separate digits
-void minuteCalculate(byte _currentMinute)
-{
-  byte theMinuteMm = _currentMinute / 10;
-  iconCalculateMinute(1, theMinuteMm); // write to the Icon array
-
-  byte theMinutemM = _currentMinute % 10;
-  iconCalculateMinute(2, theMinutemM); // write to the Icon array
-}
-
-
-
-//Define temperature control mapping - The F calculation incomplete
-void acAmpProcessTemp()
-{
-  byte currentTemp = 0;
-  byte displayOrder = 0;
-  byte fTemp = 0;
-  unsigned int tempOrder[3] = {0x01, 0x04, 0x02};
-  for (byte i = 0; i <= 2; i++)
-  {
-    displayOrder = tempOrder[i];
-
-    for (byte j = 0; j <= 3; j++)
-    {
-      bitWrite(currentTemp, j, bitRead(acAmpRxData[i + 1], j));
-    }
-
-    if (minuteChange || acAmpMessageToProcess) //as the temp is via seven segment, we need to make sure we update if the time changes.
-    {
-      sevenSegmentCalculate(displayOrder, currentTemp); //write to the sevenSegment array
-    }
-  }
-}
-
-
-void updateClockTime()
-{
-  inMenu = true;
-  if (shortPushButton == 1)
-  {
-    setHourFirst = (!setHourFirst) ? true : false;
-    menuStartValue = false;
-  }
-
-  if (setHourFirst && inMenu)
-  {
-    menuValueMax = (clock24Hour) ? 23 : 12;
-    populateFixedLcdDisplay("Set Hour");
-    menuValue = (!menuStartValue) ? currentHour : menuValue ;
-    currentHour = menuValue;
-    menuStartValue = true;
-    DateTime now = rtc.now();
-    rtc.adjust(DateTime(now.year(), now.month(), now.day(), menuValue, now.minute(), now.second()));
-  }
-
-  if (!setHourFirst && inMenu)
-  {
-    menuValueMax = 59;
-    populateFixedLcdDisplay("Set Minute");
-    menuValue = (!menuStartValue) ? currentMinute : menuValue ;
-    currentMinute = menuValue;
-    menuStartValue = true;
-    DateTime now = rtc.now();
-    rtc.adjust(DateTime(now.year(), now.month(), now.day(), now.hour(), menuValue, now.second()));
-
-  }
-}
-
-
-/*****************************************************************
-  // Hardware controls
-*****************************************************************/
-
-void checkAndSendHardwareControl()// Check hardware controls and push to A/C Amplifier with a controlled cycle
-{
-  if ((millis() - acAmpTxBetweenTime >= acAmpTxWaitTime))
-  {
-    memcpy(acAmpDataOut, acAmpDataDefault, 10);
-    checkFanRotation();
-    checkTempRotation();
-    checkPushedButton();
-    if (!confMode)
-    {
-      acAmpSend();
-    }
-
-  }
-}
-
-
-
-void checkFanRotation()
-{
-  bool aFanNew = 0;
-  bool bFanNew = 0;
-  aFanNew = (PINC & (1 << PC4));
-  bFanNew = (PINC & (1 << PC1));
-
-  if  (aFanNew != aFanOld || bFanNew != bFanOld)
-  {
-    if ((aFanNew && !aFanOld && !bFanNew && !bFanOld) || (!aFanNew && aFanOld && bFanNew && bFanOld) )  //Right movement
-    {
-      if (!confMode)
-      {
-        acAmpDataOut[3] = 0x090; acAmpDataOut[4] = 0x1EC;
-      }
-      else
-      {
-        menuIndex = (menuIndex < menuIndexMax) ? ++menuIndex : menuIndexMin ;
-      }
-    }
-    else if ((aFanNew && aFanOld && !bFanNew && bFanOld) || (!aFanNew && !aFanOld && bFanNew && !bFanOld)) //Left movement
-    {
-      if (!confMode)
-      {
-        acAmpDataOut[3] = 0x0F0; acAmpDataOut[4] = 0x18C;
-      }
-      else
-      {
-        menuIndex = (menuIndex > menuIndexMin) ? --menuIndex : menuIndexMax ;
-      }
-    }
-  }
-  aFanOld = aFanNew;
-  bFanOld = bFanNew;
-}
-
-
-
-void checkTempRotation()
-{
-  bool aTempNew = 0;
-  bool bTempNew = 0;
-  aTempNew = (PINC & (1 << PC0));
-  bTempNew = (PINC & (1 << PC2));
-
-  if  (aTempNew != aTempOld || bTempNew != bTempOld)
-  {
-    if ((aTempNew && !aTempOld && !bTempNew && !bTempOld) || (!aTempNew && aTempOld && bTempNew && bTempOld) )  //Right movement
-    {
-      if (!confMode)
-      {
-        acAmpDataOut[3] = 0x081; acAmpDataOut[4] = 0x1FB;
-      }
-      else
-      {
-        menuValue = (menuValue < menuValueMax) ? ++menuValue : menuValueMin ;
-      }
-    }
-    else if ((aTempNew && aTempOld && !bTempNew && bTempOld) || (!aTempNew && !aTempOld && bTempNew && !bTempOld)) //Left movement
-    {
-      if (!confMode)
-      {
-        acAmpDataOut[3] = 0x087; acAmpDataOut[4] = 0x0F5;
-      }
-      else
-      {
-        menuValue = (menuValue > menuValueMin) ? --menuValue : menuValueMax ;
-      }
-    }
-  }
-  aTempOld = aTempNew;
-  bTempOld = bTempNew;
-}
-
-
-
-void checkPushedButton()
-{
-  bool matrixCycle = 0;
-  bool controlButton = false;
-
-  checkMatrixCycle();  // Buttons have a matrix switch arrangement.
-
-  if (pushedButtonCurrent == 0 && buttonCycle) //Long button press is single shot, so must be reset by removing finger.
-  {
-    buttonCycle = false;
-  }
-
-  if ((!longPushButton && pushedButtonCurrent == pushedButtonOld) && pushedButtonCurrent && (millis() - buttonPushed >= buttonDebounce)) // index the button count
-  {
-    buttonCount++;
-    buttonPushed = millis();
-  }
-
-  if (pushedButtonCurrent != pushedButtonOld)
-  {
-    if (pushedButtonCurrent == 0 && buttonCount > 0 && buttonCount < buttonControl) // Short button press trigger.
-    {
-      shortPushButton = pushedButtonOld;
-    }
-    buttonPushed = millis();
-    pushedButtonOld = pushedButtonCurrent;
-    buttonCount = 0;
-  }
-
-  if (!confMode && shortPushButton) // Do something with a short button press
-  {
-    shortButtonAction(shortPushButton);
-    shortPushButton = 0;
-  }
-
-  if (!buttonCycle && pushedButtonCurrent && buttonCount > buttonControl) // Do something with a long button press
-  {
-    longPushButton = pushedButtonCurrent;
-    longButtonAction(longPushButton);
-    if (!confMode || longPushButton == 2)
-    {
-      longPushButton = 0;
-    }
-    buttonCycle = true;
-  }
-}
-
-
-
-void checkMatrixCycle() // we poll the pin matrix this takes 2 cycles and we need to set pins high\low
-{
-  pushedButtonCurrent = 0;
-  for (byte i = 0; i <= 1; i++)
-  {
-    if (i == 0)
-    {
-      PORTC |= (1 << PC6);
-      PORTA &= ~(1 << PA7);
-    }
-    else
-    {
-      PORTC &= ~(1 << PC6);
-      PORTA |= (1 << PA7);
-    }
-
-    if (!(PINA & (1 << PA2)))
-    {
-      if (i == 1)
-      {
-        pushedButtonCurrent = 1; // Auto switch
-        break;
-      }
-      else
-      {
-        pushedButtonCurrent = 2; // Mode switch
-        break;
-      }
-    }
-    else if (!(PINA & (1 << PA0)))
-    {
-      if (i == 1)
-      {
-        pushedButtonCurrent = 3; // A/C switch
-        break;
-      }
-      else
-      {
-        pushedButtonCurrent = 4; // frontDemist switch
-        break;
-      }
-    }
-    else if (!(PINA & (1 << PA3)))
-    {
-      if (i == 1)
-      {
-        pushedButtonCurrent = 5; //rearDemist switch
-        break;
-      }
-      else
-      {
-        pushedButtonCurrent = 6; // AirSource switch
-        break;
-      }
-    }
-    else if (!(PINA & (1 << PA1)))
-    {
-      if (i == 1)
-      {
-        pushedButtonCurrent = 7; //Error if we get here with RX8
-        break;
-      }
-      else
-      {
-        pushedButtonCurrent = 8; // Off switch
-        break;
-      }
-    }
-  }
-}
-
-
-
-void shortButtonAction(byte _shortPushButton)
-{
-  if (!confMode) // Lookup the correct transmission data if normally running
-  {
-    switch (_shortPushButton)
-    {
-      case 1: acAmpDataOut[1] = 0x082; acAmpDataOut[4] = 0x0FA;
-        break;
-      case 2: acAmpDataOut[1] = 0x090; acAmpDataOut[4] = 0x1EC;
-        break;
-      case 3: acAmpDataOut[1] = 0x084; acAmpDataOut[4] = 0x1F8;
-        break;
-      case 4: acAmpDataOut[1] = 0x0A0; acAmpDataOut[4] = 0x1DC;
-        break;
-      case 5: acAmpDataOut[1] = 0x0C0; acAmpDataOut[4] = 0x1BC;
-        break;
-      case 6: acAmpDataOut[1] = 0x088; acAmpDataOut[4] = 0x1F4;
-        break;
-      case 7://we should never get here with RX8;
-        break;
-      case 8: acAmpDataOut[1] = 0x081; acAmpDataOut[4] = 0x1FB;
-        break;
-    }
-  }
-}
-
-
-
-void longButtonAction(byte _longPushButton)
-{
-  //pushedLongButton
-  if (!confMode) // we can set control options on long button press
-  {
-    switch (_longPushButton)
-    {
-      case 1 :
-        break;
-      case 2 :  confMode = true; menuIndex = 1;
-        break;
-      case 3 :
-        break;
-      case 4 :
-        break;
-      case 5 :
-        break;
-      case 6 :
-        break;
-      case 7 :
-        break;
-      case 8 : acAmpAmbient = !acAmpAmbient ? true : false; acAmpDataOut[2] = 0x0A0; acAmpDataOut[4] = 0x1DC;
-        break;
-    }
-  }
-  else if (confMode && _longPushButton == 2) //Enusre there is an exit for confMode incase menu is buggy
-  {
-    confMode = false;
-    acAmpOn = true;
-    acAmpRxChanged = true;
-    acAmpMessageToProcess = true;
-    menuValue = 0;
-    menuStartValue = false;
-  }
-}
-
-
-
-void acAmpSend() //Send hardware changes to the AC Amplifier
-{
-  for (byte acAmpCycle = 0; acAmpCycle < 5; acAmpCycle ++)\
-  {
-    Serial2.write9bit(acAmpDataOut[acAmpCycle]);
-  }
-  acAmpTxBetweenTime = millis();
-}
-
-
-/*****************************************************************
-  // Menu
-*****************************************************************/
-
-void confMenu()
-{
-  menuIndexMin = 1; // Make sure we start at menu position 1.
-  menuIndexMax = 3;
-  inMenu = false;
-
-  if (longPushButton == 8) // Roll back the menu
-  {
-    confMode = false;
-    acAmpOn = true;
-    acAmpRxChanged = true;
-    acAmpMessageToProcess = true;
-    menuStartValue = false;
-    menuIndex = 1;
-  }
-
-  switch (menuIndex) // Also set subMenu and index options
-  {
-    case 1 : populateFixedLcdDisplay("Temp C or F"); if (shortPushButton == 1) acAmpCentigrade = (!acAmpCentigrade) ? true : false; iconArray[0][6] = (acAmpCentigrade) ? iconArray[0][6] += 0x10 : iconArray[0][6] += 0x08;
-      break;
-    case 2 : populateFixedLcdDisplay("24/12 Hour"); if (clock24Hour) {
-        sevenSegmentCalculate(0x01, 2);
-        sevenSegmentCalculate(0x04, 4);
-      } else {
-        sevenSegmentCalculate(0x01, 1);
-        sevenSegmentCalculate(0x04, 2);
-      } if (shortPushButton == 1) clock24Hour = (!clock24Hour) ? true : false;
-      break;
-    case 3 : menuIndexMax = 3; updateClockTime();
-      break;
-  }
-
-  longPushButton = 0;
-  shortPushButton = 0;
-}
-
-
-/*****************************************************************
-  // LCD Display
-*****************************************************************/
-
-void populateFixedLcdDisplay(String _lcdInput)
-{
-  _lcdInput.remove(12);
-
-  if (_lcdInput.length() < 12)
-  {
-    for (byte i = _lcdInput.length() + 1; i <= 12; i++)
-    {
-      _lcdInput.concat(' ');
-    }
-  }
-
-  byte _start = 0x80;
-
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x80);
-  PORTB |= (1 << PB0);
-
-  for (byte i = 0; i < _lcdInput.length(); i++)
-  {
-    PORTL |= (1 << PL0);
-    PORTB &= ~(1 << PB0);
-    SPI.transfer(_lcdInput.charAt(i));
-    PORTB |= (1 << PB0);
-    delayMicroseconds(42);
-    PORTL &= ~(1 << PL0);
-  }
-}
-
-
-
-void lcdDisplaySetIconDisplay(byte _iconAddress, byte _iconValue)
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(_iconAddress);
-  PORTB |= (1 << PB0);
-  PORTL |= (1 << PL0);
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(_iconValue);
-  PORTB |= (1 << PB0);
-  delayMicroseconds(42);
-  PORTL &= ~(1 << PL0);
-}
-
-
-
-void lcdDisplayPopulateCgramAddress(byte _CgramAddress) // Set the CGRam Address
-{
-  PORTL |= (1 << PL1);
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(_CgramAddress);
-  PORTB |= (1 << PB0);
-  PORTL &= ~(1 << PL1);
-  unsigned long time01 = millis();
-  for (byte i = 0; i < 7; i++) //populate from the Array
-  {
-    PORTL |= (1 << PL0);
-    PORTB &= ~(1 << PB0);
-    SPI.transfer(sevenSegmentArray[0][i]);
-    PORTB |= (1 << PB0);
-    delayMicroseconds(42);
-    PORTL &= ~(1 << PL0);
-    sevenSegmentArray[0][i] = 0;
-  }
-  lcdDisplayCgramToDdram(0x00, 0x8C);   // Populate into DDRam address
-  lcdDisplayCgramToDdram(0x00, 0x8D);   // Populate into DDRam address
-}
-
-
-
-void  lcdDisplayCgramToDdram(byte _CgramSource, byte _DdramDestination) // Copies a CGRam char into the DDram field
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(_DdramDestination);
-  PORTB |= (1 << PB0);
-  PORTL |= (1 << PL0);
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(_CgramSource);
-  PORTB |= (1 << PB0);
-  delayMicroseconds(42);
-  PORTL &= ~(1 << PL0);
-}
-
-
-
-void lcdDisplayStartUp()
-{
-
-  PORTL &= ~(1 << PL1);
-  PORTL &= ~(1 << PL0);
-
-  //display off
-  PORTL |= (1 << PL0);
-  SPI.transfer(0x08);
-  PORTL &= ~(1 << PL0);
-  PORTB |= (1 << PB0);
-
-  clearLcdDisplay();
-  returnHomeLcdDisplay();
-  flashingCursorLcdDisplay();
-  setStaticPortLcdDisplay();
-  entryModeIncrementLcdDisplay();
-  setContrastLcdDisplay();
-  IncrementLcdDisplay();
-  resetIconDisplay();
-  resetLcdDisplay();
-}
-
-
-
-void clearLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x1);
-  PORTB |= (1 << PB0);
-}
-
-
-
-void returnHomeLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x02);
-  PORTB |= (1 << PB0);
-}
-
-
-
-void flashingCursorLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x0C);
-  PORTB |= (1 << PB0);
-}
-
-
-
-void setStaticPortLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x00);
-  PORTB |= (1 << PB0);
-}
-
-
-
-void setContrastLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x46);
-  PORTB |= (1 << PB0);
-}
-
-
-
-void entryModeIncrementLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x06);
-  PORTB |= (1 << PB0);
-}
-
-
-
-void IncrementLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x14);
-  PORTB |= (1 << PB0);
-}
-
-
-
-void resetIconDisplay()
-{
-  for (byte i = 0x90; i < 0x9F; i++)
-  {
-    PORTB &= ~(1 << PB0);
-    SPI.transfer(i);
-    PORTB |= (1 << PB0);
-    PORTL |= (1 << PL0);
-    PORTB &= ~(1 << PB0);
-    SPI.transfer(0x00);
-    PORTB |= (1 << PB0);
-    delayMicroseconds(42);
-    PORTL &= ~(1 << PL0);
-  }
-}
-
-
-
-void resetLcdDisplay()
-{
-  PORTB &= ~(1 << PB0);
-  SPI.transfer(0x80);
-  PORTB |= (1 << PB0);
-
-  for (byte i = 0; i < 12; i++)
-  {
-    PORTL |= (1 << PL0);
-    PORTB &= ~(1 << PB0);
-    SPI.transfer(0x20);
-    PORTB |= (1 << PB0);
-    delayMicroseconds(42);
-    PORTL &= ~(1 << PL0);
-  }
-}
-
-
-
-
-


Make brightness on pulse configurable

Make brightness on pulse configurable

--- heartbeat_with_pulse.ino
+++ heartbeat_with_pulse.ino
@@ -41,8 +41,8 @@
 int movesPerBeat = 4;
 int minMagnitude = 0;
 int maxMagnitude = 50; // max difference between two magnitude measurements from accelerometer at which we show maxHue
-int minBrightness = 150; // from 0-255
-int maxBrightness = 200; // from 0-255
+int minBrightnessDivisor= 150; // lower = brighter
+int maxBrightnessDivisor = 300; // higher = dimmer
 int minHue = 160; // hue value under low motion, as defined through minMagnitude (from 0-255)
 int maxHue = 255; // hue value under high motion, as defined through maxMagnitude (from 0-255)
 int gainRatePerBeat = 6; // change towards new target magnitude
@@ -141,8 +141,8 @@
     adjustedMagnitude,
     minMagnitude,
     maxMagnitude,
-    400,
-    200
+    maxBrightnessDivisor,
+    minBrightnessDivisor
   );

   // Channel 1
@@ -360,8 +360,15 @@

   // Activate effect based on mode
   if(mode == 1) {
+    // Bright pulse meter
+    minBrightnessDivisor = 150;
+    maxBrightnessDivisor = 300;
     loopHeartRate();
   } else if (mode == 2) {
+    // Less bright pulse meter
+    minBrightnessDivisor = 200;
+    maxBrightnessDivisor = 400;
+    loopHeartRate();
   } else if (mode == 3) {
     FastLED.setBrightness(BRIGHTNESS);
     confetti(0, NUM_LEDS_CH1);


Ya no hay que desconectar el cable a mano

--- ARDUINO/proto_ver_1.0_final/protot_v1.0/protot_v1.0.ino
+++ ARDUINO/proto_ver_1.0_final/protot_v1.0/protot_v1.0.ino
@@ -26,10 +26,11 @@
  // LED PINS
  #define ledSTUP 13              // SETUP LED PIN
  #define ledREAD 12              // READ SENSORS LED PIN
- #define ledTX   11              //TRANSMISION LED PIN
+ #define ledTX   11              // TRANSMISION LED PIN

  // BLUETOOTH
- #define BT_tx 9                 //BLUETOOTH SOFTWARE COM PINOUT
+ #define pow 7                   // BLUETOOTH POWER SUPPLY PIN
+ #define BT_tx 9                 // BLUETOOTH SOFTWARE COM PINOUT
  #define BT_rx 10
  #define DevNo 0001              // DEFINE THE DEVICE NUMBER
  #define BLUETOOTH_SPEED 57600   // BLUETOOTH DEVICE BAUDRATE
@@ -285,6 +286,9 @@
  //*****************************************************************************
  void BTconn()
  {
+
+  pinMode(pow,OUTPUT);
+  digitalWrite(pow,HIGH);
   while(1)                  // WILL LAST FOREVER
   {
     while(BT.available())     // IF THERE'S SERIAL DATA TO READ


Set Pixy pinConfig and fix pixyMaxBlocks bug

Also removed spaces before semicolons.

--- examples/RoseBot/RoseBotFirmata/RoseBotFirmata.ino
+++ examples/RoseBot/RoseBotFirmata/RoseBotFirmata.ino
@@ -124,7 +124,7 @@

 /* Rotary Encoder Support */
 byte  encoderMSBLeft, encoderLSBLeft,  encoderMSBRight, encoderLSBRight;     // sysex data registers
-uint8_t encoderPin1, encoderPin2 ; // user specified encoder pins
+uint8_t encoderPin1, encoderPin2; // user specified encoder pins
 boolean encoderIsReporting = false;   // flag indicating if the encoders are counting and reporting.

 volatile uint16_t interruptCountLeft = 0; // The count will go back to 0 after hitting 65535.
@@ -145,24 +145,24 @@
 byte pixyMaxBlocks = 5;  // Sets the maximum number of Pixy blocks to report.

 // Ping variables
-int numLoops = 0 ;
-int pingLoopCounter = 0 ;
-
-
-int numActiveSonars = 0 ; // number of sonars attached
-uint8_t sonarPinNumbers[MAX_SONARS] ;
-int nextSonar = 0 ; // index into sonars[] for next device
+int numLoops = 0;
+int pingLoopCounter = 0;
+
+
+int numActiveSonars = 0; // number of sonars attached
+uint8_t sonarPinNumbers[MAX_SONARS];
+int nextSonar = 0; // index into sonars[] for next device

 // array to hold up to 6 instances of sonar devices
-NewPing *sonars[MAX_SONARS] ;
+NewPing *sonars[MAX_SONARS];

 uint8_t sonarTriggerPin;
-uint8_t sonarEchoPin ;
+uint8_t sonarEchoPin;
 uint8_t currentSonar = 0;            // Keeps track of which sensor is active.

-uint8_t pingInterval = 33 ;  // Milliseconds between sensor pings (29ms is about the min to avoid
+uint8_t pingInterval = 33;  // Milliseconds between sensor pings (29ms is about the min to avoid
 // cross- sensor echo).
-byte sonarMSB, sonarLSB ;
+byte sonarMSB, sonarLSB;

 // Stepper Motor
 Stepper *stepper = NULL;
@@ -390,14 +390,14 @@
       }
       break;
     /*
-        case ENCODER:
+        case;:
           // enable the pullups for an encoder pin
           pinMode(pin, INPUT);
           digitalWrite(pin, HIGH);

           // used as part of encoder sysex message
-          pinConfig[pin] = ENCODER ;
-          break ;
+          pinConfig[pin] = ENCODER;
+          break;
     */
     case I2C:
       if (IS_PIN_I2C(pin)) {
@@ -407,17 +407,20 @@
       }
       break;
     case TONE:
-      pinConfig[pin] = TONE ;
-      break ;
+      pinConfig[pin] = TONE;
+      break;
     case SONAR:
-      pinConfig[pin] = SONAR ;
-      break ;
+      pinConfig[pin] = SONAR;
+      break;
     case STEPPER:
-      pinConfig[pin] = STEPPER ;
-      break ;
+      pinConfig[pin] = STEPPER;
+      break;
+    case PIXY:
+      pinConfig[pin] = PIXY;
+      break;
     default:
       Firmata.sendString("Unknown pin mode"); // TODO: put error msgs in EEPROM
-      break ;
+      break;
   }
   // TODO: save status to EEPROM here, if changed
 }
@@ -519,9 +522,9 @@
   byte data;
   int slaveRegister;
   unsigned int delayTime;
-  byte pin ;// used for tone
-  int frequency ;
-  int duration ;
+  byte pin;// used for tone
+  int frequency;
+  int duration;

   switch (command) {
     case I2C_REQUEST:
@@ -661,8 +664,8 @@
           samplingInterval = MINIMUM_SAMPLING_INTERVAL;
         }
         /* calculate number of loops per ping */
-        numLoops = INTER_PING_INTERVAL / samplingInterval ;
-        //numLoops = 1 ;
+        numLoops = INTER_PING_INTERVAL / samplingInterval;
+        //numLoops = 1;
       }
       else {
         //Firmata.sendString("Not enough data");
@@ -733,8 +736,8 @@
       // instantiate an encoder object with user's
       // requested pin designators

-      encoderPin1 = argv[0] ;
-      encoderPin2 = argv[1] ;
+      encoderPin1 = argv[0];
+      encoderPin2 = argv[1];

       pinMode(encoderPin1, INPUT);
       digitalWrite(encoderPin1, HIGH);
@@ -743,18 +746,19 @@
       digitalWrite(encoderPin2, HIGH);
       // used as part of encoder sysex message

-      pinConfig[encoderPin1] = ENCODER ;
-      pinConfig[encoderPin2] = ENCODER ;
-
-      encoderIsReporting = true ;
+      pinConfig[encoderPin1] = ENCODER;
+      pinConfig[encoderPin2] = ENCODER;
+
+      encoderIsReporting = true;
       enableInterrupt(encoderPin1, interruptFunctionLeft, RISING);
       enableInterrupt(encoderPin2, interruptFunctionRight, RISING);
-      break ;
+      break;
     case PIXY_CONFIG:
       if (argv[0] == PIXY_INIT) {
         pixy.init();
+        pinConfig[encoderPin1] = PIXY;
         pixyIsReporting = true;
-        pixyMaxBlocks = argv[0];
+        pixyMaxBlocks = argv[1];
         if (pixyMaxBlocks == 0) {
           pixyIsReporting = false;
         }
@@ -788,7 +792,7 @@
       else if (toneCommand == TONE_NO_TONE) {
         noTone(pin);
       }
-      break ;
+      break;

     // arg0 = trigger pin
     // arg1 = echo pin
@@ -796,68 +800,68 @@
     // arg3 = maxdistance lsb
     // arg4 = maxdistance msb
     case SONAR_CONFIG :
-      int max_distance ;
+      int max_distance;
       if ( numActiveSonars < MAX_SONARS)
       {
-        sonarTriggerPin = argv[0] ;
-        sonarEchoPin = argv[1] ;
+        sonarTriggerPin = argv[0];
+        sonarEchoPin = argv[1];
         // set interval to a minium of 33 ms.
         if ( argv[2] >= 33 ) {
-          pingInterval = argv[2] ;
+          pingInterval = argv[2];
         }
         else {
-          pingInterval = 33 ;
-        }
-        max_distance = argv[3] + (argv[4] << 7 ) ;
-        sonarPinNumbers[numActiveSonars] = sonarTriggerPin ;
+          pingInterval = 33;
+        }
+        max_distance = argv[3] + (argv[4] << 7 );
+        sonarPinNumbers[numActiveSonars] = sonarTriggerPin;

         setPinModeCallback(sonarTriggerPin, SONAR);
         setPinModeCallback(sonarEchoPin, SONAR);
-        sonars[numActiveSonars] = new NewPing(sonarTriggerPin, sonarEchoPin, max_distance) ;
-        numActiveSonars++ ;
+        sonars[numActiveSonars] = new NewPing(sonarTriggerPin, sonarEchoPin, max_distance);
+        numActiveSonars++;
       }
       else {
         Firmata.sendString("PING_CONFIG Error: Exceeded number of supported ping devices");
       }
-      break ;
+      break;

     case STEPPER_DATA:
       // determine if this a STEPPER_CONFIGURE command or STEPPER_OPERATE command
       if (argv[0] == STEPPER_CONFIGURE)
       {
         int numSteps = argv[1] + (argv[2] << 7);
-        int pin1 = argv[3] ;
-        int pin2 = argv[4] ;
+        int pin1 = argv[3];
+        int pin2 = argv[4];
         if ( argc == 5 )
         {
           // two pin motor
-          stepper = new Stepper(numSteps, pin1, pin2) ;
+          stepper = new Stepper(numSteps, pin1, pin2);
         }
         else if (argc == 7 ) // 4 wire motor
         {
-          int pin3 = argv[5] ;
-          int pin4 = argv[6] ;
-          stepper =  new Stepper(numSteps, pin1, pin2, pin3, pin4) ;
+          int pin3 = argv[5];
+          int pin4 = argv[6];
+          stepper =  new Stepper(numSteps, pin1, pin2, pin3, pin4);
         }
         else
         {
           Firmata.sendString("STEPPER CONFIG Error: Wrong Number of arguments");
-          printData("argc = ", argc) ;
+          printData("argc = ", argc);
         }
       }
       else if ( argv[0] == STEPPER_STEP )
       {
         long speed = (long)argv[1] | ((long)argv[2] << 7) | ((long)argv[3] << 14);
         int numSteps = argv[4] + (argv[5] << 7);
-        int direction = argv[6] ;
+        int direction = argv[6];
         if (stepper != NULL )
         {
-          stepper->setSpeed(speed) ;
+          stepper->setSpeed(speed);
           if (direction == 0 )
           {
-            numSteps *= -1 ;
+            numSteps *= -1;
           }
-          stepper->step(numSteps) ;
+          stepper->step(numSteps);
         }
         else
         {
@@ -868,7 +872,7 @@
       {
         if ( stepper != NULL )
         {
-          int version = stepper->version() ;
+          int version = stepper->version();
           Firmata.write(START_SYSEX);
           Firmata.write(STEPPER_DATA);
           Firmata.write(version & 0x7F);
@@ -880,13 +884,13 @@
           // did not find a configured stepper
           Firmata.sendString("STEPPER FIRMWARE VERSION Error: NO MOTORS CONFIGURED");
         }
-        break ;
+        break;
       }
       else
       {
         Firmata.sendString("STEPPER CONFIG Error: UNKNOWN STEPPER COMMAND");
       }
-      break ;
+      break;
   }
 }

@@ -945,7 +949,7 @@
       setPinModeCallback(i, ANALOG);
     }
     else if ( IS_PIN_TONE(i)) {
-      noTone(i) ;
+      noTone(i);
     }
     else {
       // sets the output to 0, configures portConfigInputs
@@ -955,20 +959,20 @@
     servoPinMap[i] = 255;
   }
   // stop pinging
-  numActiveSonars = 0 ;
+  numActiveSonars = 0;
   for (int i = 0; i < MAX_SONARS; i++) {
-    sonarPinNumbers[i] = IGNORE ;
+    sonarPinNumbers[i] = IGNORE;
     if ( sonars[i] ) {
-      sonars[i] = NULL ;
-    }
-  }
-  numActiveSonars = 0 ;
+      sonars[i] = NULL;
+    }
+  }
+  numActiveSonars = 0;

   // by default, do not report any analog inputs
   analogInputsToReport = 0;

   // clear stepper pointer
-  stepper = NULL ;
+  stepper = NULL;

   detachedServoCount = 0;
   servoCount = 0;
@@ -989,7 +993,7 @@
   else {
      wdt_enable(WDTO_15MS);
      while(1)
-        ;
+       ;
   }
 }

@@ -1005,18 +1009,18 @@
   Firmata.attach(START_SYSEX, sysexCallback);
   Firmata.attach(SYSTEM_RESET, systemResetCallback);

-  numActiveSonars = 0 ;
-  pingLoopCounter = 0 ;
+  numActiveSonars = 0;
+  pingLoopCounter = 0;
   for (uint8_t i = 1; i < MAX_SONARS; i++) // Set the starting time for each sensor.
   {
-    sonarPinNumbers[i] = IGNORE ;
+    sonarPinNumbers[i] = IGNORE;
     if ( sonars[i] ) {
-      sonars[i] = NULL ;
+      sonars[i] = NULL;
     }
   }

   /* calculate number of loops per ping */
-  numLoops = INTER_PING_INTERVAL / samplingInterval ;
+  numLoops = INTER_PING_INTERVAL / samplingInterval;

   Firmata.begin(57600);
   systemResetCallback();  // reset to default config
@@ -1048,25 +1052,25 @@

     if ( pingLoopCounter++ > numLoops)
     {
-      pingLoopCounter = 0 ;
+      pingLoopCounter = 0;
       if (numActiveSonars)
       {
         unsigned int uS = sonars[nextSonar]->ping();
         // Convert ping time to distance in cm and print
-        pingResult = uS / US_ROUNDTRIP_CM ;
-        currentSonar = nextSonar ;
+        pingResult = uS / US_ROUNDTRIP_CM;
+        currentSonar = nextSonar;
         if ( nextSonar++ >= numActiveSonars - 1)
         {
-          nextSonar = 0 ;
-        }
-        sonarLSB = pingResult & 0x7f ;
-        sonarMSB = pingResult >> 7 & 0x7f ;
+          nextSonar = 0;
+        }
+        sonarLSB = pingResult & 0x7f;
+        sonarMSB = pingResult >> 7 & 0x7f;

         Firmata.write(START_SYSEX);
-        Firmata.write(SONAR_DATA) ;
-        Firmata.write(sonarPinNumbers[currentSonar]) ;
-        Firmata.write(sonarLSB) ;
-        Firmata.write(sonarMSB) ;
+        Firmata.write(SONAR_DATA);
+        Firmata.write(sonarPinNumbers[currentSonar]);
+        Firmata.write(sonarLSB);
+        Firmata.write(sonarMSB);
         Firmata.write(END_SYSEX);
       }
     }
@@ -1158,10 +1162,10 @@

 void printData(char * id,  long data)
 {
-  char myArray[64] ;
+  char myArray[64];

   String myString = String(data);
-  myString.toCharArray(myArray, 64) ;
-  Firmata.sendString(id) ;
+  myString.toCharArray(myArray, 64);
+  Firmata.sendString(id);
   Firmata.sendString(myArray);
 }


fix typo: lenght -> length

fix typo: lenght -> length

--- examples/WebSocketClientSSL/WebSocketClientSSL.ino
+++ examples/WebSocketClientSSL/WebSocketClientSSL.ino
@@ -22,7 +22,7 @@

 #define USE_SERIAL Serial1

-void webSocketEvent(WStype_t type, uint8_t * payload, size_t lenght) {
+void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {

     switch(type) {
@@ -44,11 +44,11 @@
 			// webSocket.sendTXT("message here");
             break;
         case WStype_BIN:
-            USE_SERIAL.printf("[WSc] get binary lenght: %u\n", lenght);
-            hexdump(payload, lenght);
+            USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
+            hexdump(payload, length);

             // send data to server
-            // webSocket.sendBIN(payload, lenght);
+            // webSocket.sendBIN(payload, length);
             break;
     }


Add option to take distance instead of depth

--- ARTF_Sensors/examples/BridgeSensorGSM/BridgeSensorGSM.ino
+++ ARTF_Sensors/examples/BridgeSensorGSM/BridgeSensorGSM.ino
@@ -40,8 +40,8 @@

 // Settings
 // -------------------------------
-#define SENSOR_TO_RIVER_BED        2000
 #define SENSOR_TYPE                "d"
+#define SENSOR_TO_RIVER_BED        0
 #define SEND_DATA_AFTER_X_READINGS 10
 #define SLEEP_CYCLES               4
 #define NUM_THERM_READINGS         5
@@ -168,7 +168,11 @@

   // 11. Use average temperature to calculate actual distance.
   // ---------------------------------------------------------
-  double adjustedDistance = SENSOR_TO_RIVER_BED - ( ( 331.1 + .6 * avgTemperature ) / 344.5 ) * avgDistance;
+  double adjustedDistance = ( ( 331.1 + .6 * avgTemperature ) / 344.5 ) * avgDistance;
+  if (SENSOR_TO_RIVER_BED > 0)
+  {
+    adjustedDistance = SENSOR_TO_RIVER_BED - adjustedDistance;
+  }

   int roundedDistance = round(adjustedDistance);
   int roundedTemperature = round(avgTemperature);


swtiched order of update gps and sensors read

--- exhaust_sensor_array.ino
+++ exhaust_sensor_array.ino
@@ -63,15 +63,16 @@
 }

 void loop() {
+
   delay(5000);

   log_file = SD.open("log.csv", FILE_WRITE);

+  // update GPS
+  while(gps_port.available()) gps.encode(gps_port.read());
+
   //read from sensors
   for(unsigned int i=0; i < 6; ++i) sensor_array[i] = analogRead(i);

-  // update GPS
-  while(gps_port.available()) gps.encode(gps_port.read());
-
   print();
 }


v1.2 Added analog measurement of rain signal

--- EM27cover.ino
+++ EM27cover.ino
@@ -101,6 +101,10 @@
 // Rain
 #define DPIN_RAIN 12
 // input from rain sensor (digital)
+#define APIN_RAIN 0
+// input for analog rain sensor (analog)
+#define MILLIVOLTS_PER_COUNT 4.8828
+// Conversion factor to get millivolts per DIO count

 // Global variables

@@ -109,7 +113,7 @@
 int requeststate = STATE_CLOSED;
 int last_state = STATE_UNKNOWN;
 int fault, condition;   // global
-float duration;
+float duration, rain_mv;

 AccelStepper stepper(AccelStepper::DRIVER, DPIN_STEP, DPIN_DIR);  // sets up 2-wire stepper driver

@@ -117,7 +121,7 @@
 void setup() {
   // Start serial for input / output
   Serial.begin(9600);
-  Serial.println("EM27Sun Cover Driver v1.1");
+  Serial.println("EM27Sun Cover Driver v1.2");
   // Set up for the Stepper motor
   stepper.setPinsInverted(true,false,true); // sets direction and enable pins inverted
   stepper.setMaxSpeed(USTEP_DIVISOR * STEP_SPEED);
@@ -165,6 +169,7 @@
   state = determine_state();  // open/closed
   condition = determine_cond(); // rain or not
   fault = determine_fault(); // check for motor fault
+  rain_mv = MILLIVOLTS_PER_COUNT * float(analogRead(APIN_RAIN));
   // print if there is a state change
   if (state != last_state) {
     if (state==STATE_OPENED) {
@@ -277,7 +282,9 @@
   if (condition == COND_RAIN){
     Serial.print("condition = rain ");
   }
-  Serial.println("");
+  Serial.print("Analog Rain Signal = ");
+  Serial.print(int(rain_mv));
+  Serial.println("mV");
 }

 int determine_state() {


mudado portas de saídas e corrigido travamento de PWM, fixes # 15

--- 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 geral = 23; // Saída Geral
-    const byte dosador = 25; // Saída do Dosador
-    const byte datador = 27; // Saída do Datador
+    const byte geral = 40; // Saída Geral
+    const byte dosador = 42; // Saída do Dosador
+    const byte datador = 44; // 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
@@ -97,11 +97,17 @@
   digitalWrite(solda_vertical, DESLIGA);
   digitalWrite(solda_horizontal, DESLIGA);
   digitalWrite(solda_datador, DESLIGA);
+  digitalWrite(53, DESLIGA); // Temporário, ver e apagar
 }

 void loop() {
   modoAlarme();
+
+  geraPWM(pot_solda_vertical, &tempo_PWM_vertical, solda_vertical, NomeSoldaVertical);
+  geraPWM(pot_solda_horizontal, &tempo_PWM_horizontal, solda_horizontal, NomeSoldaHorizontal);
+  geraPWM(pot_solda_datador, &tempo_PWM_datador, solda_datador, NomeSoldaDatador);
+
   if (!alarme_ativo){
     standBy();
     modoTeste();
@@ -111,12 +117,16 @@
 void geraPWM(byte pot, unsigned long *inicio, byte saida, String nome){
   unsigned long ativo = map(analogRead(pot), 0, 1023, 0, ciclo_PWM);
   unsigned long inativo = ciclo_PWM - ativo;
-  if (millis() > *inicio && millis() <= (*inicio + ativo)){
-    liga(saida, nome);
-  } else if (millis() > (*inicio + ativo) && millis() < (*inicio + ciclo_PWM)){
+  if (maquina_ligada and !alarme_ativo){
+    if (millis() > *inicio && millis() <= (*inicio + ativo)){
+      liga(saida, nome);
+    } else if (millis() > (*inicio + ativo) && millis() < (*inicio + ciclo_PWM)){
+      desliga(saida, nome);
+    } else if (millis() >= (*inicio + ciclo_PWM)) {
+      *inicio = millis();
+    }
+  } else {
     desliga(saida, nome);
-  } else if (millis() >= (*inicio + ciclo_PWM)) {
-    *inicio = millis();
   }
 }

@@ -151,9 +161,7 @@
 }

 void iniciaTrabalho(){
-  geraPWM(pot_solda_vertical, &tempo_PWM_vertical, solda_vertical, NomeSoldaVertical);
-  geraPWM(pot_solda_horizontal, &tempo_PWM_horizontal, solda_horizontal, NomeSoldaHorizontal);
-  geraPWM(pot_solda_datador, &tempo_PWM_datador, solda_datador, NomeSoldaDatador);
+
 }

 void modoAlarme(){


ciclo dinâmico funcional, falta corrigir reset, fixes #16 e #17

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -75,14 +75,14 @@
 bool reset_falso = FALSO;
 unsigned long conta_ciclos = 0;
 boolean produzindo = FALSO;
-boolean reset_liberado = VERDADEIRO;
+boolean reset_liberado = FALSO;
 boolean sensor_resetou = FALSO;
 // Tempos do Ciclo
 // Ciclo
 unsigned long ciclo_padrao = 1500;
 unsigned long ciclo_minimo = 900;
 unsigned long ciclo_maximo = 2000;
-unsigned long primeiro_ciclo = 0;
+unsigned long soma_ciclos = 0;
 // Mandibula
 unsigned long inicio_mandibula = 550;
 unsigned long fim_mandibula = 1500;
@@ -174,6 +174,7 @@
 void iniciaTrabalho() {
   if (!produzindo) {
     produzindo = VERDADEIRO;
+    reiniciaCiclo();
   }
   if (conta_ciclos >= 3) {
     ligaFuncao(led_teste_1, "Led Teste 1");  // Exemplo para teste.
@@ -222,75 +223,29 @@
 }

 void funcaoReset() {
-  if (produzindo){
-    unsigned long tempo_atual = millis();
-    if (primeiro_ciclo == 0) {
-      primeiro_ciclo = tempo_atual;
-      reiniciaCiclo();
-    }
-    unsigned long fim_ciclo = inicio_ciclo + ciclo_padrao;
-    // unsigned long novo_ciclo = tempo_atual - inicio_ciclo;
-    unsigned long minimo = inicio_ciclo + ciclo_minimo;
-    unsigned long maximo = inicio_ciclo + ciclo_maximo;
-    sensorReset();
-    if (sensor_resetou || tempo_atual >= maximo) {
-      conta_ciclos++;
-      escreveSerial((String)conta_ciclos + ": " +
-                      (String)(tempo_atual - inicio_ciclo) + " / R:" +
-                      (String)ciclo_padrao);
-      if (tempo_atual >= maximo){
-        ciclo_padrao = ciclo_maximo;
-      } else {
-        ciclo_padrao = ((tempo_atual - primeiro_ciclo) / (unsigned long)conta_ciclos);
-      }
-      reiniciaCiclo();
-    }
-    if (tempo_atual <= minimo){
-      reset_liberado = FALSO;
-    } else {
-      reset_liberado = VERDADEIRO;
-    }
-  }
-
-  // unsigned long tempo_atual = millis();
-
-  // if (!ciclo_resetado) {
-  //   unsigned long fim_ciclo = inicio_ciclo + ciclo_padrao;
-  //   unsigned long novo_ciclo = tempo_atual - inicio_ciclo;
-  //   unsigned long minimo = inicio_ciclo + ciclo_minimo;
-  //   unsigned long maximo = inicio_ciclo + ciclo_maximo;
-  //   if ((tempo_atual >= maximo) || (ativo(sensor_reset))) {
-  //     if (minimo < novo_ciclo < maximo) {  //  || (tempo_atual >= maximo)
-  //       conta_ciclos++;
-  //       ciclo_resetado = VERDADEIRO;
-  //       escreveSerial((String)conta_ciclos + ": " +
-  //                     (String)(tempo_atual - inicio_ciclo) + " / R:" +
-  //                     (String)tempo_atual + "-" + (String)primeiro_ciclo + "/" +
-  //                     (String)conta_ciclos + "=" + (String)ciclo_padrao);
-  //       reiniciaCiclo();
-  //       ciclo_padrao =
-  //           ((tempo_atual - primeiro_ciclo) / (unsigned long)conta_ciclos);
-  //     } else if (novo_ciclo >= maximo) {
-  //       escreveSerial("Erro, reset maior que o maximo: " + (String)novo_ciclo +
-  //                     " / R:" + (String)maximo);
-  //       // reset_falso = VERDADEIRO;
-  //     }
-  //     // } else if (novo_ciclo <= minimo) {
-  //     //   escreveSerial("Erro, reset menor que o minimo: " + (String)
-  //     // novo_ciclo + " / R:" + (String) minimo);
-  //     //   reset_falso = VERDADEIRO;
-  //     // }
-  //   }
-  // } else {
-  //   if ((tempo_atual - inicio_ciclo) > ciclo_minimo) {
-  //     escreveSerial("Erro, reset menor que o minimo.");
-  //     ciclo_resetado = FALSO;
-  //   }
-  // }
+  unsigned long tempo_atual = millis();
+  unsigned long fim_ciclo = inicio_ciclo + ciclo_padrao;
+  unsigned long minimo = inicio_ciclo + ciclo_minimo;
+  unsigned long maximo = inicio_ciclo + ciclo_maximo;
+  sensorReset();
+  if (sensor_resetou || tempo_atual >= maximo) {
+    conta_ciclos++;
+    escreveSerial((String)conta_ciclos + ": " +
+                    (String)(tempo_atual - inicio_ciclo) + " / R:" +
+                    (String)ciclo_padrao);
+    soma_ciclos += tempo_atual - inicio_ciclo;
+    reiniciaCiclo();
+  }
+  if (tempo_atual < minimo && reset_liberado){
+    reset_liberado = FALSO;
+  } else if (tempo_atual > minimo && !reset_liberado){
+    reset_liberado = VERDADEIRO;
+  }
 }

 void reiniciaCiclo() {
   inicio_ciclo = millis();
+  cicloMedio();
   ciclo_resetado = VERDADEIRO;
   sensor_resetou = FALSO;
   fotocelula_liberada = FALSO;
@@ -300,6 +255,12 @@
 void sensorReset(){
   if (ativo(sensor_reset) && reset_liberado){
     sensor_resetou = VERDADEIRO;
+  }
+}
+
+void cicloMedio(){
+  if (conta_ciclos > 0){
+    ciclo_padrao = soma_ciclos / conta_ciclos;
   }
 }


implementado funcionamento do datador, com liberação

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -227,7 +227,7 @@
     funcaoSimples(mandibula, NomeMandibula, ti_mandibula, tf_mandibula);
     funcaoSegura(faca, NomeFaca, ti_faca, tf_faca, sensor_mandibula);
     funcaoSimples(refrigeracao, NomeRefrigeracao, ti_refrigeracao, tf_refrigeracao);
-    funcaoSimples(datador, NomeDatador, ti_datador, tf_datador);
+    funcaoComLiberacao(datador, NomeDatador, ti_datador, tf_datador, datador_ligado);
     funcaoSimples(soldas, NomeSoldas, ti_soldas, tf_soldas);
   }
   funcaoReset();
@@ -371,6 +371,18 @@
   }
 }

+void funcaoComLiberacao(const byte saida, String nome, unsigned long inicio, unsigned long fim, byte liberacao){
+  inicio += inicio_ciclo;
+  fim += inicio_ciclo;
+  if (desligado(saida) && liberacao){
+    if (tempo_atual >= inicio && tempo_atual < fim) {
+      ligaFuncao(saida, nome);
+    }
+  } else if (tempo_atual >= fim) {
+    desligaFuncao(saida, nome);
+  }
+}
+
 void liberaFotocelula() {
   unsigned long inicio = ti_fotocelula + inicio_ciclo;
   unsigned long fim = tf_fotocelula + inicio_ciclo;
@@ -402,7 +414,7 @@
   if (desligado(saida)) {
     liga(saida);
     if (ligado(saida)){
-      escreveSerial(">> " + nome + " Ligado." + (String)ti_mandibula);
+      escreveSerial(">> " + nome + " Ligado.");
     } else {
       escreveSerial("Ocorreu um erro ao ligar " + nome);
     }
@@ -414,7 +426,7 @@
 void desligaFuncao(byte saida, String nome) {
   if (ligado(saida)) {
     desliga(saida);
-    escreveSerial("<< " + nome + " Desligado." + (String)tf_mandibula);
+    escreveSerial("<< " + nome + " Desligado.");
   }
 }


change power for relay(5v)

change power for relay(5v)

--- _02-mqtt-sw-temperature/_02-mqtt-sw-temperature.ino
+++ _02-mqtt-sw-temperature/_02-mqtt-sw-temperature.ino
@@ -35,7 +35,7 @@
 #define TEMPERATURE_PRECISION 12
 OneWire oneWire(ONE_WIRE_BUS);
 DallasTemperature sensors(&oneWire);
-DeviceAddress insideThermometer, outsideThermometer;
+DeviceAddress outsideThermometer;

 // mqtt
 char* topic = "esp8266/arduino/s02";
@@ -62,7 +62,6 @@
 int ResetInfo = LOW;

 //
-float tempCinside ;
 float tempCoutside ;

 float h ;
@@ -188,7 +187,7 @@
 void setup()
 {
   if (DEBUG_PRINT) {
-    Serial.begin(74880);
+    Serial.begin(115200);
   }
   delay(20);
   if (DEBUG_PRINT) {
@@ -270,19 +269,13 @@
   attachInterrupt(5, run_lightcmd, CHANGE);

   sensors.begin();
-  if (!sensors.getAddress(insideThermometer, 0)) {
+  if (!sensors.getAddress(outsideThermometer, 0)) {
     if (DEBUG_PRINT) {
       Serial.println("Unable to find address for Device 0");
     }
   }
-  if (!sensors.getAddress(outsideThermometer, 1)) {
-    if (DEBUG_PRINT) {
-      Serial.println("Unable to find address for Device 1");
-    }
-  }

   // set the resolution to 9 bit
-  sensors.setResolution(insideThermometer, TEMPERATURE_PRECISION);
   sensors.setResolution(outsideThermometer, TEMPERATURE_PRECISION);

   dht.begin();
@@ -299,10 +292,9 @@
   }

   sensors.requestTemperatures();
-  tempCinside  = sensors.getTempC(outsideThermometer);
-  tempCoutside = sensors.getTempC(insideThermometer);
-
-  if ( isnan(tempCinside) || isnan(tempCoutside) ) {
+  tempCoutside  = sensors.getTempC(outsideThermometer);
+
+  if ( isnan(tempCoutside) ) {
     if (DEBUG_PRINT) {
       Serial.println("Failed to read from sensor!");
     }
@@ -320,7 +312,7 @@
       }

       long now = millis();
-      if (now - lastReconnectAttempt > 5000) {
+      if (now - lastReconnectAttempt > 1000) {
         lastReconnectAttempt = now;
         if (reconnect()) {
           lastReconnectAttempt = 0;
@@ -347,8 +339,6 @@
   payload += ",\"Temperature\":";
   payload += t;
   payload += ",\"DS18B20\":";
-  payload += tempCinside;
-  payload += ",\"SENSORTEMP\":";
   payload += tempCoutside;
   payload += ",\"PIRSTATUS\":";
   payload += pirValue;
@@ -407,6 +397,7 @@
     Serial.print(" => ");
     Serial.println("checking relay status changelight");
   }
+  /*
   delay(30);
   digitalWrite(RELAYPIN, relaystatus);
   delay(30);
@@ -414,6 +405,8 @@
   delay(30);
   digitalWrite(RELAYPIN, relaystatus);
   delay(30);
+  */
+  digitalWrite(RELAYPIN, relaystatus);
   //oldrelaystatus = relaystatus ;
   if (EVENT_PRINT) {
     Serial.print(" => ");
@@ -442,10 +435,9 @@
 void getdalastemp()
 {
   sensors.requestTemperatures();
-  tempCinside  = sensors.getTempC(outsideThermometer);
-  tempCoutside = sensors.getTempC(insideThermometer);
-
-  if ( isnan(tempCinside) || isnan(tempCoutside) ) {
+  tempCoutside  = sensors.getTempC(outsideThermometer);
+
+  if ( isnan(tempCoutside)  ) {
     if (EVENT_PRINT) {
       Serial.println("Failed to read from sensor!");
     }


Added LED status that matches board state.

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -315,7 +315,7 @@
 void loop()
 {
   // Keep track of how many reads we haven't made so far.
-  size_t response_counter;
+  uint8_t response_counter;

   // Number of bytes received from USB.
   uint32_t bytes_read = 0;
@@ -386,42 +386,59 @@
   // Wait for a fixed time period.
   delay(100);

+  // Set the LED for current system state
+  switch (system_state)
+  {
+  case DISCONNECTED:
+    // Red blink
+    rgb_led.set((millis() >> 8) & 1, 0, 0);
+    break;
+  case CONNECTED:
+    // Green blink
+    rgb_led.set(0, (millis() >> 8) & 1, 0);
+    break;
+  case RUNNING:
+    // Solid green
+    rgb_led.set(0, 1, 0);
+    break;
+  }
+
   // Handle the motors appropriately for each system state.
   switch (system_state)
   {
-    case DISCONNECTED:
-      // Turn off motors.
-      for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx)
+  case DISCONNECTED:
+    // Turn off motors.
+    for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx)
+    {
+      if (motor[motor_idx]->enabled())
       {
-        if (motor[motor_idx]->enabled())
-        {
-          Serial.print("Disabling motor [");
-          Serial.print(motor_idx);
-          Serial.println("]");
-          motor[motor_idx]->disable();
-        }
+        Serial.print("Disabling motor [");
+        Serial.print(motor_idx);
+        Serial.println("]");
+        motor[motor_idx]->disable();
       }
-      break;
-    case CONNECTED:
-      // Decay all motors exponentially towards zero speed.
-      for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx)
+    }
+    break;
+  case CONNECTED:
+    // Decay all motors exponentially towards zero speed.
+    for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx)
+    {
+      motor[motor_idx]->velocity(motor[motor_idx]->velocity() * 0.8);
+    }
+    // NOTE: WE DO NOT BREAK OUT OF THE SWITCH HERE!
+  case RUNNING:
+    // Rearm motors if necessary.
+    for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx)
+    {
+      if (!motor[motor_idx]->enabled())
       {
-        motor[motor_idx]->velocity(motor[motor_idx]->velocity() * 0.8);
+        Serial.print("Arming motor [");
+        Serial.print(motor_idx);
+        Serial.println("]");
+        motor[motor_idx]->arm();
       }
-      // NOTE: WE DO NOT BREAK OUT OF SWITCH HERE!
-    case RUNNING:
-      // Rearm motors if necessary.
-      for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx)
-      {
-        if (!motor[motor_idx]->enabled())
-        {
-          Serial.print("Arming motor [");
-          Serial.print(motor_idx);
-          Serial.println("]");
-          motor[motor_idx]->arm();
-        }
-      }
-      break;
+    }
+    break;
   }

   // Send system status updates while connected to server.


Modifications & Testing

Modifications & Testing

--- Timer1Shot/Timer1Shot/Timer1Shot.ino
+++ Timer1Shot/Timer1Shot/Timer1Shot.ino
@@ -29,7 +29,7 @@
 #define OFFSET -40

-#define OSP_SET_WIDTH(cycles) (OCR1B = 0xffff-(cycles-1))
+#define OSP_SET_WIDTH(cycles) (OCR2B = 0xff-(cycles-1))

 int pos;
 int maxt = MAX + OFFSET;
@@ -40,24 +40,41 @@

 // Setup the one-shot pulse generator and initialize with a pulse width that is (cycles) clock counts long

-void osp_setup(uint16_t cycles) {
+void osp_setup(uint8_t cycles) {

   TCCR1B =  0;      // Halt counter by setting clock select bits to 0 (No clock source).
               // This keeps anyhting from happeneing while we get set up

-  TCNT1 = 0x0000;     // Start counting at bottom.
-  OCR1A = 0;      // Set TOP to 0. This effectively keeps us from counting because the counter just keeps reseting back to 0.
+  TCNT1 = 0x00;     // Start counting at bottom.
+  OCR1A = 0;      // Set TOP to 0. This effectively keeps us from counting becuase the counter just keeps reseting back to 0.
           // We break out of this by manually setting the TCNT higher than 0, in which case it will count all the way up to MAX and then overflow back to 0 and get locked up again.
   OSP_SET_WIDTH(cycles);    // This also makes new OCR values get loaded frm the buffer on every clock cycle.

   TCCR1A = _BV(COM2B0) | _BV(COM2B1) | _BV(WGM20) | _BV(WGM21); // OC2B=Set on Match, clear on BOTTOM. Mode 7 Fast PWM.
-  TCCR1B = _BV(WGM22) | _BV(CS20);         // Start counting now. WGM22=1 to select Fast PWM mode 7
+  TCCR1B = _BV(WGM22)| _BV(CS20);         // Start counting now. WGM22=1 to select Fast PWM mode 7

   DDRD |= _BV(3);     // Set pin to output (Note that OC2B = GPIO port PD3 = Arduino Digital Pin 3)
 }

-void timer1_setup (byte mode, int prescale, byte outmode_A, byte outmode_B, byte capture_mode)
+// Setup the one-shot pulse generator
+
+void timer1_setup() {
+  // set up 2 PWM channels on PB1 and PB2 using Timer1
+  TCCR1A = 0;     // disable all PWM on Timer1 whilst we set it up
+  ICR1 = 39999;   // frequency is every 20ms
+
+  // Configure timer 1 for Fast PWM mode via ICR1, with 8x prescaling
+  TCCR1A = (1 << WGM11);
+  TCCR1B = (1 << WGM13) | (1<<WGM12) | (1 << CS11);
+  // Set PB1 as output
+  DDRB |= _BV(1);
+  TCCR1A |= 2 <<  6;  // enable PWM on port B1 in non-inverted compare mode 2
+
+  OCR1A = ICR1 * 2 /20; // 2ms pulse to left motor on PB1
+}
+
+void timer1_setupOld (byte mode, int prescale, byte outmode_A, byte outmode_B, byte capture_mode)
 {
   // enforce field widths for sanity
   mode &= 15 ;
@@ -81,48 +98,52 @@
   TCCR1B = (capture_mode << 6) | ((mode & 0xC) << 1) | clock_mode ;
 }

-// Setup the one-shot pulse generator
-
-void osp_setup() {
-
-  timer1_setup(0x0, 1, 0x0, 0x0, 0x0);
-
-}
-
 // Fire a one-shot pulse. Use the most recently set width.

-#define OSP_FIRE() (TCNT1 = OCR1B - 1)
+#define OSP_FIRE() (TCNT2 = OCR2B - 1)

 // Test there is currently a pulse still in progress

-#define OSP_INPROGRESS() (TCNT1>0)
+#define OSP_INPROGRESS() (TCNT2>0)

 // Fire a one-shot pusle with the specififed width.
 // Order of operations in calculating m must avoid overflow of the unint8_t.
-// TCNT1 starts one count lower than the match value becuase the chip will block any compare on the cycle after setting a TCNT.
+// TCNT2 starts one count lower than the match value becuase the chip will block any compare on the cycle after setting a TCNT.

-#define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); OCR1B=m;TCNT1 =m-1;}
+#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR2B=m;TCNT2 =m-1;}

 void setup()
 {
   Serial.begin(38400);
-  osp_setup();
+  timer1_setup();
   //OSP_SET_WIDTH(254);
   start = micros();
+  //Serial.println(F_CPU);
+  //noInterrupts();
 }

 void loop()
 {
-  long time = micros();
-  //pos = round(amp*sin(2*PI*0.5*(time-start)/1000000.0) + mid);
-  noInterrupts();
-  OSP_SET_AND_FIRE(250);
+
+
+  //pos = round(amp*sin(2*PI*0.5*(time1-start)/1000000.0) + mid);
+  //double pulseLength = 900*sin(2*PI*0.5*(time1-start)/1000000.0) + 1500;
+  for (int i = 1; i < 3; i++)
+  {
+    TCCR1A = 0;     // disable all PWM on Timer1 whilst we set it up
+    OCR1A = ICR1 * i / 20; // 2ms pulse to left motor on PB1
+    TCCR1A |= 2 <<  6;  // enable PWM on port B1 in non-inverted compare mode 2
+  }
+  //noInterrupts();
+  //OSP_SET_AND_FIRE(250);
+  long time1 = micros();
   while (OSP_INPROGRESS()){};
-  interrupts();
+  //interrupts();
   long time2 = micros();
-  Serial.println(time2-time);
-  _delay_ms(20);
+  Serial.println(time2-time1);
+  delay(500);
+  //_delay_ms(20);

   // Step though 0-19 cycle long pulses for demo purposes
   /*long start = micros();


update controller

update controller

--- document/arduino/motor_control/motor_control.ino
+++ document/arduino/motor_control/motor_control.ino
@@ -24,10 +24,10 @@
 static const int decoder_pin_2 = 2;

 // Timer internal
-static const int timer_period = 50; // ms
+static const int timer_period = 20; // ms
 static const float timer_hz = 1000.0/( (float)timer_period ); // hz
 static const float timer_dt = timer_period/1000.0; // sec
-static const int filter_size = 10;
+static const int filter_size = 20;
 static const int counter_protect = 200;

 // encoder
@@ -45,19 +45,20 @@
 // controller
 volatile float WL_ref = 0.0; //reference speed for left wheel (deg/sec)
 volatile float WR_ref = 0.0;
-static const float Kp_L = 0.25; //0.11 //without loading
-static const float Kp_R = 0.25;
-static const float Ki_L = 0.1;
-static const float Ki_R = 0.1;
-static const float Kd_L = 0.005;
-static const float Kd_R = 0.005;
+static const float Kp_L = 0.15;
+static const float Kp_R = 0.15;
+static const float Ki_L = 0.45; //since the left motor of demo bot is weaker than the right
+static const float Ki_R = 0.4;
+static const float Kd_L = 0.01;
+static const float Kd_R = 0.01;
 volatile float integralL = 0.0;
 volatile float integralR = 0.0;
 volatile float prev_error_L = 0.0;
 volatile float prev_error_R = 0.0;
-static const float integral_dec = 0.995; // for position control, it should be 1.0
-static const float integral_max = 400;
-static const float integral_min = -400;
+static const float integral_dec = 1.0; // for position control, it should be 1.0
+static const float integral_max = 1000;
+static const float integral_min = -1000;
+static const float Kp_tilted = 0.0;

 void setup() {
   // Set 4 pwm channel pin to output
@@ -113,13 +114,13 @@
 // convert required deg/s to pwm command (based on statistical)
 float feedforward(float value) {
   //return 0.1335 * value + 7.07; //withous laoding
-    return 0.5 * value;
+    return 0.4 * value;
 }

 void controller_repoter_isr() {
   // copy current counter
-  int pin1_counter = decoder_pin_1_counter;
-  int pin2_counter = decoder_pin_2_counter;
+  int pin1_counter = decoder_pin_1_counter; // Left
+  int pin2_counter = decoder_pin_2_counter; // Right

   // average filter of encoder data
   total_pin1 = total_pin1 - (float)filter_pin1[filterId];
@@ -139,7 +140,12 @@
   // controller (feedforward + feedback)
   float cmd = 0.0;
   float error = 0.0;
-  if(WL_ref > 0.0)
+  int pin1_pwm = 0;
+  int pin2_pwm = 0;
+  int pin3_pwm = 0;
+  int pin4_pwm = 0;
+
+  if(WL_ref > 0.0) //Left wheel forward
   {
     error = WL_ref - average_counter_pin1*(float)(encoder_res)*timer_hz; // deg/sec
     integralL = integralL*integral_dec + error*timer_dt;
@@ -153,13 +159,13 @@

     if(cmd>=0.0)
     {
-      analogWrite(out1_pin, (int)cmd);
-      analogWrite(out2_pin, 0);
+      pin1_pwm = (int)cmd;
+      pin2_pwm = 0;
     }
     else
     {
-      analogWrite(out1_pin, 0);
-      analogWrite(out2_pin, -(int)cmd);
+      pin1_pwm = 0;
+      pin2_pwm = -(int)cmd;
     }
   }
   else if(WL_ref < 0.0) // the encoder has no capability of distinguishing the cw/ccw rotation
@@ -176,23 +182,23 @@

     if(cmd>=0.0)
     {
-      analogWrite(out2_pin, (int)cmd);
-      analogWrite(out1_pin, 0);
+      pin2_pwm = (int)cmd;
+      pin1_pwm = 0;
     }
     else
     {
-      analogWrite(out2_pin, 0);
-      analogWrite(out1_pin, -(int)cmd);
+      pin2_pwm = 0;
+      pin1_pwm = -(int)cmd;
     }
   }
   else // == 0
   {
     integralL = 0.0;
-    analogWrite(out1_pin, 0);
-    analogWrite(out2_pin, 0);
-  }
-
-  if(WR_ref > 0.0)
+    pin1_pwm = 0;
+    pin2_pwm = 0;
+  }
+
+  if(WR_ref > 0.0) //Right wheel forward
   {
     error = WR_ref - average_counter_pin2*(float)(encoder_res)*timer_hz; // deg/sec
     integralR = integralR*integral_dec + error*timer_dt;
@@ -205,13 +211,13 @@
     cmd = feedforward(WR_ref) + error*Kp_R + integralR*Ki_R + der_error*Kd_R; // controller
     if(cmd>=0.0)
     {
-      analogWrite(out3_pin, (int)cmd);
-      analogWrite(out4_pin, 0);
+      pin3_pwm = (int)cmd;
+      pin4_pwm = 0;
     }
     else
     {
-      analogWrite(out3_pin, 0);
-      analogWrite(out4_pin, -(int)cmd);
+      pin3_pwm = 0;
+      pin4_pwm = -(int)cmd;
     }
   }
   else if(WR_ref < 0.0)// the encoder has no capability of distinguishing the cw/ccw rotation
@@ -227,24 +233,42 @@
     cmd = feedforward(-WR_ref) + error*Kp_R + integralR*Ki_R + der_error*Kd_R; // controller
     if(cmd>=0.0)
     {
-      analogWrite(out4_pin, (int)cmd);
-      analogWrite(out3_pin, 0);
+      pin4_pwm = (int)cmd;
+      pin3_pwm = 0;
     }
     else
     {
-      analogWrite(out4_pin, 0);
-      analogWrite(out3_pin, -(int)cmd);
+      pin4_pwm = 0;
+      pin3_pwm = -(int)cmd;
     }
   }
   else // == 0
   {
     integralR = 0.0;
-    analogWrite(out3_pin, 0);
-    analogWrite(out4_pin, 0);
-  }
-
-
-
+    pin3_pwm = 0;
+    pin4_pwm = 0;
+  }
+
+  // Forward straight guaranteed func
+  if(WR_ref == WL_ref && WL_ref > 0.0)
+  {
+    int error_tilted = pin1_counter - pin2_counter; //Left - Right
+    int compensation = (int)(  ((float)(error_tilted*encoder_res))*timer_hz*Kp_tilted  );
+    if(error_tilted > 0) //Left is faster than right
+    {
+      pin3_pwm = pin3_pwm + compensation;
+    }
+    else if(error_tilted < 0)
+    {
+      pin1_pwm = pin1_pwm + compensation;
+    }
+  }
+
+  //Send pwm commannd to motor
+  analogWrite(out1_pin, pin1_pwm);//Left
+  analogWrite(out2_pin, pin2_pwm);
+  analogWrite(out3_pin, pin3_pwm);//Right
+  analogWrite(out4_pin, pin4_pwm);

   // This is a workaround to prevent from motor idle when speed  = 0;
   if (decoder_pin_1_delay_counter > counter_protect ) {


Modify welcome message

Modify welcome message

--- PushStart.ino
+++ PushStart.ino
@@ -50,14 +50,13 @@
   pinMode(pinIG2, OUTPUT);
   pinMode(pinST2, OUTPUT);

-  Serial.begin(115200);
+  Serial.begin(57600);

   Serial.println();
-  Serial.println(" Push Start ");
-  Serial.println(" Version 2.0 ");
-  Serial.println();
-  Serial.println(" Designed by Kevin Abraham ");
-  Serial.println(" For 97-01 Toyota Camry (XV20) ");
+  Serial.println("            Push Start            ");
+  Serial.println("  Arduino-based Keyless Ignition  ");
+  Serial.println("  for 97-01 Toyota Camry (XV20)   ");
+  Serial.println("    Designed by Kevin Abraham     ");
   Serial.println();

   Serial.println("Mode: off");


removed MY_DEVICES

removed MY_DEVICES

--- controlBox.ino
+++ controlBox.ino
@@ -38,7 +38,7 @@
 	pinMode(PIRpin, INPUT);
 	digitalWrite(relayPin, LOW);

-	Particle.subscribe(eventPrefix, eventHandler, MY_DEVICES);
+	Particle.subscribe(eventPrefix, eventHandler);

 	ThingSpeak.begin(client);
 }
@@ -126,4 +126,4 @@
 		heardFromSensor = true;
 		waterHeight = data.toFloat();
 	}
-}+}


[fixed] errors with libraries included in wrong order

--- arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
+++ arduino_sketches/PGA309/testPin_I2C/testPin_I2C.ino
@@ -2,8 +2,8 @@
 #include <Arduino.h>
 #include "PGA309.h"
 #include "ADS1110.h"
+#include "EEPROM24C02.h"
 #include "Util.h"
-#include "EEPROM24C02.h"

 #define PGA309ADDR 0x40
 #define ADS1110ADDR 0x49


src: refactor range and color parsing

src: refactor range and color parsing

refactor range and color parsing out to
a seprate function

--- MqttLEDs/MqttLEDs.ino
+++ MqttLEDs/MqttLEDs.ino
@@ -19,11 +19,54 @@
 const char* RANGE = "range";
 const char* CLEAR_AND_RANGE = "clear+range";

+boolean extractRangeAndTarget(const char* buffer,
+                              int* start,
+                              int* end,
+                              int numPixels,
+                              uint8_t* R,
+                              uint8_t* G,
+                              uint8_t* B) {
+  *start = 0;
+  *end = 0;
+  *R = 0;
+  *G = 0;
+  *B = 0;
+  char* next = strtok((char*) buffer," ");
+  next = strtok(nullptr," ");
+  *start = atoi(next);
+  next = strtok(nullptr," ");
+  *end = atoi(next);
+  next = strtok(nullptr," ");
+  *R = atoi(next);
+  next = strtok(nullptr," ");
+  *G = atoi(next);
+  next = strtok(nullptr," ");
+  *B = atoi(next);
+  if ((*start < 0)  ||
+      (*start >= numPixels)||
+      (*end >= numPixels) ||
+      (*end < 0) ||
+      (*end >= numPixels) ||
+      (*end < 0) ||
+      (*R > 255) ||
+      (*R < 0) ||
+      (*G > 255) ||
+      (*G < 0) ||
+      (*B > 255) ||
+      (*B < 0)) {
+    Serial.println("Message Invalid");
+    return false;
+  }
+  return true;
+}
+
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, LED_PIN, NEO_GRB + NEO_KHZ800);

 void callback(char* topic, uint8_t* message, unsigned int length) {
   std::string messageBuffer((const char*) message, length);
   Serial.println(messageBuffer.c_str());
+   int start, end;
+   uint8_t R, G, B;

   if (0 == strcmp(messageBuffer.c_str(), OFF)) {
     for(uint16_t i=0; i <strip.numPixels(); i++) {
@@ -36,37 +79,12 @@
         strip.setPixelColor(i, strip.Color(0,0,0));
       }
     }
-
-    char* next = strtok((char*) messageBuffer.c_str()," ");
-    next = strtok(nullptr," ");
-    int start = atoi(next);
-    next = strtok(nullptr," ");
-    int end = atoi(next);
-    next = strtok(nullptr," ");
-    int R = atoi(next);
-    next = strtok(nullptr," ");
-    int G = atoi(next);
-    next = strtok(nullptr," ");
-    int B = atoi(next);
-    if ((start < 0)  ||
-        (start >= strip.numPixels()) ||
-        (end >= strip.numPixels()) ||
-        (end < 0) ||
-        (end >= strip.numPixels()) ||
-        (end < 0) ||
-        (R > 255) ||
-        (R < 0) ||
-        (G > 255) ||
-        (G < 0) ||
-        (B > 255) ||
-        (B < 0)) {
-      Serial.println("Message Invalid");
-      return;
-    }

-    end = end + 1;
-    for(uint16_t i = start; i < end; i++) {
-      strip.setPixelColor(i, strip.Color(R, G, B));
+    if (extractRangeAndTarget(messageBuffer.c_str(), &start, &end, strip.numPixels(), &R, &G, &B)) {
+      end = end + 1;
+      for(uint16_t i = start; i < end; i++) {
+        strip.setPixelColor(i, strip.Color(R, G, B));
+      }
     }
   } else {
     Serial.println("Message Invalid");


Cleanup.

Cleanup.

--- examples/Demo/CosaVWItermostat/CosaVWItermostat.ino
+++ examples/Demo/CosaVWItermostat/CosaVWItermostat.ino
@@ -84,9 +84,15 @@
 #else
 VWI::Receiver rx(Board::D8, &codec);
 #endif
+
 Relay heater(Board::D2);
 Relay fan(Board::D3);
 RemoteRelay vent(Board::D4, 0xc05a01L, 0);
+
+const uint8_t RH_MIN = 50;
+const uint8_t RH_MAX = 70;
+const uint8_t TEMP_MIN = 22;
+const uint8_t TEMP_MAX = 26;

 void setup()
 {
@@ -124,16 +130,12 @@
   int16_t temperature = msg.temperature;

   // Check if heater should be turned on @ 22 C and off @ 26 C
-  static const uint8_t TEMP_MIN = 22;
-  static const uint8_t TEMP_MAX = 26;
   if (heater.is_on()) {
     if (temperature > TEMP_MAX) heater.off();
   }
   else if (temperature < TEMP_MIN) heater.on();

   // Check if fan/vent should be turned on @ 70 %RH and off @ 50 %RH.
-  static const uint8_t RH_MIN = 50;
-  static const uint8_t RH_MAX = 70;
   if (fan.is_on()) {
     if (humidity < RH_MIN) {
       fan.off();
@@ -150,7 +152,4 @@
   trace << PSTR("T = ") << temperature << PSTR(" C, ");
   trace << PSTR("Heater = ") << (heater.is_on() ? PSTR("ON, ") : PSTR("OFF, "));
   trace << PSTR("Fan = ") << (fan.is_on() ? PSTR("ON\n") : PSTR("OFF\n"));
-
-  // Sample every 2 seconds
-  SLEEP(2);
 }


Some functions.

Some functions.

--- wip/wip.ino
+++ wip/wip.ino
@@ -12,7 +12,7 @@
 }

 void loop() {
-  blinking(leds, NUM_LEDS, 0, 10, 0, 3000);
+  progressbarCentered(leds, NUM_LEDS, 0, 20, 0, 100);
 }

 void runner(CRGB *leds, int numOfLeds, int red, int green, int blue, int ms) {
@@ -73,9 +73,27 @@

 void progressbarCentered(CRGB *leds, int numOfLeds, int red, int green, int blue, int ms) {

-    int i, center;
+    int i, center, inv;

     center = numOfLeds / 2;
+
+    for(i = center; i < numOfLeds; i++) {
+
+        inv = (numOfLeds - i) - 1;
+        leds[i].setRGB(red, green, blue);
+        leds[inv].setRGB(red, green, blue);
+        FastLED.show();
+        delay(ms);
+    }
+
+    for(i = (numOfLeds - 1); i >= center; i--) {
+
+        inv = (numOfLeds - i) - 1;
+        leds[i].setRGB(0, 0, 0);
+        leds[inv].setRGB(0, 0, 0);
+        FastLED.show();
+        delay(ms);
+    }
 }

 void blinking(CRGB *leds, int numOfLeds, int red, int green, int blue, int ms) {
@@ -124,7 +142,7 @@

 //ms = time of pulse
 void pulse(CRGB *leds, int numOfLeds, int red, int green, int blue, int ms){
-  int numOfSteps = 25;
+  int numOfSteps = 20;

   for (int step = 0; step < numOfSteps; step++){

@@ -133,10 +151,10 @@
     int tempBlue = blue - (step * (blue / numOfSteps));

     for (int i = 0; i < numOfLeds; i++){
-      leds[i].setRGB(tempGreen, tempBlue, tempRed);
+      leds[i].setRGB(tempRed, tempGreen, tempBlue);
     }
+
+    FastLED.show();
+    delay(ms/numOfSteps);
   }
-  FastLED.show();
-  delay(ms/numOfSteps);
-
-}+}


Delete emonTxSerialOnly.ino

Delete emonTxSerialOnly.ino

--- OpenEnergyMonitor/emonTx/emonTxSerialOnly.ino
+++ OpenEnergyMonitor/emonTx/emonTxSerialOnly.ino
@@ -1 +0,0 @@
-Sketch


minor firmware refinements

minor firmware refinements

Added a RW variable S1_Calibration and locked out the CT calculation
below 0.1 lux for better stability in very low light conditions

--- software/light-sensor-suite/light-sensor-suite.ino
+++ software/light-sensor-suite/light-sensor-suite.ino
@@ -189,7 +189,8 @@
   maxlux = 65535 / (cpl * 3);

   lux = (TCS34725_R_Coef * float(r_comp) + TCS34725_G_Coef * float(g_comp) + TCS34725_B_Coef * float(b_comp)) / cpl;
-  ct = TCS34725_CT_Coef * float(b_comp) / float(r_comp) + TCS34725_CT_Offset;
+  if (lux > 0.1) // 2016-02-06 skip the CT calculation unless lux is greater than 0.1
+    ct = TCS34725_CT_Coef * float(b_comp) / float(r_comp) + TCS34725_CT_Offset;
 }

 tcs34725 tcs;
@@ -203,7 +204,7 @@
 #define BME_MOSI 11
 #define BME_CS 10

-#define SEALEVELPRESSURE_HPA (1015.03)
+#define SEALEVELPRESSURE_HPA (1027.8)

 Adafruit_BME280 bme; // I2C

@@ -220,28 +221,29 @@

 #define S1_Available            40009
 #define S1_ScanTime             40011
-#define S1_Lux                  40013
-#define S1_CT                   40015
-#define S1_IR                   40017
-#define S1_AGAINX               40019
-#define S1_ATIME_MS             40021
-#define S1_ATIME                40023
-#define S1_R_RAW                40025
-#define S1_G_RAW                40027
-#define S1_B_RAW                40029
-#define S1_C_RAW                40031
-#define S1_R_COMP               40033
-#define S1_G_COMP               40035
-#define S1_B_COMP               40037
-#define S1_C_COMP               40039
-
-#define S2_Available            40041
-#define S2_ScanTime             40043
-#define S2_SeaLevelPressureHPA  40045
-#define S2_Temperature          40047
-#define S2_Pressure             40049
-#define S2_Altitude             40051
-#define S2_Humidity             40053
+#define S1_Calibration          40013
+#define S1_Lux                  40015
+#define S1_CT                   40017
+#define S1_IR                   40019
+#define S1_AGAINX               40021
+#define S1_ATIME_MS             40023
+#define S1_ATIME                40025
+#define S1_R_RAW                40027
+#define S1_G_RAW                40029
+#define S1_B_RAW                40031
+#define S1_C_RAW                40033
+#define S1_R_COMP               40035
+#define S1_G_COMP               40037
+#define S1_B_COMP               40039
+#define S1_C_COMP               40041
+
+#define S2_Available            40043
+#define S2_ScanTime             40045
+#define S2_SeaLevelPressureHPA  40047
+#define S2_Temperature          40049
+#define S2_Pressure             40051
+#define S2_Altitude             40053
+#define S2_Humidity             40055

 bool s1, s2; // flags to indicate which sensors are available

@@ -252,7 +254,7 @@
   Serial.begin(115200);
   delay(10);
   Serial.println(); Serial.println();
-  Serial.println("2016-01-30 light-sensor-suite");
+  Serial.println("2016-02-01 light-sensor-suite");

   // Connect to WiFi access point
   m.begin(WLAN_SSID, WLAN_PASS);
@@ -262,6 +264,7 @@
   Serial.print("S1 - TCS34725 ");
   Serial.println((s1 = tcs.begin()) ? "initialized" : "error");
   m.setFloat(S1_Available, (float) s1);
+  m.setFloat(S1_Calibration, 1.0);

   // Initialize S2
   Serial.print("S2 - BME280 ");
@@ -292,7 +295,7 @@
   // update S1 registers
   while (s1 && (curMillis - S1StartTime > 5000)) {
     tcs.getData();
-    m.setFloat(S1_Lux, tcs.lux);
+    m.setFloat(S1_Lux, m.getFloat(S1_Calibration) * tcs.lux);
     m.setFloat(S1_CT, tcs.ct);
     m.setFloat(S1_IR, tcs.ir);
     m.setFloat(S1_AGAINX, tcs.againx);


switch time

switch time

--- WifiWeatherGuy.ino
+++ WifiWeatherGuy.ino
@@ -345,7 +345,7 @@
   } else if (now - display_on > on_time) {
     analogWrite(TFT_LED, --fade);
     delay(25);
-  } else if (swtch) {
+  } else if (swtch && now - display_on > 500) {
     is_weather = !is_weather;
     update_display();
   }


make sure audio is on

make sure audio is on

--- examples/Tunes/Tunes.ino
+++ examples/Tunes/Tunes.ino
@@ -167,6 +167,7 @@
   text.print("Music\nDemo");

   // audio setup
+  arduboy.audio.on();
   tunes.initChannel(PIN_SPEAKER_1);
   tunes.initChannel(PIN_SPEAKER_2);


added heat index to ThingSpeak

added heat index to ThingSpeak

--- QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
+++ QmoteRHTlogger_w_Daikin/QmoteRHTlogger_w_Daikin.ino
@@ -39,11 +39,10 @@
 #define TEMP_HIGH             26.5        // Highheat index may be caused by Rh, set High limitation to determine cooling or dehumidifier
 #define TEMP_LOW              25          // stop cooling or switch to humidifier if temerature reaches this measurement
 #define TEMP_TOO_LOW          23.5        // if temperature reaches this value means humidifier goes too much, turn off everything
-#define RH_HIGH               69          // restart humidifier if Rh reaches to this measurement
 #define RH_LOW                60          // stop humidifier if Rh reaches to this measurement

 // avoid frequent ON-OFF mode switch
-#define KEEP_ONOFF_TIMER      45
+#define KEEP_ONOFF_TIMER      60
 #define RESEND_ATTEMPS        3
 #define RESEND_CMD_TIMER      30

@@ -268,18 +267,6 @@
     unsigned int currentRhInt = (unsigned int) currentRh;
     float currentHeatIndex = heatIndex((double) currentTemp, (double) currentRh);

-    /*
-    //debug output
-    unsigned int teim = timeElapsed / (long) 60000;
-    qmoteCmd = "ATBN=0x0A,\"";        // using click combination code 0x0A, --..
-    qmoteCmd += isOn;
-    qmoteCmd += ",";
-    qmoteCmd += teim;
-    qmoteCmd += "\"\r\n";
-    portOne.write(qmoteCmd.c_str());
-    delay(3000);
-    */
-
     // RhT logging in text file
     qmoteCmd = "ATBN=0x0A,\"RH";      // using click combination code 0x0A, --..
     qmoteCmd += currentRhInt;
@@ -287,15 +274,31 @@
     qmoteCmd += currentTemp;
     qmoteCmd += ",HI";
     qmoteCmd += currentHeatIndex;
+
+    // debug info
+    unsigned int teim = timeElapsed / (long) 60000;
+    unsigned int rtim = resendTimer / (long) 60000;
+    qmoteCmd += ",";
+    qmoteCmd += isOn;
+    qmoteCmd += ",";
+    qmoteCmd += teim;
+    qmoteCmd += ",";
+    qmoteCmd += rtim;
+    qmoteCmd += ",";
+    qmoteCmd += resend;
+    // ...................
+
     qmoteCmd += "\"\r\n";
     portOne.write(qmoteCmd.c_str());    // output to Maker's module
     delay(2000);                        // delay before next command

     // get Qmote command for ThingSpeak output
-    qmoteCmd = "ATBN=0x09,\"";        // using click combination code 0x09, -...
-    qmoteCmd += currentRh;            // To save UartMsg size, leave "field1=" to IFTTT
+    qmoteCmd = "ATBN=0x09,\"field1=";   // using click combination code 0x09, -...
+    qmoteCmd += currentRh;
     qmoteCmd += "&field2=";
     qmoteCmd += currentTemp;
+    qmoteCmd += "&field3=";
+    qmoteCmd += currentHeatIndex;
     qmoteCmd += "\"\r\n";

     // output to Maker's module


Removed test code.

Removed test code.

--- aeroprobe.ino
+++ aeroprobe.ino
@@ -104,14 +104,6 @@
     ALPHA,
     BETA
   } last_angle_measured;
-
-
-  uint8_t seconds;
-  DS3231::read_all(&seconds, 0, 0,
-                   0, 0, 0, 0);
-  Serial.println(seconds);
-  delay(100);
-  return;

   uint64_t now = micros64();


tested logging

tested logging

--- exhaust_sensor_array.ino
+++ exhaust_sensor_array.ino
@@ -9,19 +9,18 @@
 // GPS
 #include <SoftwareSerial.h>
 #include "TinyGPSPlus/TinyGPS++.h"
-#define GPS_RX           9 // Arduino RX pin connected to GPS TX
-#define GPS_TX           8 // Arduino TX pin connected to GPS RX
+#define GPS_RX           9 // Arduino RX pin connected to GPS RX
+#define GPS_TX           8 // Arduino TX pin connected to GPS TX
 #define GPS_BAUD_RATE 9600 // The GPS Shield module defaults to 9600 baud
 SoftwareSerial gps_port(GPS_TX, GPS_RX);
 TinyGPSPlus gps;

 // SD card
 #include <SD.h>
-#include <SPI.h>
 #define SD_PIN 10

 // code!
-// #define DEBUG
+//#define DEBUG
 #ifdef DEBUG
 #define print   Serial.print
 #define println Serial.println
@@ -34,6 +33,8 @@
 File log_file;

 void print_log() {
+
+  log_file = SD.open("log.csv", FILE_WRITE);

   print(gps.location.lat(), 6);
   print(',');
@@ -65,26 +66,25 @@
   print(',');
   print(map(WIND, 0, 1023 , 0, 100)); // meter per second
   println();
+
+  log_file.close();
 }

 void setup() {

-  #ifdef DEBUG
   Serial.begin(9600);
-  #endif
+  gps_port.begin(GPS_BAUD_RATE); //GPS Setup

-  gps.begin(GPS_BAUD_RATE); //GPS Setup
-  SD.begin(SD_PIN);         //SD card start
+  //SD card start
+  pinMode(SD_PIN, OUTPUT);
+  digitalWrite(SD_PIN, HIGH);
+  SD.begin(SD_PIN);
+//  if( !SD.begin(SD_PIN) ) Serial.println("ERROR: SD failure");
 }

 void loop() {

-  #ifdef DEBUG
-  delay(10);
-  #else
-  delay(5000);
-  log_file = SD.open("log.csv", FILE_WRITE);
-  #endif
+  delay(500);

   // update GPS
   while(gps_port.available()) gps.encode(gps_port.read());


Check battery level

Check battery level

--- magbot_test/magbot_test.ino
+++ magbot_test/magbot_test.ino
@@ -4,6 +4,7 @@
  speaker/piezo for sound
  */

+#include <util/delay.h>
 #include <NewPing.h> // From https://code.google.com/p/arduino-new-ping/
 #include <NewTone.h> // From https://code.google.com/p/arduino-new-tone/

@@ -81,6 +82,11 @@
     // Remeber when this ping was done, so we know when to do the next one.
     melody_last = millis_now;
     playMelody();
+
+    // Check battery level
+    long vcc = readVcc();
+    Serial.print("Battery: ");
+    Serial.println(vcc);
   }

 }
@@ -104,3 +110,33 @@
   }
 }

+/**
+ * Read the internal voltage.
+ */
+long readVcc()
+{
+  // Read 1.1V reference against AVcc
+  // set the reference to Vcc and the measurement to the internal 1.1V reference
+  #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+    ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
+  #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
+    ADMUX = _BV(MUX5) | _BV(MUX0);
+  #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
+    ADMUX = _BV(MUX3) | _BV(MUX2);
+  #else
+    ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
+  #endif
+
+  _delay_ms(2); // Wait for Vref to settle
+  ADCSRA |= _BV(ADSC); // Start conversion
+  while (bit_is_set(ADCSRA,ADSC)); // measuring
+
+  uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
+  uint8_t high = ADCH; // unlocks both
+
+  long result = (high<<8) | low;
+
+  result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
+  return result; // Vcc in millivolts
+}
+