Initial upload

Initial upload

Basic functions works. Presets not working yet. Use the OEP board 2_2

#include <Adafruit_GFX.h>

/*
Grompressor1.ino
Compressor effect using floating point core. Thanks to Chip Audette!
Thanks to Paul Stoffregen, www.PJRC.com, that made the great audio library fro Teensy! Plus all the other great stuff!
This code can be loaded into a Teensy3.5/3.6 with a OnkartGromt OpenEffects project platform. Use a I2C 64x128 OLED screen to show the graphics.
Hold the On/Off switch for 1 sek to edit the input gain with pot1.
All in all use the OpenEffectsBox ref2.2 from OnkartGromt with Teensy 3.5/3.6
 */
#include <EEPROM.h>
#include <Bounce.h>
#include <Audio.h>
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
#include <SerialFlash.h>
#include <Adafruit_NeoPixel.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <math.h>
#include<string.h>
#include <OpenAudio_ArduinoLibrary.h> //for AudioConvert_I16toF32, AudioConvert_F32toI16, and AudioEffectGain_F32
using namespace std;

#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
//Blue HW:
#define PIN            8
//RED HW:
//#define PIN            3

#define NUMPIXELS      10
#define bands          6
Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

// GUItool: begin automatically generated code
AudioInputI2S        i2sAudioIn1;    //xy=144,485
AudioConvert_I16toF32    int2Float2;     //xy=317,425
AudioConvert_I16toF32    int2Float1;     //xy=342,549
AudioEffectCompressor_F32 comp1;          //xy=510,549
AudioEffectCompressor_F32 comp2;          //xy=511,425
AudioConvert_F32toI16    float2Int2;     //xy=654,425
AudioConvert_F32toI16    float2Int1;     //xy=670,549
AudioMixer4          mixer1;       //xy=847,444
AudioMixer4          mixer2;       //xy=851,542
AudioAnalyzeNoteFrequency notefreq1;
AudioOutputI2S       i2sAudioOut1;   //xy=1022,482
AudioConnection         patchCord1(i2sAudioIn1, 0, int2Float2, 0);
AudioConnection         patchCord2(i2sAudioIn1, 0, mixer1, 1);
AudioConnection         patchCord3(i2sAudioIn1, 1, int2Float1, 0);
AudioConnection         patchCord4(i2sAudioIn1, 1, mixer2, 1);
AudioConnection_F32         patchCord5(int2Float2, comp2);
AudioConnection_F32         patchCord6(int2Float1, comp1);
AudioConnection_F32         patchCord7(comp1, float2Int1);
AudioConnection_F32         patchCord8(comp2, float2Int2);
AudioConnection         patchCord9(float2Int2, 0, mixer1, 0);
AudioConnection         patchCord10(float2Int1, 0, mixer2, 0);
AudioConnection         patchCord11(mixer1, 0, i2sAudioOut1, 0);
AudioConnection         patchCord12(mixer2, 0, i2sAudioOut1, 1);
AudioControlSGTL5000     sgtl5000;     //xy=385,640
// GUItool: end automatically generated code
AudioAnalyzeRMS          rms1, rms2, rms3, rms4;  //peak indicator/detection
AudioConnection         patchCord22(i2sAudioIn1, 0, rms2, 0);
AudioConnection         patchCord23(i2sAudioIn1, 1, rms1, 0);
AudioConnection         patchCord24(float2Int1, 0, rms3, 0);
AudioConnection         patchCord25(float2Int1, 0, rms4, 0);
AudioConnection         patchCord26(float2Int1, 0, notefreq1, 0);

//Pinout board rev1
int Pot1 = A6;    // select the input pin for the potentiometer
int Pot2 = A3;    // select the input pin for the potentiometer
int Pot3 = A2;    // select the input pin for the potentiometer
int Pot4 = A1;    // select the input pin for the potentiometer
int CV1 = A10;
int CV2 = A11;

//For the RED pcb
//int Tap1 = 0;
//int Tap2 = 1;

//For Blue/black PCB:
int Tap1 = 2;
int Tap2 = 3;

int SW1 = A12;
int SW2 = A13;

//int ledPin1 = 3;      // select the pin for the LED strip
int relayL = 4;      // select the pin for the RelayL
int relayR = 5;      // select the pin for the RelayR

//Variables for values
boolean Tap1Value = 0;
boolean Tap2Value = 0;
float Pot1Value = 0;
float Pot2Value = 0;
float Pot3Value = 0;
float Pot4Value = 0;
int SW1Value = 0;
int SW2Value = 0;
float CV1Value = 0;
float CV2Value = 0;
float Pot1ValueOld = 0;  // variable to store the previous value
float Pot2ValueOld = 0;
float Pot3ValueOld = 0;
float Pot4ValueOld = 0;
int SW1ValueOld = 0;
int SW2ValueOld = 0;
int Tap1ValueOld = 1;
int Tap2ValueOld = 1;
int CV1ValueOld = 0;
int CV2ValueOld = 0;
int Tap1Timer = 0;
int Tap2Timer = 0;
float margin  = 0.1;
//int modulationMode = 0;
boolean Tap2Pressed = 0;
//int filterOrder = 24;
//float ffund = 0;

// Variables
int ledStateONOFF = LOW;         // the current state of the output pin
int ledStateONOFF_old = LOW;
int buttonState0;             // the current reading from the input pin
int lastButtonState0 = LOW;   // the previous reading from the input pin
int ledStateBOOST = LOW;         // the current state of the output pin
int buttonState1;             // the current reading from the input pin
int lastButtonState1 = LOW;   // the previous reading from the input pin

unsigned long lastDebounceTime0 = 0;  // the last time the output pin was toggled
unsigned long lastDebounceTime1 = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 40;    // the debounce time; increase if the output flickers

float peak = 0.0;
float peak_2 = 0.0;
float peak_3 =0.0;
float peak_4 =0.0;
float level = 1;
float InLevel = 1;
float outLevel = 1;
float inLevel = 0.05;
float bypassLevel = 0.42;
float mixer3Level = 1.0;
int lastParam = 0;

int updateParam = 0;
float maxGain = 0;
float response = 0;
float thres = -18;
float hardLimit = 0;
float attack_1 = 0.01f;
float decay_1 = 0.2f;
int Ratio = 3;
int inlevel = 5;

struct presets {
  float thres;
  float attack_1;
  float decay_1;
  int Ratio;
  int inputGain;
  int actualPreset;
}  ;
//new version:

float levelBand[bands] = {30,35, 40, 25, 50,60};
float levelBandScaled[bands] = {30,35, 40, 25, 50,60};
float levelBanddB[bands] = {0,0,0, 0, 0,0};
unsigned int freqBand[bands] = {30, 160, 320, 640, 2000,16000};
float freqBandDefault[bands] = {80, 160, 320, 640, 2000,16000};
float freqBandScaled[bands] = {4, 12, 32, 64, 110,110};
float slopeBand[bands] = {.7,.7,.7,.7,.7,.7};
float Qlevel[bands] = {1,1,1,1,1,1};
int updateFilter = 1;
int savePreset = 0;
int loadPreset = 0;
int actualPreset = 1;
int numberOfPresets = 10;
unsigned char loByte;
unsigned char hiByte;
uint32_t off =pixels.Color(0,0,0);
uint32_t blue =pixels.Color(0,0,50);
uint32_t red =pixels.Color(0,50,0);
uint32_t green =pixels.Color(0,40,0);
uint32_t yellow =pixels.Color(40,40,0);
int VUlag = 0;
const int myInput = AUDIO_INPUT_LINEIN;

Bounce OnOff = Bounce(Tap1, 30 );
Bounce BoostOnOff = Bounce(Tap2, 30);
elapsedMillis holdTime;
elapsedMillis tapInterval;  //timer that is used for tap tempo

void setup() {
  AudioMemory(60);
  AudioMemory_F32(40); //allocate Float32 audio data blocks
  pixels.begin();
  for (int i = 0;i<NUMPIXELS;i++){
    pixels.setPixelColor(i,off);
   }
  pixels.setPixelColor(0,green);
  pixels.show();
  InLevel = float(EEPROM.read(0)/255.0);
  outLevel = float(EEPROM.read(1));
  sgtl5000.enable();  // Enable the audio shield
  sgtl5000.inputSelect(myInput);
  sgtl5000.volume(0.8);
  sgtl5000.lineInLevel(15);   // 3.12Vp-p
  sgtl5000.lineOutLevel(21); // 3.16Vp-p
  sgtl5000.adcHighPassFilterDisable();
  //READ PRESET FROM EEPROM
  if (EEPROM.read(10) == 0) EEPROM.write(10,1);

  //pinMode(ledPin1, OUTPUT); ONLY WITH RED BOARD
  pinMode(relayL, OUTPUT);
  pinMode(relayR, OUTPUT);
  pinMode(Tap1, INPUT);
  pinMode(Tap2, INPUT);

  mixer1.gain(0, 1);
  mixer1.gain(1, 0);
  mixer1.gain(2, 0);
  mixer1.gain(3, 0);
  mixer2.gain(0, 1);
  mixer2.gain(1, 0);
  mixer2.gain(2, 0);
  mixer2.gain(3, 0);

  sgtl5000.inputSelect(myInput);
  sgtl5000.dacVolume (level);
  sgtl5000.autoVolumeControl(0,0,0,0.7,50,100);  //maxGain,response,hard limit,threshold,attack, decay
  sgtl5000.autoVolumeDisable();
  sgtl5000.audioPostProcessorEnable();
  sgtl5000.eqSelect(3);
  sgtl5000.eqBands(0,0,0,-1.0,-1.0);
  sgtl5000.dacVolumeRamp();
  Serial.begin(115200);
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3C (for the 128x64)
  display.clearDisplay();
  pixels.show();
  delay(100);
  Serial.println("setup complete");
}

//Main loop
void loop() {
  OnOff.update();      //update the bounce
  BoostOnOff.update();

  // read the value from the pots and buttons:
  Pot1Value = analogRead(Pot1);    //Level
  Pot2Value = analogRead(Pot2);    //Width
  Pot3Value = analogRead(Pot3);    //Freq
  Pot4Value = analogRead(Pot4);    //Mode
  Tap1Value = digitalRead(Tap1);   //On off
  Tap2Value = digitalRead(Tap2);   //Mode/Tap
  SW1Value = analogRead(SW1);      //Filter char
  SW2Value = analogRead(SW2);      //Direction

  SW1Value = map(SW1Value, 0, 1023, 5, 0);               //Filter char
  SW1Value = constrain(SW1Value, 1, 5);
  SW2Value = map(SW2Value, 0, 1023, 5, 0);               //Direction
  SW2Value = constrain(SW2Value, 1, 5);

//********************ON -OFF handling**********************
  buttonState0 = OnOff.read();
  if (lastButtonState0 != buttonState0){
      // only toggle the state if the new button state is HIGH
      if (buttonState0 == LOW) {
        ledStateONOFF = !ledStateONOFF;
      }
  }
  buttonState1 = BoostOnOff.read();
  if (lastButtonState1 != buttonState1){
      // only toggle the state if the new button state is HIGH
      if (buttonState1 == LOW) {
        ledStateBOOST = !ledStateBOOST;
      }
  }
  // set the outputs:
  if (ledStateONOFF != ledStateONOFF_old){
    pixels.setPixelColor(2, pixels.Color(ledStateONOFF*30,(ledStateONOFF*30),ledStateONOFF*30)); // ONOFF bright white color.
    digitalWrite(relayL, ledStateONOFF);
    digitalWrite(relayR, ledStateONOFF);
    ledStateONOFF_old = ledStateONOFF;
    pixels.show(); // This sends the updated pixel color to the hardware.
  }
  lastButtonState0 = buttonState0;  //save readings to next round
  lastButtonState1 = buttonState1;

//********************PRESET handling**********************
//
if (SW2Value == 1){
  actualPreset--;
  if (actualPreset <0)actualPreset = numberOfPresets;
  delay(50);
  }
if (SW2Value == 5){
  actualPreset++;
  if (actualPreset > numberOfPresets)actualPreset =0;
  delay(50);
  }

//******************** Handle user inputs **********************

if (SW1Value == 1){
    Ratio ++;
    if (Ratio >=20)Ratio = 20;
    updateParam = 1;
  }
if (SW1Value == 5){
   Ratio --;
   if (Ratio <=0)Ratio = 1;
   updateParam = 1;
  }
int margin = 3;

if ((Pot1Value > Pot1ValueOld+ margin) || (Pot1Value < Pot1ValueOld - margin)){  //LEVEL adjust
    inlevel = map(Pot1Value, 0, 1023, 15, 0);
    sgtl5000.lineInLevel(inlevel);   // 3.12Vp-p
    updateParam = 1;
}

if ((Pot2Value > Pot2ValueOld+ margin) || (Pot2Value < Pot2ValueOld - margin)){  //Threshold values
    thres = map(Pot2Value, 0, 1023, 0,-70.0f);
    updateParam = 1;
}

if ((Pot3Value > Pot3ValueOld+ margin) || (Pot3Value < Pot3ValueOld - margin)) {    //Attack
    attack_1 = mapfloat(Pot3Value, 0, 1023, 0.2f,0.001f);
      Serial.println(attack_1);

    updateParam = 1;
}

if ((Pot4Value > Pot4ValueOld+ margin) || (Pot4Value < Pot4ValueOld - margin)){  //Release
    decay_1 = mapfloat(Pot4Value, 0, 1023,2.0, 0.02);
    updateParam = 1;
          Serial.println(decay_1);
}
if (updateParam == 1){
    //configure the left and right compressors with the new settings
    boolean use_HP_filter = true; //enable the software HP filter to get rid of DC
    setupMyCompressors(use_HP_filter, thres, Ratio, attack_1, decay_1);
    updateParam = 0;
    }

//********************Load and saving presets **********************
if (BoostOnOff.fallingEdge()){
  holdTime = 0;
  Serial.println("pushed");
 }
if (!BoostOnOff.read() && holdTime >1500) {
        savePreset = 1;
        pixels.setPixelColor(1, green);
        pixels.show();
        Serial.println(holdTime);
        Serial.println("Save");

  }
else if (BoostOnOff.risingEdge() && (holdTime >600) && (holdTime <1500)) {
        actualPreset++;
        if (actualPreset >=10)actualPreset = 0;
        loadPreset = 1;
        pixels.setPixelColor(1, red);
        pixels.show();
        Serial.print("Loading new Preset: ");
        Serial.println(actualPreset);
        delay(500);
  }
else if (BoostOnOff.risingEdge()){
        loadPreset = 1;
        Serial.print("Load");
        Serial.println(holdTime);
   }

if (savePreset == 1){
    /*
    uint16_t value = (uint16_t)(levelBand[i]*100);
    loByte = uint8_t(value & 0x00ff);
    hiByte = uint8_t((value >> 8 )& 0x00ff);
    EEPROM.write(20+2*i+actualPreset*70,(loByte));
    EEPROM.write(20+1+2*i+actualPreset*70,(hiByte));
    value = (uint16_t)(slopeBand[i]*100);
    loByte = uint8_t(value & 0x00ff);
    hiByte = uint8_t((value >> 8 )& 0x00ff);
    EEPROM.write(40+2*i+actualPreset*70,(loByte));
    EEPROM.write(40+1+2*i+actualPreset*70,(hiByte));
    loByte = uint8_t(freqBand[i] & 0x00ff);
    hiByte = uint8_t((freqBand[i] >> 8 )& 0x00ff);
    EEPROM.write(60+2*i+actualPreset*70,loByte);
    EEPROM.write(60+1+2*i+actualPreset*70,hiByte);
    */
printParameters(&Serial);

 Serial.print("Saved");
 Serial.println(actualPreset);
    display.setCursor(68, 10);
    display.print("SAVED");
    display.display();
    delay(1000);
 savePreset = 0;
 }

if (loadPreset ==1){

    /*
    unsigned int hg[i];
    loByte= EEPROM.read(20+2*i+actualPreset*70);
    hiByte= EEPROM.read(20+1+2*i+actualPreset*70);
    levelBand[i] = (float)((hiByte << 8) | loByte)/100;
    loByte= EEPROM.read(40+2*i+actualPreset*70);
    hiByte= EEPROM.read(40+1+2*i+actualPreset*70);
    slopeBand[i] = (float)((hiByte << 8) | loByte)/100;
    loByte = EEPROM.read(60+2*i+actualPreset*70);
    hiByte = EEPROM.read(60+1+i*2+actualPreset*70);
    freqBand[i] = (hiByte << 8) | loByte;
    */

    printParameters(&Serial);

  Serial.print("loading..");
  Serial.println(actualPreset);
  loadPreset = 0;
  updateParam=1;
    display.setCursor(68, 10);
    display.print("LOAD");
    display.display();
    delay(500);
 }
display.clearDisplay();

//*******************INPUT/OUTPUT LEVEL ADJUST************************
if (SW1Value == 5){    //LP pos for input level
 if (!Tap1Value && (Tap1Value == Tap1ValueOld)){    //When Mode/tap is held down you can adjust the input gain of the input
 // Serial.print("TIME");
   Tap1Timer++;
  if (Tap1Timer > 15){
    InLevel = analogRead(Pot1);
    InLevel = mapfloat(InLevel,0,1023,10,1);
    InLevel = InLevel * inLevel; //multiply by constant inLevel
    delay(100);
    display.setTextSize(1);
    display.setTextColor(WHITE);
    display.setCursor(5, 10);
    display.print("Input:");
    display.print(InLevel);
    display.display();
    }
  }
  else if (Tap1Timer > 15){    //only write to EEPROM once
    EEPROM.write(0, InLevel*255);
  //  Serial.println(InLevel);
    Tap1Timer = 0;
  }
  else if (Tap1Value){
  //  peak = peak1.read();   //read the signal output peak
  if (peak == -1)(peak = 0);
  //analogWrite(ledPin2, peak*100);
  //pixels.setPixelColor(1, pixels.Color(peak*100,peak*100,0));
  //pixels.show();
  }
}

if (SW1Value == 1){    //HP pos for Output level
 if (!Tap1Value && (Tap1Value == Tap1ValueOld)){    //When Mode/tap is held down you can adjust the input gain of the input
 // Serial.print("TIME");
   Tap1Timer++;
  if (Tap1Timer > 15){
    outLevel = analogRead(Pot1);
    outLevel = mapfloat(outLevel,0,1023,10,1);
    delay(100);
   // analogWrite(ledPin2, 255);
    //pixels.setPixelColor(1, pixels.Color(70,70,0));
    //display.clearDisplay();
    display.setTextSize(1);
    display.setTextColor(WHITE);
    display.setCursor(5, 10);
    display.print("Output:");
    display.print(outLevel);
    display.display();
    }
  }
  else if (Tap1Timer > 15){    //only write to EEPROM once
    EEPROM.write(1, outLevel);
    Tap1Timer = 0;
  }
  else if (Tap1Value){
  //  peak = peak1.read();   //read the signal output peak
  if (peak == -1)(peak = 0);
  //analogWrite(ledPin2, peak*100);
  //pixels.setPixelColor(1, pixels.Color((peak)*100,(peak)*100,0));
  //pixels.show();
  }
}

 ////// VU meter ////////////
//Gain reduction meter

for(int i=NUMPIXELS;i>=3;i--){
  float reduction = abs(comp1.getCurrentGain_dB());
  int lvl = NUMPIXELS-(reduction/5);       //120*7=840
  int grade = 360+reduction*960;
  //Serial.println(peak_2);
  grade = grade -(120*lvl);

  if ((i > lvl)&&(i == 5))pixels.setPixelColor(i,yellow); // yellow color.
  if ((i > lvl)&&(i == 4))pixels.setPixelColor(i,red); // red color.
  else if (i > lvl)pixels.setPixelColor(i,green); // green color.
  //else if (i == lvl){
 //   pixels.setPixelColor(i, pixels.Color(grade,0,0)); // green color.
  //}
  else     {
    pixels.setPixelColor(i,off); // no color
  }
}
  pixels.show(); // This sends the updated pixel color to the hardware.

///////////end VU meter/////////

///////////////////////////PLOTTING OF COMPRESSOR CURVE//////////////////////////////////
//Draw background:
int top = 20;
int signalWidth = 6;
display.drawLine(0,top,128,top, WHITE);
display.drawLine(0,64,0,top, WHITE);
display.drawLine(signalWidth+1,64,signalWidth+1,top, WHITE);
display.drawLine(signalWidth*2+2,64,signalWidth*2+2,top, WHITE);
display.drawLine(127-signalWidth*2-2,64,127-signalWidth*2-2,top, WHITE);
display.drawLine(127-signalWidth-1,64,127-signalWidth-1,top, WHITE);
display.drawLine(127,64,127,top, WHITE);

int thresh_disp = map(thres,0,-70,(64-top),10);
int zeroX = signalWidth*2+8;
int diffY = (64-thresh_disp) - top;
int kneeX = zeroX+thresh_disp;
int kneeY = 64-thresh_disp;
int Xtop = kneeX + diffY*Ratio;

display.drawLine(zeroX,64, kneeX, kneeY, WHITE);   //first slope
display.drawLine(kneeX, kneeY, Xtop,top, WHITE);   //second slope
display.fillRect(127-signalWidth*2-1,top+1,signalWidth,(64-top),BLACK);
display.fillRect(127-signalWidth,top+1,signalWidth,(64-top),BLACK);

  //read the signal input peak
if (rms1.available()){
  peak = rms1.read();
  float peakDisp1 = top+((64-top)*(1-peak));
  display.fillRect(1,peakDisp1,signalWidth,(64),WHITE);
  }

if (rms2.available()) {
  peak_2 = rms2.read();    //Output peak
  float peakDisp2 = top+((64-top)*(1-peak_2));
  display.fillRect(2+signalWidth,peakDisp2,signalWidth,(64),WHITE);
  }
//draw gain reduction
 // (comp2.getCurrentGain_dB());
display.fillRect(127-signalWidth*2-1,top+1,signalWidth,abs(comp1.getCurrentGain_dB()),WHITE);
display.fillRect(127-signalWidth,top+1,signalWidth,abs(comp2.getCurrentGain_dB()),WHITE);
 /////////////////////END PLOTTING///////////////////////////////

 ////// VU meter ////////////
 /*
VUlag++;
if (VUlag >0){
for(int i=3;i<=NUMPIXELS;i++){
  int lvl = 3+(peak_2*12);       //120*7=840
  int grade = 360+peak_2*960;
  //Serial.println(peak_2);
  grade = grade -(120*lvl);
  if (i < lvl){
    pixels.setPixelColor(i, pixels.Color(80,0,0)); // green color.
  }
  else if (i == lvl){
    pixels.setPixelColor(i, pixels.Color(grade,0,0)); // green color.
  }
  else     {
    pixels.setPixelColor(i, pixels.Color(0,0,0)); // no color
  }
}
  pixels.show(); // This sends the updated pixel color to the hardware.
 // VUlag = 0;
}
*/
///////////end VU meter/////////

 // int cpuCap = AudioProcessorUsageMax();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(10, 10);

  display.print("Th:");
  display.print((int)thres);
  display.print("dB");

  display.setCursor(17, 23);
  display.print(Ratio);
  display.print(":1");

  display.setCursor(100, 10);
  display.print("P:");
  display.print(actualPreset);

  display.setCursor(30, 56);
  display.print("A:");
  display.print((int)(attack_1*1000));
  display.print("ms");
  display.setCursor(70, 56);
  display.print(" R:");
  display.print((int)(decay_1*1000));
  display.display();

 /*
   Serial.print(" Last: ");
   Serial.print(Pot1ValueOld);
   Serial.print(" Last: ");
   Serial.println(Pot1Value);

   Serial.print(" Freq2: ");
   Serial.print(freqBand[2]);
   Serial.print(" Freq3: ");
   Serial.print(freqBand[3]);
   Serial.print(" Freq4: ");
   Serial.print(freqBand[4]);
   Serial.print(" Freq5: ");
   Serial.println(freqBand[5]);
   Serial.print(" Peak2: ");
   Serial.println(peak_2);
   */
   Pot1ValueOld = Pot1Value;
   Pot2ValueOld = Pot2Value;
   Pot3ValueOld = Pot3Value;
   Pot4ValueOld = Pot4Value;
   SW1ValueOld = SW1Value;
   SW2ValueOld = SW2Value;
   Tap1ValueOld = Tap1Value;
   Tap2ValueOld = Tap2Value;
   CV1ValueOld = CV1Value;
   CV2ValueOld = CV2Value;
//   modFreqOld = modFreq;
//   spanfreqOld = spanfreq;
//   movingfreqOld = movingfreq;

    //printCPUandMemoryUsage(&Serial);
   //AudioInterrupts();
   //AudioNoInterrupts();
 //  pixels.show();
//printCompressorState(&Serial);
/*  if (notefreq1.available()){
  Serial.println(notefreq1.read());
 }
 */
}

void printCompressorState(Stream *s) {
  s->print("Current Compressor: Pre-Gain (dB) = ");
  s->print(comp1.getPreGain_dB());
  s->print(", Level (dBFS) = ");
  s->print(comp1.getCurrentLevel_dBFS());
  s->print(", ");
  s->print(comp2.getCurrentLevel_dBFS());
  s->print(", Dynamic Gain L/R (dB) = ");
  s->print(comp1.getCurrentGain_dB());
  s->print(", ");
  s->print(comp2.getCurrentGain_dB());
  s->println();
};

void printParameters(Stream *s) {
    s->print("Preset: ");
    s->print(actualPreset);
    s->print(" InputGain: ");
    s->print(inLevel);
    s->print(" Treshold: ");
    s->print(thres);
    s->print(" Ratio: 1: ");
    s->print(Ratio);
    s->print(" Attack: ");
    s->print(attack_1);
    s->print(" Release: ");
    s->println(decay_1);
};
/* fscale
 Floating Point Autoscale Function V0.1
 Paul Badger 2007
 Modified from code by Greg Shakar

 This function will scale one set of floating point numbers (range) to another set of floating point numbers (range)
 It has a "curve" parameter so that it can be made to favor either the end of the output. (Logarithmic mapping)
*/
float fscale( float originalMin, float originalMax, float newBegin, float
newEnd, float inputValue, float curve){

  float OriginalRange = 0;
  float NewRange = 0;
  float zeroRefCurVal = 0;
  float normalizedCurVal = 0;
  float rangedValue = 0;
  boolean invFlag = 0;

  // condition curve parameter
  // limit range

  if (curve > 10) curve = 10;
  if (curve < -10) curve = -10;

  curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
  curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function

  /*
   Serial.println(curve * 100, DEC);   // multply by 100 to preserve resolution
   Serial.println();
   */

  // Check for out of range inputValues
  if (inputValue < originalMin) {
    inputValue = originalMin;
  }
  if (inputValue > originalMax) {
    inputValue = originalMax;
  }

  // Zero Refference the values
  OriginalRange = originalMax - originalMin;

  if (newEnd > newBegin){
    NewRange = newEnd - newBegin;
  }
  else
  {
    NewRange = newBegin - newEnd;
    invFlag = 1;
  }

  zeroRefCurVal = inputValue - originalMin;
  normalizedCurVal  =  zeroRefCurVal / OriginalRange;   // normalize to 0 - 1 float

  /*
  Serial.print(OriginalRange, DEC);
   Serial.print("   ");
   Serial.print(NewRange, DEC);
   Serial.print("   ");
   Serial.println(zeroRefCurVal, DEC);
   Serial.println();
   */

  // Check for originalMin > originalMax  - the math for all other cases i.e. negative numbers seems to work out fine
  if (originalMin > originalMax ) {
    return 0;
  }

  if (invFlag == 0){
    rangedValue =  (pow(normalizedCurVal, curve) * NewRange) + newBegin;

  }
  else     // invert the ranges
  {
    rangedValue =  newBegin - (pow(normalizedCurVal, curve) * NewRange);
  }

  return rangedValue;
}

//************EEPROM functions****************
//This function will write a 2 byte (16bit) uint16_t to the eeprom at
//the specified address to address + 1.
void EEPROMWrite_uint16_t(int address, uint16_t value)
      {
      //Decomposition from a uint16_t to 2 bytes by using bitshift.
      //One = Most significant -> Two = Least significant byte
      byte two = ((value >> 0xFF) & 0xFF);
      byte one = ((value >> 8) & 0xFF);

      //Write the 2 bytes into the eeprom memory.
      EEPROM.write(address, two);
      EEPROM.write(address + 1, one);
      }

long EEPROMRead_uint16_t(int address)
      {
      //Read the 2 bytes from the eeprom memory.

      uint16_t two = EEPROM.read(address);
      uint16_t one = EEPROM.read(address + 1);

      //Return the recomposed uint16_t by using bitshift.
      return ((two << 16) & 0xFF) + ((one << 24) & 0xFFFF);
      }

void printCPUandMemoryUsage(Stream *s) {
  s->print("Usage/Max: ");
  s->print("comp1 CPU = "); s->print(comp1.processorUsage()); s->print("/"); s->print(comp1.processorUsageMax()); s->print(", ");
  s->print("all CPU = " ); s->print(AudioProcessorUsage()); s->print("/");  s->print(AudioProcessorUsageMax()); s->print(", ");
  s->print("Int16 Mem = "); s->print(AudioMemoryUsage()); s->print("/"); s->print(AudioMemoryUsageMax()); s->print(", ");
  s->print("Float Mem = "); s->print(AudioMemoryUsage_F32()); s->print("/"); s->print(AudioMemoryUsageMax_F32()); s->print(", ");
  s->println();
};

/////////////////////////////////////////

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}

//define a function to configure the left and right compressors
void setupMyCompressors(boolean use_HP_filter, float knee_dBFS, float comp_ratio, float attack_sec, float release_sec) {
  comp1.enableHPFilter(use_HP_filter);   comp2.enableHPFilter(use_HP_filter);
  comp1.setThresh_dBFS(knee_dBFS);       comp2.setThresh_dBFS(knee_dBFS);
  comp1.setCompressionRatio(comp_ratio); comp2.setCompressionRatio(comp_ratio);

  float fs_Hz = AUDIO_SAMPLE_RATE;
  comp1.setAttack_sec(attack_sec, fs_Hz);       comp2.setAttack_sec(attack_sec, fs_Hz);
  comp1.setRelease_sec(release_sec, fs_Hz);     comp2.setRelease_sec(release_sec, fs_Hz);
}

error: pathspec 'GrompressorFloat_1_1.ino' did not match any file(s) known to git


Moved RFID related functions to separate file

/*
	All RFID related functions
*/

bool getResponse(unsigned char response[]) {
	int i = 0;

	while (RDM880.available()) {
		response[i] = RDM880.read();
		/*Serial.print(response[i], HEX);
		Serial.print(" ");*/
		i++;
	}
	//Serial.println();

	// 3rd byte of response packet is the STATUS byte, 0x00 means OK
	if (response[statusOffset] == 0x00)
		return true;
	else
		return false;
}
/*
	Reads time data from card and stores it in one 4 byte chunk

	Param: readData - array containing all bytes read from card

	Function: Time is encoded as four 1 byte chunks 0xAA 0xBB 0xCC 0xDD.
			  existingTime is one 4 byte chuck 0x00000000
			  This function XORs the most significant byte with each time byte,
			  and left shifts it 1 byte size every iteration.
			  First iteration: 0x000000AA, Second iteration: 0x0000AABB, etc.

	Returns: existing time from card
*/
unsigned long getTime (unsigned char readData[]) {
	int i = 0;
	unsigned long existingTime = 0;

	for (i = 0; i < numTimeBytes; i++) {
		existingTime = (existingTime << 8) ^ readData[i + timeOffset];
	}

	return existingTime;

}

/*
	Calculates the checksum of a packet to ensure data integrity.

	Param: A[] 		- array containing all bytes in a packet
		   numBytes - number of bytes in the array

	Returns: checksum

*/
unsigned char checksum(unsigned char A[], int numBytes) {
	int i = 0;
	unsigned char BCC = A[i];

	for(i = 1; i < numBytes; i++) {
		BCC = BCC ^ A[i];
	}

	return BCC;
}

/*
	Gets the serial number of an RFID tag.

	Post: Response packet contains OK status and serial number of the tag selected

*/
void getSerialNumber(void) {
	unsigned char A[] = { 0x00, 0x03, CMD_GET_SNR, 0x26, 0x00 };
	unsigned char BCC = checksum( A, sizeof(A)/sizeof(A[0]) );
	unsigned char CMD[] = { STX, 0x00, 0x03, CMD_GET_SNR, 0x26, 0x00, BCC, ETX };
	RDM880.write( CMD, sizeof(CMD)/sizeof(CMD[0]) );
}

/*
	Writes to the selected RFID tag.

	Param: numBlocks 	- number of 16 byte blocks to be written to (max 3)
		   startAddress - address of the first block (0 - 63)
		   time 		- data to be written

	Post: Response packet contains OK status and serial number of the tag written to.

	NOTE: Block 0 contains manufacturer data.
		  Sector trailers (multiples of 4) should also not be written to.
		  i.e. Block 3, 7 and 11 are sector trailers that contain authentication keys.

*/

void writeCard(unsigned char numBlocks, unsigned char startAddress, unsigned long time) {
	int i = 0;
	int j = 24;

	// prepare data to be written, time is in format 0xAABBCCDD
	// timeByte is in format { 0xAA, 0xBB, 0xCC, 0xDD }
	unsigned char timeByte[numTimeBytes];
	for(i = 0; i < numTimeBytes; i++) {
		timeByte[i] = (time >> j) & MSB;
		j -= 8;
	}

	unsigned char A[] = { 0x00, 0x1A, CMD_WRITE, 0x01, numBlocks, startAddress,
						keyA[0], keyA[1], keyA[2], keyA[3], keyA[4], keyA[5],
						0xDD, 0xA1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
						timeByte[0], timeByte[1], timeByte[2], timeByte[3] };
	unsigned char BCC = checksum( A, sizeof(A)/sizeof(A[0]) );
	unsigned char CMD[] = { STX, 0x00, 0x1A, CMD_WRITE, 0x01, numBlocks, startAddress,
						keyA[0], keyA[1], keyA[2], keyA[3], keyA[4], keyA[5],
						0xDD, 0xA1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
						timeByte[0], timeByte[1], timeByte[2], timeByte[3],
						BCC, ETX };

	/*Serial.print("Attempting to write block ");
	Serial.println(startAddress);*/

	RDM880.write( CMD, sizeof(CMD)/sizeof(CMD[0]) );
}

/*
	Reads the selected RFID tag.

	Param: numBlocks	- number of 16 byte blocks to be read (max 3)
		   startAddress - address of first block to read (0 - 63)

	Post: Response packet contains serial number of selected tag and data.

*/
void readCard(unsigned char numBlocks, unsigned char startAddress) {
	int i = 0;
	unsigned char A[] = { 0x00, 0x0A, CMD_READ, 0x01, numBlocks, startAddress,
						keyA[0], keyA[1], keyA[2], keyA[3], keyA[4], keyA[5] };
	unsigned char BCC = checksum( A, sizeof(A)/sizeof(A[0]) );
	unsigned char CMD[] = { STX, 0x00, 0x0A, CMD_READ, 0x01, numBlocks, startAddress,
                          keyA[0], keyA[1], keyA[2], keyA[3], keyA[4], keyA[5], BCC, ETX };

	Serial.println("Reading data...");
	//Serial.println(startAddress);

	RDM880.write( CMD, sizeof(CMD)/sizeof(CMD[0]) );

}

error: pathspec 'module/module_rfid.ino' did not match any file(s) known to git


Added switch_node_v0_1

Added switch_node_v0_1

/* -----------------------------------------------------------------------------
   Switch Node

   Provides control and monitoring of an electrical switch.

   Circuit:
   * RFM12B attached to digital pins 10, 11, 12, 13
   * Battery voltage monitor attached to analog pin 0
   * Switch connected to digital pin 3
   * RF Status LED attached to digital pin 9

   Created 28-MAY-2014 by Jon Brule
----------------------------------------------------------------------------- */

#include <JeeLib.h>
#include <avr/sleep.h>

#define VERSION "v0.1"

#define SERIAL     1     // set to 1 to also report readings on the serial port
#define DEBUG      1     // set to 1 to display each loop() run
#define BAUD_RATE  57600

#define APIN_BATTERY    0     // data connection for battery
#define DPIN_CTRL_LED   3     // LED simulating the swtch
#define DPIN_RF_LED     9     // led indicating rf traffic
#define LED_DELAY       500
#define VDD_RATIO       1.622

#define MEASURE_PERIOD  100   // how often to measure, in tenths of seconds
#define RETRY_PERIOD    10    // how soon to retry if ACK didn't come in
#define RETRY_LIMIT     5     // maximum number of times to retry
#define ACK_TIME        10    // number of milliseconds to wait for an ack
#define REPORT_EVERY    2     // report every N measurement cycles
#define SMOOTH          3     // smoothing factor used for running averages

#define NODEID          3     // node ID used for this unit
#define NETWORKID       99
#define FREQUENCY       RF12_915MHZ

#define RAW_LENGTH      16
#define SWITCH_ZONE     0x02
#define CMD_TYPE        0x01
#define DATA_TYPE       0x02

#define CMD_ON          0x01
#define CMD_OFF         0x02

// set the sync mode to 2 if the fuses are still the Arduino default
// mode 3 (full powerdown) can only be used with 258 CK startup fuses
#define RADIO_SYNC_MODE 2

enum { MEASURE, REPORT, TASK_END };

Scheduler scheduler(TASK_END);

static byte reportCount;    // count up until next report, i.e. packet send

// container for command data
struct CommandData {
    union {
        byte raw[RAW_LENGTH];
        struct {
            byte type;   // command
            byte state;  // swtich state: 0 or 1
        };
    };
};
CommandData cmdData;

// container for sensor data
struct SensorData {
    byte zone;
    byte type;
    byte network;
    byte node;
    union {
        byte raw[RAW_LENGTH];
        struct {
            byte switchState;   // switch state: 0 or 1
            int battery;        // battery voltage
        };
    };
};
SensorData sensorData;

// has to be defined because we're using the watchdog for low-power waiting
ISR(WDT_vect) { Sleepy::watchdogEvent(); }

byte firstTime = true;

//------------------------------------------------------------------------------
// setup the arduino board
//
void setup() {

    #if SERIAL || DEBUG
        Serial.begin(BAUD_RATE);
        Serial.print("\n[switchNode - ");
        Serial.print(VERSION);
        Serial.println("]");
        serialFlush();
    #endif

    setup_sensors();

    pinMode(DPIN_RF_LED, OUTPUT);

    rf12_initialize(NODEID, FREQUENCY, NETWORKID);
    rf12_sleep(RF12_SLEEP);

    reportCount = REPORT_EVERY;     // report right away for easy debugging
    scheduler.timer(MEASURE, 0);    // start the measurement loop going

    sensorData.zone = SWITCH_ZONE;
    sensorData.type = DATA_TYPE;
    sensorData.network = NETWORKID;
    sensorData.node = NODEID;
    for (int i = 0; i< RAW_LENGTH; i++) {
        sensorData.raw[i] = 0x00;
    }
}

//------------------------------------------------------------------------------
// main processing loop
//
void loop() {

    switch (scheduler.pollWaiting()) {

        case MEASURE:
            // reschedule these measurements periodically
            scheduler.timer(MEASURE, MEASURE_PERIOD);

            doMeasure();

            // every so often, a report needs to be sent out
            if (++reportCount >= REPORT_EVERY) {
                reportCount = 0;
                scheduler.timer(REPORT, 0);
            }
            break;

        case REPORT:
            doReport();
            break;
    }

    if (rf12_recvDone() && rf12_crc == 0) {
        for (byte i = 0; i < rf12_len; ++i) {
            if (i < RAW_LENGTH) {
                cmdData.raw[i] = rf12_data[i];
            }
        }
        handleCommand();
    }

}

//------------------------------------------------------------------------------
// blinks the rf led pin
//
static void blink_rf_led(byte pin, int delay_ms) {
    digitalWrite(pin, HIGH);
    delay(delay_ms);
    digitalWrite(pin, LOW);
}

//------------------------------------------------------------------------------
// flushes the serial port
//
static void serialFlush () {
    #if ARDUINO >= 100
        Serial.flush();
    #endif
    delay(2); // make sure tx buf is empty before going back to sleep
}

//------------------------------------------------------------------------------
//
//
static void handleCommand() {
    switch (cmdData.type) {
        case CMD_ON:
            digitalWrite(DPIN_CTRL_LED, HIGH);
            break;
        case CMD_OFF:
            digitalWrite(DPIN_CTRL_LED, LOW);
            break;
    }
}

//------------------------------------------------------------------------------
// utility code to perform simple smoothing as a running average
//
static int smoothedAverage(int prev, int next, byte firstTime =0) {
    return (firstTime) ? next : ((SMOOTH - 1) * prev + next + SMOOTH / 2) / SMOOTH;
}

//------------------------------------------------------------------------------
// readout all the sensors and other values
//
static void doMeasure() {

    // read switch status
    sensorData.switchState = digitalRead(DPIN_CTRL_LED);

    // read battery voltage
    int val = analogRead(APIN_BATTERY);
    int battery = int(val * 0.00488 * VDD_RATIO * 10);
    sensorData.battery = smoothedAverage(sensorData.battery, battery, firstTime);

    firstTime = false;
}

//------------------------------------------------------------------------------
// generate periodic report (i.e. send out a packet and optionally report on
// serial port)
//
static void doReport() {

    rf12_sleep(RF12_WAKEUP);
    rf12_sendNow(0, &sensorData, sizeof sensorData);
    rf12_sendWait(RADIO_SYNC_MODE);
    rf12_sleep(RF12_SLEEP);
    blink_rf_led(DPIN_RF_LED, LED_DELAY);

    #if SERIAL
        Serial.print("SWITCH ");
        Serial.print((int) sensorData.switchState);
        Serial.print(' ');
        Serial.print((int) sensorData.battery);
        Serial.println();
        serialFlush();
    #endif

}

//------------------------------------------------------------------------------
// Initializes the sensors.
//
static void setup_sensors() {
    pinMode(DPIN_CTRL_LED, INPUT);
    pinMode(DPIN_RF_LED, INPUT);
}

error: pathspec 'switch_node_v0_1/switch_node_v0_1.ino' did not match any file(s) known to git


Create Human_tracker_arduino.ino

Create Human_tracker_arduino.ino

//Define pin numbers

//right motor
int m1f = 10;
int m1r = 9;
//left motor
int m2f = 6;
int m2r = 5;
int led = 13;
char value;
int val[3];
int len;
int direc;

void setup()
{
  //start serial communication at Baud rate of 9600
  Serial.begin(9600);
  pinMode(m1f, OUTPUT);
  pinMode(m1r, OUTPUT);
  pinMode(m2f, OUTPUT);
  pinMode(m2r, OUTPUT);
  pinMode(led, OUTPUT);
  digitalWrite(led, HIGH);
}

void execute()
{
  int no;
  int i = 0;

  //convert ASCII value from serial buffer into int
  no = value - '0';
  //Serial.println(no);

  int a, b, c, d;

  /*
    """
    Direction control Index:

    '<' , '>' are the frame check bits for serial communication

    Numbers represent the direction to be moved as per their     	position on numpad
    1: Back Left
    2: Back
    3: Back right
    4: Left
    5: Stay still
    6: Right
    7: Front Left
    8: Forward
    9: Forward right
    """
  */

  switch (no)
  {
    case 0:
      a = 0; b = 100; c = 100; d = 0;
      break;
    case 3:
      a = 0; b = 255; c = 0; d = 100;
      break;
    case 2:
      a = 0; b = 255; c = 0; d = 255;
      break;
    case 1:
      a = 0; b = 100; c = 0; d = 255;
      break;
    case 4:
      a = 255; b = 0; c = 0; d = 0;
      break;
    case 5:
      a = 0; b = 0; c = 0; d = 0;
      break;
    case 6:
      a = 0; b = 0; c = 255; d = 0;
      break;
    case 7:
      a = 255; b = 0; c = 100; d = 0;
      break;
    case 8:
      a = 150; b = 0; c = 150; d = 0;
      break;
    case 9:
      a = 100; b = 0; c = 255; d = 0;
      break;
  }

  analogWrite(m1f, a);
  analogWrite(m1r, b);
  analogWrite(m2f, c);
  analogWrite(m2r, d);
  //delay(255);
}

void loop()
{
  if (Serial.available())
  {
    //Check for frame control bits
    char ch = Serial.read();
    if (ch == '<')
    {
      len = 0;
    }
    else if (ch == '>')
    {
      execute();
      //Serial.println(value);
      len = 1;
    }
    else if (len == 0)
      value = ch;
  }
}

error: pathspec 'Human_tracker_arduino.ino' did not match any file(s) known to git


Add files via upload

Add files via upload

Initial commit

#include "Arduino.h"
#include "Wire.h"

#define DS3231_I2C_ADDRESS 104

// Acknowledgement: The code for reading and writing the DS3231 RTC is copied from http://www.goodliffe.org.uk/arduino/i2c_devices.php

// SCL - pin A5
// SDA - pin A4
// To set the clock, run the sketch and use the serial monitor.
// Enter T1124154091014; the code will read this and set the clock. See the code for full details.
//
byte second, minute, hour, dayOfWeek, day, month, year;
boolean daylightSavingTime;
char weekDay[4];

byte tMSB, tLSB;
float temp3231;

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

void printDigits(byte val, String separator) {
	if (val < 10) {
		Serial.print("0");
	}
	Serial.print(val);
	Serial.print(separator);
}

void loop() {

	watchConsole();

	get3231Date();

	Serial.print(weekDay);
	Serial.print(", ");
	printDigits(day, "/");
	printDigits(month, "-");
	printDigits(year, " - ");
	printDigits(hour, ":");
	printDigits(minute, ":");
	printDigits(second, " - Temp: ");
	Serial.print(get3231Temp());
	if (daylightSavingTime) {
		Serial.print(" ST");
	}
	Serial.println();

	delay(1000);
}

// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val) {
	return ((val / 10 * 16) + (val % 10));
}

void watchConsole() {
	if (Serial.available()) { // Look for char in serial queue and process if found
		if (Serial.read() == 84) {      //If command = "T" Set Date
			set3231Date();
			get3231Date();
			Serial.println(" ");
		}
	}
}

void set3231Date() {
//T(sec)(min)(hour)(dayOfWeek)(dayOfMonth)(month)(year)
//T(00-59)(00-59)(00-23)(1-7)(01-31)(01-12)(00-99)
//Example: 02-Feb-09 @ 19:57:11 for the 3rd day of the week -> T1157193020209
//Sample dates for testing:
// T0000005250316
// T3059017270316 - 30 seconds before start of DST
// T3059017301016 - 30 seconds before end of DST
// T3059225010716 - 30 seconds before new day with DST
// T3059224300616 - 30 seconds before new day on the last day of a month with DST
// T3059234300616 - 30 seconds before new day on the last day of a month with DST, real time on timer chip
// T1124154091014
	second = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48)); // Use of (byte) type casting and ascii math to achieve result.
	minute = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
	hour = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
	dayOfWeek = (byte) (Serial.read() - 48);
	day = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
	month = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
	year = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
	Wire.beginTransmission(DS3231_I2C_ADDRESS);
	Wire.write(0x00);
	Wire.write(decToBcd(second));
	Wire.write(decToBcd(minute));
	Wire.write(decToBcd(hour));
	Wire.write(decToBcd(dayOfWeek));
	Wire.write(decToBcd(day));
	Wire.write(decToBcd(month));
	Wire.write(decToBcd(year));
	Wire.endTransmission();
}

byte dateSunday() {
	byte sunday = day - dayOfWeek;
	if (sunday < 25) {
		sunday += 7;
	}
	return sunday;
}

boolean isDST() {
	switch (month) {
	case 1:
	case 2:
		return false;
	case 3:
		if (day < 25) {
			return false;
		}
		if (dayOfWeek == 7) {
			return (hour < 2) ? false : true;
		}
		return (day < dateSunday()) ? false : true;
	case 10:
		if (day < 25) {
			return true;
		}
		if (dayOfWeek == 7) {
			return (hour >= 2) ? false : true;
		}
		return (day > dateSunday()) ? false : true;
	case 11:
	case 12:
		return false;
	default: return true;	// For dst, no test for the summer months in the switch.
	}
}

byte daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};	// Only months with DST will be used in this array - no need to test for leap year.

void adjustTime() {		// Adjust for daylight saving time (clock is always winter time)
	if (daylightSavingTime) {
		hour += 1;
		if (hour > 23) {
			hour = 0;
			dayOfWeek++;
			if (dayOfWeek > 7) {
				dayOfWeek = 1;
			}
			day++;
			if (day > daysInMonth[month]) {
				day = 1;
				month++;
			}
		}
	}
}

void get3231Date() {
	// send request to receive data starting at register 0
	Wire.beginTransmission(DS3231_I2C_ADDRESS); // 104 is DS3231 device address
	Wire.write(0x00); // start at register 0
	Wire.endTransmission();
	Wire.requestFrom(DS3231_I2C_ADDRESS, 7); // request seven bytes

	if (Wire.available()) {
		second = Wire.read(); // get second
		minute = Wire.read(); // get minutes
		hour = Wire.read();   // get hour
		dayOfWeek = Wire.read();
		day = Wire.read();
		month = Wire.read(); //temp month
		year = Wire.read();

		second = (((second & B11110000) >> 4) * 10 + (second & B00001111)); // convert BCD to decimal
		minute = (((minute & B11110000) >> 4) * 10 + (minute & B00001111)); // convert BCD to decimal
		hour = (((hour & B00110000) >> 4) * 10 + (hour & B00001111)); // convert BCD to decimal (assume 24 hour mode)
		dayOfWeek = (dayOfWeek & B00000111); // 1-7
		day = (((day & B00110000) >> 4) * 10 + (day & B00001111)); // 1-31
		month = (((month & B00010000) >> 4) * 10 + (month & B00001111)); //msb7 is century overflow
		year = (((year & B11110000) >> 4) * 10 + (year & B00001111));
	} else {
		//oh noes, no data!
	}

	daylightSavingTime = isDST();
	adjustTime();

	switch (dayOfWeek) {
	case 1:
		strcpy(weekDay, "Mon");
		break;
	case 2:
		strcpy(weekDay, "Tue");
		break;
	case 3:
		strcpy(weekDay, "Wed");
		break;
	case 4:
		strcpy(weekDay, "Thu");
		break;
	case 5:
		strcpy(weekDay, "Fri");
		break;
	case 6:
		strcpy(weekDay, "Sat");
		break;
	case 7:
		strcpy(weekDay, "Sun");
		break;
	}
}

float get3231Temp() {
	//temp registers (11h-12h) get updated automatically every 64s
	Wire.beginTransmission(DS3231_I2C_ADDRESS);
	Wire.write(0x11);
	Wire.endTransmission();
	Wire.requestFrom(DS3231_I2C_ADDRESS, 2);

	if (Wire.available()) {
		tMSB = Wire.read(); //2's complement int portion
		tLSB = Wire.read(); //fraction portion

		temp3231 = (tMSB & B01111111); //do 2's math on Tmsb
		temp3231 += ((tLSB >> 6) * 0.25); //only care about bits 7 & 8
	} else {
		//oh noes, no data!
	}

	return temp3231;
}

error: pathspec 'SetRTC.ino' did not match any file(s) known to git


Fixed the firmware file

Fixed the firmware file

error: pathspec 'Rev' did not match any file(s) known to git
error: pathspec 'B/electronic_load.ino' did not match any file(s) known to git


Delete ESPArto_pinDefDebounced.ino

Delete ESPArto_pinDefDebounced.ino

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/philbowles/esparto.git/'


3254 Digital motion sensor sketch polls for data less often to prevent flooding the server.

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/myDevicesIoT/Cayenne-Arduino-Library.git/'


Add getting_started example

Add getting_started example

/*
  Demonstrates how to set and get time from the RTC.

  The type tmElements_t and functions like breakTime() are from
  the Time library.
*/

#include <PCF2123.h>

PCF2123 rtc(9); /* Chip enable on pin 9 */

void setup() {
  tmElements_t tm;
  Serial.begin(57600);

  Serial.println("Resetting RTC");
  rtc.reset();

  Serial.println("Setting time to Tue, 08 Nov 2016 23:49:50");

  /* Convert Unix timestamp to tmElements_t */
  breakTime(1478648990, tm);
  rtc.time_set(&tm);
}

/* Print human readable time */
void print_time(tmElements_t t) {
  Serial.print(String("Year ") + (1970 + t.Year));
  Serial.print(String(" Month ") + t.Month);
  Serial.print(String(" Day ") + t.Day);
  Serial.print(String(" Wday ") + t.Wday);
  Serial.print(String(" Hour ") + t.Hour);
  Serial.print(String(" Minute ") + t.Minute);
  Serial.print(String(" Second ") + t.Second);
  Serial.print("\n");
}

void loop() {
  tmElements_t t;

  /* Get and print current time */
  rtc.time_get(&t);
  print_time(t);

  /* Print Unix timestamp */
  Serial.print("Unix time: ");
  Serial.println(makeTime(t));

  delay(1000);
}

error: pathspec 'examples/getting_started/getting_started.ino' did not match any file(s) known to git


Create ReadAndWrite.ino

Create ReadAndWrite.ino

is small sketch for read write .
comments in Italian and English .
enjoy empty_skull ( Nicola Coppola )

/*
 * MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * The library file MFRC522.h has a wealth of useful info. Please read it.
 * The functions are documented in MFRC522.cpp.
 *
 * Based on code Dr.Leong   ( WWW.B2CQSHOP.COM )
 * Created by Miguel Balboa (circuitito.com), Jan, 2012.
 * Rewritten by Søren Thing Andersen (access.thing.dk), fall of 2013 (Translation to English, refactored, comments, anti collision, cascade levels.)
 *
 * Released into the public domain.
 *
 * This sample shows how to setup a block on a MIFARE Classic PICC to be in "Value Block" mode.
 * In Value Block mode the operations Increment/Decrement/Restore and Transfer can be used.
 *
 ----------------------------------------------------------------------------- empty_skull

 - Aggiunti pin per arduino Mega
 - Scritto semplice codice per la scrittura e lettura

 - add pin configuration for arduino mega
 - write simple read/write Code for new entry user

 http://mac86project.altervista.org/

 ----------------------------------------------------------------------------- Nicola Coppola
 * Pin layout should be as follows:
 * Signal     Pin              Pin               Pin
 *            Arduino Uno      Arduino Mega      MFRC522 board
 * ------------------------------------------------------------
 * Reset      9                5                 RST
 * SPI SS     10               53                SDA
 * SPI MOSI   11               52                MOSI
 * SPI MISO   12               51                MISO
 * SPI SCK    13               50                SCK
 *
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);        // Create MFRC522 instance.

void setup() {
        Serial.begin(9600);        // Initialize serial communications with the PC
        SPI.begin();                // Init SPI bus
        mfrc522.PCD_Init();        // Init MFRC522 card
        //Serial.println("Scan a MIFARE Classic PICC to demonstrate Value Blocks.");
}

void loop() {

        // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
        MFRC522::MIFARE_Key key;
        for (byte i = 0; i < 6; i++) {
                key.keyByte[i] = 0xFF;
        }
        // Look for new cards
        if ( ! mfrc522.PICC_IsNewCardPresent()) {
                return;
        }

        // Select one of the cards
        if ( ! mfrc522.PICC_ReadCardSerial()) {
                return;
        }
        // Now a card is selected. The UID and SAK is in mfrc522.uid.

        // Dump UID
        Serial.print("Card UID:");
        for (byte i = 0; i < mfrc522.uid.size; i++) {
                Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
                Serial.print(mfrc522.uid.uidByte[i], HEX);
        }
        Serial.println();

        // Dump PICC type
        byte piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
        Serial.print("PICC type: ");
        Serial.println(mfrc522.PICC_GetTypeName(piccType));
        if (        piccType != MFRC522::PICC_TYPE_MIFARE_MINI
                &&        piccType != MFRC522::PICC_TYPE_MIFARE_1K
                &&        piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
                //Serial.println("This sample only works with MIFARE Classic cards.");
                return;
        }

        // In this sample we use the second sector (ie block 4-7). the first sector is = 0
        // scegliere settore di lettura da 0 = primo settore
        byte sector         = 1;
        // block sector 0-3(sector0) 4-7(sector1) 8-11(sector2)
        // blocchi di scrittura da 0-3(sector0) 4-7(sector1) 8-11(sector2)
        byte valueBlockA    = 4;
        byte valueBlockB    = 5;
        byte valueBlockC    = 6;
        byte trailerBlock   = 7;
        byte status;
        // Authenticate using key A.
        // avvio l'autentificazione A
        //Serial.println("Authenticating using key A...");
        status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
        if (status != MFRC522::STATUS_OK) {
                Serial.print("PCD_Authenticate() failed: ");
                Serial.println(mfrc522.GetStatusCodeName(status));
                return;
        }
        // Authenticate using key B.
        // avvio l'autentificazione B
        //Serial.println("Authenticating again using key B...");
        status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_B, trailerBlock, &key, &(mfrc522.uid));
        if (status != MFRC522::STATUS_OK) {
                Serial.print("PCD_Authenticate() failed: ");
                Serial.println(mfrc522.GetStatusCodeName(status));
                return;
        }

        // Writing new value block A
        // Scrivo i valori per il settore A
        Serial.println("Writing new value block A(4) : the first of the sector TWO ");
                byte value1Block[] = { 1,2,3,4,  5,6,7,8, 9,10,255,12,  13,14,15,16,   valueBlockA,~valueBlockA,valueBlockA,~valueBlockA };
                status = mfrc522.MIFARE_Write(valueBlockA, value1Block, 16);
                if (status != MFRC522::STATUS_OK) {
                        Serial.print("MIFARE_Write() failed: ");
                        Serial.println(mfrc522.GetStatusCodeName(status));
                }
        /*

        // Writing new value block B
        // Scrivo i valori per il settore B
        Serial.println("Writing new value block B");
                byte value2Block[] = { 255,255,255,255,  0,0,0,0, 0,0,0,0,  255,255,255,255,   valueBlockB,~valueBlockB,valueBlockB,~valueBlockB };
                status = mfrc522.MIFARE_Write(valueBlockB, value2Block, 16);
                if (status != MFRC522::STATUS_OK) {
                        Serial.print("MIFARE_Write() failed: ");
                        Serial.println(mfrc522.GetStatusCodeName(status));
                }

        // Writing new value block D
        // Scrivo i valori per il settore C
        Serial.println("Writing new value block C");
                byte value3Block[] = { 255,255,255,255,  0,0,0,0, 0,0,0,0,  255,255,255,255,   valueBlockC,~valueBlockC,valueBlockC,~valueBlockC };
                status = mfrc522.MIFARE_Write(valueBlockC, value3Block, 16);
                if (status != MFRC522::STATUS_OK) {
                        Serial.print("MIFARE_Write() failed: ");
                        Serial.println(mfrc522.GetStatusCodeName(status));
                }

        */

        Serial.println("Read block A(4) : the first of the sector TWO");
        byte buffer[18];
        byte size = sizeof(buffer);
        // change this: valueBlockA , for read anather block
        // cambiate valueBlockA per leggere un altro blocco
        status = mfrc522.MIFARE_Read(valueBlockA, buffer, &size);
        Serial.print("Settore : 0 Valore :");
        Serial.println(buffer[0]);
        Serial.print("Settore : 1 Valore :");
        Serial.println(buffer[1]);
        Serial.print("Settore : 2 Valore :");
        Serial.println(buffer[2]);
        Serial.print("Settore : 3 Valore :");
        Serial.println(buffer[3]);
        Serial.print("Settore : 4 Valore :");
        Serial.println(buffer[4]);
        Serial.print("Settore : 5 Valore :");
        Serial.println(buffer[5]);
        Serial.print("Settore : 6 Valore :");
        Serial.println(buffer[6]);
        Serial.print("Settore : 7 Valore :");
        Serial.println(buffer[7]);
        Serial.print("Settore : 8 Valore :");
        Serial.println(buffer[8]);
        Serial.print("Settore : 9 Valore :");
        Serial.println(buffer[9]);
        Serial.print("Settore :10 Valore :");
        Serial.println(buffer[10]);
        Serial.print("Settore :11 Valore :");
        Serial.println(buffer[11]);
        Serial.print("Settore :12 Valore :");
        Serial.println(buffer[12]);
        Serial.print("Settore :13 Valore :");
        Serial.println(buffer[13]);
        Serial.print("Settore :14 Valore :");
        Serial.println(buffer[14]);
        Serial.print("Settore :15 Valore :");
        Serial.println(buffer[15]);

        //byte value1Block[] = { 1,2,3,4,  5,6,7,8, 9,10,255,12,  13,14,15,16,   valueBlockA,~valueBlockA,valueBlockA,~valueBlockA };
        if (
        buffer[0]  == 1   &&
        buffer[1]  == 2   &&
        buffer[2]  == 3   &&
        buffer[3]  == 4   &&
        buffer[4]  == 5   &&
        buffer[5]  == 6   &&
        buffer[6]  == 7   &&
        buffer[7]  == 8   &&
        buffer[8]  == 9   &&
        buffer[9]  == 10  &&
        buffer[10] == 255 &&
        buffer[11] == 12  &&
        buffer[12] == 13  &&
        buffer[13] == 14  &&
        buffer[14] == 15  &&
        buffer[15] == 16
        ){

        // sel a scrittura è uguale alla lettura allora e stato un successo !!
        Serial.println("Read block A(4) : the first of the sector TWO : success");
        Serial.println(":-)");

        }else{

         //  scrittura Fallita
        Serial.println("Read block A(4) : the first of the sector TWO : no match - write don't work fine ");
        Serial.println(":-( ");

        }

        // risponde successo
        //Serial.println(mfrc522.GetStatusCodeName(status));

        // Dump the result
        //mfrc522.PICC_DumpMifareClassicSectorToSerial(&(mfrc522.uid), &key, sector);

        // Halt PICC
        mfrc522.PICC_HaltA();

        // Stop encryption on PCD
        mfrc522.PCD_StopCrypto1();

}

error: pathspec 'examples/MifareClassicValueBlock/ReadAndWrite.ino' did not match any file(s) known to git


imital computer switch

imital computer switch

//----------------------------------------------------------------------------------------------------------------
// Computer_Switch.ino
//
// This sketch is designed to run on a WeMos D1 mini.  Other controllers may require extensive tweaking.
//
// This runs a small webserver hosting a tiny API to remotely power on or off a computer
// Also supports a rely to electrically isolate the server.
//
// Author - Joshua Villwock
// Created - 2019-05-28
// License - Mozilla Public License 2.0 (Do what you want, credit the author, must release under same license)
//----------------------------------------------------------------------------------------------------------------

// Import required libraries
#include <ESP8266WiFi.h>
#include <aREST.h>
extern "C" {
  #include "user_interface.h"
}

// Create aREST instance
aREST rest = aREST();

// WiFi parameters
const char* ssid = "joshua";
const char* password = "";

// The port to listen for incoming TCP connections
#define LISTEN_PORT           80

// Create an instance of the server
WiFiServer server(LISTEN_PORT);

// Variables to be exposed to the API
int relayOn;

// Declare functions to be exposed to the API
int powerOn(String command);
int flashLed(String command);
int hardReset(String command);

void setup(void)
{
  // Start Serial
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.hostname("ESP_EIDOLON_IPMI");
  wifi_station_set_hostname("ESP_EIDOLON_IPMI");
  delay(100);

  // Init variables and expose them to REST API
  relayOn = 0;
  rest.variable("relayOn",&relayOn);

  // Function to be exposed
  rest.function("power",powerOn);
  rest.function("led",flashLed);
  rest.function("reset",hardReset);

  // Give name & ID to the device (ID should be 6 characters long)
  rest.set_id("1");
  rest.set_name("ESP_EIDOLON_IPMI");

  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());

  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(D4, INPUT);
}

void loop() {
  // Handle REST calls
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while(!client.available()){
    delay(1);
  }
  rest.handle(client);
}

// Custom function accessible by the API
int flashLed(String command) {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  return 1;
}

// Custom function accessible by the API
int powerOn(String command) {
  pinMode(D4, OUTPUT);
  digitalWrite(D4,LOW);
  delay(1500);
  digitalWrite(D4,HIGH);
  pinMode(D4, INPUT);
  return 1;
}

// Custom function accessible by the API
int hardReset(String command) {
  pinMode(D4, OUTPUT);
  digitalWrite(D4,LOW);
  delay(6000);
  digitalWrite(D4,HIGH);
  pinMode(D4, INPUT);
  return 1;
}

error: pathspec 'Computer_Switch/Computer_Switch.ino' did not match any file(s) known to git


Added comments

Added comments

There is a discrepancy between the wiring as shown in the schematic vs the ones in the demonstration. I hope these comments will reduce any confusion.

Thank you to Steve Miller for spotting the descrepancy.

error: pathspec 'Shift' did not match any file(s) known to git
error: pathspec 'Registers/shiftRegisters_Demo2/shiftRegisters_Demo2.ino' did not match any file(s) known to git


Initial Upload

Initial Upload

Initial Upload

// This #include statement was automatically added by the Spark IDE.
#include "FOXFIRE_EmonLib/FOXFIRE_EmonLib.h"

// This #include statement was automatically added by the Spark IDE.
#include "FOXFIRE_BMP085/FOXFIRE_BMP085.h"

// This #include statement was automatically added by the Spark IDE.
#include "FOXFIRE_Si70xx/FOXFIRE_Si70xx.h"

// This #include statement was automatically added by the Spark IDE.
#include "FOXFIRE_Si1132/FOXFIRE_Si1132.h"

// This #include statement was automatically added by the Spark IDE.
#include "FOXFIRE_MPU6050/FOXFIRE_MPU6050.h"

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

// Initialize application variables
int SENSORDELAY = 5000; // milliseconds (runs x1)
int EVENTSDELAY = 1000; // milliseconds (runs x10)
int SLEEP_DELAY = 45; // seconds (runs x1) - should get about 24 hours on 2100mAH - 0 to disable
String SLEEP_DELAY_MIN = "15"; // seconds - easier to store as string then convert to int
String SLEEP_DELAY_STATUS = "OK"; // always OK to start with

int I2CEN = D2;
int ALGEN = D3;
int LED = D7;

int SOUND = A1;
int SOUNDV = 0; //Raw Peak-to-Peak Level/Amplitude

int POWR1 = A2;
int POWR2 = A3;
int POWR3 = A4;
double POWR1V = 0; //Watts
double POWR2V = 0; //Watts
double POWR3V = 0; //Watts

int SOILT = A6;
int SOILTV = 0; //Raw 0-4095

int SOILH = A7;
int SOILHV = 0; //Raw 0-4095

bool BMP180OK = false;
float BMP180Pressure = 0; //hPa
float BMP180Temperature = 0; //Celsius
float BMP180Altitude = 0; //Meters

bool Si7020OK = false;
float Si7020Temperature = 0; //Celsius
float Si7020Humidity = 0; //%Relative Humidity

bool Si1132OK = false;
float Si1132UVIndex = 0; //UV Index scoring is as follows: 1-2  -> Low, 3-5  -> Moderate, 6-7  -> High, 8-10 -> Very High, 11+  -> Extreme
float Si1132Visible = 0; //Lux
float Si1132InfraRd = 0; //Lux

bool ACCELOK = false;
int16_t ax, ay, az;
int16_t gx, gy, gz;

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

// Initialize cloud API float-to-string-hack
// https://community.spark.io/t/get-reads-all-return-same-variable-value/1290/7
// These values are mapped and updated in the postSensingVariableMap() function
char Sound[63] = "0";
char Power[63] = "0.00 0.00 0.00";
char SoilTnH[63] = "0 0";
char PreTAlt[63] = "0.00 0.00 0.00";
char AmbiTnH[63] = "0.00 0.00";
char UVVisIR[63] = "0.00 0.00 0.00";
char AcclXYZ[63] = "0 0 0";
char GyroXYZ[63] = "0 0 0";

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

// Power
EnergyMonitor emon1;
EnergyMonitor emon2;
EnergyMonitor emon3;

// Weather
Adafruit_BMP085_Unified bmp180 = Adafruit_BMP085_Unified(10085);
FOXFIRE_Si70xx si7020;
FOXFIRE_Si1132 si1132;

// MPU6050
// class default I2C address is 0x68
// specific I2C addresses may be passed as a parameter here
// AD0 low = 0x68 (default for InvenSense evaluation board)
// AD0 high = 0x69
MPU6050 mpu6050(0x68);

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

/*
float mapFloat(float x, float in_min, float in_max, float out_min, float out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
*/

void setPinsMode() {
    pinMode(I2CEN, OUTPUT);
    pinMode(ALGEN, OUTPUT);
    pinMode(LED, OUTPUT);

    pinMode(POWR1, INPUT);
    pinMode(POWR2, INPUT);
    pinMode(POWR3, INPUT);

    pinMode(SOILT, INPUT);
    pinMode(SOILH, INPUT);
}

int setSleepDelay(String SLEEP_DELAY_STR) {
    if (SLEEP_DELAY_STR.toInt() > SLEEP_DELAY_MIN.toInt())
    {
        SLEEP_DELAY = SLEEP_DELAY_STR.toInt();
        SLEEP_DELAY_STATUS = "OK";
        return SLEEP_DELAY;
    }
    else
    {
        SLEEP_DELAY_STATUS = "SLEEP DELAY VALUE MUST BE GREATER THAN " + SLEEP_DELAY_MIN + " SECONDS";
        return -1;
    }
}

int readSoundLevel() {
    unsigned int sampleWindow = 50; // Sample window width in milliseconds (50 milliseconds = 20Hz)
    unsigned long endWindow = millis() + sampleWindow;  // End of sample window

    unsigned int signalSample = 0;
    unsigned int signalMin = 1024; // Minimum is the lowest signal below which we assume silence
    unsigned int signalMax = signalMin; // Maximum signal starts out the same as the Minimum signal

    // collect data for milliseconds equal to sampleWindow
    while (millis() < endWindow)
    {
        signalSample = analogRead(SOUND);
        if (signalSample > signalMax)
        {
            signalMax = signalSample;  // save just the max levels
        }
        else if (signalSample < signalMin)
        {
            signalMin = signalSample;  // save just the min levels
        }
    }

    SOUNDV = signalMax - signalMin;  // max - min = peak-peak amplitude

    return 1;
}

int readPower() {
    // If voltage is fixed, e.g. 240V,
    // and resistance is known/assumed,
    // then the only variation is amperage.
    POWR1V = (emon1.calcIrms(1480) * 1000); //Watts
    POWR2V = (emon2.calcIrms(1480) * 1000); //Watts
    POWR3V = (emon3.calcIrms(1480) * 1000); //Watts

    return 1;
}

int readSoilTemperature() {
    SOILTV = analogRead(SOILT);

    return 1;
}

int readSoilHumidity() {
    SOILHV = analogRead(SOILH);

    return 2;
}

int readWeatherBMP180() {
    if (BMP180OK)
    {
        /* Get a new sensor event */
        sensors_event_t event;
        bmp180.getEvent(&event);

        // Read weather measurements from device
        if (event.pressure)
        {
            BMP180Pressure = event.pressure;

            /* First we get the current temperature from the BMP085 */
            bmp180.getTemperature(&BMP180Temperature);

            /* Then convert the atmospheric pressure, SLP and temp to altitude */
            /* Update this next line with the current SLP for better results */
            float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA;
            BMP180Altitude = bmp180.pressureToAltitude(seaLevelPressure, BMP180Pressure, BMP180Temperature);
        }
    }

    return BMP180OK ? 1 : 0;
}

int readWeatherSi7020() {
    if (Si7020OK)
    {
        Si7020Temperature = si7020.readTemperature();
        Si7020Humidity = si7020.readHumidity();
    }

    return Si7020OK ? 2 : 0;
}

int readWeatherSi1132() {
    if (Si1132OK)
    {
        Si1132UVIndex = si1132.readUV() / 100;
        Si1132Visible = si1132.readVisible();
        Si1132InfraRd = si1132.readIR();
    }

    return Si1132OK ? 3 : 0;
}

int readMotion() {
    if (ACCELOK)
    {
        // read raw accel/gyro measurements from device
        mpu6050.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
    }

    return ACCELOK ? 1 : 0;
}

void postSensingVariableMap() {
    sprintf(Sound, "%i", SOUNDV);
    sprintf(Power, "%.2f %.2f %.2f", POWR1V, POWR2V, POWR3V);
    sprintf(SoilTnH, "%i %i", SOILTV, SOILHV);
    sprintf(PreTAlt, "%.2f %.2f %.2f", BMP180Pressure, BMP180Temperature, BMP180Altitude);
    sprintf(AmbiTnH, "%.2f %.2f", Si7020Temperature, Si7020Humidity);
    sprintf(UVVisIR, "%.2f %.2f %.2f", Si1132UVIndex, Si1132Visible, Si1132InfraRd);
    sprintf(AcclXYZ, "%i %i %i", ax, ay, az);
    sprintf(GyroXYZ, "%i %i %i", gx, gy, gz);
}

void postSensingEventPublish() {
    // Publish update events
    // --> up to a burst of 4 at rate of 1 per second
    // --> testing delay of 1.0 seconds after each event
    Spark.publish("Ready", NULL, String(EVENTSDELAY / 1000).toInt() * 8, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("Sound", String(Sound), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("Power", String(Power), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("SoilTnH", String(SoilTnH), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("PreTAlt", String(PreTAlt), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("AmbiTnH", String(AmbiTnH), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("UVVisIR", String(UVVisIR), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("AcclXYZ", String(AcclXYZ), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
    Spark.publish("GyroXYZ", String(GyroXYZ), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);
}

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

void setup() {
    // Open serial over USB
    Serial.begin(9600);

    // Sets the I2C clock speed
    //Wire.setSpeed(CLOCK_SPEED_400KHZ);

    // Initialize IO pins
    setPinsMode();

    // Initialize cloud API variables
    Spark.variable("Sound", &Sound, STRING);
    Spark.variable("Power", &Power, STRING);
    Spark.variable("SoilTnH", &SoilTnH, STRING);
    Spark.variable("PreTAlt", &PreTAlt, STRING);
    Spark.variable("AmbiTnH", &AmbiTnH, STRING);
    Spark.variable("UVVisIR", &UVVisIR, STRING);
    Spark.variable("AcclXYZ", &AcclXYZ, STRING);
    Spark.variable("GyroXYZ", &GyroXYZ, STRING);

    // Initialize cloud API functions
    Spark.function("sleepDelay", setSleepDelay);
}

void loop(void) {
    if (Spark.connected())
    {
        Serial.print("RUSK --> Device --> "); Serial.println(Spark.deviceID());

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

        // Power up sensors
        digitalWrite(I2CEN, HIGH);
        digitalWrite(ALGEN, HIGH);

        // Initialize BMP180
        BMP180OK = bmp180.begin();
        // Initialize Si7020
        Si7020OK = si7020.begin();
        // Initialize Si1132
        Si1132OK = si1132.begin();
        // Initialize MPU6050 and verify connection
        mpu6050.initialize();
        ACCELOK = mpu6050.testConnection();

        // Allow sensors to warm up
        delay(SENSORDELAY);

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

        Serial.print("RUSK --> Sound --> "); Serial.println(readSoundLevel());
        Serial.print("SoundNw:\t"); Serial.println(SOUNDV);

        Serial.print("RUSK --> Power --> "); Serial.println(readPower());
        Serial.print("WattsNw:\t");
        Serial.print(POWR1V); Serial.print("\t");
        Serial.print(POWR2V); Serial.print("\t");
        Serial.println(POWR3V);

        Serial.print("RUSK --> Soil --> "); Serial.println(readSoilTemperature() + readSoilHumidity());
        Serial.print("SoilTem:\t"); Serial.println(SOILTV);
        Serial.print("SoilHum:\t"); Serial.println(SOILHV);

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

        Serial.print("RUSK --> Weather --> "); Serial.println(readWeatherBMP180() + readWeatherSi7020() + readWeatherSi1132());

        // display values
        Serial.print("BMPTemp:\t"); Serial.println(BMP180Temperature);
        Serial.print("BMPPres:\t"); Serial.println(BMP180Pressure);
        Serial.print("BMPAlti:\t"); Serial.println(BMP180Altitude);
        Serial.print("AirTemp:\t"); Serial.println(Si7020Temperature);
        Serial.print("AirHumi:\t"); Serial.println(Si7020Humidity);
        Serial.print("UVIndx0:\t"); Serial.println(Si1132UVIndex);
        Serial.print("Visible:\t"); Serial.println(Si1132Visible);
        Serial.print("InfraRd:\t"); Serial.println(Si1132InfraRd);

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

        Serial.print("RUSK --> Motion --> "); Serial.println(readMotion());

        // display tab-separated accel x/y/z values
        Serial.print("AcclXYZ:\t");
        Serial.print(ax); Serial.print("\t");
        Serial.print(ay); Serial.print("\t");
        Serial.println(az);

        // display tab-separated gyro x/y/z values
        Serial.print("GyroXYZ:\t");
        Serial.print(gx); Serial.print("\t");
        Serial.print(gy); Serial.print("\t");
        Serial.println(gz);

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

        Serial.println("RUSK --> Device --> Post Sensing Activities");

        // run post sensing activity
        digitalWrite(LED, HIGH);
        postSensingVariableMap();
        postSensingEventPublish();
        digitalWrite(LED, LOW);

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

        if (SLEEP_DELAY > 0)
        {
            // Power down sensors
            digitalWrite(I2CEN, LOW);
            digitalWrite(ALGEN, LOW);

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

            Serial.print("RUSK --> Sleep --> "); Serial.println(SLEEP_DELAY);
            Serial.print("RUSK --> Sleep --> "); Serial.println(SLEEP_DELAY_STATUS);

            // publish sleep event
            Spark.publish("Sleep", String(SLEEP_DELAY), SLEEP_DELAY, PRIVATE); delay(EVENTSDELAY);

            // run internal processes and invoke light sleep mode
            Spark.process();
            Spark.sleep(SLEEP_DELAY);
        }
    }
    else
    {
        if (WiFi.ready())
        {
            Spark.connect();
        }
    }
}

error: pathspec 'rusk-r002.ino' did not match any file(s) known to git


Add cycle test sketch

Add cycle test sketch

/*
  Cycles through each LED of the orb
  2011-10-05 <nick.oleary@gmail.com>
  http://opensource.org/licenses/mit-license.php
*/

#define l1rm 0x80
#define l1gm 0x40
#define l1bm 0x20

#define l2rm 0x01
#define l2gm 0x02
#define l2bm 0x04

#define l3rm 0x08
#define l3gm 0x10
#define l3bm 0x20

#define LEDA(r1,g1,b1) PORTD = (PORTD&0x03)|(r1*l1rm)|(g1*l1gm)|(b1*l1bm)
#define LEDB(r2,g2,b2) PORTC = (PORTC&0xF8)|(r2*l2rm)|(g2*l2gm)|(b2*l2bm)
#define LEDC(r3,g3,b3) PORTC = (PORTC&0xC7)|(r3*l3rm)|(g3*l3gm)|(b3*l3bm)

void setup() {
  DDRD = DDRD | B11111100;
  DDRC = DDRC | B00111111;
  delay(1000);
}

void loop() {

  LEDA(HIGH,LOW,LOW);
  delay(500);
  LEDA(LOW,HIGH,LOW);
  delay(500);
  LEDA(LOW,LOW,HIGH);
  delay(500);
  LEDA(LOW,LOW,LOW);

  LEDB(HIGH,LOW,LOW);
  delay(500);
  LEDB(LOW,HIGH,LOW);
  delay(500);
  LEDB(LOW,LOW,HIGH);
  delay(500);
  LEDB(LOW,LOW,LOW);

  LEDC(HIGH,LOW,LOW);
  delay(500);
  LEDC(LOW,HIGH,LOW);
  delay(500);
  LEDC(LOW,LOW,HIGH);
  delay(500);
  LEDC(LOW,LOW,LOW);
}

error: pathspec 'code/orb_cycle_test/orb_cycle_test.ino' did not match any file(s) known to git


add sketch to get MAC address and list visible networks

#include "ESP8266WiFi.h"

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

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  byte mac[6];
  WiFi.macAddress(mac);
  Serial.println("");
  Serial.print("MAC: ");
  Serial.print(mac[0],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.println(mac[5],HEX);
}

void loop()
{

  byte mac[6];
  WiFi.macAddress(mac);
  Serial.println("");
  Serial.print("MAC: ");
  Serial.print(mac[0],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.println(mac[5],HEX);

  Serial.print("Scan start ... ");
  int n = WiFi.scanNetworks();
  Serial.print(n);
  Serial.println(" network(s) found");
  for (int i = 0; i < n; i++)
  {
    Serial.println(WiFi.SSID(i));
  }
  Serial.println();

  delay(5000);
}

error: pathspec 'code/esp-scan/esp-scan.ino' did not match any file(s) known to git


#104 new example to show btree usage.

#104 new example to show btree usage.

/**
 * This list is not designed to replace the collections in the standard library, it is a fairly light collection
 * that works across a very wide range of boards. It is the underpinnings of switches, and we use it the mbed
 * support too. So it is pretty much production ready.
 *
 * Here we create a class that we are going to store in the btree list, items in btree lists are ordered so
 * insertion is a little slow, but retrieval, even by key is very quick - Log(NumItems). It dynamically reallocates
 * if needed too, so there's no need in most cases to fiddle directly with the sizes.
 *
 * The only limitation of putting an item into the btree is that the method getKey() must be implemented by the type
 * that is stored. You can see the default sizes of the list and other parameters in file SimpleCollections.h for
 * advanced users.
 *
 * It is only designed to store small, simple class types that are not polymorphic, however, you can wrap a pointer
 * to a more dynamic class type if you needed too as a field of this class.
 *
 * Important note for advanced users: This list is not thread safe. If you use it within task manager only this is not
 * an issue, but if you use it elsewhere too, it must be protected by some kind of mutex or atomic block.
 */

#include <TaskManagerIO.h>
#include <SimpleCollections.h>

//
// This is the type that we will store in our btree list, it will be stored indexed by it's key, and must implement
// the getKey() method to return the key. In this type the key is an int.
//
class Book {
private:
    int key;
    char name[20];
public:
    // You must include a default constructor that initialises the fields to empty, we store the actual
    // items in the internal array in an initially empty state.
    Book() {
        key = 0;
        name[0]=0;
    }

    // You must include a copy constructor that copies from an existing item. This is needed by the
    // collection to copy items into the internal array.
    Book(const Book& otherBook) {
        strncpy(name, otherBook.name, sizeof name);
        key = otherBook.key;
    };

    // And you'll probably need another constructor to initialise the fields for your own use.
    Book(int bookKey, const char* bookName) {
        strncpy(name, bookName, sizeof(name));
        key = bookKey;
    }

    // you must implement a method that returns the key field with this name, it must return the same type as the
    // key you specify for the list, (IE template parameter 1).
    int getKey() {
        return key;
    }

    // Just return the name we were given earlier
    const char* getName() {
        return name;
    }
};

//
// This is the declaration of the list, we declare it as a list of Book objects keyed using an int.
//
BtreeList<int, Book> myList;

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

    myList.add(Book(3, "All about Arduino"));
    myList.add(Book(2, "All about Xamarin"));
    myList.add(Book(1, "Record players"));

    // This shows us the current list capacity, do not worry if it drops to a very low value as it
    // will reallocate automatically.
    Serial.print("Capacity is now ");
    Serial.println(myList.capacity());

    // Get the index that is CLOSEST to a provided key, it is important to note that it's not an exact match
    Serial.print("The nearest index to key 100 is ");
    Serial.println(myList.nearestLocation(100));

    // now every 10 seconds lets look for a book by it's ID
    taskManager.scheduleFixedRate(10, [] {
        auto book2 = myList.getByKey(2);
        if(book2 != nullptr) {
            Serial.print("Book 2 found: ");
            Serial.println(book2->getName());
        }
        else {
            Serial.println("Book 2 not found");
        }
    }, TIME_SECONDS);

    // now every 15 seconds lets iterate all books in the collection
    taskManager.scheduleFixedRate(15, [] {
        for(bsize_t i = 0; i < myList.count(); ++i) {
            auto book = myList.itemAtIndex(i);
            Serial.print(book->getName());
            Serial.print(", ");
            Serial.println(book->getKey());
        }
    }, TIME_SECONDS);

    // after a minute lets clean down the collection
    taskManager.scheduleOnce(60, [] {
        Serial.println("Now we will tear down the list");
        myList.clear();
    }, TIME_SECONDS);
}

void loop() {
    taskManager.runLoop();
}

error: pathspec 'examples/btreeCollection/btreeCollection.ino' did not match any file(s) known to git


Add gpio-comparison.ino

Add gpio-comparison.ino

// Compare time taken by digitalRead vs. a direct AVR register read for the same pin.

#define TEST_PIN 4 // PD4

uint16_t start = 0, end = 0;

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

  // Wait for serial port to connect
  while (!Serial) {}
  Serial.println();

  // Time 10k digitalRead calls
  start = micros();
  for (int i=0; i<10000; i++)
  {
    digitalRead(PD4);
  }
  end = micros();

  Serial.print("Time (us) for 10000 digitalRead calls: ");
  Serial.println(end - start); // 22640 us

  // Time 10k AVR PIND register reads
  start = micros();
  for (int i=0; i<10000; i++)
  {
    PIND & (1 << PD4); // AVR equivalent to digitalRead(4)
  }
  end = micros();

  Serial.print("Time (us) for 10000 AVR PIND register reads: ");
  Serial.println(end - start); // 3448 us

  pinMode(TEST_PIN, OUTPUT);
  // Time 10k digitalWrite calls
  start = micros();
  for (int i=0; i<10000; i++)
  {
    digitalWrite(TEST_PIN, HIGH);
  }
  end = micros();

  Serial.print("\nTime (us) for 10000 digitalWrite calls: ");
  Serial.println(end - start); // 22640 us

  // Time 10k AVR PIND register writes
  start = micros();
  for (int i=0; i<10000; i++)
  {
    PORTD |= (1 << PD4); // AVR equivalent to digitalRead(4)
  }
  end = micros();

  Serial.print("Time (us) for 10000 AVR PIND register writes: ");
  Serial.println(end - start); // 3448 us
}

void loop()
{
  // digitalWrite(TEST_PIN, !digitalRead(TEST_PIN)); // 56.58 kHz on scope
  PORTD ^= (1 << PD4); // 444.4 kHz on scope
}

error: pathspec 'examples/gpio-comparison/gpio-comparison.ino' did not match any file(s) known to git


Create edison2fiware.ino

Create edison2fiware.ino

//################# LIBRARIES ################
  #include <SPI.h>
  #include <WiFi.h>

  //################# WIFI DETAILS #################
  char ssid[] = "xxx"; //  your network SSID (name)
  char pass[] = "xxx";    // your network password (use for WPA, or use as key for WEP)
  int keyIndex = 0;            // your network key Index number (needed only for WEP)
  int status = WL_IDLE_STATUS;

  //################# NETWORK VARIABLES #################
  // Name of the server we want to connect to
  char server[] = "test.ttcloud.net";
  int port = 8082;
  WiFiClient client;

  //################ FIWARE VARIABLES ################
  int value = 0;
  char alias[] = "l";

  void setup()
  {
    // put your setup code here, to run once:
    // initialize serial communications at 9600 bps:
    Serial.begin(9600);

    while (!Serial) {
      ; // wait for serial port to connect. Needed for Leonardo only
    }
    setupNetwork();
  }

  void loop()
  {
    // read luminosity sensor value on analogic PIN 0
    readSensor();
    // send luminosity value to FIWARE IoT Stack
    postMeasure(alias, value);
    // wait 10s between measures
    delay(10000);

    // if the server's disconnected, stop the client:
    if (!client.connected()) {
      Serial.println();
      Serial.println("Disconnecting from wifi");
      client.stop();
    }
  }

  void setupNetwork()
  {
    Serial.print("Configuring Network...");

    // check for the presence of the shield:
    if (WiFi.status() == WL_NO_SHIELD) {
      Serial.println("WiFi shield not present");
      // don't continue:
      while(true);
    }

    String fv = WiFi.firmwareVersion();
    if( fv != "1.1.0" )
      Serial.println("Please upgrade the firmware");

    // attempt to connect to Wifi network:
    while (status != WL_CONNECTED) {
      Serial.print("Attempting to connect to SSID: ");
      Serial.println(ssid);
      // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
      status = WiFi.begin(ssid, pass);

      // wait 10 seconds for connection:
      delay(10000);
    }
    Serial.println("Connected to wifi");
  }

  void readSensor()
  {
    //Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
    //read the input on analog pin 0:
    value = analogRead(A0);
  }

  void postMeasure(char alias[],int value)
  {
    Serial.println("\nStarting connection to server...");

    // if you get a connection, report back via serial:
    if (client.connect(server, port)) {
      Serial.println("connected to server");
      // Make a HTTP request:
      client.println("POST /iot/d?i=xxxx&k=xxxxx HTTP/1.1");
      client.println("Host: test.ttcloud.net:8082");
      String body = String(alias)+"|"+String(value);
      client.println("Content-Length: "+String(body.length()));
      client.println();
      client.println(body);
    }
  }

error: pathspec 'arduino/edison2fiware.ino' did not match any file(s) known to git