Fixing typo in example code and adding comment to which pin rx and tx connects to.

--- examples/ESP8266_library_test/ESP8266_library_test.ino
+++ examples/ESP8266_library_test/ESP8266_library_test.ino
@@ -1,11 +1,11 @@
 #include <SoftwareSerial.h>
 #include <ESP8266wifi.h>

-#define sw_serial_rx_pin 4
-#define sw_serial_rx_pin 6
+#define sw_serial_rx_pin 4 //  Connect this pin to TX on the esp8266
+#define sw_serial_tx_pin 6 //  Connect this pin to TX on the esp8266
 #define esp8266_reset_pin 5 // Connect this pin to CH_PD on the esp8266, not reset. (let reset be unconnected)

-SoftwareSerial swSerial(sw_serial_rx_pin, sw_serial_rx_pin);
+SoftwareSerial swSerial(sw_serial_rx_pin, sw_serial_tx_pin);

 // the last parameter sets the local echo option for the ESP8266 module..
 ESP8266wifi wifi(swSerial, swSerial, esp8266_reset_pin, Serial);//adding Serial enabled local echo and wifi debug


Small changes to fix bugs in multi-GPS transmission of information

Small changes to fix bugs in multi-GPS transmission of information

--- arduino/GPS_multi-transmitter_1/GPS_multi-transmitter_1.ino
+++ arduino/GPS_multi-transmitter_1/GPS_multi-transmitter_1.ino
@@ -21,7 +21,8 @@

 RF24 radio(pinCE, pinCSN); // Create your nRF24 object or wireless SPI connection

-#define WHICH_NODE 2     // must be a number from 1 - 6 identifying the PTX node
+// WHEN PULL CODE, SCOUTS MUST BE DIFFERENT
+#define WHICH_NODE 1     // must be a number from 1 - 6 identifying the PTX node

 const uint64_t wAddress[] = {0x7878787878LL, 0xB3B4B5B6F1LL, 0xB3B4B5B6CDLL, 0xB3B4B5B6A3LL, 0xB3B4B5B60FLL, 0xB3B4B5B605LL};

@@ -127,11 +128,11 @@
     Serial.print("Fix: "); Serial.print((int)GPS.fix);
     Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if(GPS.fix){
-      currLatLong = "GPS" + String(WHICH_NODE,1) + "Loc" + String(fabs(GPS.latitudeDegrees), 6) + GPS.lat + "," + String(fabs(GPS.longitudeDegrees), 6) + GPS.lon + "Time" + String(GPS.hour,DEC) + ":" + String(GPS.minute,DEC) + ":" + String(GPS.seconds,DEC) + "." + String(GPS.milliseconds);
+      currLatLong = "G" + String(WHICH_NODE) + "L" + String(fabs(GPS.latitudeDegrees), 6) + GPS.lat + String(fabs(GPS.longitudeDegrees), 6) + GPS.lon + String(GPS.minute,DEC) + ":" + String(GPS.seconds,DEC) + "." + String(GPS.milliseconds);
       Serial.print("Satellites: "); Serial.println((int)GPS.satellites);
       }
      else{
-      currLatLong = "GPS" + String(WHICH_NODE,1) + "null";
+      currLatLong = "GPS" + String(WHICH_NODE) + "null";
       }

@@ -139,8 +140,8 @@
      //byte randNumber = (byte)random(11); //generate random guess between 0 and 10
      //char charBuf[currLatLong.length()+1];
      //currLatLong.toCharArray(charBuf, currLatLong.length()+1);
-     char charBuf[40];
-     currLatLong.toCharArray(charBuf, 40);
+     char charBuf[65];
+     currLatLong.toCharArray(charBuf, 65);

      radio.openWritingPipe(PTXpipe);        //open writing or transmit pipe


Compute ground pressure at initialisation to be able to get altitude relative to ground (for short time) Send the pressure in mavlink messages

--- Arduino/MPU9150_MS5611_IMU/MPU9150_MS5611_IMU.ino
+++ Arduino/MPU9150_MS5611_IMU/MPU9150_MS5611_IMU.ino
@@ -169,6 +169,7 @@
 int movavg_i=0;

 const float sea_press = 1013.25;
+float ground_press;
 float press, temperature, altitude;

 short n_gyro_range = 0;
@@ -263,6 +264,7 @@

 void loop()
 {
+  //ground_press = baro.getPressure(MS561101BA_OSR_4096);
     processSerialInput();
     if (fabs(millis()-last_baro_read_ms)>1./BaroRate)
     {
@@ -363,13 +365,16 @@
         mavlink_msg_attitude_pack(system_id, component_id, &msg, time_boot_ms, roll, pitch, yaw, gx_degps*PI/180.0f, gy_degps*PI/180.0f, gz_degps*PI/180.0f);
         len = mavlink_msg_to_send_buffer(buf, &msg);
         Serial.write(buf, len);
+        mavlink_msg_scaled_pressure_pack(system_id, component_id, &msg, time_boot_ms, press, press-ground_press, temperature);
+        len = mavlink_msg_to_send_buffer(buf, &msg);
+        Serial.write(buf, len);
       }

       if (outputMode == RAW)
       {
         //static inline uint16_t mavlink_msg_highres_imu_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg,
         //						       uint64_t time_usec, float xacc, float yacc, float zacc, float xgyro, float ygyro, float zgyro, float xmag, float ymag, float zmag, float abs_pressure, float diff_pressure, float pressure_alt, float temperature, uint16_t fields_updated)
-        mavlink_msg_highres_imu_pack(system_id, component_id, &msg, (uint64_t)time_boot_us, ax_g*9.81, ay_g*9.81, az_g*9.81, gx_degps*PI/180.0f, gy_degps*PI/180.0f, gz_degps*PI/180.0f, mx, my, mz, press, press, altitude, temperature, a1);
+        mavlink_msg_highres_imu_pack(system_id, component_id, &msg, (uint64_t)time_boot_us, ax_g*9.81, ay_g*9.81, az_g*9.81, gx_degps*PI/180.0f, gy_degps*PI/180.0f, gz_degps*PI/180.0f, mx, my, mz, press, press-ground_press, altitude, temperature, a1);
         len = mavlink_msg_to_send_buffer(buf, &msg);
         Serial.write(buf, len);
       }
@@ -462,6 +467,8 @@
     press = baro.getPressure(MS561101BA_OSR_4096);
     pushAvg(press);
     press = getAvg(movavg_buff, MOVAVG_SIZE);
+    if (millis()<5000)
+      ground_press = press;
     altitude = getAltitude(press, temperature);
 }
 void automaticGyroRangeSelection()


Try to make it stable

Try to make it stable

--- net_th_meter/net_th_meter.ino
+++ net_th_meter/net_th_meter.ino
@@ -29,8 +29,10 @@
 #define TCP_PORT        502    // Modbus TCP default port
 #define EMPTY_VAL       -100.0 // empty float value of measurement
 #define MODBUS_HDR_LEN  9      // length of Modbus TCP header
-
-//#define DEBUG
+#define DISCONN_TIME    10000  // inactive time before client disconnect, ms
+#define REINIT_TIME     20000  // inactive time before reinit Ethernet, ms
+
+#define DEBUG

 #ifdef DEBUG
  #define DEBUG_PRINT(val)       Serial.print(val)
@@ -63,6 +65,7 @@
 EthernetServer server = EthernetServer(TCP_PORT);
 EthernetClient client;
 boolean clientConnected = false;
+unsigned long commTime;
 const byte modbusHeader[MODBUS_HDR_LEN] = {
   0x00, 0x00, // Transaction identifier
   0x00, 0x00, // Protocol identifier
@@ -97,6 +100,7 @@

 // Initialize ENC28J60 Ethernet controller
 void initEthernet() {
+  commTime = millis();
   Ethernet.begin(mac, ip);
   server.begin();

@@ -161,8 +165,14 @@
   DEBUG_WRITETIME();

   // manage connection
+  unsigned long inactiveSpan = millis() - commTime;
+
   if (clientConnected) {
-    if (client.connected()) {
+    if (inactiveSpan > DISCONN_TIME) {
+        DEBUG_PRINTLN("Disconnecting inactive client");
+        client.stop();
+        clientConnected = false;
+    } else if (client.connected()) {
       DEBUG_PRINTLN("Client is still connected");
     } else {
       client.stop();
@@ -172,6 +182,11 @@
   }

   if (!clientConnected) {
+    // reinit Ethernet if client can't connect
+    if (inactiveSpan > REINIT_TIME) {
+      initEthernet();
+    }
+
     // connection is considered to be established only when data are received
     client = server.available();
     if (client) {
@@ -188,17 +203,18 @@
     DEBUG_PRINT("Receiving data: ");
     boolean sendResponse = false;
     while (client.available() > 0) {
+      DEBUG_PRINT("_");
       char c = client.read();
       DEBUG_PRINTHEX(c);
-      DEBUG_PRINT(" ");

       if (c == 0x0A) {
         sendResponse = true;
+        commTime = millis();
         client.flush(); // clear input buffer
         break;
       }
     }
-    Serial.println();
+    DEBUG_PRINTLN();

     // send response
     if (sendResponse) {
@@ -211,7 +227,7 @@
       DEBUG_PRINTLN("Response not required");
     }
   }
-
+
   DEBUG_WRITETIME();
   DEBUG_PRINTLN();
 }


Fixes #1432

Fixes #1432

--- build/shared/examples/02.Digital/toneMultiple/toneMultiple.ino
+++ build/shared/examples/02.Digital/toneMultiple/toneMultiple.ino
@@ -4,7 +4,7 @@
  Plays multiple tones on multiple pins in sequence

  circuit:
- * 3 8-ohm speaker on digital pins 6, 7, and 11
+ * 3 8-ohm speaker on digital pins 6, 7, and 8

  created 8 March 2010
  by Tom Igoe
@@ -21,8 +21,8 @@
 }

 void loop() {
-   // turn off tone function for pin 11:
-   noTone(11);
+  // turn off tone function for pin 8:
+  noTone(8);
   // play a note on pin 6 for 200 ms:
   tone(6, 440, 200);
   delay(200);
@@ -35,8 +35,7 @@

   // turn off tone function for pin 7:
   noTone(7);
-  // play a note on pin 11 for 500 ms:
-  tone(11, 523, 300);
+  // play a note on pin 8 for 500 ms:
+  tone(8, 523, 300);
   delay(300);
-
 }


Fixed problem with static variable in class method. Some other additional changes. All of this was done in 06.2014.

--- arduino/labbot_2_rosserial.ino
+++ arduino/labbot_2_rosserial.ino
@@ -2,12 +2,12 @@

 #define USE_USBCON
 #include <ros.h>
-#include <robot/Num.h>
+#include <labbot/msgFromLabbot.h>
 #include <labbot/msgToLabbot.h>

 ros::NodeHandle  nh;

-robot::Num sendMsg;
+labbot::msgFromLabbot sendMsg;
 labbot::msgToLabbot recvMsg;

@@ -45,6 +45,9 @@
 		0	\
 		)

+		int32_t previousSpeed;
+		f32_t I_part;
+
 	#define AVG_ENCODER_BUFFER_SIZE 8

 		int32_t avgEncoderValue(int32_t newValue)
@@ -80,8 +83,9 @@
 			const int32_t outputMax = 100;
 			const int32_t outputMin = -100;

-			static int32_t previousSpeed;
-			static f32_t I_part = 0;
+			// static chyba tak nie dziaa w C++, le
+			//static int32_t previousSpeed;
+			//static f32_t I_part = 0;
 			// PV - process variable
 			// SP - set point
 			// CV - control variable
@@ -97,7 +101,7 @@
 			{
 				I_part = outputMin;
 			}
-			// TODO: czy ogranczenie na warto�� "naca�kowan�"?
+			// TODO: czy ogranczenie na warto "nacakowan"?
 			f32_t D_part = Kd * (f32_t)(currentSpeed - previousSpeed);

 			int32_t output = (int32_t)(P_part + I_part + D_part);
@@ -119,7 +123,7 @@

 			// scale output (-100-100) to (-400 to 400)
-			// TODO: przetestowa� czy <<2 dzia�a
+			// TODO: przetestowa czy <<2 dziaa
 			steerValue = output;

 			previousSpeed = currentSpeed;
@@ -144,8 +148,7 @@
 		f32_t Ki;
 		f32_t Kd;

-                int64_t encAbsoluteTicksleft;
-                int64_t encAbsoluteTicksright;
+

 	public:

@@ -168,9 +171,6 @@
 			this->left.steerValue = 0;

 			this->SetTunnings(2.0F, 4.0F, 0.0F);
-
-                        encAbsoluteTicksleft=0;
-                        encAbsoluteTicksright=0;

 			time1 = 0;
 			time2 = 0;
@@ -226,12 +226,11 @@
 			int32_t currentEncoderLeftValue = this->encoderLeft->read();
 			this->encoderLeft->write(0);
 			*/
-			int32_t currentEncoderRightValue = this->right.encoder.read();
-                        encAbsoluteTicksright+=currentEncoderRightValue;
+
+			int32_t currentEncoderLeftValue = this->left.encoder.read();
+			this->left.encoder.write(0);
+			int32_t currentEncoderRightValue = -this->right.encoder.read();
 			this->right.encoder.write(0);
-			int32_t currentEncoderLeftValue = this->left.encoder.read();
-                        encAbsoluteTicksleft+=currentEncoderLeftValue;
-			this->left.encoder.write(0);

 			time1 = (micros() - timeStart);

@@ -239,8 +238,11 @@
 			timeStart = micros();
 			// TODO: put this above, decide what type is required (int32_t, int8_t)
 			// what does speed means? rpm? m/s?
-			this->right.currentSpeed = this->right.avgEncoderValue(currentEncoderRightValue);
-			this->left.currentSpeed = this->left.avgEncoderValue(currentEncoderLeftValue);
+			//this->right.currentSpeed = this->right.avgEncoderValue(currentEncoderRightValue);
+			//this->left.currentSpeed = this->left.avgEncoderValue(currentEncoderLeftValue);
+
+			this->right.currentSpeed = currentEncoderRightValue;
+			this->left.currentSpeed = currentEncoderLeftValue;

 			time2 = (micros() - timeStart);

@@ -294,14 +296,6 @@
 			this->left.Kd = Kd;
 		}

-                inline int GetAbsolutLeftTicks()
-                {
-                        return encAbsoluteTicksleft;
-                }
-                inline int GetAbsolutRightTicks()
-                {
-                        return encAbsoluteTicksright;
-                }

 		inline int32_t GetCurrentSpeedMotorRight()
 		{
@@ -319,6 +313,14 @@
 		{
 			return this->left.steerValue;
 		}
+		inline int32_t GetDesiredSpeedValueMotorRight()
+		{
+			return this->right.desiredSpeed;
+		}
+		inline int32_t GetDesiredSpeedValueMotorLeft()
+		{
+			return this->left.desiredSpeed;
+		}

 		inline int32_t GetKp()
 		{
@@ -334,7 +336,7 @@
 		}
 };

-CLabbotMotors motors(3, 2, 0, 1);
+CLabbotMotors motors(2, 3, 0, 1);

 // function copied from cmdMessenger
 // https://github.com/thijse/Arduino-Libraries/tree/master/CmdMessenger
@@ -389,7 +391,7 @@
 	motors.SetDesiredSpeed(newMotorRightSpeed, newMotorLeftSpeed);
 }

-ros::Publisher fromenc("fromenc", &sendMsg);
+ros::Publisher fromLabbot("fromLabbot", &sendMsg);
 ros::Subscriber<labbot::msgToLabbot> toLabbot("toLabbot", &receivedMessagesCallback);

 void setup()
@@ -408,7 +410,7 @@

 	// ros objects
 	nh.initNode();
-	nh.advertise(fromenc);
+	nh.advertise(fromLabbot);
 	nh.subscribe(toLabbot);

 	motors.SetTunnings(2.0F, 4.0F, 0.0F);
@@ -419,10 +421,14 @@
 	// send data to PC after defined interval
 	if (hasExpired(previousPublishTime, publishInterval))
 	{
-                        sendMsg.lwheel=motors.GetAbsolutLeftTicks();
-                        sendMsg.rwheel=motors.GetAbsolutRightTicks();
-
-			fromenc.publish(&sendMsg);
+			sendMsg.motorLeftInput = motors.GetCurrentSpeedMotorLeft();
+			sendMsg.motorLeftSetpoint = motors.GetDesiredSpeedValueMotorLeft();
+			sendMsg.motorLefttOutput = motors.GetSteerValueMotorLeft();
+			sendMsg.motorRightInput = motors.GetCurrentSpeedMotorRight();
+			sendMsg.motorRightSetpoint = motors.GetDesiredSpeedValueMotorRight();
+			sendMsg.motorRightOutput = motors.GetSteerValueMotorRight();
+
+			fromLabbot.publish(&sendMsg);
 	}

 	if (hasExpired(previousMotorsUpdateTime, motorsUpdateInterval))


temporarily disabled HTTP requests for debugging

--- MyReceiver_softSPI_dht/MyReceiver_softSPI_dht.ino
+++ MyReceiver_softSPI_dht/MyReceiver_softSPI_dht.ino
@@ -75,38 +75,35 @@
   Serial.print(h);
   Serial.print(" ... ");

-  if (client.connect(server, 80)) {
-
-    // Make a HTTP request
-    client.print("GET /wsgw.php");
-    client.print("?ts="); client.print(SECONDS_SINCE_BOOT);
-    client.print("&sid="); client.print(sensor_id);
-    client.print("&gid="); client.print(gwid);
-    client.print("&d=");
-    client.print(t);
-    client.print(",");
-    client.print(h);
-    client.println(" HTTP/1.1");
-
-    client.print("Host: ");
-    client.println(server);
-
-    client.println("User-Agent: arduino");
-    client.println("Connection: close");
-    client.println();
-
-  } else {
-    // if you didn't get a connection to the server
-    Serial.println("tcp timeout");
-    return;
-  }
+//  if (client.connect(server, 80)) {
+//
+//    // Make a HTTP request
+//    client.print("GET /wsgw.php");
+//    client.print("?ts="); client.print(SECONDS_SINCE_BOOT);
+//    client.print("&sid="); client.print(sensor_id);
+//    client.print("&gid="); client.print(gwid);
+//    client.print("&d=");
+//    client.print(t);
+//    client.print(",");
+//    client.print(h);
+//    client.println(" HTTP/1.1");
+//
+//    client.print("Host: ");
+//    client.println(server);
+//
+//    client.println("User-Agent: arduino");
+//    client.println("Connection: close");
+//    client.println();
+//
+//  } else {
+//    // if you didn't get a connection to the server
+//    Serial.println("tcp timeout");
+//    return;
+//  }

   // at this point, we successfully transmitted the sensor data
   // to the REST API on a remote server
   Serial.println("ok");
+  Serial.flush();
 }

-
-
-
-


Update comments and default baud rate

Update comments and default baud rate

--- examples/Boards_WiFi/ESP8266_Shield/ESP8266_Shield.ino
+++ examples/Boards_WiFi/ESP8266_Shield/ESP8266_Shield.ino
@@ -18,11 +18,13 @@
  * to connect your project to Blynk.
  *
  * Note: Ensure a stable serial connection to ESP8266!
- *       Firmware version 1.0.0 (AT v0.22) is needed.
- *       You can change ESP baud rate. Connect to AT console and call:
+ *       Update your ESP to the latest firmware
+ *       (AT v1.1.0.0 is recommended).
+ *
+ *       It is also recommended to use Hard Serial.
+ *       If you want to use SoftSerial, you can change ESP baud rate.
+ *       Connect to AT console and call:
  *           AT+UART_DEF=9600,8,1,0,0
- *       In general, Soft Serial may be unstable.
- *       It is highly recommended to switch to Hard Serial.
  *
  * Change WiFi ssid, pass, and Blynk auth token to run :)
  * Feel free to apply it to any other example. It's simple!
@@ -50,7 +52,7 @@
 //SoftwareSerial EspSerial(2, 3); // RX, TX

 // Your ESP8266 baud rate:
-#define ESP8266_BAUD 9600
+#define ESP8266_BAUD 115200

 ESP8266 wifi(&EspSerial);


Additional configuration.

Additional configuration.

--- examples/Benchmarks/CosaBenchmarkUART/CosaBenchmarkUART.ino
+++ examples/Benchmarks/CosaBenchmarkUART/CosaBenchmarkUART.ino
@@ -31,12 +31,17 @@

 // This benchmark can be run with a background interrupt load. Set the
 // below symbol to enable a periodic job with the given period in
-// micro-seconds. Minimum is approx. 100 us.
-// #define BACKGROUND_PULSE 100
+// micro-seconds.
+#define BACKGROUND_PULSE 150
+#define PULSE_WIDTH 50

 #if defined(BACKGROUND_PULSE)
 #include "Cosa/OutputPin.hh"
 #include "Cosa/Periodic.hh"
+
+// Schedule from interrupt with time or fixed period
+// #define USE_ISR_TIME_PERIOD
+#define USE_ISR_RESCHEDULE

 class Pulse : public Periodic {
 public:
@@ -47,15 +52,29 @@
     expire_at(100000UL);
   }

+#if defined(USE_ISR_TIME_PERIOD)
+  virtual void on_expired()
+  {
+    run();
+    expire_at(time() + period());
+    start();
+  }
+#endif
+
+#if defined(USE_ISR_RESCHEDULE)
   virtual void on_expired()
   {
     run();
     reschedule();
   }
+#endif

   virtual void run()
   {
     m_pin.toggle();
+#if defined(PULSE_WIDTH)
+    DELAY(PULSE_WIDTH);
+#endif
     m_pin.toggle();
   }

@@ -65,13 +84,13 @@

 // The RTC job scheduler and background pulse generator
 RTC::Scheduler scheduler;
-Pulse background(&scheduler, BACKGROUND_PULSE, Board::LED);
+Pulse background(&scheduler, BACKGROUND_PULSE, Board::D7);
 #endif

 void setup()
 {
   // Start serial output with given baud-rate
-  uart.begin(2000000);
+  uart.begin(500000);
   // uart.begin(2000000);
   // uart.begin(1000000);
   // uart.begin(500000);
@@ -199,7 +218,13 @@
 	<< Kbps << PSTR(" Kbps")
 	<< endl;

+#if defined(BACKGROUND_PULSE)
+  uint16_t pulses = trace.measure / BACKGROUND_PULSE;
+  trace << PSTR("background pulses (") << pulses << PSTR("):")
+	<< (uint32_t) pulses * PULSE_WIDTH << PSTR(" us")
+	<< endl;
+  sleep(1);
+#else
   ASSERT(true == false);
-  // Take a nap before starting over
-  // sleep(1);
+#endif
 }


Increased baudrate to 57600

Increased baudrate to 57600

--- VendingMachineRFID.ino
+++ VendingMachineRFID.ino
@@ -45,7 +45,7 @@

   lastCardScan = 0;

-  Serial.begin(19200); // Initialize serial communications with master vending Arduino
+  Serial.begin(57600); // Initialize serial communications with master vending Arduino
   Serial.setTimeout(200);

   SPI.begin(); // Init SPI bus


Removed 3 variables.

Removed 3 variables.

--- aquacontrol2.ino
+++ aquacontrol2.ino
@@ -1,6 +1,5 @@
 #include <Time.h>
 #include <WiFiUdp.h>
-#include <ESP8266WiFi.h>
 #include <ESP8266WebServer.h>
 #include <EEPROM.h>
 #include <FS.h>
@@ -64,13 +63,8 @@
 const byte ledPin[numberOfChannels] =  { D1, D2, D3, D4, D5 } ;        //pin numbers of the channels !!!!! should contain [numberOfChannels] entries. D1 through D8 are the exposed pins on 'Wemos D1 mini'
 //see online for pin number conversion Arduino <> Wemos D1 mini: https://github.com/esp8266/Arduino/blob/master/variants/d1_mini/pins_arduino.h#L49-L61

-//I2C pins used for OLED
-const byte   SCL_pin                = D6;
-const byte   SDA_pin                = D7;
-//I2C address of OLED screen
-const byte OLEDaddress              = 0x3c;
-
-SSD1306  OLED( OLEDaddress, SDA_pin, SCL_pin );
+//       OLED( OLEDaddress, SDA_pin, SCL_pin );
+SSD1306  OLED( 0x3c, D7, D6 );

 ESP8266WebServer webServer ( 80 );


Smooth dimming brightness tracking

Smooth dimming brightness tracking

--- arduino/alarm/alarm.ino
+++ arduino/alarm/alarm.ino
@@ -27,12 +27,14 @@
   light_state = "blink";
   while(light_state == "blink") {
     digitalWrite(gate_pin, LOW);
+    light_brightness = 0;
     previousMillis = millis();
     while(millis() - previousMillis < interval) {
       loop();
     }
     if (light_state != "blink") break;
     digitalWrite(gate_pin, HIGH);
+    light_brightness = 255;
     previousMillis = millis();
     while(millis() - previousMillis < interval) {
       loop();
@@ -42,25 +44,30 @@

 boolean dim(long duration) {
   boolean brighten;
+  int startval;
   light_state = "dimming";
   if (duration > 0) {
     brighten = true;
+    startval = light_brightness + 1;
   } else {
     brighten = false;
     duration = -(duration);
+    startval = 256 - light_brightness;
   }
-  for (double i = 1; i < 256; i++) {
+  for (double i = startval; i < 256; i++) {
     if (light_state != "dimming") {
       return false;
     }
     unsigned long interval;
     if (brighten) {
-      analogWrite(gate_pin, i);
+      analogWrite(gate_pin, (int) i);
+      light_brightness = (int) i;
       interval = (unsigned long) round(duration * (sqrt(i / 254) - sqrt((i - 1) / 254)));
     } else {
-      double x = 256 - i;
-      analogWrite(gate_pin, (int) x - 1);
-      interval = (unsigned long) round(duration * (sqrt(x / 254) - sqrt((x - 1) / 254)));
+      double x = 255 - i;
+      analogWrite(gate_pin, (int) x);
+      light_brightness = (int) x;
+      interval = (unsigned long) round(duration * (sqrt((x + 1) / 254) - sqrt(x / 254)));
     }
     unsigned long previousMillis = millis();
     if (i < 255) {


Extended project 3 to save temperatures and dump on button press

--- Project_3/Project_3.ino
+++ Project_3/Project_3.ino
@@ -1,55 +1,86 @@
 const int sensorPin = A0;
-const float baselineTemp = 24.0;
+const float baselineTemp = 23.0;
+const float interval = 5 * 60000;
+const int waitDuration = 250;

 int sensorVal, lightAmount;
 float voltage, temperature;
+float temperatures[300];
+long loopCounter = 0;
+int storeIndex = 0;

 void setup() {
   Serial.begin(9600);
-  for (int i = 2; i < 5; i++) {
+  for (int i = 2; i < 8; i++) {
     pinMode(i, OUTPUT);
-    digitalWrite(i, LOW);
   }
+  pinMode(8, INPUT);
 }

 void loop() {
   sensorVal = analogRead(sensorPin);
-  Serial.print("Sensor value: ");
-  Serial.print(sensorVal);
   voltage = (sensorVal/1024.0) * 5.0;
-  Serial.print(", Volts: ");
-  Serial.print(voltage);
-  Serial.print(", degrees C: ");
   temperature = (voltage - .5) * 100;
-  Serial.println(temperature);

   lightAmount = 0;
-  if (temperature >= baselineTemp + 2) {
-    lightAmount = 1;
-    if (temperature >= baselineTemp + 4) {
-      lightAmount = 2;
-      if (temperature >= baselineTemp + 6) {
-        lightAmount = 3;
-      }
+  for (int i = 1; i < 7; i++) {
+    if (temperature >= baselineTemp + i) {
+      lightAmount = i;
+    }
+    else {
+      break;
     }
   }
   light(lightAmount);

-  delay(500);
+  if (loopCounter % (int) (interval / waitDuration) == 0) {
+    store(temperature);
+  }
+
+  input();
+
+  loopCounter++;
+  delay(waitDuration);
 }

 void light(int amount) {
   digitalWrite(2, LOW);
   digitalWrite(3, LOW);
   digitalWrite(4, LOW);
+  digitalWrite(5, LOW);
+  digitalWrite(6, LOW);
+  digitalWrite(7, LOW);
   if (amount >= 1) {
     digitalWrite(2, HIGH);
     if (amount >= 2) {
       digitalWrite(3, HIGH);
       if (amount >= 3) {
         digitalWrite(4, HIGH);
+        if (amount >= 4) {
+          digitalWrite(5, HIGH);
+          if (amount >= 5) {
+            digitalWrite(6, HIGH);
+            if (amount >= 6) {
+              digitalWrite(7, HIGH);
+            }
+          }
+        }
       }
     }
   }
 }

+void input() {
+  if (digitalRead(8) == HIGH) {
+    for (int i = 0; i < storeIndex; i++) {
+      Serial.println(temperatures[i]);
+    }
+    storeIndex = 0;
+  }
+}
+
+void store(float temperature) {
+  temperatures[storeIndex] = temperature;
+  storeIndex++;
+}
+


Update b_Main_Loop.ino

Update b_Main_Loop.ino

Change to use serial input

--- b_Main_Loop.ino
+++ b_Main_Loop.ino
@@ -1,122 +1,125 @@
-void loop() {
-
-
-  // === DELETE THIS!  JUST FOR TESTING!!! =====
-  //PSARJ=millis()*.0005;
-  //PSARJ = 90 * sin(0.0005 * millis() * 0.001 * 180 / 3.14159);
-  // === DELETE THIS!  JUST FOR TESTING!!! =====
-
-  LoopStartMillis = millis();
-  delta_t_millis = max(LoopStartMillis - previousMillis, 1); // ensure always equal to at least one, for later inversion
-  inverse_delta_t_millis = (float) delta_t_millis;
-
-  Pos = float(rightCount) / 2.5; // / 25; // 150:1 gear ratio, 6 encoder counts per motor shaft rotation 150/6=25;
-
-  PosErr = PSARJ - Pos; // Compute Position Error
-  dPosErr = PosErr - PosErr_old;
-
-  dErr_dt = dPosErr * inverse_delta_t_millis * 0.001; // For Derivative
-
-  Int_Now = Int_Old + PosErr * inverse_delta_t_millis * 0.001; // For Integrator
-  Int_Old = Int_Now;
-  millisChPt1 = millis() - LoopStartMillis;
-  // Integrator reset when error sign changes
-  if (PosErr_old * PosErr < 0) { // sign has changed
-    Int_Now = 0;
-    Int_Old = 0;
-  }
-
-  tmpSpeed = Kp * PosErr + Kd * (dErr_dt) + Ki * Int_Now;
-  tmpSpeed2 = map(abs(tmpSpeed), 2, 250, 40, 250); // Deadband seems to be about 40 (for 5V input to motor board);
-  CmdSpeed = max(min(abs(tmpSpeed2), 250), 10); // At least 10, at most 200
-  millisChPt2 = millis() - LoopStartMillis;
-  //  if (abs(PosErr) > 10) {
-  //    CmdSpeed = 100;
-  //  }
-
-  if (tmpSpeed < 0) {
-    myMotor->run(FORWARD);
-    // motor.setSpeed(CmdSpeed);// + 20);
-    myMotor->setSpeed(abs(CmdSpeed));// + 20);
-    MyFlag = 1;
-    // delay(2);
-  }
-
-  if (tmpSpeed > 0) {
-    myMotor->run(BACKWARD);
-    // motor.setSpeed(CmdSpeed);
-    myMotor->setSpeed(abs(CmdSpeed));
-    MyFlag = 2;
-    //  delay(2);
-  }
-
-  delay(10);
-  // motor.run(RELEASE);
-
-  // delay(5);
-
-  // targetCount = 1000 + 1 * 50 * millis() / 1000;
-  // targetCount = PSARJ;
-
-  //Serial.print("release");
-  //motor.run(RELEASE);
-
-  if (1) {
-    response = ""; // empty it
-    response += " | rghtCnt ";
-    response += rightCount;
-    response += " | Pos ";
-    response += Pos;
-    response += " | PSARJ:";
-    response += PSARJ;
-    response += " | PsErr:";
-    response += PosErr;
-    response += " | MyFlag";
-    response += MyFlag;
-    response += " |||CmdSpd:";
-    response += CmdSpeed;
-    response += " |||PSARJ:";
-    response += PSARJ;
-    millisChPt3 = millis() - LoopStartMillis;
-    response += " |||delta_t_millis:";
-    response += delta_t_millis;
-    //    response+= " |||inv_delta_t_mlis:";
-    //response+= inverse_delta_t_millis;
-    response += "|millis";
-    response += LoopStartMillis;
-    response += " ||**|Int_Now:";
-
-    response += "|C1:";
-    response += millisChPt1;
-    response += "|C2:";
-    response += millisChPt2;
-    response += "|C3:";
-    response += millisChPt3;
-
-    response += "|C4:";
-    response += millisChPt4;
-    response += "|C5:";
-    response += millisChPt5;
-    response += "|C6:";
-    response += millisChPt6;
-    response += "LED:";
-    response += LEDstatus;
-    millisChPt4 = millis() - LoopStartMillis;
-    Serial.println(response);
-    millisChPt5 = millis() - LoopStartMillis;
-  }
-
-
-  previousMillis = LoopStartMillis;
-  PosErr_old = PosErr;
-  millisChPt6 = millis() - LoopStartMillis;
-//  if (LEDstatus = 0) {
-//    digitalWrite(13, HIGH);
-//    LEDstatus = 1;
-//  } else {
-//    digitalWrite(13, LOW);
-//    LEDstatus = 0;
-//  }
-
-
+void loop() {
+
+  if(Serial1.available())
+  {
+    checkSerial();
+  }
+  // === DELETE THIS!  JUST FOR TESTING!!! =====
+  //PSARJ=millis()*.0005;
+  //PSARJ = 90 * sin(0.0005 * millis() * 0.001 * 180 / 3.14159);
+  // === DELETE THIS!  JUST FOR TESTING!!! =====
+
+  LoopStartMillis = millis();
+  delta_t_millis = max(LoopStartMillis - previousMillis, 1); // ensure always equal to at least one, for later inversion
+  inverse_delta_t_millis = (float) delta_t_millis;
+
+  Pos = float(rightCount) / 2.5; // / 25; // 150:1 gear ratio, 6 encoder counts per motor shaft rotation 150/6=25;
+
+  PosErr = PSARJ - Pos; // Compute Position Error
+  dPosErr = PosErr - PosErr_old;
+
+  dErr_dt = dPosErr * inverse_delta_t_millis * 0.001; // For Derivative
+
+  Int_Now = Int_Old + PosErr * inverse_delta_t_millis * 0.001; // For Integrator
+  Int_Old = Int_Now;
+  millisChPt1 = millis() - LoopStartMillis;
+  // Integrator reset when error sign changes
+  if (PosErr_old * PosErr < 0) { // sign has changed
+    Int_Now = 0;
+    Int_Old = 0;
+  }
+
+  tmpSpeed = Kp * PosErr + Kd * (dErr_dt) + Ki * Int_Now;
+  tmpSpeed2 = map(abs(tmpSpeed), 2, 250, 40, 250); // Deadband seems to be about 40 (for 5V input to motor board);
+  CmdSpeed = max(min(abs(tmpSpeed2), 250), 10); // At least 10, at most 200
+  millisChPt2 = millis() - LoopStartMillis;
+  //  if (abs(PosErr) > 10) {
+  //    CmdSpeed = 100;
+  //  }
+
+  if (tmpSpeed < 0) {
+    myMotor->run(FORWARD);
+    // motor.setSpeed(CmdSpeed);// + 20);
+    myMotor->setSpeed(abs(CmdSpeed));// + 20);
+    MyFlag = 1;
+    // delay(2);
+  }
+
+  if (tmpSpeed > 0) {
+    myMotor->run(BACKWARD);
+    // motor.setSpeed(CmdSpeed);
+    myMotor->setSpeed(abs(CmdSpeed));
+    MyFlag = 2;
+    //  delay(2);
+  }
+
+  delay(10);
+  // motor.run(RELEASE);
+
+  // delay(5);
+
+  // targetCount = 1000 + 1 * 50 * millis() / 1000;
+  // targetCount = PSARJ;
+
+  //Serial.print("release");
+  //motor.run(RELEASE);
+
+  if (1) {
+    response = ""; // empty it
+    response += " | rghtCnt ";
+    response += rightCount;
+    response += " | Pos ";
+    response += Pos;
+    response += " | PSARJ:";
+    response += PSARJ;
+    response += " | PsErr:";
+    response += PosErr;
+    response += " | MyFlag";
+    response += MyFlag;
+    response += " |||CmdSpd:";
+    response += CmdSpeed;
+    response += " |||PSARJ:";
+    response += PSARJ;
+    millisChPt3 = millis() - LoopStartMillis;
+    response += " |||delta_t_millis:";
+    response += delta_t_millis;
+    //    response+= " |||inv_delta_t_mlis:";
+    //response+= inverse_delta_t_millis;
+    response += "|millis";
+    response += LoopStartMillis;
+    response += " ||**|Int_Now:";
+
+    response += "|C1:";
+    response += millisChPt1;
+    response += "|C2:";
+    response += millisChPt2;
+    response += "|C3:";
+    response += millisChPt3;
+
+    response += "|C4:";
+    response += millisChPt4;
+    response += "|C5:";
+    response += millisChPt5;
+    response += "|C6:";
+    response += millisChPt6;
+    response += "LED:";
+    response += LEDstatus;
+    millisChPt4 = millis() - LoopStartMillis;
+    Serial.println(response);
+    millisChPt5 = millis() - LoopStartMillis;
+  }
+
+
+  previousMillis = LoopStartMillis;
+  PosErr_old = PosErr;
+  millisChPt6 = millis() - LoopStartMillis;
+//  if (LEDstatus = 0) {
+//    digitalWrite(13, HIGH);
+//    LEDstatus = 1;
+//  } else {
+//    digitalWrite(13, LOW);
+//    LEDstatus = 0;
+//  }
+
+
 }


minor

minor

--- linefollower/linefollower.ino
+++ linefollower/linefollower.ino
@@ -50,31 +50,32 @@
   if((leftSensor == 0 && middleSensor == 0 && rightSensor == 1))
   {
     steerRight();
-    Serial.println("SteerLeft");
+    Serial.print("SteerLeft");
     lastAction = 2;
   }
   // if the left sensor is the only sensor that have the value 1, the bot need to compensate by turning left
   else if((leftSensor == 1 && middleSensor == 0 && rightSensor == 0))
   {
     steerLeft();
-    Serial.println("SteerRight");
+    Serial.print("SteerRight");
     lastAction = 3;
   }
   // if sensor value = 1, then the sensor is on track
   if((leftSensor == 0 && middleSensor == 1 && rightSensor == 0))
   {
     fwd();
-    Serial.println("Forward");
+    Serial.print("Forward");
     lastAction = 1;
   }
   else
   {
-    if(lastAction == 1){fwd();Serial.println("Forward**");}
-    else if(lastAction == 2){steerLeft();Serial.println("SteerLeft**");}
-    else if(lastAction == 3){steerRight();Serial.println("SteerRight**");}
-    else {stop();Serial.println("Stop");}
+    if(lastAction == 1){fwd();Serial.print("Forward**");}
+    else if(lastAction == 2){steerLeft();Serial.print("SteerLeft**");}
+    else if(lastAction == 3){steerRight();Serial.print("SteerRight**");}
+    //else {stop();Serial.println("Stop");}
   }
   delay(loopDelay);
+  Serial.println();
 }

 void readSensors(){


We are sending data to the front end, but we are not parsing data properly when receiving it.

--- ServerSketch/ServerSketch.ino
+++ ServerSketch/ServerSketch.ino
@@ -239,27 +239,7 @@
       lwsl_err("ERROR %d writing to socket\n", iNumBytes);
       return 1;
     }
-    /*
-    getSerialCommand();
-    if( !g_iNewCode )
-    {
-      iNumBytes = sendStatusToWebsite(wsi);
-      if (iNumBytes < 0)
-      {
-        lwsl_err("ERROR %d writing to socket\n", iNumBytes);
-        return 1;
-      }
-    }
-    else
-    {
-      iNumBytes = sendStatusToWebsiteNew(wsi);
-      if (iNumBytes < 0)
-      {
-        lwsl_err("ERROR %d writing to socket\n", iNumBytes);
-        return 1;
-      }
-    }
-*/
+
     break;

   case LWS_CALLBACK_RECEIVE:
@@ -270,7 +250,8 @@
     // Process Data Receieved from the Website
     // Update Galileo's HW
     // **********************************
-    procWebMsg((char*) in, len);
+//    procWebMsg((char*) in, len);
+    processMessage((char*) in);

     break;

@@ -532,20 +513,7 @@
       Serial.println("");
       Serial.print("sTempString.len:  ");
       Serial.println(sTempString.length());
-
-  //    n = sprintf((char *)p, "%s",outBuf); // This funtion can only print 256 characters
-
-//      n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}");
-     // snprintf((char *)p, 2000, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}");
-//      n = sprintf((char *)p, "%s","{\"status\":\"OK\",\"pins\":{ \"13\":{\"label\":\"Pin 13\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"2\":{\"label\":\"Pin 2\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"4\":{\"label\":\"Pin 4\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"7\":{\"label\":\"Pin 7\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"8\":{\"label\":\"Pin 8\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"12\":{\"label\":\"Pin 12\",\"is_analog\":\"false\",\"is_input\":\"false\",\"value\":\"1\"}, \"3\":{\"label\":\"Pin 3\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"5\":{\"label\":\"Pin 5\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"6\":{\"label\":\"Pin 6\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"9\":{\"label\":\"Pin 9\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"10\":{\"label\":\"Pin 10\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}, \"11\":{\"label\":\"Pin 11\",\"is_analog\":\"true\",\"is_input\":\"false\",\"value\":\"0.9\"}   }}");
-//      n = sprintf((char *)p, "%s","---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------********************************************************************************************************************************************************************************************");
-/*
-      Serial.println("");
-      Serial.print("n before: ");
-      Serial.println(n);
-  */
-//      n = libwebsocket_write(wsi, p, n, LWS_WRITE_TEXT);
-//      n = libwebsocket_write(wsi, p, sTempString.length(), LWS_WRITE_TEXT);
+
       n = libwebsocket_write(wsi, p, sTempString.length(), LWS_WRITE_TEXT);

       Serial.println("");
@@ -995,29 +963,37 @@
       aJsonObject *poIsAnalog = aJson.getObjectItem(poPinVals, "is_analog");
       if (poIsAnalog)
       {
+        g_aPins[i].is_analog = poIsAnalog->valuebool;
+
+        /*
         if( 0 == strcmp(poIsAnalog->valuestring,"true") )
           g_aPins[i].is_analog = 1;
         else if( 0 == strcmp(poIsAnalog->valuestring,"false") )
           g_aPins[i].is_analog = 0;
         else
           g_aPins[i].is_analog = -1;
+          */
       }

       aJsonObject *poIsInput = aJson.getObjectItem(poPinVals, "is_input");
       if (poIsInput)
       {
+        g_aPins[i].is_input = poIsInput->valuebool;
+        /*
         if( 0 == strcmp(poIsInput->valuestring,"true") )
           g_aPins[i].is_input = 1;
         else if( 0 == strcmp(poIsInput->valuestring,"false") )
           g_aPins[i].is_input = 0;
         else
           g_aPins[i].is_input = -1;
+          */
       }

       aJsonObject *poValue = aJson.getObjectItem(poPinVals, "value");
       if (poValue)
       {
-        g_aPins[i].value = atof(poValue->valuestring);
+//        g_aPins[i].value = atof(poValue->valuestring);
+        g_aPins[i].value = poValue->valuefloat;
       }
     }
   }
@@ -1158,6 +1134,7 @@

     ///////////////////////////////////////
     // Connect/Disconnect
+    /*
     switch(g_iDebugState)
     {
       case 0:
@@ -1178,6 +1155,7 @@
     }

     updateBoardState();
+    */
     ///////////////////////////////////////

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


Rearranged main Roost.ino to get it to compile. Dont't touch function ordering in the main file while developing labs, the program is sensitive to where each function appears because of dependencies on variable declarations.

--- Roost/Roost.ino
+++ Roost/Roost.ino
@@ -61,7 +61,7 @@
 // -----------------------------------------------------------------------------
 // Wifi Control: code for dealing with WiFi for the "Roost!" project
 //               requires ESP8266 WiFi libraries
-//               https://github.com/esp8266/Arduino/*
+//               https://github.com/esp8266/Arduino
 //
 #include <ESP8266WiFi.h>

@@ -314,6 +314,39 @@
 }

 // -----------------------------------------------------------------------------
+// Serial output: code for dealing with serial output for the "Roost!" project
+//
+#define SERIAL_BAUD 74880               // ESP native speed
+
+void serial_setup(){
+  Serial.begin(SERIAL_BAUD);
+  Serial.println("Roost initializing!");
+}
+
+void serial_roost() {
+  Serial.print("NTP epoch: ");
+  Serial.print(ntp_epoch_in_seconds);
+
+  Serial.print(" \tHumidity: ");
+  Serial.print(h);
+
+  Serial.print(" % \tTemperature: ");
+  Serial.print(t);
+  Serial.print(" *C ");
+  Serial.print(f);
+  Serial.print(" *F");
+
+  Serial.print(" \tHeat index: ");
+  Serial.print(hic);
+  Serial.print(" *C ");
+  Serial.print(hif);
+  Serial.print(" *F\t");
+
+  Serial.print("last motion: ");
+  Serial.println(pir_last_motion);
+}
+
+// -----------------------------------------------------------------------------
 // OLED control: code for dealing with oled for the "Roost!" project
 //               uses library by Daniel Eichhorn downloaded from github
 //               https://github.com/squix78/esp8266-oled-ssd1306
@@ -378,40 +411,6 @@
   display.drawString(0, 50, ls);
   display.display();
 }
-
-// -----------------------------------------------------------------------------
-// Serial output: code for dealing with serial output for the "Roost!" project
-//
-#define SERIAL_BAUD 74880               // ESP native speed
-
-void serial_setup(){
-  Serial.begin(SERIAL_BAUD);
-  Serial.println("Roost initializing!");
-}
-
-void serial_roost() {
-  Serial.print("NTP epoch: ");
-  Serial.print(ntp_epoch_in_seconds);
-
-  Serial.print(" \tHumidity: ");
-  Serial.print(h);
-
-  Serial.print(" % \tTemperature: ");
-  Serial.print(t);
-  Serial.print(" *C ");
-  Serial.print(f);
-  Serial.print(" *F");
-
-  Serial.print(" \tHeat index: ");
-  Serial.print(hic);
-  Serial.print(" *C ");
-  Serial.print(hif);
-  Serial.print(" *F\t");
-
-  Serial.print("last motion: ");
-  Serial.println(pir_last_motion);
-}
-

 // -----------------------------------------------------------------------------
 // Web output:  code for dealing with internet for the "Roost!" project
@@ -544,6 +543,9 @@
   // Serial for debugging
   serial_setup();

+  // WiFi
+  wifi_setup();
+
   // digital humididy temperature
   dht_setup();

@@ -553,9 +555,6 @@
   // OLED
   oled_setup();

-  // WiFi
-  wifi_setup();
-
   // NTP time
   ntp_setup();


Change USE_REV_E(false) to USE_REV_E(true) for 06-AppTutorial example

--- examples/06-AppTutorial/01-BasicGain_wApp/01-BasicGain_wApp.ino
+++ examples/06-AppTutorial/01-BasicGain_wApp/01-BasicGain_wApp.ino
@@ -18,11 +18,11 @@
 #include <Tympan_Library.h>  //include the Tympan Library

 //set to true for Rev E (and set the Arduino IDE to Teensy 4.1).
-#define USE_REV_E (false)    //this also assumes that REV_E is BC127 firmware V7 whereas REV_D is assumed to be V5
+#define USE_REV_E (true)    //this also assumes that REV_E is BC127 firmware V7 whereas REV_D is assumed to be V5

 //create audio library objects for handling the audio
 #if (USE_REV_E)
-Tympan                    myTympan(TympanRev::E);  //do TympanRev::D or TympanRev::C
+Tympan                    myTympan(TympanRev::E);  //do TympanRev::E
 #else
 Tympan                    myTympan(TympanRev::D);  //do TympanRev::D or TympanRev::C
 #endif


Magnetometer calibration Read magnetometer and update filter at each interrupt (more often) to update correctly filter Add comments about plugging This version works nicely !

--- Arduino/IMU_9DOF/IMU_9DOF.ino
+++ Arduino/IMU_9DOF/IMU_9DOF.ino
@@ -22,6 +22,12 @@
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 ===============================================
+Arduino to IMU Drotek 9dof
+A4 to SDA
+A5 to SCL
+D2 to INT (#0)
+GND to GND
+5V to 5V
 */

 // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
@@ -136,12 +142,6 @@
     Serial.println(F("Testing device connections..."));
     Serial.println(mpu.testConnection() ? F("MPU6050 connection successful") : F("MPU6050 connection failed"));
     Serial.println(mag.testConnection() ? "HMC5883L connection successful" : "HMC5883L connection failed");
-
-    // wait for ready
-    Serial.println(F("\nSend any character to begin DMP programming and demo: "));
-    while (Serial.available() && Serial.read()); // empty buffer
-    while (!Serial.available());                 // wait for data
-    while (Serial.available() && Serial.read()); // empty buffer again

     // load and configure the DMP
     Serial.println(F("Initializing DMP..."));
@@ -189,7 +189,6 @@
     mpu.setI2CMasterModeEnabled(0);
     mpu.setI2CBypassEnabled(1);
 }
-
 // ================================================================
 // ===                    MAIN PROGRAM LOOP                     ===
 // ================================================================
@@ -201,8 +200,7 @@
     // wait for MPU interrupt or extra packet(s) available
     while (!mpuInterrupt && fifoCount < packetSize) {

-        // read raw heading measurements from device
-        mag.getHeading(&mx16, &my16, &mz16);
+
         // other program behavior stuff here
         // .
         // .
@@ -213,12 +211,8 @@
         // .
         // .
         // .
-        if (millis() > last_time + UPDATE_RATE)
+         if (millis() > last_time + UPDATE_RATE)
          {
-               Now = micros();
-               deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
-               lastUpdate = Now;
-               MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180*250.0f/32768.0, gy*PI/180.0*250.0f/32768.0, gz*PI/180.0*250.0f/32768.0,  mx,  my,  mz);
                sendData();
                last_time = millis();
          }
@@ -259,8 +253,8 @@
         Serial.print("\t");
         Serial.print(aa.y);
         Serial.print("\t");
-        Serial.println(aa.z);
-        */
+        Serial.println(aa.z);*/
+
         // display real acceleration, adjusted to remove gravity
         mpu.dmpGetGyro(rr, fifoBuffer);
         gx = rr[0];
@@ -274,20 +268,29 @@
         Serial.print("\t");
         Serial.println(rr[2]);
         */
+
+        // read raw heading measurements from device
+        mag.getHeading(&mx16, &my16, &mz16);
+        mx16-=60;
+        my16-=261;
+        mz16+=334;
         mx = mx16;
         my = my16;
         mz = mz16;
-        /*
-        Serial.print("m\t");
+
+        /*Serial.print("m\t");
         Serial.print(mx);
         Serial.print("\t");
         Serial.print(my);
         Serial.print("\t");
-        Serial.println(mz);
-        */
-        // blink LED to indicate activity
-        blinkState = !blinkState;
-        digitalWrite(LED_PIN, blinkState);
+        Serial.println(mz);*/
+
+        Now = micros();
+        deltat = ((Now - lastUpdate)/1000000.0f); // set integration time by time elapsed since last filter update
+        lastUpdate = Now;
+        MadgwickQuaternionUpdate(ax, ay, az, gx*PI/180*250.0f/32768.0*100, gy*PI/180.0*250.0f/32768.0*100, gz*PI/180.0*250.0f/32768.0*100,  mx,  my,  mz);
+
+
     }
 }
 void sendData()
@@ -302,5 +305,8 @@
     Serial.print(qq[3]*10000);
     Serial.print(", ");
     Serial.println("");
+    // blink LED to indicate activity
+    blinkState = !blinkState;
+    digitalWrite(LED_PIN, blinkState);

 }


fix example

fix example

--- examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
+++ examples/DEV/OnDemandConfigPortal/OnDemandConfigPortal.ino
@@ -91,8 +91,8 @@
   WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40);
   WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6);
   WiFiManagerParameter custom_token("api_token", "api token", "", 16);
-  WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0);
-  WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 19,"pattern='\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'");
+  WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces
+  WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'");

   // callbacks
   wm.setSaveConfigCallback(saveCallback);


TODO-721: WIP

TODO-721: WIP

--- V0p2_Main/V0p2_Main.ino
+++ V0p2_Main/V0p2_Main.ino
@@ -32,6 +32,9 @@

 #ifdef ALLOW_CC1_SUPPORT
 #include <OTProtocolCC.h>
+#endif
+#if defined(ENABLE_OTSECUREFRAME_ENCODING_SUPPORT) || defined(ENABLE_SECURE_RADIO_BEACON)
+#include <OTAESGCM.h>
 #endif

 #include <util/crc16.h>


Tried implementation of scan

Tried implementation of scan

--- Tests/Ping_test/Ping_test.ino
+++ Tests/Ping_test/Ping_test.ino
@@ -12,6 +12,7 @@
 const int nMeasurements = 20;
 int       measurements[nMeasurements];
 int       measureIndex = -1;
+int       stepsSinceDetection;

 const int STATE_SEARCH    = 0;
 const int STATE_SCAN      = 1;
@@ -33,12 +34,29 @@

 void loop() {
   switch (currentState) {
-    case STATE_SEARCH:
+    case STATE_SEARCH:
+      rotateStep(counterClockwise);
       measure();
-      rotateStep(counterClockwise);
       if(detectsSomething()){
         stopMovement();
         tone(4, 4000, 500);
+        stepsSinceDetection = 0;
+        currentState = STATE_SCAN;
+      }
+      delay(100);
+      break;
+    case STATE_SCAN:
+      rotateStep(counterClockwise);
+      measure();
+      if(detectsSomething()){
+        stepsSinceDetection++;
+      } else{
+        stepsSinceDetection /= 2;
+        stepsSinceDetection += 2;
+        while(stepsSinceDetection--){
+          rotateStep(clockwise);
+          delay(100);
+        }
         currentState = STATE_APPROACH;
       }
       delay(100);


disable wifi to save power

disable wifi to save power

--- Wikiduino/Wikiduino.ino
+++ Wikiduino/Wikiduino.ino
@@ -34,6 +34,7 @@
 } temp[4] = {{0,0}};

 unsigned int last = 100;
+unsigned int powersave = 0;
 unsigned long crc_errs = 0;

 // Arduino Setup and Loop
@@ -58,8 +59,18 @@
   unsigned int now = millis();
   if ((now-last) >= 1000) {
     last = now;
+    powerClock();
     analogSample();
     tempSample();
+  }
+}
+
+void powerClock() {
+  boolean poweron = powersave == 0;
+  pinMode(2,OUTPUT);
+  digitalWrite(2,poweron);
+  if (!poweron) {
+    powersave--;
   }
 }

@@ -170,6 +181,8 @@
     jsonReport();
   } else if (code == 'f') {
     faviconReport();
+  } else if (code == 'p') {
+    powersave = 55*60;
   } else {
     errorReport();
   }


bug EEPROM corrige.pb tempo

bug EEPROM corrige.pb tempo

--- calibrateur.ino
+++ calibrateur.ino
@@ -170,9 +170,10 @@
 						{
 							boutonP.acquit();
 							EEPROM.get(ADRESSE_EEPROM, bonnePositionPotence); //lire la prom
-                                                        Serial.println("j'ai lu");
+                                                        Serial.println(F("j'ai lu"));
                                                         Serial.println(bonnePositionPotence);
                                                         potence.setObjectif(bonnePositionPotence);
+                                                        sleep( TEMPOSLEEP );
                                                         etatCalibrateur=MESREFPULSE;
 						}

@@ -212,7 +213,7 @@
 							bonnePositionPotence=map(lePotar.getValue(),0,1023,potence.getMin(),potence.getMax());
 							boutonP.acquit();
                                                         EEPROM.put(ADRESSE_EEPROM, bonnePositionPotence);//enregistre en eeprom
-                                                        Serial.println("sauver en prom");
+                                                        Serial.print(F("sauver en prom = ")); Serial.println( bonnePositionPotence );
 							etatCalibrateur=MESREFPULSE;
 						}
 					break;
@@ -241,7 +242,7 @@
 					etatCalibrateur=FINDMINMAX;
 					//Serial.println("la");
 					compteurRef=compteur;
-                                        Serial.print(" SUPERcmpteurRef=");
+                                        Serial.print(F(" SUPERcmpteurRef="));
                                         Serial.println(compteurRef);
 //                                        Serial.print(" OBJTEST=");
 //                                        Serial.println(leServo.getObjectif());
@@ -254,9 +255,9 @@
 						}
                                         if (ERREURCOMPTAGE*3>compteurRef)
                                                 {
-                                                        Serial.println("ce serait bien que la marge d'erreur soit de l'ordre de 30% de la mesure de reference");
-							Serial.println("je vais faire autre chose.... Programme a recompiler");
-                                                        Serial.println("modifier macro ERREURCOMPTAGE et DELTA");
+                                                        Serial.println(F("ce serait bien que la marge d'erreur soit de l'ordre de 30% de la mesure de reference"));
+							Serial.println(F("je vais faire autre chose.... Programme a recompiler"));
+                                                        Serial.println(F("modifier macro ERREURCOMPTAGE et DELTA"));
 							etatCalibrateur=POTAR;
                                                         affichage.affiche(POTAR);
                                                 }


Add button press detection for cycling

Add button press detection for cycling

--- jacket.ino
+++ jacket.ino
@@ -1,4 +1,6 @@
 #include "FastLED.h"
+
+#include "buttons.h"

 #include "plasma.cpp"
 #include "stripes.cpp"
@@ -14,8 +16,8 @@
 #define NUM_LEDS    400

 // Reasonable for battery-powered jacket - use 300 if powering from only USB cable
-#define MAX_POWER 1000
-#define BRIGHTNESS  100
+#define MAX_POWER 500
+#define BRIGHTNESS  150

 // Sketches are tuned for this speed.  TODO: consistent framerate for sketches inside Animation class
 #define FRAMES_PER_SECOND 18
@@ -147,6 +149,77 @@
 Animation *lastAnim;
 fract8 animTransition;

+#define TIME_CYCLE 20000
+#define TIME_PAUSED ((unsigned long)-1)
+unsigned long nextAnimationTime = 0;
+int state = -1; // Start state
+
+void NextAnimation(int pin)
+{
+  state = leaveState(state);
+  Serial.print("next animation state: ");
+  Serial.println(state);
+}
+
+void Pause(int pin)
+{
+  if (nextAnimationTime == TIME_PAUSED) {
+    Serial.println("unpause");
+    nextAnimationTime = millis();
+  } else {
+    Serial.println("pause");
+    nextAnimationTime = TIME_PAUSED;
+  }
+}
+
+
+int leaveState(int i) {
+  i = (i+1) % 10;
+  return enterState( i );
+}
+
+int enterState(int i) {
+  switch (i) {
+    case 0:
+      beginAnimation(new Noise());
+      break;
+    case 1:
+      beginAnimation(new Plasma());
+      break;
+    case 2:
+      beginAnimation(new Fire());
+      break;
+    case 3:
+      beginAnimation(new Descent(true));
+      break;
+    case 4:
+      beginAnimation(new Noise());
+      break;
+    case 5:
+      beginAnimation(new Fire());
+      break;
+    case 6:
+      beginAnimation(new Plasma());
+      break;
+    case 7:
+      beginAnimation(new Descent(true));
+      break;
+    case 8:
+      beginAnimation(new Fire());
+      break;
+    case 9:
+      beginAnimation(new Plasma());
+      break;
+  }
+  return i;
+}
+
+
+
+
+FWB Button;
+
+

 void setup() {
   // sanity check delay - allows reprogramming if accidently blowing power w/leds
@@ -154,14 +227,20 @@

   // Teensy needs this?
   pinMode(13, OUTPUT);
-  // set_max_power_indicator_LED( 13);
+  // set_max_power_indicator_LED( 13);
+
+  Button.Configure(12, PULL_UP);
+  Button.OnClick = NextAnimation;
+  Button.OnLongPress = Pause;

   // Set up the LED string and appropriate power config
   FastLED.addLeds<CHIPSET, LED_PIN, COLOR_ORDER>(leds, NUM_LEDS).setCorrection( TypicalSMD5050 );
   set_max_power_in_volts_and_milliamps( 5, MAX_POWER);
   FastLED.setBrightness( BRIGHTNESS );
-  FastLED.setDither( true );
-
+  FastLED.setDither( false );
+
+  Serial.println("started");
+
   // Precalc all posiitons
   for (int i = 0; i < NUM_LEDS; i++) {
     int x,y;
@@ -179,49 +258,31 @@
   }
 }

-#define TTIME 20000
+

 void loop() {
   unsigned long now = millis();
   unsigned long next = now + (1000 / FRAMES_PER_SECOND);
+
+  Button.CheckBP();
+  if (now >= nextAnimationTime) {
+    NextAnimation(0);
+    nextAnimationTime = now + TIME_CYCLE;
+  }

   // Cycle current and previous animations
   // Continue fading between current animations
   if (anim)
     anim->loop(now);
-  if (lastAnim)
+  if (lastAnim) {
     lastAnim->loop(now);
-  if (animTransition) {
     animTransition = qsub8(animTransition, 3);
     if (!animTransition) {
       delete lastAnim;
       lastAnim = (Animation *)0;
     }
   }
-
-  // Transition if necessary
-  // TODO: this bad code is here as placeholder until I can write something that's button reactive
-  static unsigned long xx = 0;
-  if (xx < 1 && millis() > 0) {
-    xx = 1;
-    beginAnimation(new Stripes());
-  } else if (xx < 2 && millis() > TTIME) {
-    xx = 2;
-    beginAnimation(new Plasma());
-  } else if (xx < 3 && millis() > TTIME*2) {
-    xx = 3;
-    beginAnimation(new Noise());
-  } else if (xx < 4 && millis() > TTIME*3) {
-    xx = 4;
-    beginAnimation(new Descent( true ));
-  } else if (xx < 5 && millis() > TTIME*4) {
-    xx = 5;
-    beginAnimation(new Fire());
-  } else if (xx < 6 && millis() > TTIME*5) {
-    xx = 6;
-    beginAnimation(new Plasma());
-  }
-
+
   // Map from the virtual matrix to the actual LEDs, blending previous
   for(int i = 0; i < NUM_LEDS; i++) {
    if (anim)
@@ -253,3 +314,5 @@
   anim = newAnim;
   newAnim->start();
 }
+
+


Reads from analog sensors, sends over Serial

--- DigitalInOut/DigitalInOut.ino
+++ DigitalInOut/DigitalInOut.ino
@@ -1,8 +1,18 @@
 const int dPins[]  = {
   8,  // tilt sensor 1A
-  9,  // tilt sensor 1B
+  9  // tilt sensor 1B
 };
+
+const int bPins[] = {
+  A0,  // thumb
+  A1,  // index
+  A2,  // middle
+  A3,  // ring
+  A4  // pinky
+};
+
 int dNoPins = sizeof(dPins)/sizeof(int);
+int bNoPins = sizeof(bPins)/sizeof(int);
 int SAMPLES_PER_SECOND = 20;

 int buttonPin = 12;
@@ -14,25 +24,39 @@
   for(int i = 0; i < dNoPins; i++){
     pinMode(dPins[i], INPUT);
   }
+  for(int i = 0; i < bNoPins; i++){
+    pinMode(bPins[i], INPUT);
+    digitalWrite(bPins[i], HIGH);
+  }
 }

 void loop() {
-  // read and send digital value
-  for(int i = 0; i < dNoPins; i++){
-    sendInt16AsBytes(digitalRead(dPins[i]));
-    digitalWrite(dPins[i], LOW);
+  //  // read and send digital value
+  //  for(int i = 0; i < dNoPins; i++){
+  //    sendInt16AsBytes(digitalRead(dPins[i]));
+  //    digitalWrite(dPins[i], LOW);
+  //  }
+  //
+  //  digitalWrite(buttonPin, HIGH);
+  //
+  //  if(digitalRead(buttonPin)){
+  //    // Combine the tilt sensor values to one int
+  //    //int tiltValue = (int)(digitalRead(dPins[0]) << 1 | digitalRead(dPins[1]));
+  //    //sendInt16AsBytes(tiltValue);
+  //
+  //    // End transmission with a linebreak (sortof)
+  //    Serial.write(10);
+  //  }
+
+  for(int i = 0; i < bNoPins; i++){
+    int value = map(analogRead(bPins[i]), 200, 700, 0, 100);
+        //Serial.print(value);
+    sendInt16AsBytes(value);
+
   }
-
-  digitalWrite(buttonPin, HIGH);
-
-  if(digitalRead(buttonPin)){
-    // Combine the tilt sensor values to one int
-    //int tiltValue = (int)(digitalRead(dPins[0]) << 1 | digitalRead(dPins[1]));
-    //sendInt16AsBytes(tiltValue);
-
-    // End transmission with a linebreak (sortof)
-    Serial.write(10);
-  }
+ // Serial.println();
+  // End transmission with a linebreak (sortof)
+  Serial.write(10);
   // wait
   // for the analog-to-digital converter to settle
   // after the last reading:
@@ -50,3 +74,5 @@

+
+


First working implementation of communication from Arduino to Android. A lot of debug code have to be removed

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -5,21 +5,30 @@
 #include "DualMC33926MotorShield.h"
 #define BUFFSIZE   128
 #define MAX_POWER  400
-// Accessory descriptor. It's how Arduino identifies itself in Android.
+
+// Start Accessory Descriptor. It's how Arduino identifies itself in Android.
 char accessoryName[] = "UDOO Mobile Tank";
 char manufacturer[] = "Simone Mariotti";
 char model[] = "Mobile-Tanker";
-
 char versionNumber[] = "0.1.0";
 char serialNumber[] = "1";
 char url[] = "https://github.com/DMIAlumni/mobile-tanker";
+// End Accessory Descriptor

-// ADK configuration
+// Start ADK configuration
 USBHost Usb;
 ADK adk(&Usb, manufacturer, model, accessoryName, versionNumber, url, serialNumber);
+// End ADK configuration
+
+int randomint;
+int last_send = 0;
 uint8_t buffer[BUFFSIZE];
+char bufNew[BUFFSIZE];
+char charBuf[2000];
 uint32_t bytesRead = 0;
+
 DualMC33926MotorShield tank;
+
 void setup() {
   Serial.begin(115200);
   delay(1000);
@@ -28,8 +37,8 @@
 }

 void loop() {
+  Serial.println("Looping");
   readingFromADK();
-
 }

 void stopEngine() {
@@ -39,25 +48,51 @@

 void readingFromADK() {
   Usb.Task();
-
   // Starting listening when ADK is available
   if (adk.isReady()) {
     adk.read(&bytesRead, BUFFSIZE, buffer);
     if (bytesRead > 0) {
       for (int i = 0; i < bytesRead; i++) {
-        if (buffer[i]>=48 && buffer[i]<=47)
-        Serial.print(buffer[i]-48);
+        if (buffer[i] >= 48 && buffer[i] <= 47)
+          Serial.print(buffer[i] - 48);
         else
-        Serial.print((char)buffer[i]);
+          Serial.print((char)buffer[i]);
         Serial.print("-");
         //eepCommandInterpreter(extractMovement(), extractSpeed());
+        //eepCommandInterpreter(extractMovement(), extractSpeed());
+      }	Serial.print("RECEIVED FROM USB: ");
+      Serial.println(*(uint32_t*)buffer);
+    }
+  } sendingToADK();
+}

-        //eepCommandInterpreter(extractMovement(), extractSpeed());
+void sendingToADK() {
+  int time = millis();
+  if (time - last_send > 5000) {
+    last_send = time;
+    randomint = random(-1500, 1500);
+    String s = String("");
+    s += randomint;
+    s += ":";
+    s += randomint - 1000;
+    s += ":";
+    s += randomint;
+    s += ";";

-
-      }	Serial.print("RECEIVED FROM USB: ");
-      	Serial.println(*(uint32_t*)buffer);
-
+    s.toCharArray(charBuf, sizeof(charBuf));
+    //charBuf[0]='a';
+    delay(10);
+    for (int i = 0; i < s.length(); i++) {
+      bufNew[i] = s.charAt(i);
     }
   }
+  writeToAdk(charBuf);
 }
+
+void writeToAdk(char textToSend[]) {
+  Serial.print(textToSend);
+  Serial.print(" ");
+  Serial.print(strlen(textToSend));
+  Serial.println(" bytes in partenza");
+  adk.write(strlen(textToSend), (uint8_t*)textToSend);
+}


Fix buffer overflow

Fix buffer overflow

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -257,8 +257,16 @@
     newByte = Serial.read();
     if (newByte != '\n')
     {
-      // Add the current character to the buffer and increase the position
-      buffer[bufferLength++] = newByte;
+      /*
+      * Check the length of the buffer. If it is longer than the buffer itself
+      * we must prevent a buffer-overflow. In that case we don't add the read
+      * character to the buffer.
+      */
+      if (bufferLength < BUFFER_SIZE)
+      {
+        // Add the current character to the buffer and increase the position
+        buffer[bufferLength++] = newByte;
+      }
     }
     else
     {


blink on start added

blink on start added

--- nodmcu.ino
+++ nodmcu.ino
@@ -4,11 +4,6 @@
 #include <ArduinoJson.h>
 #include <WiFiManager.h>
 #include <Servo.h>
-
-extern "C" {
-  #include "user_interface.h"
-}
-

 Servo servo;
@@ -73,6 +68,13 @@
   digitalWrite(LED_PIN, !state);
    }
   }
+  void doblink(int pin, int count = 1, int timeout = 500){
+    for(int i=0; i<count; i++){
+         digitalWrite(pin, LOW);
+         delay(timeout);
+         digitalWrite(pin, HIGH);
+    }
+  }
   void checkRepo(int interval){

   }
@@ -126,7 +128,8 @@
         });
         server->begin();
     Serial.println("Custom HTTP server started");
-
+    doblink(LED_PIN, 1, 5000);
+
   }
 }


Supports left/right stick drive config. Organizes default options

New feature to support left stick or right stick drive control. Set via `leftStickDrive` boolean.

Moves variables for defaults, options, and config to the top with some additional comments.

--- padawan360_body/padawan360_body_mega_i2c_ino/padawan360_body_mega_i2c/padawan360_body_mega_i2c.ino
+++ padawan360_body/padawan360_body_mega_i2c_ino/padawan360_body_mega_i2c/padawan360_body_mega_i2c.ino
@@ -1,10 +1,11 @@
 // =======================================================================================
-// /////////////////////////Padawan360 Body Code - Mega I2C v1.0 ////////////////////////////////////
+// /////////////////////////Padawan360 Body Code - Mega I2C v2.0 ////////////////////////////////////
 // =======================================================================================
 /*
 by Dan Kraus
 dskraus@gmail.com
 Astromech: danomite4047
+Project Site: https://github.com/dankraus/padawan360/

 Heavily influenced by DanF's Padwan code which was built for Arduino+Wireless PS2
 controller leveraging Bill Porter's PS2X Library. I was running into frequent disconnect
@@ -35,20 +36,30 @@

 */

-//************************** Set speed and turn speeds here************************************//
-
+// ************************** Options, Configurations, and Settings ***********************************
+
+
+// SPEED AND TURN SPEEDS
 //set these 3 to whatever speeds work for you. 0-stop, 127-full speed.
 const byte DRIVESPEED1 = 50;
-//Recommend beginner: 50 to 75, experienced: 100 to 127, I like 100.
+// Recommend beginner: 50 to 75, experienced: 100 to 127, I like 100.
+// These may vary based on your drive system and power system
 const byte DRIVESPEED2 = 100;
 //Set to 0 if you only want 2 speeds.
 const byte DRIVESPEED3 = 127;

+// Default drive speed at startup
 byte drivespeed = DRIVESPEED1;
+
+// Set leftHandDrive to true for driving  with the left stick
+// Set leftHandDrive to false for driving with the right stick (legacy and original configuration)
+boolean leftHandDrive = true;

 // the higher this number the faster the droid will spin in place, lower - easier to control.
 // Recommend beginner: 40 to 50, experienced: 50 $ up, I like 70
+// This may vary based on your drive system and power system
 const byte TURNSPEED = 70;
+
 // If using a speed controller for the dome, sets the top speed. You'll want to vary it potenitally
 // depending on your motor. My Pittman is really fast so I dial this down a ways from top speed.
 // Use a number up to 127 for serial
@@ -69,7 +80,6 @@
 const byte DOMEDEADZONERANGE = 20;
 const byte DRIVEDEADZONERANGE = 20;

-
 // Set the baude rate for the Sabertooth motor controller (feet)
 // 9600 is the default baud rate for Sabertooth packet serial.
 // for packetized options are: 2400, 9600, 19200 and 38400. I think you need to pick one that works
@@ -81,8 +91,18 @@
 // and I think it varies across different firmware versions.
 const int DOMEBAUDRATE = 2400;

-
-// I have a pin set to pull a relay high/low to trigger my upside down compressed air like R2's extinguisher
+// Default sound volume at startup
+// 0 = full volume, 255 off
+byte vol = 20;
+
+
+// Automation Delays
+// set automateDelay to min and max seconds between sounds
+byte automateDelay = random(5, 20);
+//How much the dome may turn during automation.
+int turnDirection = 20;
+
+// Pin number to pull a relay high/low to trigger my upside down compressed air like R2's extinguisher
 #define EXTINGUISHERPIN 3

 #include <Sabertooth.h>
@@ -101,26 +121,28 @@
 #endif

 // Set some defaults for start up
-// 0 = full volume, 255 off
-byte vol = 20;
-// 0 = drive motors off ( right stick disabled ) at start
+// false = drive motors off ( right stick disabled ) at start
 boolean isDriveEnabled = false;

-// Automated function variables
+// Automated functionality
 // Used as a boolean to turn on/off automated functions like periodic random sounds and periodic dome turns
 boolean isInAutomationMode = false;
 unsigned long automateMillis = 0;
-byte automateDelay = random(5, 20); // set this to min and max seconds between sounds
-//How much the dome may turn during automation.
-int turnDirection = 20;
 // Action number used to randomly choose a sound effect or a dome turn
 byte automateAction = 0;
+
+
 int driveThrottle = 0;
-int rightStick = 0;
+int throttleStickValue = 0;
 int domeThrottle = 0;
 int turnThrottle = 0;

 boolean firstLoadOnConnect = false;
+
+AnalogHatEnum throttleAxis;
+AnalogHatEnum turnAxis;
+AnalogHatEnum domeAxis;
+

 // this is legacy right now. The rest of the sketch isn't set to send any of this
 // data to another arduino like the original Padawan sketch does
@@ -176,6 +198,16 @@

   mp3Trigger.setup();
   mp3Trigger.setVolume(vol);
+
+  if(leftHandDrive) {
+    throttleAxis = LeftHatY;
+    turnAxis = LeftHatX;
+    domeAxis = RightHatX;
+  } else {
+    throttleAxis = RightHatY;
+    turnAxis = RightHatX;
+    domeAxis = LeftHatX;
+  }

   // Start I2C Bus. The body is the master.
@@ -483,26 +515,28 @@
   }

+
   // FOOT DRIVES
   // Xbox 360 analog stick values are signed 16 bit integer value
   // Sabertooth runs at 8 bit signed. -127 to 127 for speed (full speed reverse and  full speed forward)
   // Map the 360 stick values to our min/max current drive speed
-  rightStick = (map(Xbox.getAnalogHat(RightHatY, 0), -32768, 32767, -drivespeed, drivespeed));
-  if (rightStick > -DRIVEDEADZONERANGE && rightStick < DRIVEDEADZONERANGE) {
+
+  throttleStickValue = (map(Xbox.getAnalogHat(throttleAxis, 0), -32768, 32767, -drivespeed, drivespeed));
+  if (throttleStickValue > -DRIVEDEADZONERANGE && throttleStickValue < DRIVEDEADZONERANGE) {
     // stick is in dead zone - don't drive
     driveThrottle = 0;
   } else {
-    if (driveThrottle < rightStick) {
-      if (rightStick - driveThrottle < (RAMPING + 1) ) {
+    if (driveThrottle < throttleStickValue) {
+      if (throttleStickValue - driveThrottle < (RAMPING + 1) ) {
         driveThrottle += RAMPING;
       } else {
-        driveThrottle = rightStick;
-      }
-    } else if (driveThrottle > rightStick) {
-      if (driveThrottle - rightStick < (RAMPING + 1) ) {
+        driveThrottle = throttleStickValue;
+      }
+    } else if (driveThrottle > throttleStickValue) {
+      if (driveThrottle - throttleStickValue < (RAMPING + 1) ) {
         driveThrottle -= RAMPING;
       } else {
-        driveThrottle = rightStick;
+        driveThrottle = throttleStickValue;
       }
     }
   }


remove resetsettings

remove resetsettings

--- examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino
+++ examples/AutoConnect/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino
@@ -36,7 +36,7 @@
   //Local intialization. Once its business is done, there is no need to keep it around
   WiFiManager wm;
   //reset settings - for testing
-  wm.resetSettings();
+  // wm.resetSettings();

   //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
   wm.setAPCallback(configModeCallback);


Added link to hardware

Added link to hardware

--- arduino/fasnacht/fasnacht.ino
+++ arduino/fasnacht/fasnacht.ino
@@ -1,3 +1,5 @@
+// Written for SparkFun EL Sequencer
+// https://www.sparkfun.com/products/11323

 void setup() {
     // The EL channels are on pins 2 through 9


improved left/right turning

improved left/right turning

--- arduino/pi_rover/pi_rover.ino
+++ arduino/pi_rover/pi_rover.ino
@@ -289,71 +289,39 @@

 String left(int speedInPercentage)
 {
-  int currentMotorSpeed = motorSpeed;
-  setMotorSpeed(100);
-
+  int currentMotorSpeedInPercentage = map(
+    motorSpeed,
+    0, maxMotorSpeed,
+    0, 100
+  );
+
+  // reset the speed of all motors to "motorSpeed"
   turnMotorsOn();
-
-  bool turnToTheLeftSharply = speedInPercentage > 25;
-
-  if (turnToTheLeftSharply == false)
-  {
-    motor1.setSpeed(0);
-    motor4.setSpeed(0);
-  }
-
-  motor1.run(FORWARD);
-  motor2.run(BACKWARD);
-  motor3.run(FORWARD);
-  motor4.run(BACKWARD);
-
-  delay(speedInPercentage * 2);
-
-  motorSpeed = currentMotorSpeed;
-
-  if (isMovingForward) {
-    forward(0);
-  } else if (isMovingBackward) {
-    backward(0);
-  } else {
-    turnMotorsOff();
-  }
-
+
+  int speedOfLeftMotors = ((float) currentMotorSpeedInPercentage / 100) * speedInPercentage;
+
+  motor2.setSpeed(speedOfLeftMotors);
+  motor3.setSpeed(speedOfLeftMotors);
+
   return "ok";
 }

 String right(int speedInPercentage)
 {
-  int currentMotorSpeed = motorSpeed;
-  setMotorSpeed(100);
-
+  int currentMotorSpeedInPercentage = map(
+    motorSpeed,
+    0, maxMotorSpeed,
+    0, 100
+  );
+
+  // reset the speed of all motors to "motorSpeed"
   turnMotorsOn();

-  bool turnToTheRightSharply = speedInPercentage > 25;
-
-  if (turnToTheRightSharply == false)
-  {
-    motor2.setSpeed(0);
-    motor3.setSpeed(0);
-  }
-
-  motor1.run(BACKWARD);
-  motor2.run(FORWARD);
-  motor3.run(BACKWARD);
-  motor4.run(FORWARD);
-
-  delay(speedInPercentage * 2);
-
-  motorSpeed = currentMotorSpeed;
-
-  if (isMovingForward) {
-    forward(0);
-  } else if (isMovingBackward) {
-    backward(0);
-  } else {
-    turnMotorsOff();
-  }
-
+  int speedOfRightMotors = ((float) currentMotorSpeedInPercentage / 100) * speedInPercentage;
+
+  motor1.setSpeed(speedOfRightMotors);
+  motor4.setSpeed(speedOfRightMotors);
+
   return "ok";
 }


Replace sleep function with asm

Replace sleep function with asm

--- lampka.ino
+++ lampka.ino
@@ -93,11 +93,9 @@
     // Note that the inter-bit gap can be as long as you want as long as it doesn't exceed the 5us reset timeout (which is A long time)
     // Here I have been generous and not tried to squeeze the gap tight but instead erred on the side of lots of extra time.
     // This has thenice side effect of avoid glitches on very long strings becuase
-
-
 }

-
+
 void sendByte( uint8_t byte ) {

     for( uint8_t bit = 0 ; bit < 8 ; bit++ ) {
@@ -141,8 +139,20 @@

 void show() {
   //_delay_us( (RES / 1000UL) + 1);       // Round up since the delay must be _at_least_ this long (too short might not work, too long not a problem)
- delayMicroseconds((RES / 1000UL) + 1);
-}
+ //delayMicroseconds((RES / 1000UL) + 1);
+ asm volatile (
+      ".rept %[innerCycles] \n\t"        // Now timing actually matters. The 0-bit must be long enough to be detected but not too long or it will be a 1-bit
+      "nop \n\t"                                              // Execute NOPs to delay exactly the specified number of cycles
+      ".endr \n\t"
+//      ".rept %[innerCycles] \n\t"        // Now timing actually matters. The 0-bit must be long enough to be detected but not too long or it will be a 1-bit
+      //"nop \n\t"                                              // Execute NOPs to delay exactly the specified number of cycles
+      //".endr \n\t"
+      ::
+      [innerCycles]  "I" (NS_TO_CYCLES(6000))
+      //[outerCycles]  "I" (100)
+    );
+}
+

 ////////////////////////////////////////////////////////////////////////////////////
@@ -363,6 +373,9 @@
     GIMSK |= (1<<5); //Bit 5 PCIE: Pin Change Interrupt Enable
     PCMSK |= (1<<directionButtonPin); //PCINT[5:0]: Pin Change Enable Mask 5:0
     PCMSK |= (1<<constantButtonPin); //PCINT[5:0]: Pin Change Enable Mask 5:0
+
+
+    TCCR0B &= ~(1 | 2| 4); //0 0 0 No clock source (Timer/Counter stopped)
 }

 #define constant_color_index OCR0B


fix buggy "is_shorter" function

fix buggy "is_shorter" function

--- main/main.ino
+++ main/main.ino
@@ -130,7 +130,7 @@
   quadModeGauges[0][0] = &engine_rpm;
   quadModeGauges[0][1] = &engine_map;
   quadModeGauges[0][2] = &engine_afr;
-  quadModeGauges[0][3] = &engine_tgt;
+  quadModeGauges[0][3] = &engine_tps;

   lcd.begin(20, 4);

@@ -220,14 +220,26 @@
   draw_bar(*quadModeGauges[0][0], 0, 9);

   lcd.setCursor(4, 1);
+  if(is_current_value_shorter(*quadModeGauges[0][1])) {
+    lcd.print(F("     "));
+    lcd.setCursor(4, 1);
+  }
   lcd.print(quadModeGauges[0][1]->currentValue, quadModeGauges[0][1]->decimalPlaces);
   draw_bar(*quadModeGauges[0][1], 1, 9);

   lcd.setCursor(4, 2);
+  if(is_current_value_shorter(*quadModeGauges[0][2])) {
+    lcd.print(F("     "));
+    lcd.setCursor(4, 2);
+  }
   lcd.print(quadModeGauges[0][2]->currentValue, quadModeGauges[0][2]->decimalPlaces);
   draw_bar(*quadModeGauges[0][2], 2, 9);

   lcd.setCursor(4, 3);
+  if(is_current_value_shorter(*quadModeGauges[0][3])) {
+    lcd.print(F("     "));
+    lcd.setCursor(4, 3);
+  }
   lcd.print(quadModeGauges[0][3]->currentValue, quadModeGauges[0][3]->decimalPlaces);
   draw_bar(*quadModeGauges[0][3], 3, 9);
 }
@@ -422,17 +434,19 @@

 //note: using log10 would work but this is faster
 bool is_current_value_shorter(EngineVariable engine) {
+  int roundedCurrent = round(engine.currentValue);
+  int roundedPrevious = round(engine.previousValue);
   byte currentLength;
-  if(engine.currentValue >= 10000) {
+  if(roundedCurrent >= 10000) {
     currentLength = 5;
   }
-  else if(engine.currentValue >= 1000) {
+  else if(roundedCurrent >= 1000) {
     currentLength = 4;
   }
-  else if(engine.currentValue >= 100) {
+  else if(roundedCurrent >= 100) {
     currentLength = 3;
   }
-  else if(engine.currentValue >= 10) {
+  else if(roundedCurrent >= 10) {
     currentLength = 2;
   }
   else {
@@ -444,16 +458,16 @@
   }

   byte previousLength;
-  if(engine.previousValue >= 10000) {
+  if(roundedPrevious >= 10000) {
     previousLength = 5;
   }
-  else if(engine.previousValue >= 1000) {
+  else if(roundedPrevious >= 1000) {
     previousLength = 4;
   }
-  else if(engine.previousValue >= 100) {
+  else if(roundedPrevious >= 100) {
     previousLength = 3;
   }
-  else if(engine.previousValue >= 10) {
+  else if(roundedPrevious >= 10) {
     previousLength = 2;
   }
   else {


start button code

start button code

--- main/main.ino
+++ main/main.ino
@@ -7,6 +7,17 @@
 LiquidCrystal lcd(14, 3, 4, 5, 6, 7); //RS,EN,DB4,DB5,DB6,DB7
 const byte LED_PIN = 15;
 const byte SPI_CS_PIN = 10;
+
+const byte MODE_PIN = 9;
+//button pin results with internal pullup:
+//2 mostly works but is very noisy
+//8 is always low
+//9 works
+//11,12 interrups canbus even though not declared in this file
+//16, 17 doesn't work
+//18 works
+//19 doesn't work
+

 // CREATE CUSTOM LCD CHARACTERS //////////////////////////

@@ -131,6 +142,8 @@
 void setup() {

   pinMode(LED_PIN, OUTPUT);
+  pinMode(MODE_PIN, INPUT_PULLUP);
+  //digitalWrite(MODE_PIN, INPUT_PULLUP);

   lcd.createChar(0, fill1);
   lcd.createChar(1, fill2);
@@ -209,6 +222,10 @@
       digitalWrite(LED_PIN, err);
     }
   }
+
+  bool modeButton = digitalRead(MODE_PIN);
+  //Serial.println(modeButton);
+
 }


modified RPM dec rate

modified RPM dec rate

--- resources/engine_sim/engine_sim.ino
+++ resources/engine_sim/engine_sim.ino
@@ -31,7 +31,7 @@
 #define MAX_SS_RPM        9500 //Highest steady-state RPM
 #define REDLINE_RPM      10500 //Highest RPM we should hit
 #define POWER_CONSTANT   33333 //Time to gain 500 RPM with 11.6lb-ft in microseconds (10^-6)
-#define DECEL_BASE_RATE    800 //Base engine deceleration rate in RPM/s
+#define DECEL_BASE_RATE    5000 //Base engine deceleration rate in RPM/s
 #define ACCEL_BASE_RATE    500 //Base engine acceleration rate in RPM/s

 #ifdef WHEELSPEED_ENABLE


.51: Debug option, timeout

.51: Debug option, timeout

Added debug mode; outputs colors in (0,255) ranges.  Still need to fix
leading zeroes problem.  Added timeout; after 5m of no input, flashes
random colors.

--- csarc/csarc.ino
+++ csarc/csarc.ino
@@ -4,6 +4,9 @@
  *  make gradient pulses between two colors: "G#000000:#FFFFFF:pulseTime"
  *  ???
  */
+
+
+static boolean DEBUG = true;

 #include "RGBdriver.h"
@@ -18,9 +21,14 @@

 void setup() {
   Serial.begin(BAUDRATE);
+
 }

+
+int timeOutCount = 0;
+
 void loop() {
+

   char input[255];

@@ -41,6 +49,18 @@
         Serial.print(red, HEX);
         Serial.print(green, HEX);
         Serial.println(blue, HEX);
+
+        if (DEBUG) {
+        Serial.print("red: ");
+        Serial.println(red, DEC);
+        Serial.print("green: ");
+        Serial.println(green, DEC);
+        Serial.print("blue: ");
+        Serial.println(blue, DEC);
+        Serial.println("");
+        }
+//        Serial.println("green: "+(int)green);
+//        Serial.println("blue: "+(int)blue);

         break;
       }
@@ -49,6 +69,14 @@
         break;
       }
     }
+  } else {
+    // no input;
+    if (timeOutCount > 5*60) { // 5 minutes with no comms
+      setOutput( random(255), random(255), random(255) );
+    }
+
+
+
   }
 }


BUNCH OF NEW STUFF

BUNCH OF NEW STUFF


refactoring

refactoring

--- tangibles/Token_fw/Token_fw_BEANHW.ino/Token_fw_BEANHW.ino.ino
+++ tangibles/Token_fw/Token_fw_BEANHW.ino/Token_fw_BEANHW.ino.ino
@@ -1,116 +0,0 @@
-// Token's firmware working copy
-// Code based on RFDUINO hardware, uses C char arrays
-
-#include <ArduinoJson.h>
-
-//Test JSON strings
-char OFF[]= "{\"device\":\"LED\",\"event\":\"off\"}";
-char GREEN[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"green\"}";
-char RED[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"red\"}";
-char BLUE[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"blue\"}";
-char WHITE[] = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"white\"}";
-
-void setup() {
-  Serial.begin(57600);
-  Serial.setTimeout(25);
-
-  // Test LED on startup
-  parseJSON(GREEN);
-  delay(300);
-  parseJSON(RED);
-  delay(300);
-  parseJSON(BLUE);
-  delay(300);
-  parseJSON(WHITE);
-  delay(300);
-  parseJSON(OFF);
-  delay(300);
-
-  //Initialise bluetooth
-
-}
-
-void loop() {
-String payload;
-if(Serial.available()>0)
-{
-  payload = Serial.readString();
-  // say what you got:
-  Serial.print("I received: ");
-  Serial.println(payload);
-  parseJSON(payload);
-  Serial.println("JSON succesfully parsed");
-}
-}
-
-
-
-
-
-//Parses JSON messages
-void parseJSON(String payload) {
-  char sel;
-  char json[200];
-  payload.toCharArray(json, 50);
-  StaticJsonBuffer<200> jsonBuffer;
-  JsonObject& root = jsonBuffer.parseObject(json);
-
- // Serial.print("DEBUG: "); Serial.println(json);
-  if (!root.success()) {
-    Serial.println("parseObject() failed");
-    return;
-  }
-
-  const char* device = root["device"];
-  const char* event = root["event"];
-  const char* color = root["color"];
-
-  if(strcmp(device, "LED") == 0)
-  {
-    if(strcmp(event, "on") == 0)
-    {
-     sel = color[0];
-     ledON(sel);
-    }
-    if (strcmp(event, "off") == 0)
-    {
-      ledOFF();
-    }
-  }
-}
-
-// Turns the LED off
-void ledOFF(){
-  Bean.setLed(0, 0, 0);
-}
-
-// Turns on the LED on a specific color: r=red, g=gree, osv..
-void ledON(char sel){
-  switch(sel)
-  {
-        case 'r':
-    {
-        Bean.setLed(255, 0, 0);
-        Serial.println("DEBUG: LED RED ON");
-        break;
-    }
-        case 'g':
-    {
-        Bean.setLed(0, 255, 0);
-        Serial.println("DEBUG: LED GREEN ON");
-        break;
-    }
-        case 'b':
-    {
-        Bean.setLed(0, 0, 255);
-        Serial.println("DEBUG: LED BLUE ON");
-        break;
-    }
-        case 'w':
-    {
-        Bean.setLed(255, 255, 255);
-        Serial.println("DEBUG: LED WHITE ON");
-        break;
-    }
-  }
-}


Updated notes in digitalInputPullup

Updated notes in digitalInputPullup

--- build/shared/examples/2.Digital/DigitalIputPullup/DigitalIputPullup.ino
+++ build/shared/examples/2.Digital/DigitalIputPullup/DigitalIputPullup.ino
@@ -37,8 +37,8 @@
   Serial.println(sensorVal);

   // Keep in mind the pullup means the pushbutton's
-  // logic is inverted. It goes HIGH when it's pressed,
-  // and LOW when it's not. Turn on pin 13 when the
+  // logic is inverted. It goes HIGH when it's open,
+  // and LOW when it's pressed. Turn on pin 13 when the
   // button's pressed, and off when it's not:
   if (sensorVal == HIGH) {
     digitalWrite(13, LOW);


Debug message

Debug message

--- examples/UbidotsSaveValueWithContext/UbidotsSaveValueWithContext.ino
+++ examples/UbidotsSaveValueWithContext/UbidotsSaveValueWithContext.ino
@@ -32,7 +32,7 @@

 void setup() {
   Serial.begin(115200);
-  client.setDebug(true);
+  client.setDebug(true); // Set true to make available debug messages
 }

 void loop() {


anavi-miracle-controller-gestures.ino: Use 10 LEDs

Set the number of LEDs on the strips to 10.

Signed-off-by: Leon Anavi <be92910ae7bb6f58bb9b7c6f845bc30640119592@anavi.org>

--- anavi-miracle-controller/anavi-miracle-controller-gestures/anavi-miracle-controller-gestures.ino
+++ anavi-miracle-controller/anavi-miracle-controller-gestures/anavi-miracle-controller-gestures.ino
@@ -8,7 +8,7 @@

 #define LED_PIN1    12
 #define LED_PIN2    14
-#define NUM_LEDS    15
+#define NUM_LEDS    10
 #define BRIGHTNESS  64
 #define LED_TYPE    WS2812
 #define COLOR_ORDER GRB
@@ -85,7 +85,7 @@
   }
   else if(APDS9960_RIGHT == gesture)
   {
-    if (15 > currentPosition)
+    if (NUM_LEDS > currentPosition)
     {
       Serial.println("Go right!");
       currentPosition += 1;


wrkModeStatus

wrkModeStatus

--- _09_ir_tx_rx/_09_ir_tx_rx.ino
+++ _09_ir_tx_rx/_09_ir_tx_rx.ino
@@ -26,7 +26,6 @@
 struct __eeprom_data {
   long magic;
   int pwrSrc;     // 1 : connected to TV, 0 : usb powered
-  int wrkMode;    // 1 : thermostat + TV, 0 : thermostat
   int startMode;  // if wrkMode == 1, 1 : auto start timer, pir, 0 : do nothing indicating a sign on the lcd
   int beepMode;   // 1 : beep on
   int channelGap; // 1 ~ 5
@@ -71,7 +70,6 @@

 // eeprom status
 int o_pwrSrc;
-int o_wrkMode;
 int o_startMode;
 int o_beepMode;
 int o_channelGap;
@@ -239,11 +237,9 @@
   }

   eeprom_read(o_pwrSrc, pwrSrc);
-  eeprom_read(o_wrkMode, wrkMode);
   eeprom_read(o_startMode, startMode);
   eeprom_read(o_beepMode, beepMode);
   eeprom_read(o_channelGap, channelGap);
-  // eeprom_read(o_tvOnTime, tvOnTime);

   // temp sensor
   sensors.begin();
@@ -267,7 +263,7 @@
   lcd.createChar(5, powericon);
   lcd.createChar(6, piricon);

-  if ( o_wrkMode == 1 && o_startMode == 1 ) {
+  if ( wrkModeStatus == 1 && o_startMode == 1 ) {
     lcd.setCursor(0, 1);
     lcd.write(2);

@@ -348,7 +344,7 @@
 void changelcdicon()
 {

-  if ( o_wrkMode == 1 && o_startMode == 1 ) {
+  if ( wrkModeStatus == 1 && o_startMode == 1 ) {
     lcd.setCursor(0, 1);
     lcd.write(2);

@@ -377,12 +373,6 @@
     lcd.setCursor(6, 1);
     lcd.print(" ");
   }
-
-  if ( tvPowerStatus == 1 && timerStatus == 1 ) {
-    tvOnTimer();
-    temp_Mills = millis();
-  }
-
 }

 // need to add timer reset, power status
@@ -391,12 +381,12 @@
   if ( results->bits > 0 && results->bits == 32 ) {
     switch (results->value) {
       case 0xFF02FD: // remote on
-        if ( o_wrkMode == 1 ) {
+        if ( wrkModeStatus == 1 ) {
           timerStatus = 0;
         } else {
           timerStatus = 1;
         }
-        o_wrkMode = ! o_wrkMode;
+        wrkModeStatus = ! wrkModeStatus;
         o_startMode = 1;
         r = !r;
         break;
@@ -443,7 +433,7 @@

 void tvOnTimer()
 {
-  //long time_o_tvOnTime = ( long(o_tvOnTime) * 1000 ) * 60 ;
+
   long time_o_tvOnTime = ( o_tvOnTime * 1000 ) * 60 ;
   tvIsOnEvent = t.after(time_o_tvOnTime , doTvOffTimer);

@@ -460,95 +450,91 @@
     Serial.println("doTvOffTimer called");
   }
   t.stop(tvIsOnEvent);
+  tvPowerStatus = 0 ;
   irSendTvOutbytimer(0);
 }

 //
 void doTvControlbyPir(int onoff)
 {
-  if ( o_wrkMode == 1 && o_startMode == 1 && tvPowerStatus == 1) {
-    switch (onoff) {
+
+  switch (onoff) {
+    case 1:
+      lcd.setCursor(15, 0);
+      lcd.print(" ");
+      irSendTvOutbypir(0);
+      break;
+    case 0:
+      lcd.setCursor(15, 0);
+      lcd.write(6);
+      irSendTvOutbypir(1);
+      break;
+  }
+
+  r = !r;
+}
+
+
+void irSendTvOutbypir(int a)
+{
+
+  if (DEBUG_PRINT) {
+    Serial.println("IRSend PIR input change called");
+  }
+  if ( wrkModeStatus == 1 && o_startMode == 1 && tvPowerStatus == 1) {
+    switch (a) {
+      case 0:
+        irsend.sendNEC(tv_input, 32);
+        delay(3000);
+        for ( int i = 0 ; i < o_channelGap ; i++ ) {
+          irsend.sendNEC(tv_left, 32);
+          delay(300);
+        }
+        irsend.sendNEC(tv_enter, 32);
+        break;
       case 1:
-        lcd.setCursor(15, 0);
-        lcd.print(" ");
-        irSendTvOutbypir(0);
+        irsend.sendNEC(tv_input, 32);
+        delay(3000);
+        for ( int i = 0 ; i < o_channelGap ; i++ ) {
+          irsend.sendNEC(tv_right, 32);
+          delay(300);
+        }
+        irsend.sendNEC(tv_enter, 32);
         break;
-      case 0:
-        lcd.setCursor(15, 0);
-        lcd.write(6);
-        irSendTvOutbypir(1);
-        break;
-    }
-  }
-  r = !r;
-}
-
-
-void irSendTvOutbypir(int a)
-{
-
-  if (DEBUG_PRINT) {
-    Serial.println("IRSend CH change called");
-  }
-  switch (a) {
-    case 0:
-      irsend.sendNEC(tv_input, 32);
-      delay(3000);
-      for ( int i = 0 ; i < o_channelGap ; i++ ) {
-        irsend.sendNEC(tv_left, 32);
-        delay(300);
-      }
-      irsend.sendNEC(tv_enter, 32);
-      break;
-    case 1:
-      irsend.sendNEC(tv_input, 32);
-      delay(3000);
-      for ( int i = 0 ; i < o_channelGap ; i++ ) {
-        irsend.sendNEC(tv_right, 32);
-        delay(300);
-      }
-      irsend.sendNEC(tv_enter, 32);
-      break;
-  }
-
-  irrecv.enableIRIn();
+    }
+
+    irrecv.enableIRIn();
+  }
 }

 //
 void irSendTvOutbytimer(int a)
 {
   if (DEBUG_PRINT) {
-    Serial.println("IRSend on/off called");
+    Serial.println("IRSend TV off called");
   }
   irsend.sendNEC(tv_onoff, 32);
   delay(300);
   irrecv.enableIRIn();
-  tvPowerStatus = ! tvPowerStatus ;
   r = !r;
-
 }

 // TimeTime
 void displaytimeleft() {
-  long timeleft;
-  /*
-  if ( tvPowerStatus == 1) {
-    timeleft = o_tvOnTime - ((millis() - temp_Mills) / 1000 / 60) ;
-  } else {
-    timeleft = o_tvOffTime - ((millis() - temp_Mills) / 1000 / 60) ;
-  }
-  */
-
-
-  timeleft = (( o_tvOnTime * 1000 ) * 60 ) - (millis() - temp_Mills) ;
-
-  // timeleft = ( millis() - temp_Mills) / 1000 ;
-
-  String str_a = String(int(timeleft));
+
+  long time_o_tvOnTime = ( o_tvOnTime * 1000 ) * 60 ;
+  long timeleft = time_o_tvOnTime - (millis() - temp_Mills) ;
+
+  if (DEBUG_PRINT) {
+    Serial.println(time_o_tvOnTime);
+    Serial.println(timeleft);
+  }
+
+  String str_a = String(long(timeleft));
   int length_a = str_a.length();

   lcd.setCursor(8, 1);
-  if ( timerStatus == 1 &&  o_wrkMode == 1 && o_startMode == 1 && tvPowerStatus == 1) {
+  if ( timerStatus == 1 &&  wrkModeStatus == 1 && o_startMode == 1 && tvPowerStatus == 1) {
     for ( int i = 0; i < ( 7 - length_a ) ; i++ ) {
       lcd.print(" ");
     }
@@ -724,27 +710,6 @@
   lcd.setCursor(0, 0);
   lcd.print("Select");
   lcd.setCursor(0, 1);
-  lcd.print("working mode");
-  lcd.setCursor(15, 1);
-  lcd.print("*");
-
-  irrecv.resume();
-  while (irrecv.decode(&results) != 1 ) { }
-  alarm_set();
-
-  lcd.clear();
-  lcd.setCursor(0, 0);
-  lcd.print("ON : TV + thermo");
-  lcd.setCursor(0, 1);
-  lcd.print("OFF: thermo");
-
-  o_wrkMode = initialise_boolean_select();
-  alarm_set();
-
-  lcd.clear();
-  lcd.setCursor(0, 0);
-  lcd.print("Select");
-  lcd.setCursor(0, 1);
   lcd.print("start mode");
   lcd.setCursor(15, 1);
   lcd.print("*");
@@ -825,7 +790,7 @@
   o_tvOnTime = initialise_number_select(30, 90, 50, 5);
   alarm_set();

-  int initialise_eeprom_done =  initialise_eeprom(o_pwrSrc, o_wrkMode, o_startMode, o_beepMode, o_channelGap, o_tvOnTime) ;
+  int initialise_eeprom_done =  initialise_eeprom(o_pwrSrc, o_startMode, o_beepMode, o_channelGap, o_tvOnTime) ;

   while (initialise_eeprom_done != 1 ) { }

@@ -857,10 +822,9 @@
 }

-int initialise_eeprom(int o_pwrSrc, int o_wrkMode, int o_startMode, int o_beepMode, int o_channelGap, long o_tvOnTime)
+int initialise_eeprom(int o_pwrSrc, int o_startMode, int o_beepMode, int o_channelGap, long o_tvOnTime)
 {
   eeprom_write(o_pwrSrc, pwrSrc);
-  eeprom_write(o_wrkMode, wrkMode);
   eeprom_write(o_startMode, startMode);
   eeprom_write(o_beepMode, beepMode);
   eeprom_write(o_channelGap, channelGap);


Suggestion from Koepel; counting bytes to use Wire.available

--- 2_example/example09_hum_sht31/i2c_sht31.ino
+++ 2_example/example09_hum_sht31/i2c_sht31.ino
@@ -19,26 +19,20 @@
     Wire.beginTransmission(I2C_sht);
     Wire.write(0x2C);
     Wire.write(0x06);
-    if( Wire.endTransmission() == 0){
-        delay(18);              // 15ms以上
-        Wire.requestFrom(I2C_sht,6);
-        if(Wire.available()==0) return -999.;
-        temp = Wire.read();
-        temp <<= 8;
-        if(Wire.available()==0) return -999.;
-        temp += Wire.read();
-        if(Wire.available()==0) return -999.;
-        Wire.read();
-        if(Wire.available()==0) return -999.;
-        hum = Wire.read();
-        hum <<= 8;
-        if(Wire.available()==0) return -999.;
-        hum += Wire.read();
-        if(Wire.available()==0) return -999.;
-        Wire.read();
-        _i2c_sht31_hum = (float)hum / 65535. * 100.;
-        return (float)temp / 65535. * 175. - 45.;
-    }else return -999.;
+    if(Wire.endTransmission()) return -998.;
+    delay(18);                  // 15ms以上
+    Wire.requestFrom(I2C_sht,6);
+    if(Wire.available() != 6) return -997.0;
+    temp = Wire.read();
+    temp <<= 8;
+    temp += Wire.read();
+    Wire.read();
+    hum = Wire.read();
+    hum <<= 8;
+    hum += Wire.read();
+    Wire.read();                // 未使用 not used
+    _i2c_sht31_hum = (float)hum / 65535. * 100.;
+    return (float)temp / 65535. * 175. - 45.;
 }

 float getHum(){


撮影終了信号の追加（デグレード）

撮影終了信号の追加（デグレード）

--- 2_example/example18_camL/example18_camL.ino
+++ 2_example/example18_camL/example18_camL.ino
@@ -93,6 +93,7 @@
             j += len;                       // データサイズの合算
             for(i=0;i<len;i++) client.write((byte)data[i]); // データ送信
         }
+        CamStopTakePhotoCmd();              // 撮影の終了(静止画の破棄)の実行
         CamReadADR0();                      // 読み出しアドレスのリセット
         client.stop();                      // クライアントの切断
         Serial.print(j);                    // ファイルサイズをシリアル出力表示


change Temp Rain min value with dial and change arduino code to have +10°C of ambiant T°

--- arduino/sadr_meteo_no_firmata/sadr_meteo_no_firmata.ino
+++ arduino/sadr_meteo_no_firmata/sadr_meteo_no_firmata.ino
@@ -572,7 +572,7 @@
      Consigne = HOT_TEMPERATURE_TARGET;
   } else {
      if (!isnan(T22int)) {
-        int newConsigne = ((T22int / 5) + 2 );
+        int newConsigne = ((T22ext / 5) + 2 );
         newConsigne *= 5;
         if (newConsigne > COLD_TEMPERATURE_TARGET && newConsigne < HOT_TEMPERATURE_TARGET) {
             Consigne = max(COLD_TEMPERATURE_TARGET , newConsigne);


constexpred

constexpred

--- Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/REV7RadValve/REV7RadValve.ino
+++ Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/REV7RadValve/REV7RadValve.ino
@@ -773,7 +773,7 @@
     const bool conserveBattery = (batteryLow || !valveMode.inWarmMode() || Occupancy.longVacant()) && (!NominalRadValve.isCallingForHeat());
     // Try if very near to end of cycle and thus causing an overrun.
     // Conversely, if not true, should have time to safely log outputs, etc.
-    const uint8_t nearOverrunThreshold = OTV0P2BASE::GSCT_MAX - 8; // ~64ms/~32 serial TX chars of grace time...
+    constexpr uint8_t nearOverrunThreshold = OTV0P2BASE::GSCT_MAX - 8; // ~64ms/~32 serial TX chars of grace time...

     // Go to sleep until the start of the next cycle.
     TIME_LSD = OTV0P2BASE::sleepUntilNewCycle<>(TIME_LSD);