Added comments

Added comments

--- Simon.ino
+++ Simon.ino
@@ -1,18 +1,23 @@
- #include "pitches.h"
+/*
+  A 3 LED Simon Says Game
+*/

+#include "pitches.h"

-const int NUM_LEDS = 3;
-const int speakerPin = 10;
+const int NUM_LEDS = 3; // 3 leds
+const int speakerPin = 10; // speaker connected at pin 10

-int buttonPin[] = {3, 2, 4};
-int ledPin[] = {13, 8, 9};
-int tones[] = {NOTE_C4, NOTE_A4, NOTE_G3};
+int buttonPin[] = {3, 2, 4}; // buttons connected at pins 3, 2, 4
+int ledPin[] = {13, 8, 9};   // LEDS connected at pins 13, 8, 9
+// set the tone for each LED
+int tones[] = {NOTE_C4, NOTE_A4, NOTE_G3};

 int buttonState[] = {HIGH, HIGH, HIGH};
 int lastButtonState[] = {LOW, LOW, LOW};
 boolean buttonOn[] = {false, false};

-int sequence[] = {0, 1, 0, 2, 2, 1, 0};
+// win when completing level 7
+int sequence[] = {0, 0, 0, 0, 0, 0, 0};
 int max_level = 7;
 int level = 1;

@@ -28,6 +33,7 @@
   Serial.begin(9600);
 }

+// generate a random seuqence
 void generateSequence() {
   for (int i = 0; i < max_level; i++) {
     int randLed = random(0, 3);
@@ -35,12 +41,14 @@
   }
 }

-
 void loop(){

   boolean wrong = false;
+  level = 1;
+
   generateSequence();

+  // play until win or loose
   while (!wrong && level <= max_level) {
     playSequence(level);
     wrong = inputFromUser(level);
@@ -53,9 +61,10 @@
   else {
     playWinningSequence();
   }
-  level = 1;
+
 }
-
+
+// play the sequence till the level the user has reached
 void playSequence(int level) {
   for (int i = 0; i < level; i++) {
     int ledNum = sequence[i];
@@ -68,6 +77,7 @@
   }
 }

+// listen to the buttons pressed by the user
 boolean inputFromUser(int level) {
   boolean wrong = false;
   int seqIndex = 0;
@@ -91,6 +101,7 @@
   return wrong;
 }

+// play a tone and light a LED
 void play(int ledNum, int toneValue) {
   tone(speakerPin, toneValue);
   digitalWrite(ledNum, HIGH);
@@ -115,7 +126,6 @@
     int randLed = random(0, 3);
     digitalWrite(ledPin[randLed], HIGH);

-
     // to distinguish the notes, set a minimum time between them.
     // the note's duration + 30% seems to work well:
     int pauseBetweenNotes = noteDuration * 1.30;
@@ -124,18 +134,10 @@
     // stop the tone playing:
     noTone(speakerPin);
   }
-
-  for (int t = 0; t < 5; t++) {
-    for (int i = 0; i < level; i++) {
-      digitalWrite(ledPin[sequence[i]], HIGH);
-      delay(100);
-      digitalWrite(ledPin[sequence[i]], LOW);
-      delay(200);
-    }
-  }
 }

 void playLoosingSequence() {
+  // TODO: add music
   for (int t = 0; t < 5; t++) {
     for (int i = 0; i < level; i++) {
       digitalWrite(ledPin[sequence[i]], HIGH);


Wait at middle position

Wait at middle position

--- Servo.ino
+++ Servo.ino
@@ -3,30 +3,44 @@
 Servo servo;
 unsigned long t0;
 int pulse;
+int wait;
 char dir;

 void setup() {
   servo.attach(6);
   t0 = millis();
-  pulse = 0;
-  dir = 1;
+  pulse = DEFAULT_PULSE_WIDTH;
+  dir = 0;
+  wait = 5000;
 }

 void loop() {
   // use writeMicroseconds, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH
   int dt = millis() - t0;
   t0 += dt;
-  if (dir == 1) {
+  if (dir == 0) {
+    wait -= dt;
+    if (wait < 0) {
+      wait = 5000;
+      dir = 1;
+    };
+  } else if (dir == 1) {
     pulse += dt;
     if (pulse > MAX_PULSE_WIDTH) {
       pulse = MAX_PULSE_WIDTH;
-      dir = 0;
+      dir = 2;
     }
-  } else {
+  } else if (dir == 2) {
     pulse -= dt;
     if (pulse < MIN_PULSE_WIDTH) {
       pulse = MIN_PULSE_WIDTH;
-      dir = 1;
+      dir = 3;
+    }
+  } else {
+    pulse += dt;
+    if (pulse > DEFAULT_PULSE_WIDTH) {
+      pulse = DEFAULT_PULSE_WIDTH;
+      dir = 0;
     }
   };
   servo.writeMicroseconds(pulse);


change to json

change to json

--- Test2.ino
+++ Test2.ino
@@ -58,11 +58,7 @@
   ch_fing = getFingerprintIDez();
   if (ch_fing == 1){
     //Serial.println("User Authenticated !");
-    Serial.print("RFID:");
-    dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size);
-    //Serial.println("");
-    Serial.print("Finger ID:");
-    Serial.print(finger.fingerID);
+    Serial.print("{rfid:" + "\""+dump_byte_array(mfrc522.uid.uidByte, mfrc522.uid.size) + "\",finger_id:" + finger.fingerID +"}");
     tick = tock = millis();
     Ser = 0;
     Serial.flush();
@@ -350,4 +346,4 @@
   if (p != FINGERPRINT_OK)  return -1;
   ID = id;
   return 1;
-}
+}


use nanopb on the arduino

use nanopb on the arduino

--- read_analog_data/read_analog_write_serial/read_analog_write_serial.ino
+++ read_analog_data/read_analog_write_serial/read_analog_write_serial.ino
@@ -1,6 +1,11 @@
+#include <Time.h>
 #include <pb.h>
 #include <pb_encode.h>
+#include <adcvalues.pb.h>

+unsigned short sensorValue0;
+unsigned long runtime;
+unsigned int unixtime;

 void setup() {
   // put your setup code here, to run once:
@@ -11,12 +16,17 @@

 void loop() {
   // put your main code here, to run repeatedly:
-  unsigned int sensorValue0 = analogRead(A0);
-  unsigned long t = millis();
+  sensorValue0 = analogRead(A0);
+  runtime = millis();
+  unixtime = now();

-  Serial.print("{\"t\":");
-  Serial.print(t);
-  Serial.print(", \"adc\":");
-  Serial.print(sensorValue0);
-  Serial.println("}");
-}
+  SerialData message = {runtime, unixtime, sensorValue0};
+
+  uint8_t buffer[16];
+  pb_ostream_t stream = pb_ostream_from_buffer(buffer, sizeof(buffer));
+  pb_encode(&stream, SerialData_fields, &message);
+  for(int i=0; i < stream.bytes_written; i++){
+    Serial.write(buffer[i]);
+  }
+  Serial.write("\n");
+ }


Struggling with UDP multicast.

Struggling with UDP multicast.


Fixes on DEBUG logs... and dvorak layout


fix heartbeat message

fix heartbeat message

--- robots/maproom/maproom.ino
+++ robots/maproom/maproom.ino
@@ -3,7 +3,7 @@

 // Change both of these if the ID of the robot changes
 #define ROBOT_ID 1
-#define HEARTBEAT_MSG "SENMR01HB"
+#define HEARTBEAT_MSG "SENRB01HB"

 // Serial options
 #define HEARTBEAT 1


TemperatureMonitor: version bump to 0.3: using float, updating pins, using faster serial communication


カンマ「,」を送信

カンマ「,」を送信

--- 2_example/example17_ir_rc/example17_ir_rc.ino
+++ 2_example/example17_ir_rc/example17_ir_rc.ino
@@ -67,6 +67,7 @@
         udp.beginPacket(SENDTO, PORT);      // UDP送信先を設定
         udp.print(DEVICE);                  // デバイス名を送信
         udp.print(d_len);                   // 信号長を送信
+        udp.print(",");                     // カンマ「,」を送信
         ir_data2txt(s,64,d,d_len);          // 受信データをテキスト文字に変換
         udp.println(s);                     // それを文字をUDP送信
         Serial.println(s);


dont delay in the loop..duh

dont delay in the loop..duh

--- examples/skynetim_logger/skynetim_logger.ino
+++ examples/skynetim_logger/skynetim_logger.ino
@@ -79,5 +79,5 @@
   //message to log MUST be comma seperated key value pair(s) and may
   //not be be an object or array
   skynetclient.logMessage("\"humidity\":123,\"temperature\":\"21C\"");
-  delay(10000);
+  delay(1000);
 }


Updating Arduino code to use single noise source

--- Arduino/Ziffer/Ziffer.ino
+++ Arduino/Ziffer/Ziffer.ino
@@ -25,8 +25,6 @@
 void takeSample()
 {
   byte pinInput1 = 0;
-  byte pinInput2 = 0;
-  byte combinedInput = 0;
   byte outbyte = 0;
   byte currentByte = 0;

@@ -34,13 +32,9 @@
   for(int j=0; j < 8; j++){
     //Pins are read using registers because its much faster than digitalRead()
     pinInput1 = (PINB >> 3) & B00000001;
-    pinInput2 = (PINB >> 4) & B00000001;
-
-    //Mix the two Z1FFER bits
-    combinedInput = pinInput1 ^ pinInput2;

-    //Add the bit in combinedInput to currentByte
-    currentByte = (combinedInput << j) | currentByte;
+    //Add the bit to currentByte
+    currentByte = (pinInput1 << j) | currentByte;
   }

   //Mix the current byte with the previous one


syntax errors

syntax errors


Update Navigation_Array.ino

Update Navigation_Array.ino

--- Arduino/Navigation_Array.ino
+++ Arduino/Navigation_Array.ino
@@ -63,9 +63,9 @@
     Serial.print(F("INVALID"));
   }
   Serial.print(latitude/samples, 6);
-  Serial.print(F(" "));
+  Serial.print(" ");
   Serial.print(longitude/samples, 6);
-  Serial.println();
+  Serial.print(" ");

 }
 void read_sensors(){
@@ -122,17 +122,35 @@
   if(distance1 <= 200){
     Serial.print("SF ");
     Serial.print(distance1);// In inches
-    Serial.println();
+    Serial.print(" ");
+    //Serial.println();
+  }
+  else{
+    Serial.print("SF ");
+    Serial.print(0);// In inches
+    Serial.print(" ");
   }
   if(distance2 >= 100){
     Serial.print("SL ");
     Serial.print(distance2);// In inches
-    Serial.println();
+    Serial.print(" ");
+    //Serial.println();
+  }
+  else{
+    Serial.print("SL ");
+    Serial.print(0);// In inches
+    Serial.print(" ");
   }
   if(distance3 >= 100){
     Serial.print("SR ");
     Serial.print(distance3);// In inches
-    Serial.println();
+    Serial.print(" ");
+    //Serial.println();
+  }
+  else{
+    Serial.print("SR ");
+    Serial.print(0);// In inches
+    Serial.print(" ");
   }
 }
 //Print gps lat and long
@@ -148,23 +166,28 @@
   {
     Serial.print(F("INVALID"));
   }
-  Serial.println();
+  //Serial.print(" ");
+  //Serial.println();

 }//end print_gps
+

 //Read gps Lat and long
 void read_gps(){
+  while(true){
   while (ss.available() > 0)
-    if (gps.encode(ss.read()))
+    if (gps.encode(ss.read())){
+      //gps.encode(ss.read());
       print_gps();
+      return;
+    }

   if (millis() > 5000 && gps.charsProcessed() < 10)
   {
     Serial.println(F("No GPS detected: check wiring."));
-    while(true);
-  }
-
-
+  }
+
+  }
 }//end read_gps

@@ -175,16 +198,19 @@
   {
     x=(Serial.read()-'0');
   }
-  if(x == 1 || distance1 == 0)
-  {
+  if(x == 1)
+  {
+    print_all();
     calibrate();
     x=0;
   }
   else
   {
     print_all();
-  }
-  read_gps();
-  //delay(150);
-}
-
+    read_gps();
+  }
+
+  Serial.println();
+}
+
+


Cleanup old code, fixed some random generators that were not working

--- ArduinoMotionStairLights.ino
+++ ArduinoMotionStairLights.ino
@@ -1,7 +1,8 @@
 /*
  * Description: Motion activated stair lights.
  * Author: Dean Montgomery
- * Version: 0.2 (Beta)
+ * Version: 0.4 (Beta)
+ * Date: 2015-07-26
  *
  * 2 PIR sesors at the top and bottom of the stairs.
  * WS28012B Addressable RGB lights - 2 LEDs on each stair - This spread out the strip of 30 and left 2-pairs for spare bulbs.
@@ -11,6 +12,7 @@
 */

 #include "FastLED.h"
+#include <avr/eeprom.h>

 #define NUM_LEDS 26
 #define LEDS_PER_STAIR 2        // Number of Leds per stair.  Not yet currenlty changable - just noteable
@@ -33,6 +35,7 @@
 void setup() {
   delay (3000); // Power Up 3 second safety delay.
   //Serial.begin(9600);
+  randomSeed(analogRead(0));
   FastLED.addLeds<WS2812B, PIN_LED, GRB>(leds, NUM_LEDS);  // NOTE set LED string type here.
   pinMode(PIN_PIR_DOWN, INPUT);
   pinMode(PIN_PIR_UP, INPUT);
@@ -67,20 +70,14 @@

 // Cycle through stair walkers.
 void walker(){
-  switch (gLastWalk % 3) {
-    case 0:
-      fade7();
-      break;
-    case 1:
-      flicker();
-      break;
-    default:
-      walk();
-  }
-  if (gLastWalk >= 50){
-    gLastWalk = 0;
-  }else{
-    gLastWalk++;
+  static uint8_t r = 0;
+  r = random8(1, 255); r = random8(1, 255);  // Call random twice - as it wasn't very random.
+  if ( r >= 0 && r <= 100 ){
+    walk(); // My favorite with random variations.
+  } else if ( r > 100 && r <= 175 ){
+    flicker(); // Candle with embers.
+  } else {
+    fade7();
   }
 }

@@ -98,8 +95,9 @@
   }
 }

+
+// Sparkle rainbow welcome give delay to calibrate pir sensors.  This also indicates if program crashed.
 void welcomeRainbow(){
-  // Sparkle rainbow welcome give delay to calibrate pir sensors.  This also indicates if program crashed.
   for ( int i = 0; i < 500; i++ ){
     rainbowWithGlitter();
     FastLED.show();
@@ -113,80 +111,6 @@
       FastLED.delay(1);
     }
   }
-}
-
-void walkold() {
-  static uint8_t hueStart = 208; //purple;
-  static uint8_t hueEnd = 160;
-  static uint8_t hueShift = 0;
-  static uint8_t brightTop = 200;
-  static int i = 0;
-
-  for(gStair=0; gStair < NUM_LEDS; gStair+=2) {
-    // Fade in step
-    hueShift = hueStart;
-    for (gBright=0; gBright<=brightTop; gBright+=2) {
-      leds[gUpDown[gStair]] = CHSV( hueStart, 204, gBright );  // purple
-      leds[gUpDown[gStair + 1]] = CHSV( hueStart, 204, gBright );  // purple
-      if (  gStair >= 2 ) { // slide hue from pruple to blue on previous stair
-        //hueShift = hueShift + ((hueEnd-hueStart)/brightTop*gBright); //=D1+((160-240)/200*10)
-        if ( hueShift >= hueEnd ) {
-          hueShift--;
-          leds[gUpDown[gStair - 1]] = CHSV( hueShift, 204, 200 );
-          leds[gUpDown[gStair - 2]] = CHSV( hueShift, 204, 200 );
-        }
-      }
-      FastLED.show();
-      //FastLED.delay(1);
-    }
-  }
-
-  // Hue shift the last two stairs
-  hueShift = hueStart;
-  for (gBright=0; gBright<=brightTop; gBright+=2) {
-    if ( hueShift >= hueEnd )
-    //hueShift = 1/(hueShift + ((hueEnd-hueStart)/brightTop*bright));
-    hueShift--;
-    leds[gUpDown[NUM_LEDS - 1]] = CHSV( hueShift, 204, 200 );
-    leds[gUpDown[NUM_LEDS - 2]] = CHSV( hueShift, 204, 200 );
-    FastLED.show();
-    //FastLED.delay(1);
-  }
-  //Flash
-  FastLED.delay(500);
-  for(gStair=0; gStair < NUM_LEDS; gStair+=2) {
-    leds[gUpDown[gStair]] = CRGB( 100, 100, 100);
-    leds[gUpDown[gStair + 1]] = CRGB( 100, 100, 100);
-    FastLED.show();
-  }
-  for(gStair=0; gStair < NUM_LEDS; gStair+=2) {
-    leds[gUpDown[gStair]] = CHSV( hueEnd, 204, 200 );
-    leds[gUpDown[gStair+1]] = CHSV( hueEnd, 204, 200 );
-    FastLED.show();
-  }
-
-
-  // Stay on for a bit
-  fill_solid(leds, NUM_LEDS, CHSV( hueEnd, 204, 200 ));
-  //addGlitter(70);
-  FastLED.show();
-  FastLED.delay(5000);
-
-  // Turn off steps
-  for(gStair=0; gStair < NUM_LEDS; gStair+=2) {
-    // Fade in step
-    //hueShift = hueStart;
-    for (gBright=200; gBright>=1; gBright--) {
-      leds[gUpDown[gStair]] = CHSV(hueEnd, 204, gBright);
-      leds[gUpDown[gStair + 1]] = CHSV(hueEnd, 204, gBright);
-      FastLED.show();
-      FastLED.delay(1);
-    }
-    leds[gUpDown[gStair]].setHSV( 0, 0, 0);
-    leds[gUpDown[gStair + 1]].setHSV( 0, 0, 0);
-    FastLED.show();
-  }
-  lightsOn = LOW;
 }

 // Increment to the next color pair in the palette.
@@ -201,16 +125,17 @@
 // Fill a palette with some colors that my wife picked.
 void setPalette(){
   /*
- * Jenn's colors RGB  0 0 81  BLUE
- * 0 100 100 Teal 006464
- * 60 100 100 Cool White 3C6464
- * 60 10 100 Violet 3C0A64
- * 60 0 50 Purple 3C0032
- * start white fades to Teal
- * violet to purple
- * teal to blue
- * red to blue
- */
+   * Jenn's colors RGB  0 0 81  BLUE
+   * 0 100 100 Teal 006464
+   * 60 100 100 Cool White 3C6464
+   * 60 10 100 Violet 3C0A64
+   * 60 0 50 Purple 3C0032
+   * start white fades to Teal
+   * violet to purple
+   * teal to blue
+   * red to blue
+   */
+  uint8_t r = random8(1, 255); // call it once first.
   fill_solid( gPalette, 16, CRGB::Red);
   gPalette[0] = CRGB( 60, 100, 100 ); // Jenn cool white
   gPalette[1] = CRGB( 0, 90, 90 );    // Jenn teal
@@ -234,6 +159,7 @@
   choosePalette();
   CRGB c1 = gPalette[gLastPalette];
   CRGB c2 = gPalette[gLastPalette+1];
+  i = random8(1,255); i = random8(1,255); // bit of seeding
   if ( random8( 5 ) == 3 ){
     c1 = CRGB(random8(100),random8(100),random8(100));
     c2 = CRGB(random8(100),random8(100),random8(100));
@@ -293,8 +219,9 @@

 // Random effects for the walk() stair function.
 void randomEffect(CRGB c1, CRGB c2){
+  int i = 0, x = 0;
+  i = random8(1,255); i = random8(1,255); // bit of seeding
   uint8_t var = random8( 1, 5 );
-  int i = 0, x = 0;
   CRGB trans2 = CRGB::Black;
   FastLED.delay(500); // Wait for it...
   switch (var) {
@@ -424,7 +351,6 @@
   lightsOn = LOW;
 }

-
 // Fade7 effect with each led: r,rb,b,bg,g,gr rgb(white)
 void fade7(){
   const uint8_t mx = BRIGHTNESS;
@@ -499,4 +425,3 @@
   lightsOn = LOW;
 }

-


changed processing code example

changed processing code example

--- src/bmp180-example/bmp180-example.ino
+++ src/bmp180-example/bmp180-example.ino
@@ -132,7 +132,9 @@

 /*
- * import processing.serial.*;
+//the example code for processing to graph a println
+// in 1.6.5 for graph doesnt work. this those i found it in the arduino.cc forums
+ import processing.serial.*;

 Serial myPort;        // The serial port
 int xPos = 1;         // horizontal position of the graph
@@ -172,5 +174,4 @@
     newVal = true;
   }
 }
-*/
  */


lowpower_mote_v0_1: Removed flash sleep test

--- lowpower_mote_v0_1/lowpower_mote_v0_1.ino
+++ lowpower_mote_v0_1/lowpower_mote_v0_1.ino
@@ -1,18 +1,17 @@
 #include <LowPower.h>
 #include <RFM69.h>
 #include <SPI.h>
-#include <SPIFlash.h>

 #define LED 9

 RFM69 radio;
-SPIFlash flash(8, 0xEF30);

 void setup() {
   radio.initialize(RF69_915MHZ, 99, 99);
   radio.setHighPower();
-  flash.initialize();
   pinMode(LED, OUTPUT);
+  PORTD = B00000000;  // enable pullups on pins 2 to 7, leave pins 0 and 1 alone
+  PORTB = B00000000;  // enable pullups on pins 2 to 7, leave pins 0 and 1 alone
 }

 void loop() {
@@ -20,7 +19,5 @@
   delay(4000);
   digitalWrite(LED, LOW);
   radio.sleep();
-  flash.sleep();
   LowPower.powerDown(SLEEP_4S, ADC_OFF, BOD_OFF);
-  flash.wakeup();
 }


Update motor_1.ino

Update motor_1.ino

--- arduino/motor_1.ino
+++ arduino/motor_1.ino
@@ -46,8 +46,6 @@
  }
 void loop()
 {
-           Serial.print("got: ");
-	   Serial.println(angle);

                  Errorcalc();
                 if (abs(Error) <2.2){ // prevent integral 'windup'
@@ -105,7 +103,8 @@
 {
   int x = Wire.read();
   angle = (double) x;
-
+  Serial.print("got: ");
+  Serial.println(angle);
   if(angle == 40) digitalWrite(13, HIGH);
   else digitalWrite(13, LOW);
 }


some changes

some changes

--- laserharp.ino
+++ laserharp.ino
@@ -1,87 +1,41 @@
+
+#include <SerialCommand.h>
+
 #include <Logging.h>
-
-#ifdef GINSING
-#include <GinSing.h>
-#include <GinSingDefs.h>
-#include <GinSingMaster.h>
-#include <GinSingPoly.h>
-#include <GinSingPreset.h>
-#include <GinSingSerial.h>
-#include <GinSingSerialMacros.h>
-#include <GinSingSynth.h>
-#include <GinSingVoice.h>
-
-#include <Wire.h>
-#include <GinSing.h>
-#endif

 #include <Adafruit_MotorShield.h>
 #include "utility/Adafruit_PWMServoDriver.h"

-#include "HarpNoteChoice.h"
-#include "HarpNoteDetection.h"
-
-//When debugging I wanted more information. So ... set this boolean to true
-//to get more stuff printed to the console. When it's true the console dumps LOTS of
-//great stuff - but the code CRAWLS and the laser harp isn't great.
-const boolean debug = false;
-
-boolean gPauseMotor = false;
-
-// Create the motor shield object with the default I2C address
-Adafruit_MotorShield AFMS = Adafruit_MotorShield();
-// Or, create it with a different I2C address (say for stacking)
-// Adafruit_MotorShield AFMS = Adafruit_MotorShield(0x61);
-
-// Connect a stepper motor with 200 steps per revolution (1.8 degree)
-// to motor port #2 (M3 and M4)
-Adafruit_StepperMotor *myMotor = AFMS.getStepper(200, 2);
-
-#ifdef GINSING
-GinSing  GS;
-#define rcvPin  4  // this is the pin used for receiving    ( can be either 4 or 12 )
-#define sndPin  3  // this is the pin used for transmitting ( can be either 3 or 11 )
-#define ovfPin  2  // this is the pin used for overflow control ( can be either 2 or 10 )
-GinSingPoly * poly;
-
-#define GINSING0 0
-#define GINSING1 1
-#endif
-
-const int lightSensorPin = 0;
-const int sonarPin = 1;
-
-const int stepSize = 1;
-const int delayBetweenSteps = 15;
-const int numberNotes = 7;
-
-#ifdef GINSING
-GSNote ginsingNotes[numberNotes + 1];
-#endif
-
-#ifdef ADJUSTER_BUTTONS
-const int buttonApin = 9;
-const int buttonBpin = 8;
-#endif
-
-HarpNoteChoice harpNoteChoice;
-HarpNoteDetection harpNoteDetector;
-
-boolean pluckedNotes[numberNotes];
-int reflectedLightValues[numberNotes];
-
-
-int gLogLevel = LOG_LEVEL_NOOUTPUT;
-//int gLogLevel = LOG_LEVEL_ERRORS;
+#define BAUD             115200
+#define LIGHT_SENSOR_PIN      0
+#define RANGE_SENSOR_PIN      1
+
+#define MIDICMD_NOTEON     0x90 // MIDI command (Note On, Channel 0)
+#define MIDICMD_NOTEOFF    0x80 // MIDI command (Note On, Channel 0)
+
+#define NOTE_COUNT_MAX      100 // kinda a hack to allow static initialization in waitForNote
+
+int  gNoteCount        =   10;
+bool gMute             =   false;
+
+int gMotorStepSize    =   4;
+int gMotorStepsPerRev = 200;
+int gMotorStepDelay   =  10; // set to <= 0 to pause motor
+
+int    gLightAverage     = 0;
+double gLightSensitivity = 5;
+
+//int gLogLevel = LOG_LEVEL_NOOUTPUT;
+int gLogLevel = LOG_LEVEL_ERRORS;
 //int gLogLevel = LOG_LEVEL_INFOS;
 //int gLogLevel = LOG_LEVEL_DEBUG;
 //int gLogLevel = LOG_LEVEL_VERBOSE;

-int gAverageLightReading = 0;
-const unsigned long gBaud = 115200;
-
-#define MIDICMD_NOTEON  0x90 // MIDI command (Note On, Channel 0)
-#define MIDICMD_NOTEOFF 0x80 // MIDI command (Note On, Channel 0)
+Adafruit_MotorShield AFMS = Adafruit_MotorShield();
+Adafruit_StepperMotor *myMotor = AFMS.getStepper(gMotorStepsPerRev, 2);
+
+SerialCommand sCmd;
+

 // buf must be an array with length > segmentCount. This function can write to buf[segmentCount]
 void drawMeter(int value, int maxValue, char * buf, char segmentSymbol = '=', size_t totalSegments = 80)
@@ -116,188 +70,181 @@
   }
 }

+int runningAverage(int average, int sample, int index) {
+
+  unsigned long sum = average * index;
+  sum += sample;
+  return (int)(sum /= (index + 1));
+
+}
+
 int sampleLight(int sampleCount, int interval=2)
 {
-  unsigned long average = analogRead(lightSensorPin);
-  for (int i = 1; i < sampleCount; i++)
+  int average = 0;
+  for (int i = 0; i < sampleCount; i++)
   {
     delay(interval);
-    int sample = analogRead(lightSensorPin);
-    average *= i;
-    average += sample;
-    average /= i + 1;
+    int sample = analogRead(LIGHT_SENSOR_PIN);
+    average = runningAverage(average, sample, i);
     Log.Info("sample %d: %d, average - %d\n", i, sample, average);
   }
   return max(1, (int)average);
 }

+void stepMotor(int directionToStep=FORWARD, int steps = -1)
+{
+  if (steps == -1) steps = gMotorStepSize;
+
+  myMotor->step(steps, directionToStep, DOUBLE);
+}
+
+void setupMotor() {
+  AFMS.begin();  // create with the default frequency 1.6KHz
+  myMotor->setSpeed(250);
+
+  int maxLight = 0;
+  int maxLightStep = 0;
+  for (int i = 0; i < gMotorStepsPerRev; i++) {
+    stepMotor(FORWARD, 1);
+    int sample = sampleLight(10);
+    logMeter(Log, sample, 600, LOG_LEVEL_INFOS);
+    if (sample > maxLight)
+    {
+      maxLight = sample;
+      maxLightStep = i;
+    }
+  }
+  Log.Error("Max light value (%d) at motor step %d\n", maxLight, maxLightStep);
+  stepMotor(FORWARD, maxLightStep + (gMotorStepsPerRev / 8));
+}
+
+void sampleLightCmd()
+{
+  Serial.println(F("Running sampleLightCmd"));
+  Serial.print(F("Before: ")); Serial.println(gLightAverage);
+  gLightAverage = sampleLight(50);
+  Serial.print(F("After:  ")); Serial.println(gLightAverage);
+}
+
+void setLightSensitivityCmd()
+{
+  Serial.println(F("Running setLightSensitivityCmd"));
+  char * str = sCmd.next();
+  if (str && *str)
+  {
+    double val = atof(str);
+    if (val > 1)
+    {
+      Serial.print(F("Before: ")); Serial.println(gLightSensitivity);
+      gLightSensitivity = val;
+      Serial.print(F("After:  ")); Serial.println(gLightSensitivity);
+    }
+    else
+    {
+      Serial.print(F("Invalid value: "));
+      Serial.print(val);
+      Serial.println(F(". Must be > 1."));
+    }
+  }
+  else
+  {
+    Serial.print(F("Invalid input: \""));
+    Serial.print(str);
+    Serial.println(F("\""));
+  }
+}
+
+void setNoteCountCmd()
+{
+  Serial.println(F("Running setNoteCountCmd"));
+  char * str = sCmd.next();
+  if (str && *str)
+  {
+    int val = atoi(str);
+    if (val > 1)
+    {
+      Serial.print(F("Before: ")); Serial.println(gNoteCount);
+      gNoteCount = val;
+      Serial.print(F("After:  ")); Serial.println(gNoteCount);
+    }
+    else
+    {
+      Serial.print(F("Invalid value: "));
+      Serial.print(val);
+      Serial.println(F(". Must be > 1."));
+    }
+  }
+  else
+  {
+    Serial.print(F("Invalid input: \""));
+    Serial.print(str);
+    Serial.println(F("\""));
+  }
+}
+void unrecognizedSerialCmd(const char * cmd)
+{
+  Serial.print(F("Unrecognized serial command: "));
+  Serial.println(cmd);
+}
+
+void setupSerialCommands()
+{
+  sCmd.addCommand("SampleLight", sampleLightCmd);
+  sCmd.addCommand("SetLightSensitivity", setLightSensitivityCmd);
+  sCmd.addCommand("SetNoteCount", setNoteCountCmd);
+  //sCmd.addCommand("PlayNote")
+  sCmd.setDefaultHandler(unrecognizedSerialCmd);
+}
+
 void setup()
 {
-  Log.Init(gLogLevel, gBaud);
-  harpNoteDetector.setNumNotes(numberNotes);
+  Log.Init(gLogLevel, BAUD);

   //For the light sensor
   analogReference(EXTERNAL);

-#ifdef ADJUSTER_BUTTONS
-  pinMode(buttonApin, INPUT_PULLUP);
-  pinMode(buttonBpin, INPUT_PULLUP);
-#endif
-
-  AFMS.begin();  // create with the default frequency 1.6KHz
-  myMotor->setSpeed(250);
+  setupMotor();

   //Get some initial values for each light string
-  gAverageLightReading = sampleLight(50);
-  for (int i = 0; i < numberNotes; i++)
-  {
-    reflectedLightValues[i] = analogRead(lightSensorPin);
-    pluckedNotes[i] = false;
-  }
-
-#ifdef GINSING
-  setupGinSing();
-#endif
-}
-
-#ifdef GINSING
-//This is the code required to get GinSing ready to go.
-void setupGinSing()
-{
-  GS.begin(rcvPin, sndPin, ovfPin);               // start the device (required) and enter preset mode
-  //For preset mode - change this when going to poly mode
-  poly = GS.getPoly();
-  poly->begin();                                    // enter presetmode
-
-  poly->setWaveform(GINSING0, SAWTOOTH);
-  poly->setWaveform(GINSING1, SAWTOOTH);
-
-  setupGinsingNotes();
-}
-
-//These are the notes I want to play with GinSing.
-void setupGinsingNotes()
-{
-  ginsingNotes[0] = C_4;
-  ginsingNotes[1] = D_4;
-  ginsingNotes[2] = E_4;
-  ginsingNotes[3] = F_4;
-  ginsingNotes[4] = G_4;
-  ginsingNotes[5] = A_4;
-  ginsingNotes[6] = B_4;
-}
-#endif
-
-//This code is used to take the sonar reading and convert
-//that into something to change the GinSing note being played.
-int findMultiplier(int height)
-{
-  /*
-    Over 170 = nothing
-    140 = high           80 - 5
-    125 = normal  64 - 4
-    110 = low            48 - 3
-    92 = very low       32 - 2
-    74 = lower          16 - 1
-    62 bottom out
-  */
-  if (height > 135) return 5;
-  if (height > 119) return 4;
-  if (height > 100) return 3;
-  if (height > 80) return 2;
-  //My speaker gets weird at the low values. So I commented that one out.
-  //	if (height > 65) return 1;
-  return 0;
+  gLightAverage = sampleLight(50);
+
+  setupSerialCommands();
 }

 //Read the sonar unit and figure out if the
 //notes should move up or down
 void checkSonar()
 {
-  int height = analogRead(sonarPin);
+  int height = analogRead(RANGE_SENSOR_PIN);

   logMeter(Log, height, 160);

-  if (height > 170)
-  {
-    return;
-  }
-  int multiplier = findMultiplier(height);
-  int baseValue = 16 * multiplier;
-#ifdef GINSING
-  ginsingNotes[0] = (GSNote)baseValue;
-  ginsingNotes[1] = (GSNote)(baseValue + 1);
-  ginsingNotes[2] = (GSNote)(baseValue + 2);
-  ginsingNotes[3] = (GSNote)(baseValue + 3);
-  ginsingNotes[4] = (GSNote)(baseValue + 4);
-  ginsingNotes[5] = (GSNote)(baseValue + 5);
-  ginsingNotes[6] = (GSNote)(baseValue + 6);
-#endif
-}
-
-#ifdef GINSING
-//These two are the notes that Ginsing is currently playing.
-int ginsingNote0 = -1;
-int ginsingNote1 = -1;
-#endif
-
-//FirstNote and SecondNote are the notes we want to be playing.
-void playNote(int firstNote, int secondNote)
-{
-
-  Log.Verbose("Playing notes %d and %d\n", firstNote, secondNote);
-
-  //Pick the notes to be played and which channel to play them on
-#if GINSING
-  harpNoteChoice.pickNotes(ginsingNote0, ginsingNote1, firstNote, secondNote);
-  if (ginsingNote0 == -1)
-  {
-    poly->release(GINSING0);
-  }
-  else
-  {
-    poly->setNote(GINSING0, ginsingNotes[ginsingNote0]);
-    poly->trigger(GINSING0);
-  }
-
-  if (ginsingNote1 == -1)
-  {
-    poly->release(GINSING1);
-  }
-  else
-  {
-    poly->setNote(GINSING1, ginsingNotes[ginsingNote1]);
-    poly->trigger(GINSING1);
-  }
-#endif
-}
+}
+

 void SendMIDI(char cmd, char data1, char data2)
 {
-  Serial.print(cmd);
-  Serial.print(data1);
-  Serial.print(data2);
-}
-
-//Move the motor one step.
-void stepTheMotor(int directionToStep)
-{
-  if (gPauseMotor == false)
-    myMotor->step(stepSize, directionToStep, DOUBLE);
-}
+  if (gMute == false)
+  {
+    Serial.print(cmd);
+    Serial.print(data1);
+    Serial.print(data2);
+  }
+}
+

 void waitForNote(int note)
 {
-  static bool noteStates[numberNotes] = {0};
+  static bool noteStates[NOTE_COUNT_MAX] = {0};
   bool detected = false;
   bool currentlyOn = noteStates[note];
-  unsigned long duration = millis() + delayBetweenSteps;
+  unsigned long duration = millis() + gMotorStepDelay;
   while (millis() < duration)
   {
-    int light = analogRead(lightSensorPin);
+    int light = analogRead(LIGHT_SENSOR_PIN);
     logMeter(Log, light, 600, LOG_LEVEL_INFOS, '.');

-    detected = (light > (gAverageLightReading * 2));
+    detected = (light > (gLightAverage * gLightSensitivity));

     if (currentlyOn != detected)
     {
@@ -313,120 +260,92 @@
   noteStates[note] = detected;
 }

-void checkNotes(int reflectedLightValues[], boolean pluckedNotes[])
-{
-  for (int i = 0; i < numberNotes; i++)
-  {
-    Log.Verbose("%d=%d - ", i, reflectedLightValues[i]);
-  }
-  Log.Verbose("\n");
-
-  //So ... are any light readings different from any others?
-  //To find the anomaly, see how different each string is to every other string.
-  //One or two strings should stand out. Those are the plucked strings.
-  harpNoteDetector.checkNotes(reflectedLightValues, pluckedNotes);
-
-  //So what strings are plucked? Note that if more than two are plucked,
-  //that counts as an error ... if that's the case, just keep playing the current notes
-  //and hope the player gets his act straight.
-  int firstNote = -1;
-  int secondNote = -1;
-  if (harpNoteDetector.getNotes(firstNote, secondNote, pluckedNotes))
-  {
-    if (firstNote >= 0)
-    {
-      Log.Verbose("==============PLUCKED 1: %d\n", firstNote);
-    }
-    if (secondNote >= 0)
-    {
-      Log.Verbose("==============PLUCKED 2: %d\n", secondNote);
-    }
-    playNote(firstNote, secondNote);
-  }
-  else
-  {
-    Log.Verbose("getNotes returned false - more than three notes were counted as plucked.\n");
-  }
-  return;
-}
-
-//Is a button pressed? If so move the motor a bit. This lets the user adjust the laser fan so it's pointing upwards properly.
+void printInfo()
+{
+  Serial.print(F("BAUD                ")); Serial.println(BAUD);
+  Serial.print(F("LIGHT_SENSOR_PIN    ")); Serial.println(LIGHT_SENSOR_PIN);
+  Serial.print(F("RANGE_SENSOR_PIN    ")); Serial.println(RANGE_SENSOR_PIN);
+
+  Serial.print(F("MIDICMD_NOTEON      ")); Serial.println(MIDICMD_NOTEON);
+  Serial.print(F("MIDICMD_NOTEOFF     ")); Serial.println(MIDICMD_NOTEOFF);
+
+  Serial.print(F("NOTE_COUNT_MAX      ")); Serial.println(NOTE_COUNT_MAX);
+
+  Serial.print(F("gNoteCount        = ")); Serial.println(gNoteCount);
+  Serial.print(F("gMute             = ")); Serial.println(gMute ? F("true") : F("false"));
+
+  Serial.print(F("gMotorStepSize    = ")); Serial.println(gMotorStepSize);
+  Serial.print(F("gMotorStepsPerRev = ")); Serial.println(gMotorStepsPerRev);
+  Serial.print(F("gMotorStepDelay   = ")); Serial.println(gMotorStepDelay);
+
+  Serial.print(F("gLightAverage     = ")); Serial.println(gLightAverage);
+  Serial.print(F("gLightSensitivity = ")); Serial.println(gLightSensitivity);
+
+  Serial.print(F("gLogLevel         = ")); Serial.println(gLogLevel);
+}
+
 void checkButtons()
 {
-#ifdef ADJUSTER_BUTTONS
-  if (digitalRead(buttonApin) == LOW)
-  {
-    myMotor->step(stepSize, BACKWARD, DOUBLE);
-  }
-
-  if (digitalRead(buttonBpin) == LOW)
-  {
-    myMotor->step(stepSize, FORWARD, DOUBLE);
-  }
-#else
   while (Serial.available() > 0)
   {
     char c = Serial.read();
+    Serial.print(F("Read character from serial: ")); Serial.println(c);
     switch (c)
     {
       case 'f':
-        myMotor->step(stepSize, FORWARD, DOUBLE);
+        stepMotor(FORWARD);
         break;
       case 'b':
-        myMotor->step(stepSize, BACKWARD, DOUBLE);
+        stepMotor(BACKWARD);
         break;
       case 'p':
-        gPauseMotor = !gPauseMotor;
+        gMotorStepDelay *= -1;
+        break;
+      case 'c':
+        Serial.println("Entering sCmd.readSerial()");
+        sCmd.readSerial();
+        Serial.println("Exited sCmd.readSerial()");
         break;
       case 'l':
         gLogLevel = (gLogLevel + 1) % (LOG_LEVEL_VERBOSE + 1);
         //Log.Init(9600, gLogLevel);
         static const  char* levelStrings[]  = {"DISABLED","VERBOSE", "DEBUG", "INFO", "ERROR"};
-        Serial.print("Log level is "); Serial.println(levelStrings[gLogLevel]);
-      case 'n':
-        SendMIDI(MIDICMD_NOTEON, 0x4a, 0x49);
-        break;
+        Serial.print(F("Log level is ")); Serial.println(levelStrings[gLogLevel]);
       case 'm':
-        SendMIDI(MIDICMD_NOTEOFF, 0x4a, 0x49);
-        break;
+        gMute = !gMute;
+        break;
+      case 'i':
+        printInfo();
+        break;
+      case '\n':
+        break; // ignore newlines
       default:
-        Log.Error("Ignorning unknown command: %c\n", c);
-
-    }
-  }
-#endif
+        Serial.print(F("Ignorning unknown command: ")); Serial.println(c);
+    }
+  }
 }

 void loop()
 {

-  //There must be at least a handful notes for the code below to work right.
-  if (numberNotes < 5)
-  {
-    return;
-  }
-
-  //Run the laser forward, read all values, and see what is there. Note that this pretty much uses one
-  //less note than requested - but the START position counts as a spot. So moving it numberNotes makes that many
-  //strings plus the start string.
-
-  //It's already read the zero item. So read array items 1 through 7.
-  for (int i = 1; i < numberNotes; i++)
-  {
-    stepTheMotor(FORWARD);
-    waitForNote(i);
+  for (int i = 1; i < gNoteCount; i++)
+  {
+    if (gMotorStepDelay > 0) {
+      stepMotor(FORWARD);
+      waitForNote(i);
+    }
   }

   checkSonar();

-  //It just read item 7. So going backwards, read items 6 through zero.
-  for (int i = numberNotes - 2; i >= 0; i--)
-  {
-    stepTheMotor(BACKWARD);
-    waitForNote(i);
+  for (int i = gNoteCount - 2; i >= 0; i--)
+  {
+    if (gMotorStepDelay > 0) {
+      stepMotor(BACKWARD);
+      waitForNote(i);
+    }
   }

   checkButtons();
   checkSonar();
-
-}
+}


Changed pulse duration to 5 ms.

Changed pulse duration to 5 ms.

--- arduino/test/tx_test/tx_test.ino
+++ arduino/test/tx_test/tx_test.ino
@@ -6,7 +6,7 @@
   TX_PIN_1 = 3,
   TX_PIN_2 = 11,
   FREQ = 25000u,  // Hz
-  DURATION = 2u,  // ms
+  DURATION = 5u,  // ms
 };

 void setup() {


Formatei

Formatei

usando o format do sublime para organizar o arquivo

--- codigo.ino
+++ codigo.ino
@@ -28,10 +28,10 @@

 void setup()
 {
-  Serial.begin(9600);
-  irrecv.enableIRIn(); // Start the receiver
-  pinMode(BUTTON_PIN, INPUT);
-  pinMode(STATUS_PIN, OUTPUT);
+    Serial.begin(9600);
+    irrecv.enableIRIn(); // Start the receiver
+    pinMode(BUTTON_PIN, INPUT);
+    pinMode(STATUS_PIN, OUTPUT);
 }

 // Storage for the recorded code
@@ -43,125 +43,151 @@

 // Stores the code for later playback
 // Most of this code is just logging
-void storeCode(decode_results *results) {
-  codeType = results->decode_type;
-  int count = results->rawlen;
-  if (codeType == UNKNOWN) {
-    Serial.println("Received unknown code, saving as raw");
-    codeLen = results->rawlen - 1;
-    // To store raw codes:
-    // Drop first value (gap)
-    // Convert from ticks to microseconds
-    // Tweak marks shorter, and spaces longer to cancel out IR receiver distortion
-    for (int i = 1; i <= codeLen; i++) {
-      if (i % 2) {
-        // Mark
-        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK - MARK_EXCESS;
-        Serial.print(" m");
-      }
-      else {
-        // Space
-        rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK + MARK_EXCESS;
-        Serial.print(" s");
-      }
-      Serial.print(rawCodes[i - 1], DEC);
+void storeCode(decode_results *results)
+{
+    codeType = results->decode_type;
+    int count = results->rawlen;
+    if (codeType == UNKNOWN)
+    {
+        Serial.println("Received unknown code, saving as raw");
+        codeLen = results->rawlen - 1;
+        // To store raw codes:
+        // Drop first value (gap)
+        // Convert from ticks to microseconds
+        // Tweak marks shorter, and spaces longer to cancel out IR receiver distortion
+        for (int i = 1; i <= codeLen; i++)
+        {
+            if (i % 2)
+            {
+                // Mark
+                rawCodes[i - 1] = results->rawbuf[i] * USECPERTICK - MARK_EXCESS;
+                Serial.print(" m");
+            }
+            else
+            {
+                // Space
+                rawCodes[i - 1] = results->rawbuf[i] * USECPERTICK + MARK_EXCESS;
+                Serial.print(" s");
+            }
+            Serial.print(rawCodes[i - 1], DEC);
+        }
+        Serial.println("");
     }
-    Serial.println("");
-  }
-  else {
-    if (codeType == NEC) {
-      Serial.print("Received NEC: ");
-      if (results->value == REPEAT) {
-        // Don't record a NEC repeat value as that's useless.
-        Serial.println("repeat; ignoring.");
-        return;
-      }
+    else
+    {
+        if (codeType == NEC)
+        {
+            Serial.print("Received NEC: ");
+            if (results->value == REPEAT)
+            {
+                // Don't record a NEC repeat value as that's useless.
+                Serial.println("repeat; ignoring.");
+                return;
+            }
+        }
+        else if (codeType == SONY)
+        {
+            Serial.print("Received SONY: ");
+        }
+        else if (codeType == RC5)
+        {
+            Serial.print("Received RC5: ");
+        }
+        else if (codeType == RC6)
+        {
+            Serial.print("Received RC6: ");
+        }
+        else
+        {
+            Serial.print("Unexpected codeType ");
+            Serial.print(codeType, DEC);
+            Serial.println("");
+        }
+        Serial.println(results->value, HEX);
+        codeValue = results->value;
+        codeLen = results->bits;
     }
-    else if (codeType == SONY) {
-      Serial.print("Received SONY: ");
-    }
-    else if (codeType == RC5) {
-      Serial.print("Received RC5: ");
-    }
-    else if (codeType == RC6) {
-      Serial.print("Received RC6: ");
-    }
-    else {
-      Serial.print("Unexpected codeType ");
-      Serial.print(codeType, DEC);
-      Serial.println("");
-    }
-    Serial.println(results->value, HEX);
-    codeValue = results->value;
-    codeLen = results->bits;
-  }
 }

-void sendCode(int repeat) {
-  if (codeType == NEC) {
-    if (repeat) {
-      irsend.sendNEC(REPEAT, codeLen);
-      Serial.println("Sent NEC repeat");
+void sendCode(int repeat)
+{
+    if (codeType == NEC)
+    {
+        if (repeat)
+        {
+            irsend.sendNEC(REPEAT, codeLen);
+            Serial.println("Sent NEC repeat");
+        }
+        else
+        {
+            irsend.sendNEC(codeValue, codeLen);
+            Serial.print("Sent NEC ");
+            Serial.println(codeValue, HEX);
+        }
     }
-    else {
-      irsend.sendNEC(codeValue, codeLen);
-      Serial.print("Sent NEC ");
-      Serial.println(codeValue, HEX);
+    else if (codeType == SONY)
+    {
+        irsend.sendSony(codeValue, codeLen);
+        Serial.print("Sent Sony ");
+        Serial.println(codeValue, HEX);
     }
-  }
-  else if (codeType == SONY) {
-    irsend.sendSony(codeValue, codeLen);
-    Serial.print("Sent Sony ");
-    Serial.println(codeValue, HEX);
-  }
-  else if (codeType == RC5 || codeType == RC6) {
-    if (!repeat) {
-      // Flip the toggle bit for a new button press
-      toggle = 1 - toggle;
+    else if (codeType == RC5 || codeType == RC6)
+    {
+        if (!repeat)
+        {
+            // Flip the toggle bit for a new button press
+            toggle = 1 - toggle;
+        }
+        // Put the toggle bit into the code to send
+        codeValue = codeValue & ~(1 << (codeLen - 1));
+        codeValue = codeValue | (toggle << (codeLen - 1));
+        if (codeType == RC5)
+        {
+            Serial.print("Sent RC5 ");
+            Serial.println(codeValue, HEX);
+            irsend.sendRC5(codeValue, codeLen);
+        }
+        else
+        {
+            irsend.sendRC6(codeValue, codeLen);
+            Serial.print("Sent RC6 ");
+            Serial.println(codeValue, HEX);
+        }
     }
-    // Put the toggle bit into the code to send
-    codeValue = codeValue & ~(1 << (codeLen - 1));
-    codeValue = codeValue | (toggle << (codeLen - 1));
-    if (codeType == RC5) {
-      Serial.print("Sent RC5 ");
-      Serial.println(codeValue, HEX);
-      irsend.sendRC5(codeValue, codeLen);
+    else if (codeType == UNKNOWN /* i.e. raw */)
+    {
+        // Assume 38 KHz
+        irsend.sendRaw(rawCodes, codeLen, 38);
+        Serial.println("Sent raw");
     }
-    else {
-      irsend.sendRC6(codeValue, codeLen);
-      Serial.print("Sent RC6 ");
-      Serial.println(codeValue, HEX);
-    }
-  }
-  else if (codeType == UNKNOWN /* i.e. raw */) {
-    // Assume 38 KHz
-    irsend.sendRaw(rawCodes, codeLen, 38);
-    Serial.println("Sent raw");
-  }
 }

 int lastButtonState;

-void loop() {
-  // If button pressed, send the code.
-  int buttonState = digitalRead(BUTTON_PIN);
-  if (lastButtonState == HIGH && buttonState == LOW) {
-    Serial.println("Released");
-    irrecv.enableIRIn(); // Re-enable receiver
-  }
+void loop()
+{
+    // If button pressed, send the code.
+    int buttonState = digitalRead(BUTTON_PIN);
+    if (lastButtonState == HIGH && buttonState == LOW)
+    {
+        Serial.println("Released");
+        irrecv.enableIRIn(); // Re-enable receiver
+    }

-  if (buttonState) {
-    Serial.println("Pressed, sending");
-    digitalWrite(STATUS_PIN, HIGH);
-    sendCode(lastButtonState == buttonState);
-    digitalWrite(STATUS_PIN, LOW);
-    delay(50); // Wait a bit between retransmissions
-  }
-  else if (irrecv.decode(&results)) {
-    digitalWrite(STATUS_PIN, HIGH);
-    storeCode(&results);
-    irrecv.resume(); // resume receiver
-    digitalWrite(STATUS_PIN, LOW);
-  }
-  lastButtonState = buttonState;
+    if (buttonState)
+    {
+        Serial.println("Pressed, sending");
+        digitalWrite(STATUS_PIN, HIGH);
+        sendCode(lastButtonState == buttonState);
+        digitalWrite(STATUS_PIN, LOW);
+        delay(50); // Wait a bit between retransmissions
+    }
+    else if (irrecv.decode(&results))
+    {
+        digitalWrite(STATUS_PIN, HIGH);
+        storeCode(&results);
+        irrecv.resume(); // resume receiver
+        digitalWrite(STATUS_PIN, LOW);
+    }
+    lastButtonState = buttonState;
 }


Fix disable function

Fix disable function

--- arduino/scetch/scetch.ino
+++ arduino/scetch/scetch.ino
@@ -47,9 +47,7 @@
   delay(periodMillis);
   digitalWrite(eePin, LOW);
   delay(periodMillis);
-  for(byte i = 0; i < 8; i++) {
-    digitalWrite(powerPins[i], LOW);
-  }
+  digitalWrite(adjPowerPin, LOW);
   digitalWrite(prrPin, LOW);
   laserEnabled = false;
   digitalWrite(ledPin, LOW);


Updated App

Updated App

--- MiHome_Hub/MiHome_Hub.ino
+++ MiHome_Hub/MiHome_Hub.ino
@@ -6,12 +6,12 @@
 #include <ArduinoJson.h>
 #include <Ticker.h>
 // WiFi AP Mode library for setup on on the hub
-#include "WiFiManager.h"
+#include "WiFiManager.h"
 // Radio Configs
 #define RF69_FREQ 915.0
-#define RFM69_CS      2
-#define RFM69_IRQ     15
-#define RFM69_RST     16
+#define RFM69_CS      2
+#define RFM69_IRQ     15
+#define RFM69_RST     16
 #define LED           0
 #define FREQUENCY RF69_915MHZ
 RH_RF69 rf69(RFM69_CS, RFM69_IRQ);
@@ -37,21 +37,21 @@
 //const char* password = "";

 // The WiFi Host and PostURL
-const char* postURI = "http://pacific-springs-32410.herokuapp.com/api/data";
+const char* postURI = "http://pacific-springs-32410.herokuapp.com/api/data";
 const char* nodeID = "00000012340987011";

 const char* socketHost = "192.168.50.52";
 const int socketPort = 8888;
 const char* socketPath = "/socket.io/?transport=websocket";

-long previousMillis = 0;
+long previousMillis = 0;
 long interval = 60000;

 int setup_status = 0;
-
+
 void tick()
 {
-  int state = digitalRead(0);
+  int state = digitalRead(0);
   digitalWrite(LED, !state);
 }

@@ -68,32 +68,32 @@
   Serial.println(command);
   Serial.println(data_payload);
   String setup_data = transmit(command);
-  if (setup_data != "") {
+  if (setup_data != "") {
     Serial.println(setup_data);
   } else {
-
-  }
-  webSocket.emit("back", "\"ok\"");
+
+  }
+  webSocket.emit("back", "\"ok\"");
 }
 void webSocketConnect(const char * payload, size_t length) { }

-void setup()
+void setup()
 {
   Wire.begin();
   Serial.begin(9600);
   // Default setup led blinking
-  pinMode(LED, OUTPUT);
-  Blink(LED, 1000, 2);
+  pinMode(LED, OUTPUT);
+  Blink(LED, 1000, 2);
   Blink(LED, 100, 5);
-  Blink(LED, 1000, 2);
+  Blink(LED, 1000, 2);
   // Settle delay
   delay(5000);
   pinMode(0, OUTPUT);
   //Connecting to the WiFi network
   WiFiManager wifiManager;
   wifiManager.setDebugOutput(false);
-  Serial.println();
-  Serial.print("Connecting... ");
+  Serial.println();
+  Serial.print("Connecting... ");
   Serial.println(WiFi.macAddress());
   wifiManager.setAPCallback(configModeCallback);
   wifiManager.autoConnect("MiHome");
@@ -102,7 +102,7 @@
   Serial.println("-----------------------------------------");
   Serial.println("ESP8266 (WiFi): RFM69 TX/RX Hub");
   Serial.println("-----------------------------------------");
-  Serial.println("WiFi Connected => Details: ");
+  Serial.println("WiFi Connected => Details: ");
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   Serial.println("Netmask: ");
@@ -114,7 +114,7 @@
   Serial.println("-----------------------------------------");
   Serial.println();
   delay(2000);
-  // Setuping the pins
+  // Setuping the pins
   pinMode(RFM69_RST, OUTPUT);
   digitalWrite(RFM69_RST, LOW);
   // Reset Radio
@@ -140,7 +140,7 @@
     Serial.println("Setting Frequency Failed!");
   }
   // Sets the power and the encryption key
-  rf69.setTxPower(20, true);
+  rf69.setTxPower(20, true);
   uint8_t key[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
                     0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};
   rf69.setEncryptionKey(key);
@@ -150,8 +150,8 @@

   webSocket.on("connect", webSocketConnect);
   webSocket.on(nodeID, webSocketDeviceCallBack);
-  webSocket.begin(socketHost, socketPort, socketPath);
-}
+  webSocket.begin(socketHost, socketPort, socketPath);
+}

 void parse(String payload,int size,String command) {
   // Creates the JSON object and POST it to the web server
@@ -171,7 +171,7 @@
       if (index == 1) { humidity = strtod(str,NULL); }
       if (index == 2) { co2 = strtod(str,NULL); }
       if (index == 3) { voc = strtod(str,NULL); }
-      if (index == 4) { visible = strtod(str,NULL); }
+      if (index == 4) { visible = strtod(str,NULL); }
     }
     if (command == "data_2") {
       if (index == 0) { light = strtod(str,NULL); }
@@ -203,7 +203,7 @@
     root.printTo(cbuf,sizeof(cbuf));
     Serial.print("Post Payload: ");
     Serial.println(cbuf);
-
+
     String content = cbuf;
     HTTPClient http;
     http.begin(postURI);
@@ -217,7 +217,7 @@
      Serial.println(res);
     }
     http.end();
-    Blink(LED, 100, 5);
+    Blink(LED, 100, 5);
     Serial.println("[Send End]");
   }
 }
@@ -225,7 +225,7 @@
 String transmit(String name) {
   digitalWrite(LED,HIGH);
   char radiopacket[20];
-  name.toCharArray(radiopacket, 20);
+  name.toCharArray(radiopacket, 20);
   //itoa(packetnum++, radiopacket+13, 10);
   Serial.print("Sending - Command Data: ");
   Serial.println(name);
@@ -234,57 +234,57 @@
   uint8_t buf[RH_RF69_MAX_MESSAGE_LEN];
   uint8_t len = sizeof(buf);
   String res = "";
-  if (rf69.waitAvailableTimeout(2000))  {
+  if (rf69.waitAvailableTimeout(2000))  {
     if (rf69.recv(buf, &len)) {
       Serial.print("Response: ");
       Serial.println((char*)buf);
       res = (char*)buf;
-      Blink(LED, 200, 3);
+      Blink(LED, 200, 3);
     } else { }
-  } else {
+  } else {
     Serial.print("No Response?");
     digitalWrite(LED,LOW);
-    Serial.println();
+    Serial.println();
   }
   return res;
 }

 void loop() {
-  // Loops the websocket for the client
+  // Loops the websocket for the client
   webSocket.loop();

   /*if (setup_status) {
     String setup_data = transmit("setup");
-    if (setup_data != "") {
+    if (setup_data != "") {
       Serial.println(setup_data);
     } else {
-
+
     }
     setup_status = 0;
   }*/
-
+
   // Gets the current timestamp in millis()
   unsigned long currentMillis = millis();
   // Check the time pasted to see if match interval
   if(currentMillis - previousMillis > interval) {
     previousMillis = currentMillis;
-
+
     String data_1 = transmit("data_1");
-    if (data_1 != "") {
+    if (data_1 != "") {
       parse(data_1,data_1.length(),"data_1");
     }
-
+
     String data_2 = transmit("data_2");
     if (data_2 != "") {
       parse(data_2,data_2.length(),"data_2");
     }
-
+
     send();
   }
-
+
 }
 void blink(){
-  Serial.println("blinking");
+  Serial.println("blinking");
 }
 void Blink(byte PIN, byte DELAY_MS, byte loops) {
   for (byte i=0; i<loops; i++)  {


マイナス値の対応

マイナス値の対応

--- 2_example/example17_bell/html.ino
+++ 2_example/example17_bell/html.ino
@@ -25,7 +25,7 @@
     client.println("
chimeBells STATUS
");
     if(chime==0) sprintf(s,"
0 (チャイム OFF)
");
     else if(chime>0)  sprintf(s,"
%d (チャイム %d回)
",chime,chime);
-    else sprintf(s,"
%d (エラー)
",chime);
+    else sprintf(s,"
%d (チャイム 単音)
",chime);
     client.println(s);
     client.println("
");
     client.println("
HTTP GET
");


Update BLE_server_authorization.ino

Update BLE_server_authorization.ino

--- cpp_utils/tests/BLETests/Arduino/security/BLE_server/BLE_server_authorization/BLE_server_authorization.ino
+++ cpp_utils/tests/BLETests/Arduino/security/BLE_server/BLE_server_authorization/BLE_server_authorization.ino
@@ -17,7 +17,7 @@
   Serial.begin(115200);
   Serial.println("Starting BLE work!");

-  BLEDevice::init("MyESP32");
+  BLEDevice::init("ESP32");
   BLEServer *pServer = BLEDevice::createServer();
   BLEService *pService = pServer->createService(SERVICE_UUID);
   BLECharacteristic *pCharacteristic = pService->createCharacteristic(
@@ -41,4 +41,4 @@
 void loop() {
   // put your main code here, to run repeatedly:
   delay(2000);
-}+}


Fixed issue with freezing on connect.

Fixed issue with freezing on connect.

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -71,16 +71,6 @@
  */
 void reportError(const char *error_message, const char *buffer)
 {
-  // Replace double quote characters in buffer with single quote.
-  size_t buffer_len = strlen(buffer);
-  for (size_t buffer_idx = 0; buffer_idx < buffer_len; ++buffer_idx)
-  {
-    if (buffer[buffer_idx] = '"')
-    {
-      buffer[buffer_idx] = '\'';
-    }
-  }
-
   // Construct a JSON error message.
   snprintf(output_buffer, OUTPUT_BUFFER_SIZE,
            "{"
@@ -336,10 +326,14 @@
  */
 void motorDecayLoop()
 {
+  // Only run while connected via USB.
+  if (!adk.isReady()) {
+    yield();
+    return;
+  }
+
   // Wait for a fixed time period.
-  rgb_led.B(0);
-  delay(1000);
-  rgb_led.B(1);
+  delay(100);

   // Decay all motors exponentially towards zero speed.
   for (size_t motor_idx = 0; motor_idx < NUM_MOTORS; ++motor_idx) {


Removed symultaneous attach of all servos Changed default delay between rotations to 600ms

--- firmware/firmware.ino
+++ firmware/firmware.ino
@@ -42,14 +42,15 @@
  * Row 1: (16-01) 22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37
  * Row 2: (17-32) 38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53
  *
- *
+ * In windows, an easy way to make an upgrade without using the Arduino IDE is
+ * to adopt XLoader http://xloader.russemotto.com/
  *
  */

 #include <Servo.h>
 #include <SerialCommand.h>

-const String VERSION = "0.8";
+const String VERSION = "0.9";
 const int SERVO_NUMBER = 32;

 const int servoPINS[SERVO_NUMBER] = {37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,
@@ -60,7 +61,7 @@

 int SHAKE = 2; // number of times the servo rotates
-int ROTATION_DELAY = 500; // pause between each motor movement
+int ROTATION_DELAY = 600; // pause between each motor movement
 int GROUP_SIZE = 4; // the size of the group of motors rotating at once

 boolean USE_SERVO = true;
@@ -82,8 +83,6 @@
  Serial.begin(57600);

  setupSerialCommands();
-
- if ( USE_SERVO ) { attachServos(); }//attach all servos

  if ( IR_ON ) {
   digitalWrite(IR_LED_LEFT,HIGH);
@@ -221,18 +220,6 @@

 // ================= ROTATE FUNCTIONS ================== //

-void attachServos() {
-    //this function attaches all servos
-    //it's called at the beginning
-
-  const int DELAY_BTWN_ATTACH = 250;
-
-  for (int i = 0; i < SERVO_NUMBER; i++) {
-    servoarray[i].attach(servoPINS[i]);
-    delay(DELAY_BTWN_ATTACH);
-  }
-}
-
 void moveChannel() {
   //Move only the specified channel (1-SERVO_NUMBER)
   int channel;
@@ -259,6 +246,7 @@
   //move a single servo
   if ( USE_SERVO )
   {
+    servoarray[channel-1].attach(servoPINS[channel-1]);
     for( int s = 0; s < SHAKE; s++)
     {
       servoarray[channel-1].write(0);
@@ -266,6 +254,7 @@
       servoarray[channel-1].write(180);
       delay(ROTATION_DELAY);
     }
+    servoarray[channel-1].detach();
   }

 }
@@ -287,15 +276,21 @@

 void moveServoGroup(int bat[]) {
     //move a group of servo
-    //bat is an array containing the channels to be moved
+    //bat is an array containing the channels to be moved, 1-32 (e.g: 1,2,3,4)
+
+  const int DELAY_BTWN_ATTACH = 10;

   if ( DEBUG_MODE ) {

-    Serial.print("Moving: ");
     for (int i = 0; i<GROUP_SIZE; i++) {
-      Serial.print(String(bat[i]) + " ");
-    }
-    Serial.println("");
+      Serial.print("Moving channel:" + String(bat[i]) + " ");
+      Serial.println(" with PIN: " + String(servoPINS[bat[i]-1]));
+    }
+  }
+
+  for (int i = 0; i < GROUP_SIZE; i++) {
+    servoarray[bat[i]-1].attach(servoPINS[bat[i]-1]);
+    //delay(DELAY_BTWN_ATTACH);
   }

   for( int s = 0; s < SHAKE; s++)
@@ -310,6 +305,13 @@
     }
     delay(ROTATION_DELAY);
   }
+
+  for (int i = 0; i < GROUP_SIZE; i++) {
+    servoarray[bat[i]-1].detach();
+    //delay(DELAY_BTWN_ATTACH);
+  }
+
+
 }

 // ================= PRINT FUNCTIONS ================== //


arduino.ino: Send knock to computer

arduino.ino: Send knock to computer

--- board/arduino/arduino.ino
+++ board/arduino/arduino.ino
@@ -9,8 +9,13 @@
 /* General global value definitions */
 #define ARDUINO_ID 201
 #define C_ID 200
-#define BUFFER_DATA_LENGTH 5
+#define BUFFER_DATA_LENGTH 3
 #define BAUDRATE 9600
+#define LED_PIN 2
+#define LIGHT_SENSOR_PIN A0
+#define TOUCH_SENSOR_PIN 3
+#define BUZZER_PIN 4
+#define PIEZO_PIN A1

 long updateTime = 0;

@@ -19,6 +24,10 @@
   /* Begin communication over Serial Port with a baud
      rate of 9600*/
   Serial.begin(BAUDRATE);
+  pinMode(LED_PIN, OUTPUT);
+  digitalWrite(LED_PIN, HIGH);
+  pinMode(TOUCH_SENSOR_PIN, INPUT);
+  pinMode(BUZZER_PIN, OUTPUT);
 }

 /* Main Arduino loop */
@@ -36,6 +45,7 @@
   if (!(curMillis - updateTime >= updateMilliThreshold)) {
     /* Prevent writing to serial to avoid serial port data overflow */
     writeToSerial = false;
+
   }

   /* Wait for 6 bytes of data to have been sent over serial */
@@ -48,11 +58,14 @@
       /* Read the servoAngles */
       Serial.read();

-      for (int i = 0; i < BUFFER_DATA_LENGTH; i++) {
-        uint8_t data = (uint8_t) Serial.read();
-
-        // TODO: Do something with data
+      uint8_t data = (uint8_t) Serial.read();
+      if(data == 1) {
+        digitalWrite(BUZZER_PIN, HIGH);
+      } else {
+        digitalWrite(BUZZER_PIN, LOW);
       }
+      Serial.read();
+

       /* Force a reply */
       writeToSerial = true;
@@ -63,13 +76,13 @@

   /* When it is possible to reply to serial */
   if (writeToSerial) {
+    updateTime = curMillis;
     /* Identification byte */
     Serial.write(ARDUINO_ID);

-    for (int i = 0; i < BUFFER_DATA_LENGTH; i++) {
-        Serial.write((uint8_t) 0);
-
-        // TODO: Instead of writing zero, write something else
-      }
+    Serial.write(analogRead(LIGHT_SENSOR_PIN) < 800 );
+    Serial.write(digitalRead(TOUCH_SENSOR_PIN));
+    Serial.write(analogRead(PIEZO_PIN) > 600);
+
   }
 }


Changed name from controller to gateway

Changed name from controller to gateway

--- Arduino/MQTTRF/MQTTRF.ino
+++ Arduino/MQTTRF/MQTTRF.ino
@@ -1,4 +1,4 @@
-// MQTTRF Arduino web controller to RF433 transmitter controller
+// MQTTRF Arduino web gateway to RF433 transmitter controller
 // Copyright (c) 2014, Guilherme Ramos <longinus@gmail.com>
 // https://github.com/guibom/WebMQonttrol
 // Released under the MIT license. See LICENSE file for details.
@@ -142,10 +142,10 @@
 void setup()
 {
     Ethernet.begin(mac, ip);
-    if (client.connect("MQTTRF", "home/controller/MQTTRF", 0, 1, STR_OFF)) {
-        //Publish controller abilities and conencted hardware
-        client.publish("home/controller/MQTTRF", (uint8_t *)"on", 2, 1);
-        client.publish("home/controller/MQTTRF/light/1", (uint8_t *)"1", 1, 1);
+    if (client.connect("MQTTRF", "home/gateway/MQTTRF", 0, 1, STR_OFF)) {
+        //Publish gateway abilities and conencted hardware
+        client.publish("home/gateway/MQTTRF", (uint8_t *)"on", 2, 1);
+        client.publish("home/gateway/MQTTRF/light/1", (uint8_t *)"1", 1, 1);

         //Subscriptions
         client.subscribe("home/light/1/#");
@@ -162,4 +162,4 @@
 void loop()
 {
     client.loop();
-}+}


can bus

can bus

--- main/main.ino
+++ main/main.ino
@@ -106,7 +106,7 @@
   Serial.begin(9600);

   //int canbusSpeed = Canbus.init(-1);
-  int can_init = mcp2515_init(CANSPEED_500); //CANSPEED_500 = 1
+  int can_init = mcp2515_init(1); //CANSPEED_500 = 1

   //int msg = mcp2515_check_message();

@@ -175,21 +175,21 @@
   int timeout = 0;
   char message_ok = 0;
   // Prepair message
-  message.id = 0x7D0; //id of 2000, lower priority than other node
-  message.header.rtr = 0;
+  message.id = 0x5e8; //0x5e8; //0x7D0; //id of 2000, lower priority than other node
+  message.header.rtr = 1;
   message.header.length = 8;
-  message.data[0] = 0x02;
-  message.data[1] = 0x01;
+  /*message.data[0] = 0x00;
+  message.data[1] = 0x00;
   message.data[2] = 0x5e8; //MegaSquirt base identifier
   message.data[3] = 0x00;
   message.data[4] = 0x00;
   message.data[5] = 0x00;
   message.data[6] = 0x00;
-  message.data[7] = 0x00;
+  message.data[7] = 0x00;*/

   mcp2515_bit_modify(CANCTRL, (1<<REQOP2)|(1<<REQOP1)|(1<<REQOP0), 0);

-  if(mcp2515_send_message(&message)) {
+  /*if(mcp2515_send_message(&message)) {
     Serial.println("send_message true");
   }
   else {
@@ -197,19 +197,32 @@
   }
   if (mcp2515_check_message()) {
     Serial.println("check_message success");
-    if (mcp2515_get_message(&message)) {
-      Serial.println("get_message success");
-      Serial.print("message: ");
-      Serial.println(message.data[0]);
-      return (int)message.data[3];
-    }
+
   }
   else {
     Serial.println("check_message false");
   }
-  delay(1500);
-}
-
-
-
-
+*/
+  if (mcp2515_get_message(&message)) {
+    Serial.println("get_message success");
+    Serial.print("message: ");
+    Serial.println(message.data[0]);
+    return (int)message.data[3];
+  }
+  else {
+    Serial.println("get_message false");
+    Serial.println(message.data[0]);
+    Serial.println(message.data[1]);
+    Serial.println(message.data[2]);
+    Serial.println(message.data[3]);
+    Serial.println(message.data[4]);
+    Serial.println(message.data[5]);
+    Serial.println(message.data[6]);
+    Serial.println(message.data[7]);
+  }
+  delay(5000);
+}
+
+
+
+


added termination

added termination


bug in the http interface class

bug in the http interface class

--- src/sonoff-interface-http.ino
+++ src/sonoff-interface-http.ino
@@ -22,7 +22,6 @@
   String _status = "{'status':'success'}";

   if (server.args()==1) {
-      ESP.restart();
     if (server.arg(0)=="on") {
       Relay.on();
     } else if (server.arg(0)=="off") {
@@ -30,6 +29,7 @@
     } else if (server.arg(0)=="configurationMode") {
       Sonoff.toggle();
     } else if (server.arg(0)=="reboot") {
+       ESP.restart();
     } else {
       _status = "{'status':'not implemented'}";
     }


Fixed typo

Fixed typo

--- Keypad/CustomKeypad/CustomKeypad.ino
+++ Keypad/CustomKeypad/CustomKeypad.ino
@@ -18,8 +18,8 @@
   {'7','8','9','C'},
   {'*','0','#','D'}
 };
-byte rowPins[COLS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
-byte colPins[ROWS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad
+byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
+byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad

 //initialize an instance of class NewKeypad
 Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);


Fixed a plain wrong assignments that was causing scope errors.


シリアル通信でRGB値を取得してLEDを制御

シリアル通信でRGB値を取得してLEDを制御

--- arduino-neopixel.ino
+++ arduino-neopixel.ino
@@ -12,7 +12,8 @@
 //   NEO_KHZ800  800 KHz bitstream (e.g. High Density LED strip)
 Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, 6, NEO_GRB + NEO_KHZ800);

-char input[30];   // 文字列格納用
+char input[11];   // 文字列格納用
+String input_str;   // 文字列格納用
 int i = 0;  // 文字数のカウンタ
 boolean serialAvailable = true;

@@ -37,55 +38,18 @@
 //  rainbow(DELAY_TIME2);
 //  rainbowCycle(DELAY_TIME2);

-//  int c;
-//  if (Serial.available()) {
-//    c = int(Serial.read());
-//    Serial.println(c);
-////    if(c==1){      colorWipe(strip.Color(MAX_VAL, 0, 0), DELAY_TIME); }
-////    else if(c==2){ colorWipe(strip.Color(0, MAX_VAL, 0), DELAY_TIME); }
-////    else if(c==3){ colorWipe(strip.Color(0, 0, MAX_VAL), DELAY_TIME); }
-////    else {           colorWipe(strip.Color(0, 0, 0), DELAY_TIME);     }
-//    switch (c) {
-//      case 1:
-//        colorWipe(strip.Color(MAX_VAL, 0, 0), DELAY_TIME); // Red
-//        break;
-//      case 2:
-//        colorWipe(strip.Color(0, MAX_VAL, 0), DELAY_TIME); // Green
-//        break;
-//      case 3:
-//        colorWipe(strip.Color(0, 0, MAX_VAL), DELAY_TIME); // Blue
-//        break;
-//      default:
-//        colorWipe(strip.Color(0, 0, 0), DELAY_TIME); // Black
-//    }
-//  }
-
-  if (Serial.available()) {
-    input[i] = Serial.read();
-    Serial.println(input[i]);
-    // 255.255.255
-    if (11 <= i) {
-
-      String input_str = input;
-      int r = input_str.substring(0,3).toInt();
-      int g = input_str.substring(4,7).toInt();
-      int b = input_str.substring(8,11).toInt();
-
-      colorWipe(strip.Color(r, g, b), DELAY_TIME2);
-
-      // 末尾に終端文字の挿入
-//      input[i] = '\0';
-      // 受信文字列を送信
-//      Serial.println(input);
-//      Serial.println(r);
-//      Serial.println(g);
-//      Serial.println(b);
-//      Serial.println("---");
-
-      // カウンタの初期化
-      i = 0;
-    }
-    else { i++; }
+  if (0<Serial.available()) {
+    String str = Serial.readStringUntil('\n');
+    int r = str.substring(0,3).toInt();
+    int g = str.substring(4,7).toInt();
+    int b = str.substring(8,11).toInt();
+    Serial.print("R:");
+    Serial.println(r);
+    Serial.print("G:");
+    Serial.println(g);
+    Serial.print("B:");
+    Serial.println(b);
+    color(strip.Color(r, g, b));
   }
 }

@@ -102,6 +66,13 @@
   }
  }
   return found>index ? data.substring(strIndex[0], strIndex[1]) : "";
+}
+
+void color(uint32_t c) {
+  for(uint16_t i=0; i<strip.numPixels(); i++) {
+    strip.setPixelColor(i, c);
+  }
+  strip.show();
 }

 // Fill the dots one after the other with a color


led display no longer flickers! interrupts ftw

--- Thermostat/Thermostat.ino
+++ Thermostat/Thermostat.ino
@@ -19,6 +19,8 @@
 const int lowTemp = 138;
 const int highTemp = 142;

+volatile float temperatureInF;
+
 LedDisplay ledDisplay(segmentShiftRegisterClockPin, registerClockPin, whichSegmentDataPin,digitShiftRegisterClockPin, registerClockPin, whichDigitDataPin);
 AsyncTemperatureSensor sensor(temperatureSensorPin);

@@ -31,17 +33,23 @@
   pinMode(heatOnPin, OUTPUT);
   pinMode(deviceLedPin, OUTPUT);

+  OCR0A = 0xAF;
+  TIMSK0 |= _BV(OCIE0A);
+
   sensor.Start();
   ledDisplay.Start();
+}
+
+SIGNAL(TIMER0_COMPA_vect)
+{
+  ledDisplay.SetValue(temperatureInF);
+  ledDisplay.Update();
 }

 void loop()
 {
   sensor.Update();
-
-  float temperatureInF = sensor.GetTempF();
-  ledDisplay.SetValue(temperatureInF);
-  ledDisplay.Update();
+  temperatureInF = sensor.GetTempF();

   if (temperatureInF < lowTemp)
   {


Tweet language

Tweet language

--- hvacMonitor.ino
+++ hvacMonitor.ino
@@ -120,8 +120,8 @@
   timer.setInterval(2500L, sendTemps); // Temperature sensor polling interval
   timer.setInterval(2500L, sendBlowerStatus); // Blower fan status polling interval
   timer.setInterval(5000L, sendHeartbeat); // Blinks Blynk LED to reflect online status
-  timer.setInterval(300000L, sendWU); // 5 minutes between Wunderground API calls.
-  timer.setInterval(330000L, sendWUtoBlynk); // 5ish minutes between API data updates to Blynk.
+  timer.setInterval(180000L, sendWU); // 3 minutes between Wunderground API calls.
+  //timer.setInterval(330000L, sendWUtoBlynk); // 5ish minutes between API data updates to Blynk.
   timer.setInterval(1000L, countRuntime);  // Counts blower runtime for daily accumulation displays.
   timer.setInterval(1000L, totalRuntime);  // Counts blower runtime for daily EEPROM storage.
   timer.setInterval(500L, timeKeeper);
@@ -255,6 +255,7 @@

   // Kept this because I haven't quite figured out how to keep ESP from crashing without it.
   if (showWeather(respBuf)) {
+    timer.setTimeout(5000L, sendWUtoBlynk); // Send update to Blynk app shortly after API update.
     delay(DELAY_NORMAL);
   }
   else {
@@ -576,7 +577,7 @@
   // Resets the timer on the next day if the blower is running.
   else if (digitalRead(blowerPin) == LOW && todaysDate != day())
   {
-    Blynk.tweet(String("On ") + yesterdaysMonth + "/" + yesterdaysDate + "/" + year() + " the A/C ran for " + currentRuntimeMin + " minutes total. Airport was " + dailyOutsideHigh + "°F/" + dailyOutsideLow + "°F."); // Tweet total runtime and outdoor high/low.
+    Blynk.tweet(String("On ") + yesterdaysMonth + "/" + yesterdaysDate + "/" + year() + " the A/C ran for " + currentRuntimeMin + " minutes total. Outside was " + dailyOutsideHigh + "°F/" + dailyOutsideLow + "°F."); // Tweet total runtime and outdoor high/low.
     dailyOutsideHigh = 0;
     dailyOutsideLow = 200;
     yesterdayRuntime = currentRuntimeMin; // Moves today's runtime to yesterday for the app display.
@@ -595,7 +596,7 @@
   // Resets the timer on the next day if the blower isn't running.
   else if (digitalRead(blowerPin) == HIGH && todaysDate != day())
   {
-    Blynk.tweet(String("On ") + yesterdaysMonth + "/" + yesterdaysDate + "/" + year() + " the A/C ran for " + currentRuntimeMin + " minutes total. Airport was " + dailyOutsideHigh + "°F/" + dailyOutsideLow + "°F."); // Tweet total runtime and outdoor high/low.
+    Blynk.tweet(String("On ") + yesterdaysMonth + "/" + yesterdaysDate + "/" + year() + " the A/C ran for " + currentRuntimeMin + " minutes total. Outside was " + dailyOutsideHigh + "°F/" + dailyOutsideLow + "°F."); // Tweet total runtime and outdoor high/low.
     dailyOutsideHigh = 0;
     dailyOutsideLow = 200;
     yesterdayRuntime = currentRuntimeMin;


part-way through adding MCP multiplexer; revised channels for RC switch and changed pin

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -12,6 +12,7 @@
 #include <Adafruit_Sensor.h>
 #include <Adafruit_TSL2591.h>
 #include <RCSwitch.h>
+#include "Adafruit_MCP23008.h"

 /////////////////////////////////////////////////////////////////////////////
 // resource management stuff ////////////////////////////////////////////////
@@ -54,6 +55,27 @@
     "<form method='POST' action='actuate'>\n"
     "External power: "
     "on <input type='radio' name='state' value='on'>\n"
+    "off <input type='radio' name='state' value='off'>\n"
+    "<input type='submit' value='Submit'></form>\n"
+  "
\n"
+  "
\n"
+    "<form method='POST' action='pump1'>\n"
+    "Water Pump 1: "
+    "on <input type='radio' name='state' value='on'>\n"
+    "off <input type='radio' name='state' value='off' checked>\n"
+    "<input type='submit' value='Submit'></form>\n"
+  "
\n"
+  "
\n"
+    "<form method='POST' action='pump2'>\n"
+    "Water Pump 2: "
+    "on <input type='radio' name='state' value='on'>\n"
+    "off <input type='radio' name='state' value='off' checked>\n"
+    "<input type='submit' value='Submit'></form>\n"
+  "
\n"
+  "
\n"
+    "<form method='POST' action='pump3'>\n"
+    "Water Pump 3: "
+    "on <input type='radio' name='state' value='on'>\n"
     "off <input type='radio' name='state' value='off' checked>\n"
     "<input type='submit' value='Submit'></form>\n"
   "
\n"
@@ -98,7 +120,7 @@

 /////////////////////////////////////////////////////////////////////////////
 // humidity sensor stuff ////////////////////////////////////////////////////
-DHT dht(12, DHT22); // what digital pin we're on, plus type DHT22 aka AM2302
+DHT dht(0, DHT22); // what digital pin we're on, plus type DHT22 aka AM2302
 boolean GOT_HUMID_SENSOR = false;  // we'll change later if we detect sensor

 /////////////////////////////////////////////////////////////////////////////
@@ -120,6 +142,12 @@
 /////////////////////////////////////////////////////////////////////////////
 // RC switch stuff //////////////////////////////////////////////////////////
 RCSwitch mySwitch = RCSwitch();
+const int RCSW_CHANNEL = 2; // which 433 channel to use
+const int RCSW_HEATER = 2;  // which 433 device to switch
+
+/////////////////////////////////////////////////////////////////////////////
+// MCP23008 stuff ///////////////////////////////////////////////////////////
+Adafruit_MCP23008 mcp; // Create object for MCP23008

 /////////////////////////////////////////////////////////////////////////////
 // config utils /////////////////////////////////////////////////////////////
@@ -152,6 +180,11 @@
   startDNS();

   startWebServer();
+
+  mcp.begin();      // use default address 0 for mcp23008
+  mcp.pinMode(0, OUTPUT);
+  mcp.pinMode(3, OUTPUT);
+  mcp.pinMode(7, OUTPUT);

   if(WiFi.hostname("waterelf"))
     Serial.println("set hostname succeeded");
@@ -177,7 +210,7 @@
 //    Serial.print("; AP="); Serial.println(WiFi.softAPIP());
   }
   if(loopCounter == TICK_HEAP_DEBUG) {
-//    Serial.print("free heap="); Serial.println(ESP.getFreeHeap());
+    Serial.print("free heap="); Serial.println(ESP.getFreeHeap());
   }

   if(loopCounter++ == LOOP_ROLLOVER) loopCounter = 0;
@@ -456,15 +489,15 @@

   // now we trigger the 433 transmitter
   if(newState == true){
-    mySwitch.switchOn(4, 2);
+    mySwitch.switchOn(RCSW_CHANNEL, RCSW_HEATER);
     Serial.println("Actuator on");
   } else {
-    mySwitch.switchOff(4, 2);
+    mySwitch.switchOff(RCSW_CHANNEL, RCSW_HEATER);
     Serial.println("Actuator off");
   }

   toSend += "
Actuator triggered
\n";
-  toSend += "
(New state is ";
+  toSend += "
(New state should be ";
   toSend += (newState) ? "on" : "off";
   toSend += ".)
\n";
   toSend += pageFooter;
@@ -475,7 +508,7 @@
 // sensor/actuator stuff ////////////////////////////////////////////////////
 void startPeripherals() {
   Serial.println("startPeripherals");
-  mySwitch.enableTransmit(13);   // RC transmitter is connected to Pin 13
+  mySwitch.enableTransmit(15);   // RC transmitter is connected to Pin 15

   tempSensor.begin();     // start the onewire temperature sensor
   if(tempSensor.getDeviceCount()==1) {


use jsonMonitorEntry for printing entries, so dont need two printer funcs

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -16,11 +16,11 @@
 /////////////////////////////////////////////////////////////////////////////
 // resource management stuff ////////////////////////////////////////////////
 int loopCounter = 0;
-const int LOOP_ROLLOVER = 1000; // how many loops per action slice
-const byte TICK_MONITOR = 0;
-const byte TICK_WIFI_DEBUG = 500;
-const byte TICK_POST_DEBUG = 200;
-const byte TICK_HEAP_DEBUG = 1000;
+const int LOOP_ROLLOVER = 5000; // how many loops per action slice
+const int TICK_MONITOR = 0;
+const int TICK_WIFI_DEBUG = 500;
+const int TICK_POST_DEBUG = 200;
+const int TICK_HEAP_DEBUG = 1000;

 /////////////////////////////////////////////////////////////////////////////
 // wifi management stuff ////////////////////////////////////////////////////
@@ -65,7 +65,7 @@
   "

\n";
 const char* pageFooter =
   "\n
WaterElf   "
-  "CleanFood
";
+  "WeGrow
";

 /////////////////////////////////////////////////////////////////////////////
 // data monitoring stuff ////////////////////////////////////////////////////
@@ -230,19 +230,15 @@
   String toSend = pageTop;
   toSend += ": Sensor Data";
   toSend += pageTop2;
-  toSend += "
\n";
-
-  // Serial.print("monitorCursor="); Serial.print(monitorCursor);
-  // Serial.print(" monitorSize=");  Serial.println(monitorSize);
+  toSend += "\n
Sensor Data

\n";
+
   int mSize = monitorSize;
   for(
     int i = monitorCursor - 1, j = 1;
     j <= DATA_ENTRIES && j <= monitorSize;
     i--, j++
   ) {
-    // Serial.print("printMonitorEntry(monitorData["); Serial.print(i);
-    // Serial.println("], &toSend)");
-    printMonitorEntry(monitorData[i], &toSend);
+    jsonMonitorEntry(&monitorData[i], &toSend);
     toSend += "\n";
     if(i == 0)
       i = MONITOR_POINTS;
@@ -479,7 +475,7 @@
   float airHumid = dht.readHumidity();
   float airCelsius = dht.readTemperature();
   if (isnan(airHumid) || isnan(airCelsius)) {
-    Serial.println("failed to find Humidity sensor");
+    Serial.println("failed to find humidity sensor");
   } else {
     GOT_HUMID_SENSOR = true;
   }
@@ -542,7 +538,7 @@
     monitorCursor = 0;
 }
 void postSensorData(monitor_t *monitorData) {
-  Serial.println("postSensorData");
+  Serial.println("\npostSensorData");

   // create a JSON form
   String jsonBuf = "";
@@ -566,6 +562,7 @@
     Serial.println(" - no couch server");
   }

+  Serial.println("");
   return;
 }
 void jsonMonitorEntry(monitor_t *m, String* buf) {
@@ -591,39 +588,11 @@
     buf->concat(m->lux);
   }
   if(GOT_PH_SENSOR){
-  buf->concat(", ");
-  buf->concat(", \"pH\": ");
-  buf->concat(m->pH);
+    buf->concat(", ");
+    buf->concat(", \"pH\": ");
+    buf->concat(m->pH);
   }
   buf->concat(" }");
-}
-void printMonitorEntry(monitor_t m, String* buf) {
-  buf->concat("{ ");
-  buf->concat("\"timestamp\": ");
-  buf->concat(m.timestamp);
-  if(GOT_TEMP_SENSOR){
-    buf->concat(", Water Temp: ");
-    buf->concat(m.waterCelsius);
-    buf->concat(" °C");
-  }
-  if(GOT_HUMID_SENSOR){
-    buf->concat(", Air Temp: ");
-    buf->concat(m.airCelsius);
-    buf->concat(" °C");
-    buf->concat(", Humidity: ");
-    buf->concat(m.airHumid);
-    buf->concat(" %RH");
-  }
-  if(GOT_LIGHT_SENSOR){
-    buf->concat(", Light: ");
-    buf->concat(m.lux);
-    buf->concat(" lux");
-  }
-  if(GOT_PH_SENSOR){
-    buf->concat(", pH: ");
-    buf->concat(m.pH);
-    buf->concat(" pH");
-  }
 }
 void getTemperature(float* waterCelsius) {
   tempSensor.requestTemperatures(); // send command to get temperatures


Update sketch_reco.ino

Update sketch_reco.ino

--- dragino/sketch_reco.ino
+++ dragino/sketch_reco.ino
@@ -1,9 +1,9 @@
-//Hello, this is a sketch to get remote control to your dragino device by bridge mode
+//Hello!, this is a sketch to get remote control to your dragino device by bridge mode
 //The original source and Pubsubclient code comes from:
 //https://github.com/knolleary/pubsubclient
 //this is a modified sketch from those repository
 //
-//Este es un sketch de prueba para tomar control remoto de su dispositivo dragino en modo bridge
+//Hola ! Este es un sketch de prueba para tomar control remoto de su dispositivo dragino en modo bridge
 //la libreria Pubsubclient.* y el codigo fuente proviene desde:
 //https://github.com/knolleary/pubsubclient
 //y este es un sketch modificado desde el repositorio origen y adaptado para funcionar con nuestra


Fixing Menu LED Text

Fixing Menu LED Text


Initial rework of hi score rendering.

Initial rework of hi score rendering.