Fade in and fade out, dim functioni

Fade in and fade out, dim functioni

--- arduino/alarm/alarm.ino
+++ arduino/alarm/alarm.ino
@@ -4,24 +4,32 @@
 void serialEvent();
 void alarm();

-void alarm() {
-  boolean alarm_stopped = false;
+void dim(unsigned long duration, boolean brighten) {
+  double lnb = log(pow(256.0, 1.0 / (float) duration));
   for (int i = 1; i < 256; i++) {
-    if (light_state != "alarm") {
-      boolean alarm_stopped = true;
+    if (light_state != "dimming") {
       return;
     }
-    int brightness = (int) pow(1.0219, (float) i);
-    analogWrite(gate_pin, brightness);
-    for (int j = 0; j < 7059; j++) {
-      if (Serial.available() > 0) {
-        serialEvent();
+    unsigned long interval;
+    if (brighten) {
+      analogWrite(gate_pin, i);
+      interval = (unsigned long) round(log(((float) i + 1) / (float) i) / lnb);
+    } else {
+      int x = 256 - i;
+      analogWrite(gate_pin, x - 1);
+      interval = (unsigned long) round(log((float) x / ((float) x - 1)) / lnb);
+    }
+    unsigned long previousMillis = millis();
+    if (i < 255) {
+      while(millis() - previousMillis < interval) {
+        loop();
       }
-      delay(1);
     }
   }
-  if (!(alarm_stopped)) {
+  if (brighten) {
     light_state = "on";
+  } else {
+    light_state = "off";
   }
 }

@@ -31,20 +39,17 @@
   if (serial_data == "i") {
     Serial.println(light_state);
   } else if (light_state != "on" && serial_data == "o") {
-    analogWrite(gate_pin, 255);
-    light_state = "on";
+    light_state = "dimming";
+    dim(500, true);
     Serial.println(light_state);
   } else if (serial_data == "o") {
-    analogWrite(gate_pin, 0);
-    light_state = "off";
+    light_state = "dimming";
+    dim(500, false);
     Serial.println(light_state);
   } else if (serial_data == "a" && light_state == "off") {
-    light_state = "alarm";
-    alarm();
-  } //else {
-  //   return false;
-  // }
-  // return true;
+    light_state = "dimming";
+    dim(1800000, true);
+  }
 }

 void setup() {


Update example to note cycle threshold parameter for Arduino Due.

--- examples/DHTtester/DHTtester.ino
+++ examples/DHTtester/DHTtester.ino
@@ -11,11 +11,22 @@
 //#define DHTTYPE DHT21   // DHT 21 (AM2301)

 // Connect pin 1 (on the left) of the sensor to +5V
+// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
+// to 3.3V instead of 5V!
 // Connect pin 2 of the sensor to whatever your DHTPIN is
 // Connect pin 4 (on the right) of the sensor to GROUND
 // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

+// Initialize DHT sensor for normal 16mhz Arduino
 DHT dht(DHTPIN, DHTTYPE);
+// NOTE: For working with a faster chip, like an Arduino Due or Teensy, you
+// might need to increase the threshold for cycle counts considered a 1 or 0.
+// You can do this by passing a 3rd parameter for this threshold.  It's a bit
+// of fiddling to find the right value, but in general the faster the CPU the
+// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
+// Arduino Due that runs at 84mhz a value of 30 works.
+// Example to initialize DHT sensor for Arduino Due:
+//DHT dht(DHTPIN, DHTTYPE, 30);

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


Tweaked parameters

Tweaked parameters

--- people/mikewesthad/Week5/Arduino/AnalogReadWithSmoothing/AnalogReadWithSmoothing.ino
+++ people/mikewesthad/Week5/Arduino/AnalogReadWithSmoothing/AnalogReadWithSmoothing.ino
@@ -8,7 +8,7 @@
 //  NOTE: The larger NUM_SAMPLES, the smoother the values, but also
 //  the longer it will take the average to move in response to you turning the
 //  potentiometer
-const int NUM_SAMPLES = 10;
+const int NUM_SAMPLES = 20;
 int potSamples[NUM_SAMPLES];
 int potIndex = 0;
 int totalPotValue = 0;
@@ -19,7 +19,7 @@
 //  update the pot value sent out from the arduino if the pot value
 //  has changed by a specified amount
 int lastAveragePotValue = 0;
-int changeThreshold = 2;
+const int CHANGE_THRESHOLD = 3;

 void setup()
 {
@@ -52,7 +52,8 @@

   // Detect whether the new average pot value has changed enough
   // from our last saved average pot value
-  if (abs(averagePotValue-lastAveragePotValue)>=changeThreshold){
+  int change = abs(averagePotValue-lastAveragePotValue);
+  if (change >= CHANGE_THRESHOLD){
     lastAveragePotValue = averagePotValue;
   }

@@ -61,6 +62,6 @@
   Serial.println(lastAveragePotValue);

   // Delay
-  delay(50);
+  delay(10);
 }


added first working version of DCF updated RTC


arduino code

arduino code

--- ArduinoController/ArduinoController.ino
+++ ArduinoController/ArduinoController.ino
@@ -23,7 +23,10 @@
 #include <SPI.h>
 #include <EEPROM.h>
 #include <boards.h>
+#include <Servo.h>
 #include <RBL_nRF8001.h>
+
+Servo myservo;

 const int BTN_PIN = 4;
 const int LED_PIN = 3;
@@ -43,9 +46,10 @@

   pinMode(BTN_PIN,INPUT);
   pinMode(LED_PIN,OUTPUT);
-  pinMode(SERVO_PIN, OUTPUT);
   pinMode(POT_PIN, INPUT);
   digitalWrite( LED_PIN, LOW );
+
+  myservo.attach(SERVO_PIN);

   // Init. and start BLE library.
   ble_begin();
@@ -59,6 +63,10 @@
 String command;
 int buttonState = 0;
 int potVal = 0;
+bool lightOn = LOW;
+int strobeMode = 0;
+
+int delayVals[4] = {0,100,70,30};

 void loop()
 {
@@ -73,14 +81,16 @@
     Serial.println(command);

     if( command.substring(0,9) == "Light ON;" ) {
+      lightOn = HIGH;
       digitalWrite( LED_PIN, HIGH );
     }
     else if ( command.substring(0,10) == "Light OFF;" ) {
+      lightOn = LOW;
       digitalWrite( LED_PIN, LOW );
     }
     else if ( command.substring(0,5) == "Servo" ) {
-        String servoSpeed = command.substring(6,command.indexOf(';'));
-        analogWrite(SERVO_PIN, servoSpeed.toInt());
+        String servoPos = command.substring(6,command.indexOf(';'));
+        myservo.write(servoPos.toInt());
     }

@@ -100,25 +110,54 @@
   //read from button
   int newBtnState = digitalRead(BTN_PIN);
   if( newBtnState != buttonState ) {
-
+
+    //send button state along BLE
     buttonState = newBtnState;
     String sendCommand = "BTN " + String(buttonState);
     for( int i = 0; i < sendCommand.length(); i++ ) {
       ble_write( sendCommand[i] );
+    }
+
+    // update button state when button is pressed
+    if(buttonState==1) {
+      strobeMode += 1;
+
+      //reset strobeMode if it's greater than 3
+      if(strobeMode > 3) {
+        strobeMode = 0;
+      }
     }
   }

   //read from pot
   int newPotVal = analogRead(POT_PIN);
   if( newPotVal != potVal ) {
-
+
+    //update potentiometer value
     potVal = newPotVal;
-    int newBrightness = potVal/4;
-    analogWrite(LED_PIN, newBrightness);
+
+    //send the potentiometer value along BLE
     String sendCommand = "POT " + String(potVal);
     for( int i = 0; i < sendCommand.length(); i++ ) {
       ble_write( sendCommand[i] );
     }
+  }
+
+
+  // determine strobe mode
+  if(lightOn) {
+    //turn LED off
+    digitalWrite(LED_PIN,LOW);
+    analogWrite(LED_PIN, 0);
+
+    //wait a certain amount of time
+    delay( delayVals[strobeMode] );
+
+
+    //turn LED back on
+    digitalWrite(LED_PIN,HIGH);
+    int newBrightness = potVal/4;
+    analogWrite(LED_PIN, newBrightness);
   }

   delay(10);


remove minorspan from Arduino sketch

remove minorspan from Arduino sketch

--- arduino-controller/SDAnimation.ino
+++ arduino-controller/SDAnimation.ino
@@ -40,8 +40,7 @@
 		Serial.write(data[i]);
 	}

-	delayMicroseconds(makeWord(data[4], data[5]));
-	delay(makeWord(data[6], data[7]));
+	delay(makeWord(data[4], data[5]));
 }

 void readAnimation(File & file)
@@ -50,9 +49,6 @@
 	while (file.available())
 	{
 		file.read(data, 72);
-//		for (byte i = 0; i < 72; i++)
-//			Serial.write(data[i]);
-
 		sendAnimation(data);
 	}
 }


Hot potato game

Hot potato game

For the time being without using the accelerometer

--- firmware/HotPotato/HotPotato.ino
+++ firmware/HotPotato/HotPotato.ino
@@ -2,20 +2,8 @@
 #include <avr/power.h>
 #include <avr/wdt.h>

-const unsigned int BUZZER_PIN = PB0;
-const unsigned int MOTOR_PIN = PB1;
-const unsigned int BUTTON_PIN = PB2;
-const unsigned int ACCELEROMETER_IN = PB3;
-const unsigned int ACCELEROMETER_POWER = PB4;
-const unsigned long DEBOUNCE_TIME = 50;
-
-volatile bool watchDogBarked = false;
-bool watchDogEnabled = false;
-
-volatile bool buttonPressed = false;
-
 enum WatchDogTimeout {
-  WDT_16ms,
+  WDT_16ms = 0,
   WDT_32ms,
   WDT_64ms,
   WDT_128ms,
@@ -28,11 +16,89 @@
 };

 enum PowerState {
-  SLEEP,
+  DEEP_SLEEP,
   GAME
 };

-PowerState currentState = SLEEP; // Start with sleep as the initial state
+const unsigned int BUZZER_PIN = PB0;
+const unsigned int MOTOR_PIN = PB1;
+const unsigned int BUTTON_PIN = PB2;
+const unsigned int ACCELEROMETER_IN = PB3;
+const unsigned int ACCELEROMETER_POWER = PB4;
+
+const unsigned long TURN_DURATION = 90000; // The time in milliseconds that game lasts
+const float beepingRatio = 0.95; // Percentage of the remaining time that should we beep
+unsigned long timeToBeep = (float) TURN_DURATION * beepingRatio;
+volatile bool watchDogBarked = false;
+bool watchDogEnabled = false;
+const WatchDogTimeout gameWdt = WDT_128ms;
+
+
+WatchDogTimeout currentWdt = gameWdt;
+unsigned long elapsedTime = 0; // How much time has elapsed in the running turn in milliseconds
+
+volatile bool buttonPressed = false;
+
+const unsigned long remindBeepDuration = 50; // How long in milliseconds we should beep to "stress" the user
+
+
+PowerState currentState = DEEP_SLEEP; // Start with sleep as the initial state
+
+/**
+   Vibrate for the specified amount of time (blocking)
+   @param duration milliseconds the motor will vibrate
+*/
+void vibrateFor(unsigned long duration) {
+  startVibrating();
+  delay(duration);
+  stopVibrating();
+}
+
+/**
+   Utility method that starts the vibrating motor
+*/
+void startVibrating() {
+  digitalWrite(MOTOR_PIN, HIGH);
+}
+
+/**
+   Utility method that stops the vibrating motor
+*/
+void stopVibrating() {
+  digitalWrite(MOTOR_PIN, LOW);
+}
+
+/**
+   Ring the buzzer for the specified amount of time (blocking)
+   @param duration milliseconds the buzzer will ring
+*/
+void ringFor(unsigned long duration) {
+  startRinging();
+  delay(duration);
+  stopRinging();
+}
+
+/**
+   Utility method that starts ringing the buzzer
+*/
+void startRinging() {
+  digitalWrite(BUZZER_PIN, HIGH);
+}
+
+/**
+   Utility method that stops ringing the buzzer
+*/
+void stopRinging() {
+  digitalWrite(BUZZER_PIN, LOW);
+}
+
+/**
+   A utility method to derive a watchdog timeout's duration
+   @return the amount of milliseconds corresponding to a watchdog timeout
+*/
+unsigned long getTimeoutDuration() {
+  return 1 << (currentWdt + 4);
+}

 void setupWatchDogTimeoutOneshot(WatchDogTimeout wdt) {
   // Adopted from InsideGadgets (www.insidegadgets.com)
@@ -47,6 +113,7 @@
   WDTCR = timeoutVal;
   WDTCR |= _BV(WDIE);
   wdt_reset();  // pat the dog
+  currentWdt = wdt;
 }

 /**
@@ -93,7 +160,7 @@
 /**
    Sets the MCU into a deep sleep state until a change interrupt is triggered
 */
-void goToDeepSleep() {
+void goToSleep() {
   set_sleep_mode(SLEEP_MODE_PWR_DOWN);
   ADCSRA = 0; // turn off ADC
   power_all_disable (); // power off ADC, Timer 0 and 1, serial interface
@@ -114,35 +181,57 @@

 void loop() {
   switch (currentState) {
-    case SLEEP:
-      turnAccelerometerOff();
+    case DEEP_SLEEP:
       // Go to deep sleep until an interrupt occurs
-      goToDeepSleep();
+      goToSleep();
       // Proceed to the
       if (buttonPressed) {
+        // Beep fast twice to indicate the beginning of a game
+        ringFor(100);
+        delay(100);
+        ringFor(100);
         currentState = GAME;
         buttonPressed = false;
       }
       break;
     case GAME:
-      // If watchdog is not enabled, then we just arrived from SLEEP state
+      // If watchdog is not enabled, then we either just arrived from SLEEP state
+      // or from a watchdog bark. Therefore we need to set another watchdog timer.
       if (!watchDogEnabled) {
-        turnAccelerometerOn();
         // Set up watchdog to be triggered (once) after the specified time
-        setupWatchDogTimeoutOneshot(WDT_1sec);
+        setupWatchDogTimeoutOneshot(gameWdt);
         watchDogEnabled = true;
-        digitalWrite(BUZZER_PIN, HIGH);
       }
       // Go to deep sleep until an interrupt occurs
-      goToDeepSleep();
+      goToSleep();
       // We might have gone out of sleep due to another interrupt (i.e. the switch)
-      // So make sure that we only get out of this state using the watchdog
+      // So make sure that we know what we are doing depending on who interrupted our sleep
       if (watchDogBarked) {
-        digitalWrite(BUZZER_PIN, LOW);
-        currentState = SLEEP;
         watchDogBarked = false;
         watchDogEnabled = false;
+        elapsedTime += getTimeoutDuration();
+        unsigned long remainingTime = TURN_DURATION - elapsedTime;
+        /* --- Main game logic --- */
+        if (elapsedTime >= TURN_DURATION) {
+          // Play a sound and vibration sequence to indicate the end of a game due to timeout
+          ringFor(50);
+          delay(50);
+          ringFor(50);
+          delay(50);
+          startVibrating();
+          ringFor(800);
+          stopVibrating();
+          currentState = DEEP_SLEEP;
+          elapsedTime = 0;
+          timeToBeep = TURN_DURATION * beepingRatio; // reset the remaining time since the turn is over
+        } else if (remainingTime <= timeToBeep) {
+          // Ring when we reach half of the remaining time available
+          ringFor(remindBeepDuration);
+          elapsedTime += remindBeepDuration; // Add the time we spent ringing
+          timeToBeep *= beepingRatio;
+        }
       }
+      buttonPressed = false;
       break;
     default:
       break;


pub test

pub test

--- _11-mqtt-lwt-test/_11-mqtt-lwt-test.ino
+++ _11-mqtt-lwt-test/_11-mqtt-lwt-test.ino
@@ -171,7 +171,7 @@

   client.loop();
-  delay(2000);
+  delay(100);
 }


Updates status to use mcu_get_battery_voltage

--- status.ino
+++ status.ino
@@ -6,8 +6,8 @@
 void status_show() {
   uint8_t ypos = 0;

-  dtostrf(Xadow.getBatVol(), 1, 1, _sbuf2);
-  sprintf(_sbuf, "Battery: %sV", _sbuf2);
+  uint8_t batv = mcu_get_battery_voltage();
+  sprintf(_sbuf, "Battery: %d.%dV", batv/10, batv%10);
   oled.drawString(_sbuf, 0, ypos, FONT_SIZE, STATUS_COLOR);

   ypos += LINE_HEIGHT;
@@ -37,4 +37,4 @@
   else s = "Batt log exists";

   oled.drawString(s, 0, ypos, FONT_SIZE, STATUS_COLOR);
-}+}


Created a sketch that calibrates the ITG3701 and performs basic testing


Create mr-cylinder-code.ino

Create mr-cylinder-code.ino


Midterm's loader code.

Midterm's loader code.

--- src/pong_loader/arduino_code/loader_arduino/loader_arduino.ino
+++ src/pong_loader/arduino_code/loader_arduino/loader_arduino.ino
@@ -19,16 +19,80 @@
 std_msgs::String state_msg;
 ros::Publisher pub_state("loader/state", &state_msg);

-const int switch_pin = 5;
+const int switch_pin = 2;
 const int led_pin = 13;
-const int motor_pin = 9;
+const int motor_pin = 3;

-const int motor_speed = 50;
+const int motor_speed = 100;

 //bool last_reading;
 //long last_debounce_time=0;
 //long debounce_delay=50;
 //bool published = true;
+
+/**
+ * Divides a given PWM pin frequency by a divisor.
+ *
+ * The resulting frequency is equal to the base frequency divided by
+ * the given divisor:
+ *   - Base frequencies:
+ *      o The base frequency for pins 3, 9, 10, and 11 is 31250 Hz.
+ *      o The base frequency for pins 5 and 6 is 62500 Hz.
+ *   - Divisors:
+ *      o The divisors available on pins 5, 6, 9 and 10 are: 1, 8, 64,
+ *        256, and 1024.
+ *      o The divisors available on pins 3 and 11 are: 1, 8, 32, 64,
+ *        128, 256, and 1024.
+ *
+ * PWM frequencies are tied together in pairs of pins. If one in a
+ * pair is changed, the other is also changed to match:
+ *   - Pins 5 and 6 are paired on timer0
+ *   - Pins 9 and 10 are paired on timer1
+ *   - Pins 3 and 11 are paired on timer2
+ *
+ * Note that this function will have side effects on anything else
+ * that uses timers:
+ *   - Changes on pins 3, 5, 6, or 11 may cause the delay() and
+ *     millis() functions to stop working. Other timing-related
+ *     functions may also be affected.
+ *   - Changes on pins 9 or 10 will cause the Servo library to function
+ *     incorrectly.
+ *
+ * Thanks to macegr of the Arduino forums for his documentation of the
+ * PWM frequency divisors. His post can be viewed at:
+ *   http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1235060559/0#4
+ */
+void setPwmFrequency(int pin, int divisor) {
+  byte mode;
+  if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
+    switch(divisor) {
+      case 1: mode = 0x01; break;
+      case 8: mode = 0x02; break;
+      case 64: mode = 0x03; break;
+      case 256: mode = 0x04; break;
+      case 1024: mode = 0x05; break;
+      default: return;
+    }
+    if(pin == 5 || pin == 6) {
+      TCCR0B = TCCR0B & 0b11111000 | mode;
+    } else {
+      TCCR1B = TCCR1B & 0b11111000 | mode;
+    }
+  } else if(pin == 3 || pin == 11) {
+    switch(divisor) {
+      case 1: mode = 0x01; break;
+      case 8: mode = 0x02; break;
+      case 32: mode = 0x03; break;
+      case 64: mode = 0x04; break;
+      case 128: mode = 0x05; break;
+      case 256: mode = 0x06; break;
+      case 1024: mode = 0x7; break;
+      default: return;
+    }
+    TCCR2B = TCCR2B & 0b11111000 | mode;
+  }
+}
+

 void run_motor(int motor_speed){
   analogWrite(motor_pin, motor_speed);
@@ -38,21 +102,27 @@
   analogWrite(motor_pin, 0);
 }

-void load_ball(){
-  // While we haven't seen the switch be high,
-  //   run the motor
-
-  while(digitalRead(switch_pin) != HIGH){
-    run_motor(motor_speed);
+//void stop_motor_interrupt(){
+//  if switc
+//}

-    delay(10);
-    break; // put this in here to test, don't want to kill the motor
-  }
-
-  stop_motor();
-
-}
+
+//void load_ball(){
+//  // While we haven't seen the switch be high,
+////  //   run the motor
+////
+////  while(digitalRead(switch_pin) != HIGH){
+////    run_motor(motor_speed);
+////
+////
+////    delay(10); // run for .1 seconds.
+//////    break; // put this in here to test, don't want to kill the motor
+////  }
+////
+////  stop_motor();
+//
+//}

 void load_cmd_cb(const std_msgs::Bool& cmd_msg){

@@ -62,29 +132,42 @@
     pub_state.publish(&state_msg);
     digitalWrite(led_pin, HIGH);

+    run_motor(motor_speed);
+//    load_ball();

-    load_ball();
-
+//    delay(100);
     state_msg.data = "loaded";
     pub_state.publish(&state_msg);
     digitalWrite(led_pin,LOW);

-  }
+  } else {
+    stop_motor();
+  }

 }

-ros::Subscriber<std_msgs::Bool> load_sub("load_cmd", load_cmd_cb);
+ros::Subscriber<std_msgs::Bool> load_sub("loader/load_cmd", load_cmd_cb);

 void setup()
 {
   nh.initNode();
   nh.advertise(pub_state);
+  nh.subscribe(load_sub);

   //initialize an LED output pin for status purposes
   //init input pin for switch input and motor control pin
   pinMode(led_pin, OUTPUT);
   pinMode(switch_pin, INPUT);
   pinMode(motor_pin, OUTPUT);
+
+  // set the motor to be initially off
+  setPwmFrequency(motor_pin, 1); // highest pwm frequency
+  stop_motor();
+
+  // interrupt on the switch pin that
+  //  turns the motor off when the switch pin
+  //   goes from low to high
+  attachInterrupt(0, stop_motor, RISING);

 }


オフセット値を0に変更

オフセット値を0に変更

--- 1_practice/esp32_04_adc2/esp32_04_adc2.ino
+++ 1_practice/esp32_04_adc2/esp32_04_adc2.ino
@@ -23,7 +23,7 @@
 void loop() {                           // setup実行後に繰り返し実行される関数
     int adc;                            // AD変換値保存用の整数型変数adcを定義

-    adc=(int)mvAnalogIn(PIN_AIN, 0.1);  // AD変換器から値を取得
+    adc=(int)mvAnalogIn(PIN_AIN, 0.0);  // AD変換器から値を取得
     Serial.println(adc);                // 変数adcの値をシリアル出力表示
     delay(3000);                        // 3秒間(3000ms)の待ち時間処理
 }


examples: ServoSweep: set default pin number to 0

The current pin number, 9, does not exist on the LtC board.  Update it
to a pin that exists.

Signed-off-by: Sean Cross <d7e19930cc1f42c2d0781f4d9e6f1fe5891bf9cf@xobs.io>

--- examples-ltc/8.Actuators/1_ServoSweep/ServoSweep.ino
+++ examples-ltc/8.Actuators/1_ServoSweep/ServoSweep.ino
@@ -14,7 +14,7 @@
 int pos = 0;    // variable to store the servo position

 void setup() {
-  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
+  myservo.attach(0);  // attaches the servo on pin 0 to the servo object
 }

 void loop() {


fixed withoutLib_HS

fixed withoutLib_HS

- Now Compatible with ARDUINO MEGA
- Clean and correct ordered response

--- examples/withoutLib_HS/withoutLib_HS.ino
+++ examples/withoutLib_HS/withoutLib_HS.ino
@@ -1,34 +1,47 @@
 /*
-  1 - THIS DOES NOT USES CS5490 LIBRARY, use only if you want to understand
+  1 - THIS EXAMPLE DOES NOT USES CS5490 LIBRARY, use only if you want to understand
 only if you are having some trouble or needs to understante how it works

   2 - THIS EXAMPLES USES SoftwareSerial library, it means that will be useful
 only for ARDUINO MEGA, ESP32 and others with multiple hardware serial components
 */

+byte data[3]; //data buffer
+
 void setup(){
   // Open serial communications and wait for port to open:
   Serial.begin(115200);
-  while (!Serial) {
-    ; // wait for serial port to connect. Needed for Leonardo only
-  }
-  // set the data rate for the SoftwareSerial port
+  // wait for serial port to connect. Needed for Leonardo only
+  while (!Serial);
+  // set the data rate for the HardwareSerial 2 port
   Serial2.begin(600);
-  //Defines the page for the register address
-  Serial2.write(0b10010000); //Select Page 16
 }

 void loop(){
-  Serial2.write(0x31); //Read Address 49
-  while (Serial2.available() > 3){ //Wait for 3 bytes to arrive
-    char inByte = Serial2.read();
-    Serial.print(inByte,HEX);
-    inByte = Serial2.read();
-    Serial.print(inByte,HEX);
-    inByte = Serial2.read();
-    Serial.print(inByte,HEX);
-    //The result must be 9A991
-  }
-  Serial.println("");
+
+  /* The default value is: 01999A */
+  clearSerial2Buffer();
+  Serial2.write(0b10010000); //Select Page 16
+  Serial2.write(0b00110001); //Read Address 49
+	//Wait for 3 bytes to arrive
+	while(Serial2.available() < 3);
+  //Read 3 byte information
+	for(int i=0; i<3; i++){
+		data[i] = Serial2.read();
+	}
+  //Data concatenation
+  uint32_t value = 0;
+  value = value + data[2] << 8;
+  value = value + data[1] << 8;
+  value = value + data[0];
+
+  Serial.println(value,HEX);
   delay(1000);
 }
+
+/* Clearing Serial2 Buffer */
+void clearSerial2Buffer(){
+  while(Serial2.available()){
+    Serial2.read();
+  }
+}


turtlebot3 friends bug fixed

turtlebot3 friends bug fixed

--- arduino/opencr_arduino/opencr/libraries/turtlebot3/examples/turtlebot_friends/turtlebot3_omni/turtlebot3_omni.ino
+++ arduino/opencr_arduino/opencr/libraries/turtlebot3/examples/turtlebot_friends/turtlebot3_omni/turtlebot3_omni.ino
@@ -93,11 +93,11 @@

     if (received_data & RC100_BTN_L)
     {
-      linear_y += VELOCITY_LINEAR_Y * SCALE_VELOCITY_LINEAR_Y;
+      linear_y -= VELOCITY_LINEAR_Y * SCALE_VELOCITY_LINEAR_Y;
     }
     else if (received_data & RC100_BTN_R)
     {
-      linear_y -= VELOCITY_LINEAR_Y * SCALE_VELOCITY_LINEAR_Y;
+      linear_y += VELOCITY_LINEAR_Y * SCALE_VELOCITY_LINEAR_Y;
     }

     if (received_data & RC100_BTN_1)


Agrego variables de configuración al sketch


Change input pin to D4, fix memcpy->memset

--- geiger_esp/geiger_esp.ino
+++ geiger_esp/geiger_esp.ino
@@ -4,6 +4,8 @@
 #include <ESP8266WiFi.h>
 #include <WiFiManager.h>
 #include <PubSubClient.h>
+
+#define PIN_TICK    D4

 #define MQTT_HOST   "mosquitto.space.revspace.nl"
 #define MQTT_PORT   1883
@@ -48,9 +50,11 @@
     wifiManager.autoConnect("ESP-GEIGER");

     // start counting
-    memcpy(secondcounts, 0, sizeof(secondcounts));
+    memset(secondcounts, 0, sizeof(secondcounts));
     Serial.println("Starting count ...");
-    attachInterrupt(0, tube_impulse, FALLING);
+
+    pinMode(PIN_TICK, INPUT);
+    attachInterrupt(digitalPinToInterrupt(PIN_TICK), tube_impulse, FALLING);
 }

 static void mqtt_send(const char *topic, const char *value)


reconfigured sensor to work with smart_psu

--- hacks/rf_temp_sensor/rf_temp_sensor_sensor/rf_temp_sensor_sensor.ino
+++ hacks/rf_temp_sensor/rf_temp_sensor_sensor/rf_temp_sensor_sensor.ino
@@ -15,10 +15,6 @@
 #include <OneWire.h>
 #include <DallasTemperature.h>

-// Sleep mode includes
-#include <avr/sleep.h>
-#include <avr/wdt.h>
-
 #define LED_PIN_TX 13   // the number of the LED pin on the transmitter board
 #define ONE_WIRE_BUS 3 // Data wire is plugged into pin 3 on the Arduino

@@ -31,21 +27,32 @@
 int messageId = 0;
 float temp1C = -127.00; //-127.00 is the error temp
 float temp2C = -127.00; //-127.00 is the error temp
-float vIn = 0.00;
+long vcc = 0;

-// watchdog interrupt
-ISR(WDT_vect) {
-  wdt_disable();  // disable watchdog
-}
+long readVcc() {
+  // Read 1.1V reference against AVcc
+  // set the reference to Vcc and the measurement to the internal 1.1V reference
+  #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+    ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
+  #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
+    ADMUX = _BV(MUX5) | _BV(MUX0);
+  #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
+    ADMUX = _BV(MUX3) | _BV(MUX2);
+  #else
+    ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
+  #endif

-void myWatchdogEnable(const byte interval) {
-  MCUSR = 0;                          // reset various flags
-  WDTCSR |= 0b00011000;               // see docs, set WDCE, WDE
-  WDTCSR =  0b01000000 | interval;    // set WDIE, and appropriate delay
+  delay(2); // Wait for Vref to settle
+  ADCSRA |= _BV(ADSC); // Start conversion
+  while (bit_is_set(ADCSRA,ADSC)); // measuring

-  wdt_reset();
-  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
-  sleep_mode();            // now goes to Sleep and waits for the interrupt
+  uint8_t low  = ADCL; // must read ADCL first - it then locks ADCH
+  uint8_t high = ADCH; // unlocks both
+
+  long result = (high<<8) | low;
+
+  result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000
+  return result; // Vcc in millivolts
 }

 void setup() {
@@ -74,15 +81,8 @@
   sensors.requestTemperatures();
   temp1C = sensors.getTempC(firstThermometer);
   temp2C = sensors.getTempC(secondThermometer);
+  vcc = readVcc();

-  // Get and print battery voltage
-  Serial.println("Getting voltage...");
-  // 9,41v = 2.52 * k => k = 3.57,
-  float readVIn = analogRead(1) * (5.0/1023.0);
-  vIn = 3.75 * readVIn;
-  Serial.println(readVIn);
-  Serial.println("Getting voltage...");
-
   // Make message, e.g. "I:1 T:22.50 \n"
   messageString = "I:";
   messageString = messageString + String(messageId, DEC);
@@ -101,7 +101,7 @@
     messageString = messageString + String(temp2C, 2);
   }
   messageString = messageString + " V:";
-  messageString = messageString + String(vIn, 2);
+  messageString = messageString + String(vcc, DEC);
   messageString = messageString + "\n";

   // Prepare and send message
@@ -123,10 +123,5 @@
   digitalWrite(LED_PIN_TX, HIGH);
   delay(1000);
   digitalWrite(LED_PIN_TX, LOW);
-
-  // sleep for a total of 8*8=64 seconds
-  for(int i = 0; i < 8; ++i) {
-    myWatchdogEnable (0b100001);  // 8 seconds
-  }

 }


Fix problems in timed write to serial

Fix problems in timed write to serial

--- sketchbook/timer_echo/timer_echo.ino
+++ sketchbook/timer_echo/timer_echo.ino
@@ -211,6 +211,7 @@
 void timerWrite()
 {
   int prefix_len = 0;
+  int timer_write_len = 0;
   char write_buf[80];
   int write_buf_len = 0;

@@ -218,10 +219,13 @@
   memset(write_buf,0,sizeof(write_buf));
   sprintf(write_buf," %d\r",prefix_write_count);

+  memset(timer_write_buf,0,TIMER_WRITE_BUF_SIZE);
   prefix_len = strlen(prefix_string);
-  fifoCmdBufEnqueueString(prefix_string,prefix_len,output_buf,IO_BUF_SIZE);
+  fifoCmdBufEnqueueString(prefix_string,prefix_len,timer_write_buf,TIMER_WRITE_BUF_SIZE);
   write_buf_len = strlen(write_buf);
-  fifoCmdBufEnqueueString(write_buf,write_buf_len,output_buf,IO_BUF_SIZE);
+  fifoCmdBufEnqueueString(write_buf,write_buf_len,timer_write_buf,TIMER_WRITE_BUF_SIZE);
+  timer_write_len = strlen(timer_write_buf);
+  fifoCmdBufEnqueueString(timer_write_buf,timer_write_len,output_buf,IO_BUF_SIZE);
 }

 // Remove the first character in output_buf and write to serial


goallien, fix newxy

goallien, fix newxy


Identified reason for crashes

Identified reason for crashes

--- ESP8266HueEmulator/ESP8266HueEmulator.ino
+++ ESP8266HueEmulator/ESP8266HueEmulator.ino
@@ -130,6 +130,8 @@

     RgbColor rgb;

+    // FIXME: Right now this code crashes the ESP when the hue app is used to change the brightness.
+    // FIXME: The hue app sends only bri and on when one changes the brightness; so we cannot assume there is hue in the request and need to get the hue from somewhere else!
     if (HTTP.arg("plain").length() > 30 )  // FIXME: Find a cleaner way to do this, can't aJson determine whether a key is present?
     {
       Serial.println("REQUEST CONTAINS HUE");
@@ -459,28 +461,26 @@
 struct HsbColor rgb2hsb(RgbColor color)
 {

-  Serial.println("FIXME HERE!");
-
   struct HsbColor hsb_instance;
   int hue, sat, bri;

   HslColor hsl = HslColor(color);
-  Serial.print("H = ");
-  Serial.println(hsl.H);
-  Serial.print("S = ");
-  Serial.println(hsl.S);
-  Serial.print("L = ");
-  Serial.println(hsl.L);
+  //  Serial.print("H = ");
+  //  Serial.println(hsl.H);
+  //  Serial.print("S = ");
+  //  Serial.println(hsl.S);
+  //  Serial.print("L = ");
+  //  Serial.println(hsl.L);

   hue = floor(hsl.H * 65535);
-  Serial.print("hue = ");
-  Serial.println(hue);
   sat = floor(hsl.S * 255);
-  Serial.print("sat = ");
-  Serial.println(sat);
   bri = floor(hsl.L * 2.55);
-  Serial.print("bri = ");
-  Serial.println(bri);
+  //  Serial.print("hue = ");
+  //  Serial.println(hue);
+  //  Serial.print("sat = ");
+  //  Serial.println(sat);
+  //  Serial.print("bri = ");
+  //  Serial.println(bri);

   hsb_instance.hue = hue;
   hsb_instance.sat = sat;


get temperature and display to screen

get temperature and display to screen

--- short-circuit-limiter/short-circuit-limiter.ino
+++ short-circuit-limiter/short-circuit-limiter.ino
@@ -5,8 +5,9 @@
 #define CURRENT_MCB_CUT 20

 #define PIN_LED 26
-#define PIN_ANALOG A0
+#define PIN_CT A0
 #define PIN_BUTTON_ENTER 24
+#define PIN_TEMP A11

 #define PIN_RELAY_MCB 5
 #define PIN_RELAY_LIMITER 7
@@ -15,11 +16,14 @@
 #define INITIAL_SETTLE_TIME 15000 //15 seconds

 #define DELAY_BEFORE_LIMITER_RELAY_ENABLE 1000
+
+//Number of temperature reads to average over
+#define TEMP_READS_SET 50

 //The MCU can take 5500 samples/s.
 //0.05s seconds will require 275 samples/set
 #define NUM_CT_SAMPLES 275
-#define INTERVAL_PRINT 500
+#define INTERVAL_PRINT 1000

 typedef enum {
   STATE_MCB_TRIPPED, STATE_WINDOW_BEFORE, STATE_WINDOW_WITHIN, STATE_WINDOW_EXITED
@@ -30,7 +34,7 @@
 STATE nextState = STATE_WINDOW_BEFORE;

 U8G2_UC1701_MINI12864_F_4W_SW_SPI u8g2(U8G2_R2, 21, 20, 19, 22);
-CTSensor clamp(PIN_ANALOG, CT_CALIBRATION_VALUE);
+CTSensor clamp(PIN_CT, CT_CALIBRATION_VALUE);

 unsigned long lastDisplayTime = 0;
 double runningTotal = 0;
@@ -47,6 +51,7 @@
   pinMode(PIN_RELAY_LIMITER, OUTPUT);
   pinMode(PIN_RELAY_MCB, OUTPUT);
   pinMode(PIN_BUTTON_ENTER, INPUT);
+  pinMode(PIN_TEMP, INPUT);

   changeDisplayBacklight(true);
   passFullCurrentThrough(false);
@@ -142,22 +147,27 @@

   //We don't want to keep printing to screen as it is slow so we just do a running average
   if((currentTime - lastDisplayTime) >= INTERVAL_PRINT){
+    float temperature = getTemperature();

     lastDisplayTime = currentTime;
     double average = runningTotal / samplesTaken;
+    Serial.println(average);

     runningTotal = 0;
     samplesTaken = 0;

     u8g2.setFont(u8g2_font_9x18_tr);
-    char currentBuffer[10];
-
-    dtostrf(currentValue, 4, 2, currentBuffer);
-
+    char buffer[10];
+
+    dtostrf(currentValue, 4, 2, buffer);

     u8g2.clearBuffer();

-    u8g2.drawStr(0,20, currentBuffer);
+    u8g2.drawStr(0,20, buffer);
+
+    dtostrf(temperature, 4, 0, buffer);
+
+    u8g2.drawStr(0,40, buffer);

     u8g2.sendBuffer();
   }
@@ -188,10 +198,6 @@
   if(currentState != STATE_WINDOW_BEFORE){

     passFullCurrentThrough(false);
-    changeMCBRelayState(false);
-
-    //In order to turn off the Bypass SSR, we have cut power to the entire setup first to prevent residual current from holding the Bypass SSR open
-    delay(50);
     changeMCBRelayState(true);

     currentState = STATE_WINDOW_BEFORE;
@@ -267,3 +273,28 @@
     digitalWrite(PIN_LED, HIGH);
   }
 }
+
+//Obtained from https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor
+float getTemperature(){
+
+  long total = 0;
+
+  //First value is usually off
+  analogRead(PIN_TEMP);
+
+  for(int i = 0; i < TEMP_READS_SET; i++){
+    total += analogRead(PIN_TEMP);
+  }
+
+  int reading = total / TEMP_READS_SET;
+
+  // converting that reading to voltage, for 3.3v arduino use 3.3
+  float voltage = reading * 5.0;
+  voltage /= 1024.0;
+
+  // now print out the temperature
+  float temperatureC = (voltage - 0.5) * 100 ;
+
+  return temperatureC;
+}
+


Update Encoder.ino

Update Encoder.ino

--- Testbench/Encoder_TestBench/Software/Encoder/Encoder.ino
+++ Testbench/Encoder_TestBench/Software/Encoder/Encoder.ino
@@ -4,7 +4,7 @@
 LiquidCrystal lcd(12,11,7,6,5,4);
 #define encoderPinA 2
 #define encoderPinB 3
-int pi = 3.1415926;
+float pi = 3.1415926;
 int count = 0;
 volatile int encoderCount = 0;
 volatile float angle = 0;
@@ -12,8 +12,10 @@
 volatile float angle_previous = 0;
 volatile float angle_post = 0;

+//initializing float values and int values.

-// Timer 2
+
+// Timer

 volatile int tcnt = 131;
 volatile int t = 0;
@@ -24,8 +26,8 @@
   // put your setup code here, to run once:
   pinMode(encoderPinA, INPUT);
   pinMode(encoderPinB, INPUT);
-  attachInterrupt(0, doEncoderA, CHANGE);
-  attachInterrupt(1, doEncoderB, CHANGE);
+  attachInterrupt(2, doEncoderA, CHANGE);
+  attachInterrupt(3, doEncoderB, CHANGE);
   lcd.begin(16,2);
   lcd.print("Angle:");
   lcd.setCursor(0,1);
@@ -40,9 +42,10 @@
   TCCR2B &= ~(1<<CS21);
   TCNT2 = tcnt;
   TIMSK2 |= (1<<TOIE2);
-  Serial.begin (9600); // for debugging
+  Serial.begin (9600); //
   delay(500);
 }
+

 void printlcdAngle(){
   lcd.setCursor(7,0);
@@ -121,3 +124,8 @@
   }
 }

+//changes made on 1/15/2017
+//int changed to float
+//Interrrupts changed to pins 2 and 3
+//bitwise operations?
+


505pm

--- acelaso.ino/acelaso.ino.ino
+++ acelaso.ino/acelaso.ino.ino
@@ -1,4 +1,3 @@
-
 #include <SI114.h>
 #include <Si114_defs.h>
 #include <Adafruit_FRAM_I2C.h>
@@ -32,7 +31,7 @@
 void setup()
 {
   Wire.begin(); // join i2c bus (address optional for master)
-  expanderSetInput(INaddr, 0xFF);
+  expanderSetInput(ExpAddress, 0xFF);
   Serial.begin(57600);
   Serial.println("Waiting for connection...");
   RFduinoBLE.begin();
@@ -55,8 +54,8 @@

   // I2C routines to talk to 8574 and 8574A
   void expanderSetInput(int i2caddr, byte dir) {
-  Wire.beginTransmission(INaddr);
-  Wire.send(dir);  // outputs high for input
+  Wire.beginTransmission(ExpAddress);
+  Wire.write(dir);  // outputs high for input
   Wire.endTransmission();
 }

@@ -64,7 +63,7 @@
   int _data = -1;
   Wire.requestFrom(i2caddr, 1);
   if(Wire.available()) {
-    _data = Wire.receive();
+    _data = Wire.read();
   }
   return _data;
 }
@@ -72,11 +71,8 @@
 void expanderWrite(int i2caddr, byte data)
 {
   Wire.beginTransmission(i2caddr);
-  Wire.send(data);
+  Wire.write(data);
   Wire.endTransmission();
-}
-
-
 }

 void RFduinoBLE_onConnect() {


Remove wrong path file.

Remove wrong path file.

--- examples/mqtt_bluemix_adc_test.ino
+++ examples/mqtt_bluemix_adc_test.ino
@@ -1,119 +0,0 @@
-#define DEBUG_MODE
-// #define DEBUG_LEVEL_VERBOSE
-
-#include <ESP8266WiFi.h>
-#include <ArduinoJson.h>
-#include <MqttWrapper.h>
-#include <PubSubClient.h>
-
-// const char* ssid     = "OpenWrt_NAT_500GP.101";
-// const char* pass = "activegateway";
-
-// const char* ssid     = "MAKERCLUB-CM";
-// const char* pass = "welcomegogogo";
-
-const char* ssid     = "Opendream Play";
-const char* pass = "5k,skrijv',7'sik";
-
-// const char* ssid     = "Opendream";
-// const char* pass = "gfkgvkgv'2015!!!!";
-
-
-MqttWrapper *mqtt;
-
-void connect_wifi()
-{
-    WiFi.begin(ssid, pass);
-
-    int retries = 0;
-    while ((WiFi.status() != WL_CONNECTED))
-    {
-        Serial.print(".");
-        retries++;
-        delay(500);
-    }
-
-    Serial.println("WIFI CONNECTED ");
-}
-
-void reconnect_wifi_if_link_down() {
-    if (WiFi.status() != WL_CONNECTED) {
-        DEBUG_PRINTLN("WIFI DISCONNECTED");
-        connect_wifi();
-    }
-}
-
-
-void callback(const MQTT::Publish& pub) {
-    if (pub.payload_string() == "0") {
-        Serial.print(" => ");
-        Serial.println(pub.payload_string());
-    }
-    else if(pub.payload_string() == "1") {
-        Serial.print(" => ");
-        Serial.println(pub.payload_string());
-    }
-    else {
-        Serial.print(pub.topic());
-        Serial.print(" => ");
-        Serial.println(pub.payload_string());
-    }
-}
-
-void hook_prepare_data(JsonObject** root) {
-  JsonObject& data = (*(*root))["d"];
-
-  data["myName"] = "NAT";
-  data["adc"] = analogRead(A0);;
-
-}
-
-void hook_configuration(MqttWrapper::Config config) {
-    uint8_t mac[6];
-    WiFi.macAddress(mac);
-    String result;
-    for (int i = 0; i < 6; ++i)
-    {
-        result += String(mac[i], 16);
-    }
-
-    *(config.clientId) = String("d:quickstart:esp8266:") + result;
-
-    // uncomment when user & password is required.
-    // *(config.username) = String("test");
-    // *(config.password) = String("test");
-    // *(config.channelId) = String("esp8266/");
-
-    *(config.topicPub) = "iot-2/evt/status/fmt/json";
-    Serial.println(
-        String("https://quickstart.internetofthings.") +
-                "ibmcloud.com/#/device/"+
-                result +"/sensor/"
-              );
-
-}
-
-void hook_publish_data(char* data) {
-    Serial.print("PUBLISH: ->");
-    Serial.println(data);
-}
-
-void setup() {
-    Serial.begin(115200);
-    pinMode(0, INPUT_PULLUP);
-    delay(10);
-    Serial.println();
-    Serial.println();
-
-    connect_wifi();
-
-    mqtt = new MqttWrapper("quickstart.messaging.internetofthings.ibmcloud.com", 1883, hook_configuration);
-    mqtt->connect();
-    mqtt->set_prepare_data_hook(hook_prepare_data, 5000);
-    mqtt->set_publish_data_hook(hook_publish_data);
-}
-
-void loop() {
-    reconnect_wifi_if_link_down();
-    mqtt->loop();
-}


Fix inverted yaw logic

Fix inverted yaw logic

--- examples/quadcopter/quadcopter.ino
+++ examples/quadcopter/quadcopter.ino
@@ -114,7 +114,7 @@
     if(timer()){
         float pitchCmd = ((float)APMRadio::get(RADIO_PITCH)-90) /-70.0;
         float rollCmd  = ((float)APMRadio::get(RADIO_ROLL)-90)  /-70.0;
-        float yawCmd   = ((float)APMRadio::get(RADIO_YAW)-90)   / 90.0;
+        float yawCmd   = ((float)APMRadio::get(RADIO_YAW)-90)   /-90.0;
         float throttle = ((float)APMRadio::get(RADIO_THROTTLE)-25)/130.0;
         bool altSwitch = (APMRadio::get(RADIO_GEAR) > 90);


Fixed the send_to_robot function.

Fixed the send_to_robot function.

--- firmware/2016/radio_pipe/radio_pipe.ino
+++ firmware/2016/radio_pipe/radio_pipe.ino
@@ -7,7 +7,8 @@
 /**********************************************************/

 byte pipe[][6] = {"1Node","2Node","3Node","4Node"};
-int receive_msg[1]; //pipe number
+int msg_from_robot[2]; //pipe number
+int msg_from_ROS[2];

 void setup() {
   Serial.begin(250000);
@@ -31,7 +32,7 @@
 bool receive_data_from_robot() {
   if(radio.available()){
     while (radio.available()) {
-      radio.read(&receive_msg, sizeof(receive_msg));
+      radio.read(&msg_from_robot, sizeof(msg_from_robot));
     }
     return true;
   }
@@ -39,34 +40,25 @@
 }

 void send_data_to_ROS() {
-  Serial.println(receive_msg[0]); //Serial.write() may be a better choice for this
-  Serial.println(receive_msg[1]); //Serial.write() may be a better choice for this
+  Serial.println(msg_from_robot[0]); //Serial.write() may be a better choice for this
+  Serial.println(msg_from_robot[1]); //Serial.write() may be a better choice for this
 }
-
-String input_string;
-int string_length = 0;

 bool receive_data_from_ROS() {
   if(Serial.available()){
-    input_string = "";
+    int i=0;
     while (Serial.available()) {
-      char in_char = (char)Serial.read(); //taken from the SerialEvent example
-      input_string += in_char;
+      msg_from_ROS[i] = Serial.read();
     }
-    if (input_string.length() == string_length)
-      return true;
+    return true;
   }
   return false;
 }

 void send_data_to_robot() {
-  if(radio.available()){
-    while (radio.available()) {
-      radio.read(&receive_msg, sizeof(receive_msg));
-    }
-    return true;
-  }
-  return false;
+  radio.stopListening();
+  radio.write(msg_from_ROS, sizeof(msg_from_ROS));
+  radio.startListening();
 }

 void loop() {


move wifiMills outside of debug

move wifiMills outside of debug

--- _15-esp8266-dash-deepsleep-reset/_15-esp8266-dash-deepsleep-reset.ino
+++ _15-esp8266-dash-deepsleep-reset/_15-esp8266-dash-deepsleep-reset.ino
@@ -135,8 +135,8 @@
       }
     }

-    if (DEBUG_PRINT) {
-      wifiMills = millis() - startMills;
+    wifiMills = millis() - startMills;
+    if (DEBUG_PRINT) {
       Serial.println();
       Serial.print("===> WiFi connected : ");
       Serial.println(wifiMills);
@@ -172,7 +172,7 @@
   }

   system_deep_sleep_set_option(2);
-  //wifi_set_phy_mode(PHY_MODE_11N);
+  wifi_set_phy_mode(PHY_MODE_11N);

   digitalWrite(redLED, LOW);
   wifi_connect();
@@ -207,7 +207,7 @@
   }

   if ( subMsgReceived == HIGH ) {
-    subMills = millis() - startMills;
+    subMills = (millis() - startMills) - wifiMills ;
     if (DEBUG_PRINT) {
       Serial.print("sub received ---> ");
       Serial.println(subMills);
@@ -254,6 +254,7 @@
     buttonpayload += ",\"subMills\":";
     buttonpayload += subMills ;
     buttonpayload += "}";
+
     if (DEBUG_PRINT) {
       Serial.print("status pub ---> ");
       Serial.println(millis() - startMills);


check relay status

check relay status

--- _15-esp8266-dash-deepsleep-reset/_15-esp8266-dash-deepsleep-reset.ino
+++ _15-esp8266-dash-deepsleep-reset/_15-esp8266-dash-deepsleep-reset.ino
@@ -1,5 +1,6 @@
 #include <ESP8266WiFi.h>
 #include <PubSubClient.h>
+#include <ArduinoJson.h>

 #define _IS_MY_HOME
 // wifi
@@ -45,6 +46,7 @@
 volatile int subMsgReceived = LOW;
 volatile int topicMsgSent   = LOW;
 volatile int relaystatus    = LOW;
+volatile int relayReady     = LOW;

 int vdd;

@@ -76,19 +78,47 @@
     Serial.println(receivedpayload);
   }

-  if ( receivedpayload == "{\"LIGHT\":1}") {
-    relaystatus = 1 ;
-  }
-  else if ( receivedpayload == "{\"LIGHT\":0}") {
-    relaystatus = 0 ;
+  char json[] = "{\"LIGHT\":1,\"READY\":1}";
+  receivedpayload.toCharArray(json, 100);
+  StaticJsonBuffer<100> jsonBuffer;
+  JsonObject& root = jsonBuffer.parseObject(json);
+
+  if (!root.success()) {
+    if (DEBUG_PRINT) {
+      Serial.println("parseObject() failed");
+    }
+    subMsgReceived = HIGH;
+    relayReady = LOW ;
+    return;
+  }
+
+  int LIGHT = root["LIGHT"];
+  int READY = root["READY"];
+
+  if ( READY == 1 ) {
+    if ( LIGHT == 1 ) {
+      relaystatus = 1;
+    }
+    if ( LIGHT == 0) {
+      relaystatus = 0;
+    }
+    subMsgReceived = HIGH;
+    relayReady = HIGH ;
+  }
+
+  if ( READY == 0 ) {
+    subMsgReceived = HIGH;
+    relayReady = LOW ;
   }

   if (DEBUG_PRINT) {
     Serial.print("mqtt sub => ");
-    Serial.print("relaystatus => ");
-    Serial.println(relaystatus);
-  }
-  subMsgReceived = HIGH;
+    Serial.print("ready ==> ");
+    Serial.print(READY);
+    Serial.print(" relaystatus => ");
+    Serial.println(LIGHT);
+  }
+
 }

 boolean reconnect()
@@ -252,14 +282,22 @@
     wifi_connect();
   }

-
-  if ( subMsgReceived == HIGH ) {
+  if (( subMsgReceived == HIGH ) && ( relayReady == HIGH )) {
     subMills = (millis() - startMills) - wifiMills ;
     if (DEBUG_PRINT) {
-      Serial.print("sub received ---> ");
+      Serial.print("sub received : ready ---> ");
       Serial.println(subMills);
     }
     sendlightcmd();
+  }
+
+  if (( subMsgReceived == HIGH ) && ( relayReady == LOW )) {
+    subMills = (millis() - startMills) - wifiMills ;
+    if (DEBUG_PRINT) {
+      Serial.print("sub received : not ready ---> ");
+      Serial.println(subMills);
+    }
+    goingToSleepWithFail();
   }

   if ( topicMsgSent == HIGH ) {


Set optimal gain in 4-20mA continuous mode example.

--- examples/ContinuousMode4to20mA/ContinuousMode4to20mA.ino
+++ examples/ContinuousMode4to20mA/ContinuousMode4to20mA.ino
@@ -21,6 +21,9 @@
   Serial.println("ADC Nanoshield - Continuous Mode");
   adc.begin();

+  // Adjust gain to two (2.048V range) to get maximum resolution for 4-20mA range
+  adc.setGain(GAIN_TWO);
+
   // Set sample rate. Possible values are:
   //   - 16-bit (Nanoshield_ADC): 8, 16, 32, 64, 128, 250, 475, 860
   // If not one of the above, the closest lower value will be selected.


Several changes

Several changes

Fixed bug that limited baud rate
improved meter logging
measure average light during setup
take multiple light readings while motor is stopped


Updated code

Updated code

Just a few optimisations

--- esp32LightServerRGB.ino
+++ esp32LightServerRGB.ino
@@ -1,630 +1,675 @@
-#include <WiFi.h>
-#include <DNSServer.h>
-#include <WebServer.h>
-#include <WiFiManager.h>
-#include <WiFiMulti.h>
-#include <HTTPClient.h>
-
-// sensors stuff
-#include <OneWire.h>
-#include <DallasTemperature.h>
-#include <DHT.h>
-#include <ESPmDNS.h>
-#define ONE_WIRE_BUS 15
-#define DHTPIN 2
-#define DHTTYPE DHT11
-DHT dht(DHTPIN, DHTTYPE);
-OneWire oneWire(ONE_WIRE_BUS);
-DallasTemperature sensors(&oneWire);
-// end of sensors
-
-// Settings you should check/change
-String resetpass = "YOURresetPASSWORD"; // password to reset wifimanager when allready connected
-const String thingkey = "YourThingSpeakApiWriteKey"; //your thingspeak API key
-const String thingchanel = "000000"; //your thingspeak Chanel #
-// other settings you might like to change
-const long interval = 60000; // interval in ms for sending temperature data to thingspeak
-const String liens = "Acceuil - Température - Version - Reset - Temp stats\n"; // html/links shown at bottom of pages
-String dernadd = "Fraichement booté"; //variable for ip logging (you can put your fresh boot mesage here in text/html)
-// led pins
-uint8_t pinRouge = 12;
-uint8_t pinVerte = 14; // internally pulled up
-uint8_t pinBleu = 13;
-// end of settings you should check/change
-
-// internally used vars
-WebServer server(80);
-String derncoul = "#000000";
-long r = 0;
-long g = 0;
-long b = 0;
-int rouge = 0;
-int vert = 0;
-int bleu = 0;
-unsigned long previousMillis = 0;
-unsigned long previousMillisr = 0;
-unsigned long previousMillisg = 0;
-unsigned long previousMillisb = 0;
-unsigned long previousMillisf = 0;
-int attendR = 70;
-int attendG = 70;
-int attendB = 70;
-int attendF = 700;
-unsigned long flashfois = 0;
-unsigned long flashrendu = 0;
-int roulepastusuite = 0;
-int flashoufade = 0;
-// end of internally used vars
-
-// stylesheet for web pages
-const String css = "\n";
-// end of stylesheet for web pages
-
-// functions used internally
-
-// used to flash leds
-void flashfunk() {
-  if (flashrendu <= flashfois) {
-    flashrendu++;
-    if (rouge == r) {
-      ledcWrite(1, 0);
-      rouge = 0;
-    } else {
-      ledcWrite(1, r);
-      rouge = r;
-    }
-    if (vert == g) {
-      ledcWrite(2, 0);
-      vert = 0;
-    } else {
-      ledcWrite(2, g);
-      vert = g;
-    }
-    if (bleu == b) {
-      ledcWrite(3, 0);
-      bleu = 0;
-    } else {
-      ledcWrite(3, b);
-      bleu = b;
-    }
-  } else {
-    r = rouge;
-    b = bleu;
-    g = vert;
-    flashoufade = 0;
-    flashrendu = 0;
-    Serial.println("Flash fini");
-  }
-}
-
-// used to fade red
-void fadeR() {
-  if (rouge < r) {
-    rouge++;
-    ledcWrite(1, rouge);
-  } else if (rouge > r) {
-    rouge--;
-    ledcWrite(1, rouge);
-  }
-}
-
-// used to fade green
-void fadeG() {
-  if (vert < g) {
-    vert++;
-    ledcWrite(2, vert);
-  } else if (vert > g) {
-    vert--;
-    ledcWrite(2, vert);
-  }
-}
-
-// used to fade blue
-void fadeB() {
-  if (bleu  b) {
-    bleu--;
-    ledcWrite(3, bleu);
-  }
-}
-
-// web page to handle flashing of leds (color/delay/number of flashes)
-void handleFlash() {
-  String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("Flash");
-  String testteu = server.arg("COULEUR");
-  String attend = server.arg("DELAIS");
-  attendF = attend.toInt();
-  String flashnombre = server.arg("FOIS");
-  flashfois = flashnombre.toInt();
-  flashfois = flashfois * 2;
-  Serial.println(testteu);
-  Serial.print("Delais - ");
-  Serial.println(attendF);
-  Serial.print("Fois - ");
-  Serial.println(flashfois / 2);
-  if (testteu != 0) {
-    derncoul = testteu;
-    long number = strtol( &testteu[1], NULL, 16);
-    r = number >> 16;
-    g = number >> 8 & 0xFF;
-    b = number & 0xFF;
-    Serial.print("Rouge = ");
-    Serial.println(r);
-    Serial.print("Vert = ");
-    Serial.println(g);
-    Serial.print("Bleu = ");
-    Serial.println(b);
-    dernadd = addy;
-    flashoufade = 1;
-    flashrendu = 0;
-    ledcWrite(1, 0);
-    ledcWrite(2, 0);
-    ledcWrite(3, 0);
-    rouge = 0;
-    bleu = 0;
-    vert = 0;
-  }
-  String contenu = "<!DOCTYPE html>\n\n\n";
-  contenu += "<meta http-equiv=\"refresh\" content=\"0;url=/\" />\n";
-  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere soit</title>\n"
-             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
-  contenu += css;
-  contenu += "\n\n"
-             "Merci\n";
-  server.send(200, "text/html", contenu);
-}
-
-// web page to handle leds fading
-void handleLeds() {
-  String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  String testteu = server.arg("COULEUR");
-  Serial.println(testteu);
-  if (testteu != 0) {
-    derncoul = testteu;
-    long number = strtol( &testteu[1], NULL, 16);
-    r = number >> 16;
-    g = number >> 8 & 0xFF;
-    b = number & 0xFF;
-    if (r != rouge) {
-      Serial.print("Rouge = ");
-      Serial.println(r);
-      dernadd = addy;
-      flashoufade = 0;
-    }
-    if (g != vert) {
-      Serial.print("Vert = ");
-      Serial.println(g);
-      dernadd = addy;
-      flashoufade = 0;
-    }
-    if (b != bleu) {
-      Serial.print("Bleu = ");
-      Serial.println(b);
-      dernadd = addy;
-      flashoufade = 0;
-    }
-  }
-  String contenu = "<!DOCTYPE html>\n\n\n";
-  contenu += "<meta http-equiv=\"refresh\" content=\"0;url=/\" />\n";
-  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere soit</title>\n"
-             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
-  contenu += css;
-  contenu += "\n\n"
-             "Merci\n";
-  server.send(200, "text/html", contenu);
-}
-
-// index page
-void handleRoot() {
-  String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("Page acceuil");
-  String contenu = "<!DOCTYPE html>\n\n\n";
-  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere soit</title>\n"
-             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
-  contenu += css;
-  contenu += "\n";
-  contenu += "\n\n"
-             "
\n"
-             "<form id=\"laforme\" action=\"/leds\" method=\"post\">\n"
-             "
Change la couleur de mon bureau:
"
-             "<input id=\"colorpad\" type=\"color\" name=\"COULEUR\" class=\"color\" value=\"" + derncoul + "\">
\n"
-             "<input type=\"submit\" class=\"button1\" value=\"Changer\">\n"
-             "</form>\n"
-             "<button onclick=\"disco()\">Hazard</button>
\n"
-             "<button onclick=\"startDisco()\">Auto Disco</button>
\n"
-             "Dernier IP à avoir changé la couleur : ";
-  contenu += dernadd;
-  contenu += "
\n";
-  contenu += liens;
-  contenu += "\n"
-             "
\n";
-  server.send(200, "text/html", contenu);
-}
-
-//reset page
-void handleReset() {
-  int ouireset = 0;
-  String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.println("!!! RESET PAGE !!!");
-  String testteu = server.arg("RESET");
-  String passme = server.arg("PASSME");
-  if (testteu == "OUI") {
-    if (passme == resetpass) {
-      ouireset = 1;
-    } else {
-      ouireset = 2;
-    }
-  }
-  String contenu = "<!DOCTYPE html>\n\n\n";
-  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere se RESET</title>\n"
-             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
-  contenu += css;
-  contenu += "\n\n"
-             "
\n";
-  if (!ouireset) {
-    contenu += "<form action=\"/reset\" method=\"post\">\n"
-               "
Tu veux resetter le wifi network pour reconfigurer ?
"
-               "<input type=\"hidden\" name=\"RESET\" value=\"OUI\">
\n"
-               "<input type=\"password\" name=\"PASSME\" value=\"password\">
\n"
-               "<input type=\"submit\" class=\"button1\" value=\"Reset Wifi Network\">\n"
-               "</form>\n";
-  } else if (ouireset != 1) {
-    contenu += "<form action=\"/reset\" method=\"post\">\n"
-               "
Tu veux resetter le wifi network pour reconfigurer ?
"
-               "<input type=\"hidden\" name=\"RESET\" value=\"OUI\">
\n"
-               "<input type=\"password\" name=\"PASSME\" value=\"password\">
\n"
-               "
!!! MAUVAIS PASSWORD !!!

\n"
-               "<input type=\"submit\" class=\"button1\" value=\"Reset Wifi Network\">\n"
-               "</form>\n";
-    Serial.print("BAD PASSWORD : ");
-    Serial.println(passme);
-  } else if (ouireset == 1) {
-    contenu += "
Reset Dans 10 Secondes
\n";
-  }
-  contenu += "
Dernier IP à avoir changé la couleur :";
-  contenu += dernadd;
-  contenu += "\n
";
-  contenu += liens;
-  contenu += "\n

\n";
-  server.send(200, "text/html", contenu);
-  if (ouireset == 1) {
-    Serial.println("Reset dans 10 secondes");
-    delay(10000);
-    WiFiManager wifiManager;
-    wifiManager.resetSettings();
-    ESP.restart();
-  }
-}
-
-// 404 not found page
-void handleNotFound() {
-  String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  String htmlmessage = "<!DOCTYPE html>\n\n\n";
-  htmlmessage += "<meta charset=\"UTF-8\" />\n<title>404 Not found</title>\n"
-                 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
-  htmlmessage += css;
-  htmlmessage += "\n\n"
-                 "
\n";
-  htmlmessage += "
404 File Not Found

\n";
-  htmlmessage += "URI: ";
-  htmlmessage += server.uri();
-  htmlmessage += "
\nMethod: ";
-  htmlmessage += (server.method() == HTTP_GET) ? "GET" : "POST";
-  htmlmessage += "
\nArguments: ";
-  htmlmessage += server.args();
-  htmlmessage += "
\n";
-  for (uint8_t i = 0; i < server.args(); i++) {
-    htmlmessage += " " + server.argName(i) + ": " + server.arg(i) + "
\n";
-  }
-  htmlmessage += "
\n";
-  htmlmessage += liens;
-  htmlmessage += "
\n
\n";
-  server.send(404, "text/html", htmlmessage);
-  String message = "404 File Not Found\n";
-  message += "URI: ";
-  message += server.uri();
-  message += "\nMethod: ";
-  message += (server.method() == HTTP_GET) ? "GET" : "POST";
-  message += "\nArguments: ";
-  message += server.args();
-  message += "\n";
-  for (uint8_t i = 0; i < server.args(); i++) {
-    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
-  }
-  Serial.print(message);
-}
-
-// function executed in main loop every minute to update sensors data to thingspeak.com
-void latemp() {
-  sensors.requestTemperatures();
-  float thetemp = sensors.getTempCByIndex(0);
-  char buffer[10];
-  String tempC = dtostrf(thetemp, 5, 2, buffer);
-  float h = dht.readHumidity();
-  float t = dht.readTemperature();
-  if (tempC != "-127.00") {
-    if (tempC != "85.00") {
-      Serial.print("Envoi de temperature et humidite: ");
-      Serial.print(tempC);
-      Serial.print(" - ");
-      HTTPClient http;
-      String webadd = "http://api.thingspeak.com/update?key=";
-      webadd += thingkey;
-      webadd += "&field1=";
-      webadd += tempC;
-      if (h == h) { // to prevent NaN
-        webadd += "&field2=";
-        webadd += h;
-        Serial.print(h);
-        webadd += "&field3=";
-        webadd += t;
-      }
-      Serial.println("");
-      http.begin(webadd);
-      int httpCode = http.GET();//Send the request
-      http.end();   //Close connection
-    }
-  }
-}
-
-// web page for showing sensors data
-void handleTemp() {
-  sensors.requestTemperatures();
-  float latemp = sensors.getTempCByIndex(0);
-  float h = dht.readHumidity();
-  while (latemp == -127.00) {
-    sensors.requestTemperatures();
-    latemp = sensors.getTempCByIndex(0);
-  }
-  String addy = server.client().remoteIP().toString();
-  Serial.println("");
-  Serial.println(addy);
-  Serial.print("Temperature : ");
-  Serial.println(latemp);
-  String contenu = "<!DOCTYPE html>\n\n\n";
-  contenu += "<meta charset=\"UTF-8\" />\n<title>Quel chaleur</title>\n"
-             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
-  contenu += css;
-  contenu += "\n\n"
-             "
\n";
-  contenu += "<form action=\"/\" method=\"get\">\n"
-             "
Voici la temperature
"
-             "
";
-  contenu += latemp;
-  contenu += "°C Humidité : ";
-  contenu += h;
-  contenu += "

\n"
-             ""
-             ""
-             "<input type=\"submit\" class=\"button1\" value=\"Acceuil\">\n"
-             "</form>\n"
-             "
Dernier IP à avoir changé la couleur :";
-  contenu += dernadd;
-  contenu += "\n
";
-  contenu += liens;
-  contenu += "\n

\n";
-  server.send(200, "text/html", contenu);
-}
-
-void setup() {
-  Serial.begin(115200);
-  dht.begin();
-  ledcAttachPin(pinRouge, 1); // assign RGB led pins to channels
-  ledcAttachPin(pinVerte, 2);
-  ledcAttachPin(pinBleu, 3);
-  pinMode(pinRouge, OUTPUT);
-  pinMode(pinVerte, OUTPUT);
-  pinMode(pinBleu, OUTPUT);
-  digitalWrite(pinRouge, LOW);
-  digitalWrite(pinBleu, LOW);
-  digitalWrite(pinVerte, LOW);
-  ledcSetup(1, 12000, 8); // 12 kHz PWM, 8-bit resolution
-  ledcSetup(2, 12000, 8);
-  ledcSetup(3, 12000, 8);
-  WiFiManager wifiManager;
-  wifiManager.autoConnect();
-  MDNS.begin("lumiere");
-  server.on("/", handleRoot);
-  server.on("/leds", handleLeds);
-  server.on("/flash", handleFlash);
-  server.on("/reset", handleReset);
-  server.on("/temp", handleTemp);
-  server.on("/version", []() {
-    String addy = server.client().remoteIP().toString();
-    Serial.println("");
-    Serial.println(addy);
-    Serial.println("Version request");
-    server.send(200, "text/html", "V2.0, Steve Olmstead sansillusion@gmail.com\n\n

"
-                "Added fader function\nRemoved connection watchdog (better have good signal)\n
"
-                "Removed mDns (did not work anyway)\n\n

"
-                "Added smoother fading\n\n

"
-                "Added AutoConect WifiManager !\n\n

"
-                "Added basic last IP logging\n
"
-                "Added /reset page to reset wifiManager connection settings\n\n

"
-                "Added /temp (temperature sensor read of ky-001)\n\n

"
-                "Added thingspeak support to send temperature each minute
\n\n
"
-                "Major rewrite for RGB led trip usin mosfet
\n"
-                "Removed serial to free resources for software pwm (still flikers but less than before)
\n\n
"
-                "Seperated LEDs handling page from index\n
"
-                "Added jQuery to load settings without reloading page\n
"
-                "Added random color selection button\n\n

"
-                "Added disco mode script and buttons\n\n

"
-                "Removed mDNS (does not work with esp32)\n
"
-                "        (Re-aded mDNS in 2.0 for esp32 but does not seem to work yet)\n
"
-                "Rewrite of code (removed Ticker and changed a few libraries) for esp32 !!!\n\n

"
-                "Changed fader functions for smoother fade\n
"
-                "Cleaned code\n\n

"
-                "Added Flashing function and page for smart widget usage\n
"
-                "Added var to show your thingspeak channel in /temp iframes\n\n

" + liens);
-  });
-  server.onNotFound(handleNotFound);
-  server.begin();
-  Serial.println("HTTP server started");
-  delay(100);
-  MDNS.addService("http", "tcp", 80);
-  sensors.begin();
-}
-
-void loop() {
-  server.handleClient();
-  unsigned long currentMillis = millis();
-  if (currentMillis - previousMillis >= interval) {
-    previousMillis = currentMillis;
-    latemp();
-  }
-  if (flashoufade == 1) {
-    currentMillis = millis();
-    if (currentMillis - previousMillisf >= attendF) {
-      previousMillisf = currentMillis;
-      flashfunk();
-    }
-  } else {
-    if (r != rouge) {
-      currentMillis = millis();
-      if (currentMillis - previousMillisr >= attendR) {
-        fadeR();
-        previousMillisr = currentMillis;
-        if (rouge > 0)
-          attendR = 70;
-        if (rouge > 40)
-          attendR = 60;
-        if (rouge > 80)
-          attendR = 50;
-        if (rouge > 100)
-          attendR = 40;
-        if (rouge > 120)
-          attendR = 30;
-        if (rouge > 140)
-          attendR = 20;
-        if (rouge > 180)
-          attendR = 10;
-      }
-    }
-    if (g != vert) {
-      currentMillis = millis();
-      if (currentMillis - previousMillisg >= attendG) {
-        fadeG();
-        previousMillisg = currentMillis;
-        if (vert > 0)
-          attendG = 70;
-        if (vert > 40)
-          attendG = 60;
-        if (vert > 80)
-          attendG = 50;
-        if (vert > 100)
-          attendG = 40;
-        if (vert > 120)
-          attendG = 30;
-        if (vert > 140)
-          attendG = 20;
-        if (vert > 180)
-          attendG = 10;
-      }
-    }
-    if (b != bleu) {
-      currentMillis = millis();
-      if (currentMillis - previousMillisb >= attendB) {
-        fadeB();
-        previousMillisb = currentMillis;
-        if (bleu > 0)
-          attendB = 70;
-        if (bleu > 40)
-          attendB = 60;
-        if (bleu > 80)
-          attendB = 50;
-        if (bleu > 100)
-          attendB = 40;
-        if (bleu > 120)
-          attendB = 30;
-        if (bleu > 140)
-          attendB = 20;
-        if (bleu > 180)
-          attendB = 10;
-      }
-    }
-  }
-}
-
-
+#include <WiFi.h>
+#include <DNSServer.h>
+#include <WebServer.h>
+#include <WiFiManager.h>
+#include <WiFiMulti.h>
+#include <HTTPClient.h>
+
+// sensors stuff
+#include <OneWire.h>
+#include <DallasTemperature.h>
+#include <DHT.h>
+#include <ESPmDNS.h>
+#define ONE_WIRE_BUS 5
+#define DHTPIN 15
+#define DHTTYPE DHT11
+DHT dht(DHTPIN, DHTTYPE);
+OneWire oneWire(ONE_WIRE_BUS);
+DallasTemperature sensors(&oneWire);
+// end of sensors
+
+// Settings you should check/change
+String resetpass = "YourWifiResetPassword"; // password to reset wifimanager when allready connected
+const String thingkey = "YourThingSpeakKey"; //your thingspeak API key
+const String thingchanel = "000000"; //your thingspeak Chanel #
+const long interval = 60000; // interval in ms for sending temperature data to thingspeak
+const String liens = "Acceuil - Température - Version - Reset - Temp stats\n"; // html/links shown at bottom of pages
+String dernadd = "Fraichement booté"; //variable for ip logging (you can put your fresh boot mesage here in text/html)
+// led pins
+uint8_t pinRouge = 12;
+uint8_t pinVerte = 14; // internally pulled up
+uint8_t pinBleu = 13;
+// end of settings you should check/change
+
+// internally used vars
+WebServer server(80);
+String derncoul = "#000000";
+long r = 0;
+long g = 0;
+long b = 0;
+int rouge = 0;
+int vert = 0;
+int bleu = 0;
+unsigned long previousMillis = 0;
+unsigned long previousMillisr = 0;
+unsigned long previousMillisg = 0;
+unsigned long previousMillisb = 0;
+unsigned long previousMillisf = 0;
+int attendR = 70;
+int attendG = 70;
+int attendB = 70;
+int attendF = 700;
+unsigned long flashfois = 0;
+unsigned long flashrendu = 0;
+int roulepastusuite = 0;
+int flashoufade = 0;
+// end of internally used vars
+
+// stylesheet for web pages
+const String css = "\n";
+// end of stylesheet for web pages
+
+// functions used internally
+
+// used to flash leds
+void flashfunk() {
+  if (flashrendu <= flashfois) {
+    flashrendu++;
+    if (rouge == r) {
+      ledcWrite(1, 0);
+      rouge = 0;
+    } else {
+      ledcWrite(1, r);
+      rouge = r;
+    }
+    if (vert == g) {
+      ledcWrite(2, 0);
+      vert = 0;
+    } else {
+      ledcWrite(2, g);
+      vert = g;
+    }
+    if (bleu == b) {
+      ledcWrite(3, 0);
+      bleu = 0;
+    } else {
+      ledcWrite(3, b);
+      bleu = b;
+    }
+  } else {
+    r = rouge;
+    b = bleu;
+    g = vert;
+    flashoufade = 0;
+    flashrendu = 0;
+    Serial.println("Flash fini");
+  }
+}
+
+// used to fade red
+void fadeR() {
+  if (rouge < r) {
+    rouge++;
+    ledcWrite(1, rouge);
+  } else if (rouge > r) {
+    rouge--;
+    ledcWrite(1, rouge);
+  }
+}
+
+// used to fade green
+void fadeG() {
+  if (vert < g) {
+    vert++;
+    ledcWrite(2, vert);
+  } else if (vert > g) {
+    vert--;
+    ledcWrite(2, vert);
+  }
+}
+
+// used to fade blue
+void fadeB() {
+  if (bleu  b) {
+    bleu--;
+    ledcWrite(3, bleu);
+  }
+}
+
+// web page to handle flashing of leds (color/delay/number of flashes)
+void handleFlash() {
+  String addy = server.client().remoteIP().toString();
+  Serial.println("");
+  Serial.println(addy);
+  Serial.println("Flash");
+  String testteu = server.arg("COULEUR");
+  String attend = server.arg("DELAIS");
+  attendF = attend.toInt();
+  String flashnombre = server.arg("FOIS");
+  flashfois = flashnombre.toInt();
+  flashfois = flashfois * 2;
+  Serial.println(testteu);
+  Serial.print("Delais - ");
+  Serial.println(attendF);
+  Serial.print("Fois - ");
+  Serial.println(flashfois / 2);
+  if (testteu != 0) {
+    derncoul = testteu;
+    long number = strtol( &testteu[1], NULL, 16);
+    r = number >> 16;
+    g = number >> 8 & 0xFF;
+    b = number & 0xFF;
+    Serial.print("Rouge = ");
+    Serial.println(r);
+    Serial.print("Vert = ");
+    Serial.println(g);
+    Serial.print("Bleu = ");
+    Serial.println(b);
+    dernadd = addy;
+    flashoufade = 1;
+    flashrendu = 0;
+    ledcWrite(1, 0);
+    ledcWrite(2, 0);
+    ledcWrite(3, 0);
+    rouge = 0;
+    bleu = 0;
+    vert = 0;
+  }
+  String contenu = "<!DOCTYPE html>\n\n\n";
+  contenu += "<meta http-equiv=\"refresh\" content=\"0;url=/party\" />\n";
+  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere soit</title>\n"
+             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  contenu += css;
+  contenu += "\n\n"
+             "Merci\n";
+  server.send(200, "text/html", contenu);
+}
+
+// web page for flash mode
+void handleClignote() {
+  String addy = server.client().remoteIP().toString();
+  Serial.println("");
+  Serial.println(addy);
+  Serial.println("Page flash");
+  String contenu = "<!DOCTYPE html>\n\n\n";
+  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere flash</title>\n"
+             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  contenu += css;
+  contenu += "\n";
+  contenu += "\n\n"
+             "
\n"
+             "<form id=\"laforme\" action=\"/flash\" method=\"post\">\n"
+             "
Change la couleur de mon bureau:
"
+             "<input id=\"colorpad\" type=\"color\" name=\"COULEUR\" class=\"color\" value=\"" + derncoul + "\">
\n"
+             "Fois: <input id=\"fois\" type=\"number\" name=\"FOIS\" class=\"numbers\"> "
+             "Delais(ms): <input id=\"delais\" type=\"number\" name=\"DELAIS\" class=\"numbers\">
\n"
+             "<input type=\"submit\" class=\"button1\" value=\"Changer\">\n"
+             "</form>\n"
+             "<button onclick=\"disco()\">Hazard</button>
\n"
+             "<button onclick=\"startDisco()\">Auto Disco</button>
\n"
+             "Dernier IP à avoir changé la couleur : ";
+  contenu += dernadd;
+  contenu += "
\n";
+  contenu += liens;
+  contenu += "\n"
+             "
\n";
+  server.send(200, "text/html", contenu);
+}
+
+// web page to handle leds fading
+void handleLeds() {
+  String addy = server.client().remoteIP().toString();
+  Serial.println("");
+  Serial.println(addy);
+  String testteu = server.arg("COULEUR");
+  Serial.println(testteu);
+  if (testteu != 0) {
+    derncoul = testteu;
+    long number = strtol( &testteu[1], NULL, 16);
+    r = number >> 16;
+    g = number >> 8 & 0xFF;
+    b = number & 0xFF;
+    if (r != rouge) {
+      Serial.print("Rouge = ");
+      Serial.println(r);
+      dernadd = addy;
+      flashoufade = 0;
+    }
+    if (g != vert) {
+      Serial.print("Vert = ");
+      Serial.println(g);
+      dernadd = addy;
+      flashoufade = 0;
+    }
+    if (b != bleu) {
+      Serial.print("Bleu = ");
+      Serial.println(b);
+      dernadd = addy;
+      flashoufade = 0;
+    }
+  }
+  String contenu = "<!DOCTYPE html>\n\n\n";
+  contenu += "<meta http-equiv=\"refresh\" content=\"0;url=/\" />\n";
+  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere soit</title>\n"
+             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  contenu += css;
+  contenu += "\n\n"
+             "Merci\n";
+  server.send(200, "text/html", contenu);
+}
+
+// index page
+void handleRoot() {
+  String addy = server.client().remoteIP().toString();
+  Serial.println("");
+  Serial.println(addy);
+  Serial.println("Page acceuil");
+  String contenu = "<!DOCTYPE html>\n\n\n";
+  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere soit</title>\n"
+             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  contenu += css;
+  contenu += "\n";
+  contenu += "\n\n"
+             "
\n"
+             "<form id=\"laforme\" action=\"/leds\" method=\"post\">\n"
+             "
Change la couleur de mon bureau:
"
+             "<input id=\"colorpad\" type=\"color\" name=\"COULEUR\" class=\"color\" value=\"" + derncoul + "\">
\n"
+             "<input type=\"submit\" class=\"button1\" value=\"Changer\">\n"
+             "</form>\n"
+             "<button onclick=\"disco()\">Hazard</button>
\n"
+             "<button onclick=\"startDisco()\">Auto Disco</button>
\n"
+             "Dernier IP à avoir changé la couleur : ";
+  contenu += dernadd;
+  contenu += "
\n";
+  contenu += liens;
+  contenu += "\n"
+             "
\n";
+  server.send(200, "text/html", contenu);
+}
+
+//reset page
+void handleReset() {
+  int ouireset = 0;
+  String addy = server.client().remoteIP().toString();
+  Serial.println("");
+  Serial.println(addy);
+  Serial.println("!!! RESET PAGE !!!");
+  String testteu = server.arg("RESET");
+  String passme = server.arg("PASSME");
+  if (testteu == "OUI") {
+    if (passme == resetpass) {
+      ouireset = 1;
+    } else {
+      ouireset = 2;
+    }
+  }
+  String contenu = "<!DOCTYPE html>\n\n\n";
+  contenu += "<meta charset=\"UTF-8\" />\n<title>Que la lumiere se RESET</title>\n"
+             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  contenu += css;
+  contenu += "\n\n"
+             "
\n";
+  if (!ouireset) {
+    contenu += "<form action=\"/reset\" method=\"post\">\n"
+               "
Tu veux resetter le wifi network pour reconfigurer ?
"
+               "<input type=\"hidden\" name=\"RESET\" value=\"OUI\">
\n"
+               "<input type=\"password\" name=\"PASSME\" value=\"password\">
\n"
+               "<input type=\"submit\" class=\"button1\" value=\"Reset Wifi Network\">\n"
+               "</form>\n";
+  } else if (ouireset != 1) {
+    contenu += "<form action=\"/reset\" method=\"post\">\n"
+               "
Tu veux resetter le wifi network pour reconfigurer ?
"
+               "<input type=\"hidden\" name=\"RESET\" value=\"OUI\">
\n"
+               "<input type=\"password\" name=\"PASSME\" value=\"password\">
\n"
+               "
!!! MAUVAIS PASSWORD !!!

\n"
+               "<input type=\"submit\" class=\"button1\" value=\"Reset Wifi Network\">\n"
+               "</form>\n";
+    Serial.print("BAD PASSWORD : ");
+    Serial.println(passme);
+  } else if (ouireset == 1) {
+    contenu += "
Reset Dans 10 Secondes
\n";
+  }
+  contenu += "
Dernier IP à avoir changé la couleur :";
+  contenu += dernadd;
+  contenu += "\n
";
+  contenu += liens;
+  contenu += "\n

\n";
+  server.send(200, "text/html", contenu);
+  if (ouireset == 1) {
+    Serial.println("Reset dans 10 secondes");
+    delay(10000);
+    WiFiManager wifiManager;
+    wifiManager.resetSettings();
+    ESP.restart();
+  }
+}
+
+// 404 not found page
+void handleNotFound() {
+  String addy = server.client().remoteIP().toString();
+  Serial.println("");
+  Serial.println(addy);
+  String htmlmessage = "<!DOCTYPE html>\n\n\n";
+  htmlmessage += "<meta charset=\"UTF-8\" />\n<title>404 Not found</title>\n"
+                 "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  htmlmessage += css;
+  htmlmessage += "\n\n"
+                 "
\n";
+  htmlmessage += "
404 File Not Found

\n";
+  htmlmessage += "URI: ";
+  htmlmessage += server.uri();
+  htmlmessage += "
\nMethod: ";
+  htmlmessage += (server.method() == HTTP_GET) ? "GET" : "POST";
+  htmlmessage += "
\nArguments: ";
+  htmlmessage += server.args();
+  htmlmessage += "
\n";
+  for (uint8_t i = 0; i < server.args(); i++) {
+    htmlmessage += " " + server.argName(i) + ": " + server.arg(i) + "
\n";
+  }
+  htmlmessage += "
\n";
+  htmlmessage += liens;
+  htmlmessage += "
\n
\n";
+  server.send(404, "text/html", htmlmessage);
+  String message = "404 File Not Found\n";
+  message += "URI: ";
+  message += server.uri();
+  message += "\nMethod: ";
+  message += (server.method() == HTTP_GET) ? "GET" : "POST";
+  message += "\nArguments: ";
+  message += server.args();
+  message += "\n";
+  for (uint8_t i = 0; i < server.args(); i++) {
+    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
+  }
+  Serial.print(message);
+}
+
+// function executed in main loop every minute to update sensors data to thingspeak.com
+void latemp() {
+  sensors.requestTemperatures();
+  float thetemp = sensors.getTempCByIndex(0);
+  char buffer[10];
+  String tempC = dtostrf(thetemp, 5, 2, buffer);
+  float h = dht.readHumidity();
+  float t = dht.readTemperature();
+  if (tempC != "-127.00") {
+    if (tempC != "85.00") {
+      Serial.print("Envoi de temperature et humidite: ");
+      Serial.print(tempC);
+      Serial.print(" - ");
+      HTTPClient http;
+      String webadd = "http://api.thingspeak.com/update?key=";
+      webadd += thingkey;
+      webadd += "&field1=";
+      webadd += tempC;
+      if (h == h) { // to prevent NaN
+        webadd += "&field2=";
+        webadd += h;
+        Serial.print(h);
+        webadd += "&field3=";
+        webadd += t;
+      }
+      Serial.println("");
+      http.begin(webadd);
+      int httpCode = http.GET();//Send the request
+      http.end();   //Close connection
+    }
+  }
+}
+
+// web page for showing sensors data
+void handleTemp() {
+  sensors.requestTemperatures();
+  float latemp = sensors.getTempCByIndex(0);
+  float h = dht.readHumidity();
+  while (latemp == -127.00) {
+    sensors.requestTemperatures();
+    latemp = sensors.getTempCByIndex(0);
+  }
+  String addy = server.client().remoteIP().toString();
+  Serial.println("");
+  Serial.println(addy);
+  Serial.print("Temperature : ");
+  Serial.println(latemp);
+  String contenu = "<!DOCTYPE html>\n\n\n";
+  contenu += "<meta charset=\"UTF-8\" />\n<title>Quel chaleur</title>\n"
+             "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n";
+  contenu += css;
+  contenu += "\n\n"
+             "
\n";
+  contenu += "<form action=\"/\" method=\"get\">\n"
+             "
Voici la temperature
"
+             "
";
+  contenu += latemp;
+  contenu += "°C Humidité : ";
+  contenu += h;
+  contenu += "

\n"
+             ""
+             ""
+             "<input type=\"submit\" class=\"button1\" value=\"Acceuil\">\n"
+             "</form>\n"
+             "
Dernier IP à avoir changé la couleur :";
+  contenu += dernadd;
+  contenu += "\n
";
+  contenu += liens;
+  contenu += "\n

\n";
+  server.send(200, "text/html", contenu);
+}
+
+int fadecomment(int claire) {
+  int combien = 70;
+  if (claire > 0)
+    combien = 100;
+  if (claire > 40)
+    combien = 80;
+  if (claire > 80)
+    combien = 60;
+  if (claire > 100)
+    combien = 40;
+  if (claire > 120)
+    combien = 30;
+  if (claire > 140)
+    combien = 20;
+  if (claire > 180)
+    combien = 10;
+  return combien;
+}
+
+void setup() {
+  Serial.begin(115200);
+  dht.begin();
+  ledcAttachPin(pinRouge, 1); // assign RGB led pins to channels
+  ledcAttachPin(pinVerte, 2);
+  ledcAttachPin(pinBleu, 3);
+  pinMode(pinRouge, OUTPUT);
+  pinMode(pinVerte, OUTPUT);
+  pinMode(pinBleu, OUTPUT);
+  digitalWrite(pinRouge, LOW);
+  digitalWrite(pinBleu, LOW);
+  digitalWrite(pinVerte, LOW);
+  ledcSetup(1, 12000, 8); // 12 kHz PWM, 8-bit resolution
+  ledcSetup(2, 12000, 8);
+  ledcSetup(3, 12000, 8);
+  WiFiManager wifiManager;
+  wifiManager.autoConnect();
+  MDNS.begin("lumiere");
+  server.on("/", handleRoot);
+  server.on("/leds", handleLeds);
+  server.on("/flash", handleFlash);
+  server.on("/reset", handleReset);
+  server.on("/temp", handleTemp);
+  server.on("/party", handleClignote);
+  server.on("/version", []() {
+    String addy = server.client().remoteIP().toString();
+    Serial.println("");
+    Serial.println(addy);
+    Serial.println("Version request");
+    server.send(200, "text/html", "V2.1, Steve Olmstead sansillusion@gmail.com\n\n

"
+                "Added fader function\nRemoved connection watchdog (better have good signal)\n
"
+                "Removed mDns (did not work anyway)\n\n

"
+                "Added smoother fading\n\n

"
+                "Added AutoConect WifiManager !\n\n

"
+                "Added basic last IP logging\n
"
+                "Added /reset page to reset wifiManager connection settings\n\n

"
+                "Added /temp (temperature sensor read of ky-001)\n\n

"
+                "Added thingspeak support to send temperature each minute
\n\n
"
+                "Major rewrite for RGB led trip usin mosfet
\n"
+                "Removed serial to free resources for software pwm (still flikers but less than before)
\n\n
"
+                "Seperated LEDs handling page from index\n
"
+                "Added jQuery to load settings without reloading page\n
"
+                "Added random color selection button\n\n

"
+                "Added disco mode script and buttons\n\n

"
+                "Removed mDNS (does not work with esp32)\n
"
+                "        (Re-aded mDNS in 2.0 for esp32 but does not seem to work yet)\n
"
+                "Rewrite of code (removed Ticker and changed a few libraries) for esp32 !!!\n\n

"
+                "Changed fader functions for smoother fade\n
"
+                "Cleaned code\n\n

"
+                "Added Flashing function and page for smart widget usage\n
"
+                "Added var to show your thingspeak channel in /temp iframes\n\n

"
+                "Added /party page for easy control of flash mode\n\n

" + liens);
+  });
+  server.onNotFound(handleNotFound);
+  server.begin();
+  Serial.println("HTTP server started");
+  delay(100);
+  MDNS.addService("http", "tcp", 80);
+  sensors.begin();
+}
+
+void loop() {
+  server.handleClient();
+  unsigned long currentMillis = millis();
+  if (currentMillis - previousMillis >= interval) {
+    previousMillis = currentMillis;
+    latemp();
+  }
+  if (flashoufade == 1) {
+    currentMillis = millis();
+    if (currentMillis - previousMillisf >= attendF) {
+      previousMillisf = currentMillis;
+      flashfunk();
+    }
+  } else {
+    if (r != rouge) {
+      currentMillis = millis();
+      if (currentMillis - previousMillisr >= attendR) {
+        fadeR();
+        previousMillisr = currentMillis;
+        attendR = fadecomment(rouge);
+
+      }
+    }
+    if (g != vert) {
+      currentMillis = millis();
+      if (currentMillis - previousMillisg >= attendG) {
+        fadeG();
+        previousMillisg = currentMillis;
+        attendG = fadecomment(vert);
+
+      }
+    }
+    if (b != bleu) {
+      currentMillis = millis();
+      if (currentMillis - previousMillisb >= attendB) {
+        fadeB();
+        previousMillisb = currentMillis;
+        attendB = fadecomment(bleu);
+      }
+    }
+  }
+}
+
+


update todo

update todo

--- esp8266_160220_BYOP.ino
+++ esp8266_160220_BYOP.ino
@@ -276,3 +276,5 @@
 }

+// TODO: 0z > CMD_DEBUG_ON // on default, debug_outputDebugString() does not show any string
+


add debug_outputDebugString()

add debug_outputDebugString()

--- esp8266_160220_BYOP.ino
+++ esp8266_160220_BYOP.ino
@@ -6,7 +6,10 @@

 /*
- * v0.6 2016 Feb 21
+ * v0.7 2016 Feb 20
+ *  - add proc_hello();
+ *  - add debug_outputDebugString();
+ * v0.6 2016 Feb 20
  *  - UARTlib > extractCsvRow: fix bug > "AAA" return "AAA","AAA","AAA"
  * v0.5 2016 Feb 20
  *  - add kCmdList String array and CMD_e enum
@@ -47,6 +50,16 @@
 } CMD_e;

 //-------------------------------------------------------------------------
+// for debug
+
+void debug_outputDebugString(String prefix, String msg)
+{
+  // this function is used to turn off/on all the debug prints
+
+  Serial.println("[DEBUG] " + prefix + " > " + msg);
+}
+
+//-------------------------------------------------------------------------

 void setup() {
   Serial.begin(115200);
@@ -64,12 +77,7 @@
 }

 bool proc_hello(String csvline)
-{
-#if 1
-  Test_extractCsvRow();
-  return false;
-#endif
-
+{
   String cmdstr = extractCsvRow(csvline, 0);
   String serNo = extractCsvRow(csvline, 1);
   String nickName = extractCsvRow(csvline, 2);
@@ -77,6 +85,8 @@
   if (nickName.length() == 0) {
     return false;
   }
+
+  debug_outputDebugString("proc_hello", "line89 > " + csvline);

 #if 1
   Serial.println("Your S/N:" + serNo);


change filter ratio back to 1.0

change filter ratio back to 1.0

--- src/delta5node/delta5node.ino
+++ src/delta5node/delta5node.ino
@@ -60,7 +60,7 @@
 	uint16_t volatile calibrationThreshold = 95;
 	// Rssi must fall below trigger - settings.triggerThreshold to end a normal pass
 	uint16_t volatile triggerThreshold = 40;
-	uint8_t volatile filterRatio = 50;
+	uint8_t volatile filterRatio = 10;
 	float volatile filterRatioFloat = 0.0f;
 } settings;


Updated comments in main.

Updated comments in main.

--- src/Arduino/_23cm-trx/_23cm-trx.ino
+++ src/Arduino/_23cm-trx/_23cm-trx.ino
@@ -1,22 +1,24 @@
 /*
  * Firmware for the PE1JPD 23cm TRX project.
  *
- * PLEASE NOTE: SOFTWARE IS UNTESTED AND HAS NEVER RUN
- * ON A 23CM TRANSCEIVER. THIS WARNING WILL BE REMOVED
- * AFTER TESTING.
- *
  * This is an Ardiuno version of the firmware for the
  * popular PE1JPD 23cm Transceiver. Information on how
  * to build this transceiver and where to get the parts
  * are at: http://www.pe1jpd.nl/index.php/23cm_nbfm/
  *
- * This software is targeted at Board version 2.2, in the original
- * software indicated as BOARD2 on line 13 of 23nbfm21.c.
+ * Given correct wiring, see https://github.com/realrolfje/23CM-TRX/tree/master/src/Arduino
+ * you can run this software on both version 1 and
+ * version 2 of the board.
  *
  * Developed using Arduini IDE 1.6.7 on OSX 10.10.5 (Yosemite).
  *
  * This software will give your 23cm Transceiver:
  * - An Arduino-based project, for easy modification.
+ * - Slow-decay S-meter with scale and single digit readout
+ * - VFO mode with settings menu (long-press the rotary)
+ * - Memory mode with 10 memories (long-press for memory scanning)
+ * - Bargraph mode, 5 MHz wide with last set Rx frequency
+ *   at the center of the graph.
  *
  * Arduino project on atmega with internal oscillator
  * http://waihung.net/using-internal-oscillator-on-atmega328p/
@@ -52,7 +54,7 @@
 const byte LCD_BACKLIGHT = 10;

 /* Global constants */
-const byte VFO_MEMORY_LOCATION = 10;
+const byte VFO_MEMORY_LOCATION = 10; // 0-9 are user memories, 10 is used for VFO mode.

 /* Global variables and settings */
 unsigned long tcxoRefHz     = 12800000;
@@ -113,6 +115,3 @@
   }
 }

-
-
-


add minimum shifting cadence logic

add minimum shifting cadence logic

--- software/decision/decision.ino
+++ software/decision/decision.ino
@@ -9,6 +9,8 @@
 #define SHIFT_OFFSET 10

 #define GEAR_COUNT 8
+
+#define MIN_SHIFT 20

 // global variable declarations
 unsigned long oldtime;
@@ -69,10 +71,14 @@

     calc_average();

-    int offset = target - average;
+    int offset;
+    if (average >= MIN_SHIFT)
+      offset = target - average;
+    else
+      offset = 0;

     // pedaling is getting hard shift down to make it easier
-    if(offset <= SHIFT_OFFSET)
+    if(offset <= -SHIFT_OFFSET)
       shift_down();

     // pedaling is getting easy shift up to make it easier


Adding ability to control the speed of the robot through ROS topic.

--- src/robot_racing_car/arduino/arduino.ino
+++ src/robot_racing_car/arduino/arduino.ino
@@ -16,6 +16,24 @@
 int ENA=5;
 int ENB=11;
 int ABS = 100;
+
+void set_speed(const std_msgs::Int16& msg)
+{
+  int new_speed = msg.data;
+
+  if (new_speed <= 0)
+  {
+    ABS = 0;
+  }
+  else if (new_speed >= 255)
+  {
+    ABS = 255;
+  }
+  else
+  {
+    ABS = msg.data;
+  }
+}

 void move_robot(const std_msgs::UInt8& msg)
 {
@@ -99,6 +117,7 @@
 }

 ros::Subscriber<std_msgs::UInt8> steering_subscriber("robot_car_steering", &move_robot);
+ros::Subscriber<std_msgs::Int16> speed_subscriber("robot_car_speed", &set_speed);

 std_msgs::Int16 ultrasonic_sensor_message;
 ros::Publisher ultrasonic_sensor_publisher("robot_car_ultrasonic_sensor", &ultrasonic_sensor_message);
@@ -118,6 +137,7 @@
   nh.initNode();

   nh.subscribe(steering_subscriber);
+  nh.subscribe(speed_subscriber);
 }

 void loop()


Arduino code fix

Arduino code fix

--- Arduino/Specturm/Specturm.ino
+++ Arduino/Specturm/Specturm.ino
@@ -18,7 +18,7 @@
 //   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
 //   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
 //   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
-Adafruit_NeoPixel strip = Adafruit_NeoPixel(10, PIN, NEO_GRB + NEO_KHZ800);
+Adafruit_NeoPixel strip = Adafruit_NeoPixel(100, PIN, NEO_GRB + NEO_KHZ800);

 // IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
 // pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input


Added large step PWM tuning

Added large step PWM tuning

--- ppt/ppt.ino
+++ ppt/ppt.ino
@@ -398,30 +398,42 @@
 //------------------------------------------------------------------------------------------------------

 void constant_power_control(int target_watts) {
-  static int old_sol_watts = 0;
-
-  int current_watts = power_status.sol_watts;
+
   int current_pwm = power_status.pwm_duty;
-
-  if (target_watts < current_watts) {
-    current_pwm -= PWM_INC;
-  } else if (target_watts > current_watts) {
-    current_pwm += PWM_INC;
+  int target_difference = target_watts - power_status.sol_watts;
+
+  // if target difference is large, use big steps
+  int pwm_delta = 1;
+  if (abs(target_difference) > 100) {
+    pwm_delta = 16;
+  }
+
+  // adjust pwm either up or down based on difference sign
+  if (target_difference < 0) {
+    current_pwm -= pwm_delta;
+  } else if (target_difference > 0) {
+    current_pwm += pwm_delta;
   }

   set_pwm_duty(current_pwm);
 }

 void constant_voltage_control(int target_voltage) {
-  static int old_bat_volt = 0;
-
-  int current_voltage = power_status.bat_volts;
+
   int current_pwm = power_status.pwm_duty;
-
-  if (target_voltage < current_voltage) {
-    current_pwm -= PWM_INC;
-  } else if (target_voltage > current_voltage) {
-    current_pwm += PWM_INC;
+  int target_difference = target_voltage - power_status.bat_volts;
+
+  // if target difference is large, use big steps
+  int pwm_delta = 1;
+  if (abs(target_difference) > 100) {
+    pwm_delta = 16;
+  }
+
+  // adjust pwm either up or down based on difference sign
+  if (target_difference < 0) {
+    current_pwm -= pwm_delta;
+  } else if (target_difference > 0) {
+    current_pwm += pwm_delta;
   }

   set_pwm_duty(current_pwm);


different pixels for different axis

different pixels for different axis

--- sketch_feb09a/sketch_feb09a.ino
+++ sketch_feb09a/sketch_feb09a.ino
@@ -22,6 +22,65 @@
     uint8_t blue;
 };

+class HSVPixel
+{
+  public:
+    uint8_t hue;
+    uint8_t saturation;
+    uint8_t value;
+
+    void loadTo(RGBPixel *pix) {
+      int i;
+      float f, p, q, t;
+
+      if ( saturation == 0 ) {
+        // achromatic (grey)
+        pix->red = pix->green = pix->blue = value;
+        return;
+      }
+
+      hue /= 60;			// sector 0 to 5
+      i = floor( hue );
+      f = hue - i;			// factorial part of h
+      p = value * ( 1 - saturation );
+      q = value * ( 1 - saturation * f );
+      t = value * ( 1 - saturation * ( 1 - f ) );
+
+      switch ( i ) {
+        case 0:
+          pix->red = value;
+          pix->green = t;
+          pix->blue = p;
+          break;
+        case 1:
+          pix->red = q;
+          pix->green = value;
+          pix->blue = p;
+          break;
+        case 2:
+          pix->red = p;
+          pix->green = value;
+          pix->blue = t;
+          break;
+        case 3:
+          pix->red = p;
+          pix->green = q;
+          pix->blue = value;
+          break;
+        case 4:
+          pix->red = t;
+          pix->green = p;
+          pix->blue = value;
+          break;
+        default:		// case 5:
+          pix->red = value;
+          pix->green = p;
+          pix->blue = q;
+          break;
+      }
+    }
+};
+
 const float seaLevelPressure PROGMEM = SENSORS_PRESSURE_SEALEVELHPA;
 const int maxAcceleration PROGMEM = 10;
 Adafruit_10DOF dof = Adafruit_10DOF();
@@ -61,11 +120,28 @@
   int8_t y_delta = abs(event->acceleration.y - previous_event->acceleration.y);
   int8_t z_delta = abs(event->acceleration.z - previous_event->acceleration.z);

+  RGBPixel * p = &frame[x];
+
   avg_color(x,
             map(x_delta, 0, maxAcceleration, 0, 255),
+            p->green,
+            p->blue
+           );
+
+  p = &frame[0];
+  avg_color(0,
+            p->red,
             map(y_delta, 0, maxAcceleration, 0, 255),
+            p->blue
+           );
+
+  p = &frame[NUM_PIXELS - 1];
+  avg_color(NUM_PIXELS - 1,
+            p->red,
+            p->green,
             map(z_delta, 0, maxAcceleration, 0, 255)
            );
+
 }

 void loop() {


Add initial power manager firmware

Add initial power manager firmware

* TO-DO: Update wifi off and on times
* TO-DO: Implement shutdown prevention strategy

Fixes #23

--- ins-node/src/power_controller/power_controller.ino
+++ ins-node/src/power_controller/power_controller.ino
@@ -1,17 +1,207 @@
 #include <stdint.h>
-
-const uint8_t WIFI_MODULE_PIN = PB2;
-
-uint8_t turnWifi(uint8_t state) {
-  uint8_t error = 0;
-  digitalWrite(WIFI_MODULE_PIN, state);
-  return error;
+#include <avr/sleep.h>
+#include <avr/power.h>
+#include <avr/wdt.h>
+
+enum WatchDogTimeout {
+  WDT_16ms = 0,
+  WDT_32ms,
+  WDT_64ms,
+  WDT_128ms,
+  WDT_250ms,
+  WDT_500ms,
+  WDT_1sec,
+  WDT_2sec,
+  WDT_4sec,
+  WDT_8sec
+};
+
+enum PowerState {
+  // The wifi module is off, while power controller is
+  // in deep sleep and can be woken up by a watchdog timer.
+  SLEEP_WIFI_OFF,
+  // The wifi module is on, while power controller is in
+  // deep sleep and can be woken up by a watchdog timer
+  // or an external interrupt.
+  SLEEP_WIFI_ON,
+  // The power controller warns the Wifi module it is time
+  // to shutdown and then it goes to deep sleep for a
+  // limited period. The Wifi module can ask to postpone
+  // shutdown if it is not ready yet.
+  PREPARE_SHUTDOWN
+};
+
+const uint8_t TX_PIN = PB0;
+const uint8_t RX_PIN = PB1;
+const uint8_t WIFI_MODULE_PIN = PB2; // Controls the power to the Wifi module
+
+WatchDogTimeout currentTimeout = WDT_8sec; // Current watchdog timeout
+
+unsigned long timeWeHaveSlept = 0; // The total amount of time we have been asleep
+volatile bool watchDogBarked = false; // Flag to determine the source of a wake up
+bool watchDogEnabled = false;
+
+const unsigned long WIFI_OFF_SLEEP_DURATION = 16000UL; // TO-DO: Change this to something larger
+const unsigned long WIFI_ON_SLEEP_DURATION = 16000UL; // TO-DO: Change this to something larger
+
+volatile bool signalFromWifiModule = false; // Flag to determine if WiFi module has signaled us
+
+PowerState currentState = SLEEP_WIFI_OFF; // Current operational state
+
+/**
+   Change interrupt routine (e.g. when WiFi module signals us)
+*/
+ISR (PCINT0_vect) {
+  // Only consider interrupts from the defined source and during the proper state(s)
+  if ((currentState == SLEEP_WIFI_ON) && (digitalRead(RX_PIN) == HIGH)) {
+    signalFromWifiModule = true;
+  }
+}
+
+/**
+  Watchdog interrupt routine to be triggered when watchdog times out.
+*/
+ISR(WDT_vect) {
+  watchDogBarked = true;
+  wdt_disable(); // Disable watchdog so it does not get automatically retriggered
+}
+
+/**
+    Sets up watchdog to be triggered (once) after the specified time
+    @param wdt  the watchdog timeout duration
+*/
+void triggerWatchDogIn(WatchDogTimeout wdt) {
+  // Adopted from InsideGadgets (www.insidegadgets.com)
+  byte timeoutVal = wdt & 7;
+  if (wdt > 7) {
+    timeoutVal |= (1 << 5);
+  }
+  timeoutVal |= (1 << WDCE);
+
+  MCUSR &= ~(1 << WDRF);
+  WDTCR |= (1 << WDCE) | (1 << WDE); // Start timed sequence
+  WDTCR = timeoutVal;
+  WDTCR |= _BV(WDIE);
+  wdt_reset();  // Pat the dog
+  currentTimeout = wdt;
+}
+
+/**
+   Sets the MCU into a deep sleep state until a change interrupt is triggered
+*/
+void goToSleep() {
+  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
+  ADCSRA = 0; // Turn off ADC
+  power_all_disable (); // Power off ADC, Timer 0 and 1, serial interface
+  sleep_enable();
+  sleep_cpu(); // Sleep here and wait for an interrupt or watchdog bark
+  sleep_disable();
+  power_all_enable(); // Power everything back on
+}
+
+/**
+   Sets up pin change interrupt for RX
+*/
+void setupRXInterrupt() {
+  PCMSK |= bit (PCINT1); // Want pin D1 (PB1)
+  GIFR |= bit (PCIF); // Clear any outstanding interrupts
+  GIMSK |= bit (PCIE); // Enable pin change interrupts
+}
+
+/**
+   A utility method to derive a watchdog timeout's duration
+   @return the amount of milliseconds corresponding to a watchdog timeout
+*/
+unsigned long getTimeoutDuration() {
+  return 1 << (currentTimeout + 4);
+}
+
+/**
+    Puts the MCU to deep sleep and uses a watchdog timeout to wake it up after
+    the currently set timeout. Monitors how long it has remained asleep since the
+    last time it signaled a wake up.
+    @param  totalSleepDuration how long to sleep in milliseconds
+    @return                    whether it has remained asleep enough
+*/
+bool stayAsleepFor(const unsigned long totalSleepDuration) {
+  // If watchdog is not enabled, then we either just arrived from a different state
+  // or from a watchdog bark. Therefore we need to set another watchdog timer.
+  if (!watchDogEnabled) {
+    // If watchdog is not enabled and we are in this state
+    // then we should set it up.
+    triggerWatchDogIn(currentTimeout);
+    watchDogEnabled = false;
+  }
+  // Go to deep sleep until an interrupt or watchdog bark occurs
+  goToSleep();
+  // We might have gone out of sleep due to an interrupt so make sure that we
+  // know what we are doing depending on who interrupted our sleep.
+  if (watchDogBarked) {
+    watchDogBarked = false;
+    watchDogEnabled = false;
+    timeWeHaveSlept += getTimeoutDuration(); // Log how much time we've been in this state
+    // Check if it is time to signal a state change
+    if (timeWeHaveSlept >= totalSleepDuration) {
+      timeWeHaveSlept = 0;
+      return true;
+    }
+    return false;
+  }
+}
+
+/**
+   Notify the WiFi module that it is time to shut down
+*/
+void notifyWifiShutdown() {
+  // Send a short pulse
+  digitalWrite(TX_PIN, HIGH);
+  delayMicroseconds(5);
+  digitalWrite(TX_PIN, LOW);
 }

 void setup() {
-  // Setup pins
+  // Setup I/O pins
+  pinMode(RX_PIN, INPUT);
+  pinMode(TX_PIN, OUTPUT);
   pinMode(WIFI_MODULE_PIN, OUTPUT);
-  turnWifi(HIGH);
-}
-
-void loop() {}
+
+  // Initialize the pin states
+  digitalWrite(TX_PIN, LOW);
+  digitalWrite(WIFI_MODULE_PIN, LOW);
+
+  setupRXInterrupt();
+}
+
+void loop() {
+  switch (currentState) {
+    case SLEEP_WIFI_OFF:
+      {
+        bool timeToChangeState = stayAsleepFor(WIFI_OFF_SLEEP_DURATION);
+        if (timeToChangeState) {
+          currentState = SLEEP_WIFI_ON;
+          digitalWrite(WIFI_MODULE_PIN, HIGH); // Turn WiFi module on
+        }
+        break;
+      }
+    case SLEEP_WIFI_ON:
+      {
+        bool timeToChangeState = stayAsleepFor(WIFI_ON_SLEEP_DURATION);
+        if (timeToChangeState || signalFromWifiModule) {
+          currentState = PREPARE_SHUTDOWN;
+          notifyWifiShutdown();
+
+          signalFromWifiModule = false;
+          timeWeHaveSlept = 0; // Reset this in case sleep was prematurely halted by an interrupt
+        }
+      }
+      break;
+    case PREPARE_SHUTDOWN:
+      {
+        currentState = SLEEP_WIFI_OFF; // TO-DO: Implement some logic here to prevent shutdown
+        digitalWrite(WIFI_MODULE_PIN, LOW); // Turn WiFi module off
+        break;
+      }
+    default:
+      break;
+  }
+}