New code with Encoder library and I2C

New code with Encoder library and I2C

This code works only with Arduino Mega

--- Arduino_code/Arduino_LidarLitePWM_rotaryEncoder_3D/Lidar_PWM_rotary_3D.ino
+++ Arduino_code/Arduino_LidarLitePWM_rotaryEncoder_3D/Lidar_PWM_rotary_3D.ino
@@ -1,99 +1,48 @@
+#include <Encoder.h>
+#include <I2C.h>
+#define LIDARLite_ADDRESS 0x62 // Default I2C Address of LIDAR-Lite.
+#define RegisterMeasure 0x00 // Register to write to initiate ranging.
+#define MeasureValue 0x04 // Value to initiate ranging.
+#define RegisterHighLowB 0x8f // Register to get both High and Low bytes in 1 call.

-//Micro: 0, 1, 2, 3, 7   Mega: 2, 3, 18, 19, 20, 21   Due: all
-#define MYPIN1 2
-#define MYPIN2 3
-#define MYPIN3 0
-#define MYPIN4 1
-
-
-volatile int counter_tetha = 0;  //This variable will increase or decrease depending on the rotation of encoder
-volatile int counter_phi = 0;  //This variable will increase or decrease depending on the rotation of encoder
-volatile int previous_counter_t = 0;
-volatile int previous_counter_p = 0;
-volatile int tetha = 0;
-volatile int phi = 0;
+Encoder rotaryX(2, 3);
+Encoder rotaryY(18, 19);

 void setup() {
-  Serial.begin (9600);
-  Serial.flush();
-  //Setting up interrupt
-  //A rising pulse from encodenren activated ai0(). AttachInterrupt 0 is DigitalPin nr 2 on moust Arduino.
-  attachInterrupt(digitalPinToInterrupt(MYPIN1), ai0, RISING);
-
-  //B rising pulse from encodenren activated ai1(). AttachInterrupt 1 is DigitalPin nr 3 on moust Arduino.
-  attachInterrupt(digitalPinToInterrupt(MYPIN2), ai1, RISING);
-
-  //A rising pulse from encodenren activated ai0(). AttachInterrupt 2 is DigitalPin nr 18 on moust Arduino.
-  attachInterrupt(digitalPinToInterrupt(MYPIN3), ai2, RISING);
-
-  //B rising pulse from encodenren activated ai1(). AttachInterrupt 3 is DigitalPin nr 19 on moust Arduino.
-  attachInterrupt(digitalPinToInterrupt(MYPIN4), ai3, RISING);
-
-  pinMode(11, OUTPUT); // Set pin 2 as trigger pin
-  pinMode(5, INPUT); // Set pin 3 as monitor pin
-  digitalWrite(11, LOW); // Set trigger LOW for continuous read
-
+  Serial.begin(9600);
+  I2c.begin(); // Opens & joins the irc bus as master
   delay(100); // Waits to make sure everything is powered up before sending or receiving data
-
+  I2c.timeOut(50); // Sets a timeout to ensure no locking up of sketch if I2C communication fails
+  Serial.println("Basic Encoder Test:");
 }

+long oldPositionX  = -999;
+long oldPositionY  = -999;
+
 void loop() {
+  long newPositionX = rotaryX.read();
+  long newPositionY = rotaryY.read();

+  if (newPositionX != oldPositionX || newPositionY != oldPositionY ) {

-  int rho = pulseIn(5, HIGH); // Count how long the pulse is high in microseconds
-  if(rho != 0){ // If we get a reading that isn't zero, let's print it
-        rho = rho/10; // 10usec = 1 cm of distance for LIDAR-Lite
+    oldPositionX = newPositionX;
+    oldPositionY = newPositionY;
+
+    // Write 0x04 to register 0x00
+    uint8_t nackack = 100; // Setup variable to hold ACK/NACK resopnses
+    while (nackack != 0) { // While NACK keep going (i.e. continue polling until sucess message (ACK) is received )
+      nackack = I2c.write(LIDARLite_ADDRESS, RegisterMeasure, MeasureValue); // Write 0x04 to 0x00
+      delay(1); // Wait 1 ms to prevent overpolling
+    }
+    byte distanceArray[2]; // array to store distance bytes from read function
+    // Read 2byte distance from register 0x8f
+    nackack = 100; // Setup variable to hold ACK/NACK resopnses
+    while (nackack != 0) { // While NACK keep going (i.e. continue polling until sucess message (ACK) is received )
+      nackack = I2c.read(LIDARLite_ADDRESS, RegisterHighLowB, 2, distanceArray); // Read 2 Bytes from LIDAR-Lite Address and store in array
+      delay(1); // Wait 1 ms to prevent overpolling
+    }
+    int distance = (distanceArray[0] << 8) + distanceArray[1]; // Shift high byte [0] 8 to the left and add low byte [1] to create 16-bit int

-    // Calcul angles
-    tetha += counter_tetha - previous_counter_t;
-  phi += counter_phi - previous_counter_p;
-
-  previous_counter_t = counter_tetha;
-  previous_counter_p = counter_phi;
-  // Send the value of counter
-  Serial.print(rho, DEC); Serial.print ("    "); Serial.print (tetha, DEC); Serial.print ("    "); Serial.println (phi, DEC);
-  delay(20); //Delay so we don't overload the serial port
-}
-}
-
-void ai0() {
-  // ai0 is activated if DigitalPin nr 2 is going from LOW to HIGH
-  // Check pin 3 to determine the direction
-  if (digitalRead(MYPIN2) == LOW) {
-    counter_tetha++;
-  } else {
-    counter_tetha--;
+    Serial.print(newPositionX); Serial.print("    "); Serial.print(newPositionY);Serial.print("    "); Serial.println(distance);
   }
 }
-
-void ai1() {
-  // ai0 is activated if DigitalPin nr 3 is going from LOW to HIGH
-  // Check with pin 2 to determine the direction
-  if (digitalRead(MYPIN1) == LOW) {
-    counter_tetha--;
-  } else {
-    counter_tetha++;
-  }
-}
-
-void ai2() {
-  // ai0 is activated if DigitalPin nr 18 is going from LOW to HIGH
-  // Check with pin 19 to determine the direction
-  if (digitalRead(MYPIN4) == LOW) {
-    counter_phi--;
-  } else {
-    counter_phi++;
-  }
-}
-
-void ai3() {
-  // ai3 is activated if DigitalPin nr 19 is going from LOW to HIGH
-  // Check with pin 18 to determine the direction
-  if (digitalRead(MYPIN3) == LOW) {
-    counter_phi++;
-  } else {
-    counter_phi--;
-  }
-}
-
-


I forgot

I forgot

--- module/module_rfid.ino
+++ module/module_rfid.ino
@@ -98,6 +98,7 @@
 			j -= eightBits;
 		}
 	}
+
 	#ifdef FRONTDESK
 	else if (command == COMMAND_REGISTER) {
 		payload[0] = (id >> eightBits) & MSB;


Servo test

Servo test

Updated code, todos and wrote servo test.

--- SEA_Biped.ino
+++ SEA_Biped.ino
@@ -1,7 +1,4 @@
 // TODO Rea:
-// Write code for reading current sensor (output Amp) : [done]
-// Add code for foot servo: [done]
-// Work on ways of adding the current reading to over current protection: [done]
 // Work on ways of adding the current reading to the control loop (Motor): [....TODO...]

@@ -12,7 +9,7 @@

 #define PC_COMM_DEBUG
 //#define MOTOR_DEBUG
-#define SERVO_DEBUG
+//#define SERVO_DEBUG
 //#define ENCODER_DEBUG
 //#define INNER_LOOP_DEBUG
 #define CUR_SENSE_DEBUG
@@ -210,6 +207,7 @@
     if (m1_des_angle < -90) m1_des_angle = -90;

     m1_pid();
+    moveFootServo(rightFootServo, 90+m1_des_angle);
   }
   else {
     set_motor_speed(0);


remove extra copy of ticc.ino

remove extra copy of ticc.ino

and the folder, too

--- TICC/TICC.ino
+++ TICC/TICC.ino
@@ -1,324 +0,0 @@
-// TICC Time interval Counter based on TICC Shield using TDC7200
-// version -0.5 6 March 2016
-// Copyright John Ackermann N8UR 2016
-// Portions Copyright George Byrkit K9TRV 2016
-// Licensed under BSD 2-clause license
-
-// the TI TDC7200 communicates using SPI, so include the library:
-#include <SPI.h>
-
-// set up for ISR
-int interrupt = 1; // interrupt for Uno pin 3
-int int_pin = 3; // physical pin
-volatile unsigned long long coarse_count = 0;
-
-// hardware connections to TDC2700 -- need to reassign these more logically (todo in Eagle)
-const int ENABLE_0 = 13;
-const int INTB_0 = 12;
-const int CSB_0 = 11;
-const int ENABLE_1 = 10;
-const int INTB_1 = 9;
-const int CSB_1 = 8;
-const int STOP_0 = 7;
-const int STOP_1 = 8;
-
-// TDC7200 register addresses
-const int CONFIG1 = 0x00;                 // default 0x00
-const int CONFIG2 = 0x01;                 // default 0x40
-const int INT_STATUS = 0x02;              // default 0x00
-const int INT_MASK = 0x03;                // default 0x07
-const int COARSE_CNTR_OVF_H = 0x04;       // default 0xff
-const int COARSE_CNTR_OVF_L = 0x05;       // default 0xff
-const int CLOCK_CNTR_OVF_H = 0x06;        // default 0xff
-const int CLOCK_CNTR_OVF_L = 0x07;        // default 0xff
-const int CLOCK_CNTR_STOP_MASK_H = 0x08;  // default 0xff
-const int CLOCK_CNTR_STOP_MASK_L = 0x09;  // default 0xff
-// gap from 0x0A thru 0x0F...
-const int TIME1 = 0x10;                   // default 0x00_0000
-const int CLOCK_COUNT1 = 0x11;            // default 0x00_0000
-const int TIME2 = 0x12;                   // default 0x00_0000
-const int CLOCK_COUNT2 = 0x13;            // default 0x00_0000
-const int TIME3 = 0x14;                   // default 0x00_0000
-const int CLOCK_COUNT3 = 0x15;            // default 0x00_0000
-const int TIME4 = 0x16;                   // default 0x00_0000
-const int CLOCK_COUNT4 = 0x17;            // default 0x00_0000
-const int TIME5 = 0x18;                   // default 0x00_0000
-const int CLOCK_COUNT5 = 0x19;            // default 0x00_0000
-const int TIME6 = 0x1A;                   // default 0x00_0000
-const int CALIBRATION1 = 0x1B;            // default 0x00_0000
-const int CALIBRATION2 = 0x1C;            // default 0x00_0000
-
-// properties of the TDC7200 chip:
-// Most Significant Bit is clocked first (MSBFIRST)
-// clock is low when idle
-// data is clocked on the rising edge of the clock (seems to be SPI_MODE0)
-// max clock speed: 20 mHz
-// Using TDC7200 timing mode 1...
-
-// global vars
-long long unsigned stop_time_0;
-long long unsigned stop_time_1;
-long result_0;
-long result_1;
-
-  int timeResult_0 = 0;
-  int clockResult_0 = 0;
-  int calResult_0 = 0;
-  int timeResult_1 = 0;
-  int clockResult_1 = 0;
-  int calResult_1 = 0;
-
-void setup() {
-  // start the SPI library:
-  SPI.begin();
-
-  pinMode(int_pin, INPUT);
-
-  pinMode(ENABLE_0,OUTPUT);
-  pinMode(INTB_0,INPUT);
-  pinMode(CSB_0,OUTPUT);
-  pinMode(STOP_0,INPUT);
-  pinMode(ENABLE_1,OUTPUT);
-  pinMode(INTB_1,INPUT);
-  pinMode(CSB_1,OUTPUT);
-  pinMode(STOP_1,INPUT);
-
-  attachInterrupt(interrupt, coarse_timer, RISING);
-
-  TDC_setup_0();
-  TDC_setup_1();
-  delay(10);
-  ready_next_0();
-  ready_next_1();
-
-  Serial.begin(115200);
-  Serial.println("Starting...");
-}
-
-void loop() {
-
- if (STOP_0) {
-   stop_time_0 = coarse_count; // capture time stamp of gated stop clock
- }
- if (STOP_1) {
-    stop_time_1 = coarse_count;
- }
-
-  if (INTB_0) { // channel 1 measurement complete
-    result_0 = TDC_calc(0); // get registers and calc TOF
-    ready_next_0(); // enable next measurement
-  }
-  if (INTB_1) {
-    result_1 = TDC_calc(1);
-    ready_next_1();
-  }
-
-   // if we have both channels, subtract channel 0 from channel 1, print result, and reset vars
-   if (result_0 && result_1) {
-    output_ti();
-    result_0 = 0;
-    result_1 = 0;
-    stop_time_0 = 0;
-    stop_time_1 = 0;
-   }
-
-}
-
-// ISR for timer NOTE: need to deal with rollover
-void coarse_timer() {
-  coarse_count++;
-}
-
-// Initial config for TDC7200
-int TDC_setup( int ch) {
-  return 0;
-}
-
-int TDC_setup_0() {
-  digitalWrite(ENABLE_0, HIGH);
-}
-
-int TDC_setup_1() {
-  digitalWrite(ENABLE_1, HIGH);
-}
-
-// Fetch and calculate results from TDC7200
-int TDC_calc(int ch) {
-  if (ch == 0) {
-    TDC_read_0();
-    // calc the values (John...)
-  }
-  else if (ch == 1){
-    TDC_read_1();
-    // calc the values (John...)
-  }
-}
-
-void TDC_read_0() {
-  byte inByte = 0;
-  int timeResult = 0;
-  int clockResult = 0;
-  int calResult = 0;
-
-  // read the TIMER1 register
-    // take the chip select low to select the device:
-  digitalWrite(CSB_0, LOW);
-
-  SPI.transfer(TIME1);
-  inByte = SPI.transfer(0x00);
-  timeResult |= inByte;
-  inByte = SPI.transfer(0x00);
-  timeResult = timeResult<<8 | inByte;
-  inByte = SPI.transfer(0x00);
-  timeResult = timeResult<<8 | inByte;
-
-  digitalWrite(CSB_0, HIGH);
-
-// read the CLOCK1 register
-    // take the chip select low to select the device:
-  digitalWrite(CSB_0, LOW);
-
-  SPI.transfer(CLOCK_COUNT1);
-  inByte = SPI.transfer(0x00);
-  clockResult |= inByte;
-  inByte = SPI.transfer(0x00);
-  clockResult = clockResult<<8 | inByte;
-  inByte = SPI.transfer(0x00);
-  clockResult = clockResult<<8 | inByte;
-
-  digitalWrite(CSB_0, HIGH);
-
-// read the CALIBRATION1 register
-   // take the chip select low to select the device:
-  digitalWrite(CSB_0, LOW);
-
-  SPI.transfer(CALIBRATION1);
-  inByte = SPI.transfer(0x00);
-  calResult |= inByte;
-  inByte = SPI.transfer(0x00);
-  calResult = calResult<<8 | inByte;
-  inByte = SPI.transfer(0x00);
-  calResult = calResult<<8 | inByte;
-
-  digitalWrite(CSB_0, HIGH);
-
-  timeResult_0 = timeResult;
-  clockResult_0 = clockResult;
-  calResult_0 = calResult;
-
-  return;
-}
-void TDC_read_1() {
-  byte inByte = 0;
-  int timeResult = 0;
-  int clockResult = 0;
-  int calResult = 0;
-
-  // read the TIMER1 register
-    // take the chip select low to select the device:
-  digitalWrite(CSB_1, LOW);
-
-  SPI.transfer(TIME1);
-  inByte = SPI.transfer(0x00);
-  timeResult |= inByte;
-  inByte = SPI.transfer(0x00);
-  timeResult = timeResult<<8 | inByte;
-  inByte = SPI.transfer(0x00);
-  timeResult = timeResult<<8 | inByte;
-
-  digitalWrite(CSB_1, HIGH);
-
-// read the CLOCK1 register
-    // take the chip select low to select the device:
-  digitalWrite(CSB_1, LOW);
-
-  SPI.transfer(CLOCK_COUNT1);
-  inByte = SPI.transfer(0x00);
-  clockResult |= inByte;
-  inByte = SPI.transfer(0x00);
-  clockResult = clockResult<<8 | inByte;
-  inByte = SPI.transfer(0x00);
-  clockResult = clockResult<<8 | inByte;
-
-  digitalWrite(CSB_1, HIGH);
-
-// read the CALIBRATION1 register
-   // take the chip select low to select the device:
-  digitalWrite(CSB_1, LOW);
-
-  SPI.transfer(CALIBRATION1);
-  inByte = SPI.transfer(0x00);
-  calResult |= inByte;
-  inByte = SPI.transfer(0x00);
-  calResult = calResult<<8 | inByte;
-  inByte = SPI.transfer(0x00);
-  calResult = calResult<<8 | inByte;
-
-  digitalWrite(CSB_1, HIGH);
-
-  timeResult_1 = timeResult;
-  clockResult_1 = clockResult;
-  calResult_1 = calResult;
-
-  return;
-}
-
-// Enable next measurement cycle
-void ready_next_0() {
-  // needs to set the enable bit (START_MEAS in CONFIG1)
-  writeTDC7200_0(CONFIG1, 0x03);  // measurement mode 2 ('01'),
-}
-void ready_next_1() {
-  // needs to set the enable bit (START_MEAS in CONFIG1)
-  writeTDC7200_1(CONFIG1, 0x03);  // measurement mode 2 ('01'),
-}
-
-// Calculate and print time interval to serial
-void output_ti() {
-}
-
-void writeTDC7200_0(byte address, byte value) {
-  // take the chip select low to select the device:
-  digitalWrite(CSB_0, LOW);
-
-  SPI.transfer(address);
-  SPI.transfer(value);
-
-  digitalWrite(CSB_0, HIGH);
-}
-void writeTDC7200_1(byte address, byte value) {
-  // take the chip select low to select the device:
-  digitalWrite(CSB_1, LOW);
-
-  SPI.transfer(address);
-  SPI.transfer(value);
-
-  digitalWrite(CSB_1, HIGH);
-}
-
-byte readTDC7200_0(byte address) {
-  byte inByte = 0;
-    // take the chip select low to select the device:
-  digitalWrite(CSB_0, LOW);
-
-  SPI.transfer(address);
-  inByte = SPI.transfer(0x00);
-
-  digitalWrite(CSB_0, HIGH);
-
-  return inByte;
-}
-
-byte readTDC7200_1(byte address) {
-  byte inByte = 0;
-    // take the chip select low to select the device:
-  digitalWrite(CSB_1, LOW);
-
-  SPI.transfer(address);
-  inByte = SPI.transfer(0x00);
-
-  digitalWrite(CSB_1, HIGH);
-
-  return inByte;
-}
-


Arduino NN code compiles

Arduino NN code compiles

--- arduino/anna.ino
+++ arduino/anna.ino
@@ -1,12 +1,16 @@
+
+#include <EEPROM.h>
+

 enum ActType{
   linear = 0, sigmoid, tangenth, none, bias };
+

 template <class T>
 class funcs
 {
-  public:
+public:
   static T actBias( T n )
   {
     return 1.0;
@@ -26,12 +30,12 @@
   {
     return 1.0 / ( 1.0 + exp(-n) );
   }
-
+
   static T derivLinear( T n )
   {
     return 1.0;
   }
-
+
   static T derivSigmoid( T n )
   {
     return n * ( 1.0 - n );
@@ -530,6 +534,25 @@

   }

+  int EEPROM_writeAnything(int ee, const T& value)
+  {
+    const byte* p = (const byte*)(const void*)&value;
+    int i;
+    for (i = 0; i < sizeof(value); i++)
+      EEPROM.write(ee++, *p++);
+    return i;
+  }
+
+  int EEPROM_readAnything(int ee, T& value)
+  {
+    byte* p = (byte*)(void*)&value;
+    int i;
+    for (i = 0; i < sizeof(value); i++)
+      *p++ = EEPROM.read(ee++);
+    return i;
+  }
+
+
 };

@@ -551,3 +574,4 @@
 }

+


modified:   serial_experiment/serial_experiment.ino

--- serial_experiment/serial_experiment.ino
+++ serial_experiment/serial_experiment.ino
@@ -1,8 +1,18 @@
-void setup(){
-  Serial.begin(9600);
+int incomingByte = 0;   // for incoming serial data
+
+void setup() {
+        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
 }

-void loop()
-{
-  Serial.write("84\r\n"); // send a byte with the value 45
+void loop() {
+
+        // send data only when you receive data:
+        if (Serial.available() > 0) {
+                // read the incoming byte:
+                incomingByte = Serial.read();
+
+                // say what you got:
+                Serial.print("I received: ");
+                Serial.println(incomingByte, DEC);
+        }
 }


Updated RotorController.ino File 1/20/16

Changes made so that the Arduino rotor controller better interfaces with a Yaesu G-5500. AZIMUTH_STARTING_POINT_DEFAULT global variable defined to start azimuth measurement at zero degrees. Additionally, the Arduino feedback voltage ranges are "re-mappped" to better suit the output voltage feeback from the G-5500 (these values may still need to be adjusted in the future as the system is tested in the ground station control room).

More details about these changes can be found in the Blogs on Far Horizon's Elgg website.

--- RotorControllerInterface.ino
+++ RotorControllerInterface.ino
@@ -563,6 +563,8 @@

 /*----------------------- variables -------------------------------------*/

+#define AZIMUTH_STARTING_POINT_DEFAULT 0
+
 byte incoming_serial_byte = 0;

 byte reset_the_unit = 0;
@@ -4278,8 +4280,8 @@
   #endif

     #ifdef FEATURE_AZ_POSITION_POTENTIOMETER
-      analog_az = analogReadEnhanced(rotator_analog_az);
-      raw_azimuth = map(analog_az, configuration.analog_az_full_ccw, configuration.analog_az_full_cw, (azimuth_starting_point * HEADING_MULTIPLIER), ((azimuth_starting_point + azimuth_rotation_capability) * HEADING_MULTIPLIER));
+      analog_az = constrain(analogReadEnhanced(rotator_analog_az), 409, 921);
+      raw_azimuth = map(analog_az, 409, 921, (azimuth_starting_point * HEADING_MULTIPLIER), ((azimuth_starting_point + azimuth_rotation_capability) * HEADING_MULTIPLIER));
       //raw_azimuth = map(analog_az* HEADING_MULTIPLIER, configuration.analog_az_full_ccw* HEADING_MULTIPLIER, configuration.analog_az_full_cw* HEADING_MULTIPLIER, (azimuth_starting_point * HEADING_MULTIPLIER), ((azimuth_starting_point + azimuth_rotation_capability) * HEADING_MULTIPLIER));

       #ifdef FEATURE_AZIMUTH_CORRECTION
@@ -5203,8 +5205,8 @@
   #endif

     #ifdef FEATURE_EL_POSITION_POTENTIOMETER
-    analog_el = analogReadEnhanced(rotator_analog_el);
-    elevation = (map(analog_el, configuration.analog_el_0_degrees, configuration.analog_el_max_elevation, 0, (ELEVATION_MAXIMUM_DEGREES * HEADING_MULTIPLIER)));
+    analog_el = constrain(analogReadEnhanced(rotator_analog_el), 409, 921);
+    elevation = (map(analog_el, 409, 921, 0, (ELEVATION_MAXIMUM_DEGREES * HEADING_MULTIPLIER)));
     #ifdef FEATURE_ELEVATION_CORRECTION
     elevation = (correct_elevation(elevation / (float) HEADING_MULTIPLIER) * HEADING_MULTIPLIER);
     #endif // FEATURE_ELEVATION_CORRECTION


send device usage values to the API in VA

--- iot/device/device.ino
+++ iot/device/device.ino
@@ -8,15 +8,20 @@
 #include <WiFiManager.h>

 OpenWiFi hotspot;
+String chipID;
+String serverURL = "https://watt-next-api.herokuapp.com/";
+bool registered = false;

 const int pot = A0;
 int read_out = 0;
-String chipID;
+// Usage in Volt-Ampere
+int minUsage = 2500; // 2 kW
+int avgUsage = 3125; // 2.5 kW
+int maxUsage = 3750; // 3 kW

 void setup() {
-  // put your setup code here, to run once:
   Serial.begin(9600);
-
+  chipID = generateChipID();
   WiFiManager wifiManager;

   while (WiFi.status() != WL_CONNECTED) {
@@ -26,7 +31,6 @@

   hotspot.begin(BACKUP_SSID, BACKUP_PASSWORD);

-  chipID = generateChipID();
   String configSSID = String(CONFIG_SSID) + "_" + chipID;
   wifiManager.autoConnect(configSSID.c_str());

@@ -34,21 +38,68 @@
   Serial.println("WiFi connected");
   Serial.print("IP address: ");
   Serial.println(WiFi.localIP());
+
+  while (registered == false) {
+  	HTTPClient http;
+		String requestString = serverURL + "api/v1/init/stand/nicks-tacos/real-device/taco-grill-" + chipID;
+  	http.begin(requestString);
+  	int httpCode = http.GET();
+  	String response;
+		response = http.getString();
+		Serial.println(response);
+
+  	if (httpCode == 200) {
+  		String response;
+  		response = http.getString();
+  		Serial.println(response);
+
+  		if (response == "success") {
+  			registered = true;
+  		}
+  	}
+
+  	http.end();
+  	delay(1000);
+  }
 }

 void loop() {
+	Serial.println('in loop');
   // put your main code here, to run repeatedly:
-	read_out = analogRead(pot);
-	Serial.println(read_out);
+	read_out = map(analogRead(pot), 0, 1024, minUsage, maxUsage);
+	send_readout(read_out);
 }

-String generateChipID()
-{
+void send_readout(int val) {
+	Serial.println('in send_readout');
+	HTTPClient http;
+	String requestString = serverURL + "api/v1/stand/nicks-tacos/real-device/taco-grill-" + chipID + "/va/" + val;
+	http.begin(requestString);
+
+	int httpCode = http.GET();
+
+	if (httpCode == 200) {
+		String response;
+		response = http.getString();
+
+		if (response == "success") {
+			Serial.println(response);
+		} else {
+			// try again
+			send_readout(val);
+		}
+	}
+
+	http.end();
+}
+
+String generateChipID() {
   String chipIDString = String(ESP.getChipId() & 0xffff, HEX);

   chipIDString.toUpperCase();
-  while (chipIDString.length() < 4)
+  while (chipIDString.length() < 4) {
     chipIDString = String("0") + chipIDString;
+  }

   return chipIDString;
 }


-Set valid I2C frequency.

-Set valid I2C frequency.

--- aquacontrol32.ino
+++ aquacontrol32.ino
@@ -311,7 +311,7 @@
     ESP_LOGI( TAG, "No ILI9341 found" );
   }

-  Wire.begin( I2C_SDA_PIN, I2C_SCL_PIN, 1000000 );
+  Wire.begin( I2C_SDA_PIN, I2C_SCL_PIN, 400000 );

   Wire.beginTransmission( OLED_ADDRESS );
   uint8_t err = Wire.endTransmission();


added 4 relays

added 4 relays

--- T3/src/AFE-MQTT.ino
+++ T3/src/AFE-MQTT.ino
@@ -68,14 +68,19 @@
                       Serial << endl << "INFO: Subsribed";
           */
           // Setting Relay state after connection to MQTT
-          if (!Relay.setRelayAfterRestoringMQTTConnection()) {
-            // Requesting state from MQTT Broker / service
-            publish(Relay.getMQTTTopic(), "get", "defaultState");
-          } else {
-            // Updating relay state after setting default value after MQTT
-            // connected
-            publish(Relay.getMQTTTopic(), "state",
-                    Relay.get() == RELAY_ON ? "on" : "off");
+
+          for (uint8_t i = 0; i < 4; i++) {
+            if (Device.configuration.isRelay[i]) {
+              if (!Relay[i].setRelayAfterRestoringMQTTConnection()) {
+                // Requesting state from MQTT Broker / service
+                publish(Relay[i].getMQTTTopic(), "get", "defaultState");
+              } else {
+                // Updating relay state after setting default value after MQTT
+                // connected
+                publish(Relay[i].getMQTTTopic(), "state",
+                        Relay[i].get() == RELAY_ON ? "on" : "off");
+              }
+            }
           }
         } else {
           connections++;


Arduino: Feature: Changed Linear Actuator to stop/hold position by default unless given a signal to go up/down

--- Arduino/soil_sensor_w_linear_actuator/soil_sensor_w_linear_actuator.ino
+++ Arduino/soil_sensor_w_linear_actuator/soil_sensor_w_linear_actuator.ino
@@ -161,25 +161,24 @@

     }

-    // 0
-    else if (incomingByte == 48) // Stop
-    {
-      analogWrite(PWMA, 0);
-    }
-
-    // 2
+    // 2: 50 - 48 = 2 (ASCII to dec conversion)
     else if (incomingByte == 50) // Move up
     {
       analogWrite(PWMA, 64);
       digitalWrite(AIN1, LOW);       // sets the digital pin 13 on
       digitalWrite(AIN2, HIGH);  // LOW, LOW -> Freeze, HIGH, HIGH -> Freeze
     }
+
+    // By Default, if there is no signal. Stop
+    // 0
+    else // else if (incomingByte == 48) // Stop
+    {
+      analogWrite(PWMA, 0);
+    }
+
   } // End Serial.available()

-
-
-
-
+  // For Debugging
   // Waiting for Serial Input
   //Serial.println("Waiting for Serial Input");
   //analogWrite(PWMA, 128); // Use servo, analogWrite and servo both work


break compilation to test travis script

break compilation to test travis script

--- Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/REV8HardwareTest/REV8HardwareTest.ino
+++ Arduino/hardware/V0p2_Main_PCB_REV7_DORM1_and_REV8/REV8HardwareTest/REV8HardwareTest.ino
@@ -32,7 +32,7 @@
  * See also, for previous version of this code:
  *     Arduino/snapshots/20150110-r4107-V0p2-Arduino-REV8-boiler-relay-test
  */
-
+breakstuff
 // INCLUDES & DEFINES
 // Debug output flag
 #define DEBUG


Minor change to default status message text

--- FumeHoodMonitor/ThingSpeak.ino
+++ FumeHoodMonitor/ThingSpeak.ino
@@ -29,7 +29,7 @@
     if (onFire) statusMsg += " - On Fire";
     if (airHigh) statusMsg += " - Air Temp High";
     if (oilHigh) statusMsg += " - Oil Temp High";
-    if (!onFire && !airHigh && !oilHigh) statusMsg += "All Systems Operational";
+    if (!onFire && !airHigh && !oilHigh) statusMsg += " - All Systems Operational";
     setThingSpeakStatus(statusMsg);
     postToThingSpeak();
     ThingSpeakTimer = now;


Improved SPC load speed

Improved SPC load speed

--- SNES_Jukebox/SNES_Jukebox.ino
+++ SNES_Jukebox/SNES_Jukebox.ino
@@ -95,49 +95,62 @@
   file.seek(desiredPosition);
 }

-byte readSpcRamData(File &spcFile, SPCInfo &info, word address) {
-  // Extra RAM
-  if (info.getShouldLoadExtraRAM() && address >= 0xFFC0) {
-    seekIfNecessary(spcFile, EXTRA_RAM_START + (uint32_t)(address - 0xFFC0));
-    return (byte)spcFile.read();
-  }
-
-  // Bootloader code
-  if (address >= info.getBootLocation() && address < (info.getBootLocation() + info.getBootCount())) {
-    word bootAddress = address - info.getBootLocation();
-    switch (bootAddress) {
-      case 0x19: return info.getExtraData(0);
-      case 0x1F: return info.getExtraData(1);
-      case 0x25: return info.getExtraData(2);
-      case 0x2B: return info.getExtraData(3);
-      case 0x01: return info.getExtraData(4);
-      case 0x04: return info.getExtraData(5);
-      case 0x07: return info.getExtraData(6);
-      case 0x0A: return info.getExtraData(7);
-      case 0x0D: return info.getExtraData(8);
-      case 0x10: return info.getExtraData(9);
-      case 0x38: return info.getExtraData(10);
-      case 0x3E: return info.getExtraData(11);
-      case 0x41: return info.getExtraData(12);
-      case 0x44: return info.getSPLow();
-      case 0x47: return info.getPSW();
-      case 0x4b: return info.getA();
-      case 0x4d: return info.getY();
-      case 0x4f: return info.getX();
-      case 0x51: return info.getPCLow();
-      case 0x52: return info.getPCHigh();
-      default: return pgm_read_byte(bootloaderCode + bootAddress);
-    }
-  }
-
-  // Echo region
-  if (info.getEchoEnabled() && address >= info.getEchoRegion() && address < (info.getEchoRegion() + info.getEchoSize())) {
-    return 0;
-  }
-
-  // If no special RAM re-mapping is to be done, just load the byte
-  seekIfNecessary(spcFile, RAM_START + (uint32_t)address);
-  return (byte)spcFile.read();
+word readSpcRamData(File &spcFile, SPCInfo &info, word startAddress, byte *out, word readCount) {
+  seekIfNecessary(spcFile, RAM_START + (uint32_t)startAddress);
+
+  const word realReadCount = (word)min((uint32_t)readCount, (word)min(spcFile.size() - RAM_START - (uint32_t)startAddress, (uint32_t)65535));
+  spcFile.read(out, realReadCount);
+
+  const uint32_t endAddress = (uint32_t)startAddress + (uint32_t)realReadCount;
+
+  // Load extra RAM
+  if (info.getShouldLoadExtraRAM() && endAddress > 0xFFC0) {
+    const word extraRamStart = max(startAddress, 0xFFC0);
+    seekIfNecessary(spcFile, EXTRA_RAM_START + (uint32_t)(extraRamStart - 0xFFC0));
+    spcFile.read(&out[extraRamStart - startAddress], 0xFFFF - extraRamStart + 1);
+  }
+
+  // Load bootloader code
+  const uint32_t bootStart = max(startAddress, info.getBootLocation());
+  const uint32_t bootEnd = min(endAddress, (uint32_t)(info.getBootLocation() + info.getBootCount()));
+  for (uint32_t i = bootStart; i < bootEnd; ++i) {
+    const word bootOffset = i - info.getBootLocation();
+    const word outOffset = i - startAddress;
+    switch (bootOffset) {
+      case 0x19: out[outOffset] = info.getExtraData(0); break;
+      case 0x1F: out[outOffset] = info.getExtraData(1); break;
+      case 0x25: out[outOffset] = info.getExtraData(2); break;
+      case 0x2B: out[outOffset] = info.getExtraData(3); break;
+      case 0x01: out[outOffset] = info.getExtraData(4); break;
+      case 0x04: out[outOffset] = info.getExtraData(5); break;
+      case 0x07: out[outOffset] = info.getExtraData(6); break;
+      case 0x0A: out[outOffset] = info.getExtraData(7); break;
+      case 0x0D: out[outOffset] = info.getExtraData(8); break;
+      case 0x10: out[outOffset] = info.getExtraData(9); break;
+      case 0x38: out[outOffset] = info.getExtraData(10); break;
+      case 0x3E: out[outOffset] = info.getExtraData(11); break;
+      case 0x41: out[outOffset] = info.getExtraData(12); break;
+      case 0x44: out[outOffset] = info.getSPLow(); break;
+      case 0x47: out[outOffset] = info.getPSW(); break;
+      case 0x4b: out[outOffset] = info.getA(); break;
+      case 0x4d: out[outOffset] = info.getY(); break;
+      case 0x4f: out[outOffset] = info.getX(); break;
+      case 0x51: out[outOffset] = info.getPCLow(); break;
+      case 0x52: out[outOffset] = info.getPCHigh(); break;
+      default: out[outOffset] = pgm_read_byte(bootloaderCode + bootOffset); break;
+    }
+  }
+
+  // Silence echo region
+  if (info.getEchoEnabled()) {
+    const uint32_t echoStart = max(startAddress, info.getEchoRegion());
+    const uint32_t echoEnd = min(endAddress, (uint32_t)(info.getEchoRegion() + info.getEchoSize()));
+    for (uint32_t i = echoStart; i < echoEnd; ++i) {
+      out[i - startAddress] = 0;
+    }
+  }
+
+  return realReadCount;
 }

 /**
@@ -225,9 +238,7 @@
   // Read some data from the SD card
   beginSdRead();
   readDspRamData(file, &buffer[0]);
-  for (word i = 0; i < SPC_UPLOAD_BUFFER_SIZE - 128; i++) {
-    buffer[128 + i] = readSpcRamData(file, info, i);
-  }
+  readSpcRamData(file, info, 0, &buffer[128], SPC_UPLOAD_BUFFER_SIZE - 128);
   endSdRead();

   // Initialize
@@ -241,9 +252,7 @@
   for (uint32_t i = 0x180; i < 0x10000; i += SPC_UPLOAD_BUFFER_SIZE) {
     // Read more data from the card
     beginSdRead();
-    for (uint32_t j = 0; j < SPC_UPLOAD_BUFFER_SIZE && i + j < 0x10000; j++) {
-      buffer[j] = readSpcRamData(file, info, (word)(j + i));
-    }
+    readSpcRamData(file, info, (word)i, buffer, min(SPC_UPLOAD_BUFFER_SIZE, (word)(0x10000 - i)));
     endSdRead();

     // Write data to the SPC 700


Use safeload for assets

Use safeload for assets

--- nightstrike.ino
+++ nightstrike.ino
@@ -863,7 +863,7 @@
 {
   Streamer stream;

-  GD.load("nightw.gd2");
+  GD.safeload("nightw.gd2");
   byte fade = 0;
   int t;


fix error begin

fix error begin

--- finger-web/finger-web.ino
+++ finger-web/finger-web.ino
@@ -6,13 +6,14 @@

 // Ethernet config
 byte mac[] = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
-IPAddress ip(, , , );
-IPAddress server(, , , );
+//IPAddress ip(, , , );
+//IPAddress server(, , , );

 // MQTT config

-EthernetClient ethClient;
-PubSubClient client(ethClient);
+//EthernetClient ethClient;
+//PubSubClient client(ethClient);
+#define PORT 1883

 // sensor config
 SoftwareSerial mySerial(2, 3);
@@ -24,11 +25,12 @@

 void setup()
 {
-  Serial.begin(9600);
+  Serial.begin(57600);

   finger.begin(57600);
-
+  //client.setServer(server, PORT);
+
   if (finger.verifyPassword()) {
     Serial.println("Sensor encontrado!");
   } else {


refine debug msg and comments

refine debug msg and comments

--- client/client.ino
+++ client/client.ino
@@ -110,8 +110,6 @@

   if(irrecv.decode(&results)) {
     delay(5);
-    // DEBUG_PRINT("\nIR received: ");
-    // DEBUG_PRINTLN(results.value);
     DEBUG_TAGGING("IR: ", results.value);
     if(results.value == 0xFFFF){
       digitalWrite(ledSignalPin, 1);
@@ -171,13 +169,14 @@

       } else if(strcmp(p.data, "080") == 0) {
         //the one is hovered => blink fast
-        //the rest => don't do anything
+
         if(atoi(p.id) == atoi(deviceId)) {
           statePending = true;
           ledStateInterval = blinkFast;
           eighty_twenty = false;
-          // digitalWrite(ledStatePin, HIGH);
+
         } else {
+          //the rest => blink at low frequency
           ledStateInterval = blinkSlow;
           statePending = true;
           eighty_twenty = true;


tuned for denny; time-based, 18 min stagger, 6 min flood...

--- ardesp/waterelf/waterelf.ino
+++ ardesp/waterelf/waterelf.ino
@@ -213,7 +213,7 @@
   int fillLevel = 10;           // cms below the level sensor: drain point
   bool filling = false;         // true when closed / on
   long lastFlip = -1;           // millis at last state change
-  int floodMins = 1; // TODO 10;
+  int floodMins = 6; // TODO 10;

   Valve() { number = counter++; }
   void stateChange(bool newState) { // turn on or off
@@ -298,7 +298,7 @@
 class FlowController { // the set of valves and their config ////////////////
   public:
   int numValves = 3;         // WARNING! call init if resetting!
-  int cycleMins = 3; // TODO// how long is a flood/drain cycle?
+  int cycleMins = 18; // TODO// how long is a flood/drain cycle?
   int maxSimultDrainers = 1; // how many beds can drain simultaneously?
   int minBedsWet = 1;        // min beds that are full or filling
   int maxBedsWet = 2;        // max beds that are full or filling


remove unused code

remove unused code

--- examples/RF12/RF12demo/RF12demo.ino
+++ examples/RF12/RF12demo/RF12demo.ino
@@ -164,13 +164,6 @@
     uint16_t crc = ~0;
     for (byte i = 0; i < len; ++i)
         crc = _crc16_update(crc, ((const byte*) ptr)[i]);
-    return crc;
-}
-
-static uint16_t calcCrcEeprom (const void* ptr, uint8_t len) {
-    uint16_t crc = ~0;
-    for (byte i = 0; i < len; ++i)
-        crc = _crc16_update(crc, eeprom_read_byte((const byte*) ptr + i));
     return crc;
 }


brian's version

brian's version

--- Teensy-Reactor-Controller.ino
+++ Teensy-Reactor-Controller.ino
@@ -30,9 +30,6 @@

 // Create a Flag to tell the main loop when the StartPin interrupt has been triggered.
 boolean StartPinFlag = false;
-
-// Create a Flag to tell if AutoPurge is on.
-boolean AutoPurgeFlag = false;

 // Sets the trigger edge for the StartPin signal. 0 is falling, 1 is rising. I am making it
 // an int instead of a define so that you can for instance have a command that changes which
@@ -67,7 +64,6 @@
   // Register the commands created to attach running the function with receiving a starting string over USB Serial.
   // Third argument is a description to be displayed when you send the command ListCommands.
   registerCommand("SetPurge", setPurge, "Set Purge Valve State (0/1)");
-  registerCommand("SetAutoPurge", setAutoPurge, "Sets the Purve Valve to purge automatically after GC takes a sample");
 }

 elapsedMillis elapsed;
@@ -99,22 +95,11 @@
     // which assumes a globally defined elapsedMillis named elapsed, or
     // setting some pin:
     digitalWrite(TriggeredPin, HIGH);
-
-    // If AutoPurge is on and GC signal sends an interrupt, start the AutoPurge sequence.
-    if (AutoPurgeFlag) {
-      // Utilize evaluateCommand("setPurge 1")????
-      digitalWrite(PurgePin, HIGH);
-      Serial.println("Purge valve set to ON.");
-    }
   }

   // This example shows a way to used the elapsed time to set the TriggeredPin low after TriggeredPinDelay (ms).
   if (elapsed > TriggeredPinDelay) {
     digitalWrite(TriggeredPin, LOW);
-    if (digitalRead(PurgePin) == HIGH) {
-      digitalWrite(PurgePin, LOW);
-      Serial.println("Purge valve set to OFF.")
-    }
     elapsed =- TriggeredPinDelay;
   }

@@ -160,31 +145,4 @@

   // and if the argument isn't 0 or 1, return an error.
   else Serial.println("ERROR: Purge valve state invalid (must be 0 or 1).");
-}
-
-
-command(setAutoPurge) {
-  // A quick check that the number of arguments received is correct.
-  // Does not include the command name in the number of arguments.
-  if (numArgs() != 1) {
-    Serial.println("ERROR: SetPurge expects 1 argument, received " + String(numArgs()) + ".");
-    return;
-  }
-
-  // Create a place to put the argument into a real value.
-  int AutoPurgeState;
-
-  // Collect the first argument to the Command sent over Serial, convert to int, and put into AutoPurgeState.
-  intArg(1, &AutoPurgeState);
-
-  // Sets AutoPurgeFlag as true or false to determine whether to initialize AutoPurge sequence.
-  if (AutoPurgeState == 0) {
-    AutoPurgeFlag = false;
-    Serial.println("AutoPurge is set to OFF.")
-  }
-  else if (AutoPurgeState == 1) {
-    AutoPurgeFlag = true;
-    Serial.println("AutoPurge is set to ON.")
-  }
-}
-
+}


spark code da funçãoReset

spark code da funçãoReset

--- EMP-B-Due.ino
+++ EMP-B-Due.ino
@@ -6,103 +6,103 @@
 */

 // Constantes
-  // Entradas
-    const byte bt_geral = 22; // Entrada do botão de Liga/Desliga Geral
-    const byte bt_dosador = 24; // Entrada do botão de Liga/Desliga do Dosador
-    const byte bt_datador = 26; // Entrada do botão de Liga/Desliga do Datador
-    const byte sensor_reset = 28; // Entrada do Sensor de Reset de Ciclo
-    const byte sensor_porta = 32; // Sensor de Segurança da Porta Frontal
-    const byte sensor_painel = 34; // Sensor de Segurança da Porta do Painel
-    const byte sensor_maquina = 36; // Sensor de Segurança da Porta da Máquina
-    const byte pot_solda_vertical = A0; // Potenciômetro da Solda Vertical
-    const byte pot_solda_horizontal = A1; // Potenciômetro da Solda Vertical
-    const byte pot_solda_datador = A2; // Potenciômetro da Solda Vertical
-  // Saídas
-    const byte geral = 40; // Saída Geral
-    const byte dosador = 42; // Saída do Dosador
-    const byte datador = 44; // Saída do Datador
-    const byte solda_vertical = 33; // Saída da Solda Vertical
-    const byte solda_horizontal = 35; // Saída da Solda Horizontal
-    const byte solda_datador = 37; // Saída da Solda do Datador
-    const byte led_teste_1 = 23;
-    const byte led_teste_2 = 25;
-    const byte led_teste_3 = 27;
-
+// Entradas
+const byte bt_geral = 22;        // Entrada do botão de Liga/Desliga Geral
+const byte bt_dosador = 24;      // Entrada do botão de Liga/Desliga do Dosador
+const byte bt_datador = 26;      // Entrada do botão de Liga/Desliga do Datador
+const byte sensor_reset = 28;    // Entrada do Sensor de Reset de Ciclo
+const byte sensor_porta = 32;    // Sensor de Segurança da Porta Frontal
+const byte sensor_painel = 34;   // Sensor de Segurança da Porta do Painel
+const byte sensor_maquina = 36;  // Sensor de Segurança da Porta da Máquina
+const byte pot_solda_vertical = A0;    // Potenciômetro da Solda Vertical
+const byte pot_solda_horizontal = A1;  // Potenciômetro da Solda Vertical
+const byte pot_solda_datador = A2;     // Potenciômetro da Solda Vertical
+                                       // Saídas
+const byte geral = 40;                 // Saída Geral
+const byte dosador = 42;               // Saída do Dosador
+const byte datador = 44;               // Saída do Datador
+const byte solda_vertical = 33;        // Saída da Solda Vertical
+const byte solda_horizontal = 35;      // Saída da Solda Horizontal
+const byte solda_datador = 37;         // Saída da Solda do Datador
+const byte led_teste_1 = 23;
+const byte led_teste_2 = 25;
+const byte led_teste_3 = 27;

 // Variáveis
-  // Configurações
-    #define BOTAO INPUT_PULLUP // INPUT ou INPUT_PULLUP
-    #define SENSOR INPUT // INPUT ou INPUT_PULLUP
-    #define SAIDA OUTPUT
-    #define ALTO LOW // Deve ser invertido para INPUT_PULLUP
-    #define BAIXO HIGH // Deve ser invertido para INPUT_PULLUP
-    #define LIGA HIGH
-    #define DESLIGA LOW
-    #define VERDADEIRO true
-    #define FALSO false
-  // Nomes de Funções
-    #define NomeGeral "Geral"
-    #define NomeDosador "Dosador"
-    #define NomeDatador "Datador"
-    #define NomeSoldaVertical "Solda Vertical"
-    #define NomeSoldaHorizontal "Solda Horizontal"
-    #define NomeSoldaDatador "Solda Datador"
-  // Botões de Entrada Um Clique
-    unsigned long atraso = 50;
-    int estbt_geral; // Estado do Botão Geral
-    int estbta_geral = BAIXO; // Estado anterior do Botão Geral
-    unsigned long atr_geral = 0; // Atraso do Botão Geral
-    int estbt_dosador; // Estado do Botão Dosador
-    int estbta_dosador = BAIXO; // Estado anterior do Botão Dosador
-    unsigned long atr_dosador = 0; // Atraso do Botão Dosador
-    int estbt_datador; // Estado do Botão Datador
-    int estbta_datador = BAIXO; // Estado anterior do Botão Dosador
-    unsigned long atr_datador = 0; // Atraso do Botão Dosador
-  // PWM das Soldas
-    const unsigned long ciclo_PWM = 1000;
-    unsigned long tempo_PWM_vertical = 0; // Tempo do PWM da solda vertical
-    unsigned long tempo_PWM_horizontal = 0; // Tempo do PWM da solda horizontal
-    unsigned long tempo_PWM_datador = 0; // Tempo do PWM da solda do Datador
-  // Programa
-    boolean stand_by = FALSO;
-    boolean maquina_ligada = FALSO;
-    boolean dosador_ligado = FALSO;
-    boolean datador_ligado = FALSO;
-    boolean alarme_ativo = FALSO;
-    unsigned long inicio_ciclo = millis();
-    bool fotocelula_liberada = FALSO;
-    bool fotocelula_cortou = FALSO;
-    bool ciclo_resetado = FALSO;
-    bool reset_falso = FALSO;
-    unsigned long conta_ciclos = 0;
-    boolean produzindo = FALSO;
-  // Tempos do Ciclo
-    // Ciclo
-    unsigned long ciclo_padrao = 2000;
-    unsigned long ciclo_minimo = 900;
-    unsigned long ciclo_maximo = 2000;
-    unsigned long primeiro_ciclo = 0;
-    // Mandibula
-    unsigned long inicio_mandibula = 550;
-    unsigned long fim_mandibula = 1500;
-    // Fotocélula
-    unsigned long inicio_fotocelula = 1250;
-    unsigned long fim_fotocelula = 1400;
-    // Faca
-    unsigned long inicio_faca = 600;
-    unsigned long fim_faca = 800;
-    // Refrigeração
-    unsigned long inicio_refrigeracao = 800;
-    unsigned long fim_refrigeracao = 1450;
-    // Datador
-    unsigned long inicio_datador = 0;
-    unsigned long fim_datador = 400;
-    // Solda Vertical
-    unsigned long inicio_soldas = 0;
-    unsigned long fim_soldas = 400;
-    // Atraso entre resets consecutivos
-    unsigned long atraso_resets = ciclo_padrao / 3;
-
+// Configurações
+#define BOTAO INPUT_PULLUP  // INPUT ou INPUT_PULLUP
+#define SENSOR INPUT        // INPUT ou INPUT_PULLUP
+#define SAIDA OUTPUT
+#define ALTO LOW    // Deve ser invertido para INPUT_PULLUP
+#define BAIXO HIGH  // Deve ser invertido para INPUT_PULLUP
+#define LIGA HIGH
+#define DESLIGA LOW
+#define VERDADEIRO true
+#define FALSO false
+// Nomes de Funções
+#define NomeGeral "Geral"
+#define NomeDosador "Dosador"
+#define NomeDatador "Datador"
+#define NomeSoldaVertical "Solda Vertical"
+#define NomeSoldaHorizontal "Solda Horizontal"
+#define NomeSoldaDatador "Solda Datador"
+// Botões de Entrada Um Clique
+unsigned long atraso = 50;
+int estbt_geral;                // Estado do Botão Geral
+int estbta_geral = BAIXO;       // Estado anterior do Botão Geral
+unsigned long atr_geral = 0;    // Atraso do Botão Geral
+int estbt_dosador;              // Estado do Botão Dosador
+int estbta_dosador = BAIXO;     // Estado anterior do Botão Dosador
+unsigned long atr_dosador = 0;  // Atraso do Botão Dosador
+int estbt_datador;              // Estado do Botão Datador
+int estbta_datador = BAIXO;     // Estado anterior do Botão Dosador
+unsigned long atr_datador = 0;  // Atraso do Botão Dosador
+                                // PWM das Soldas
+const unsigned long ciclo_PWM = 1000;
+unsigned long tempo_PWM_vertical = 0;    // Tempo do PWM da solda vertical
+unsigned long tempo_PWM_horizontal = 0;  // Tempo do PWM da solda horizontal
+unsigned long tempo_PWM_datador = 0;     // Tempo do PWM da solda do Datador
+                                         // Programa
+boolean stand_by = FALSO;
+boolean maquina_ligada = FALSO;
+boolean dosador_ligado = FALSO;
+boolean datador_ligado = FALSO;
+boolean alarme_ativo = FALSO;
+unsigned long inicio_ciclo = millis();
+bool fotocelula_liberada = FALSO;
+bool fotocelula_cortou = FALSO;
+bool ciclo_resetado = FALSO;
+bool reset_falso = FALSO;
+unsigned long conta_ciclos = 0;
+boolean produzindo = FALSO;
+boolean reset_liberado = VERDADEIRO;
+boolean sensor_resetou = FALSO;
+// Tempos do Ciclo
+// Ciclo
+unsigned long ciclo_padrao = 1500;
+unsigned long ciclo_minimo = 900;
+unsigned long ciclo_maximo = 2000;
+unsigned long primeiro_ciclo = 0;
+// Mandibula
+unsigned long inicio_mandibula = 550;
+unsigned long fim_mandibula = 1500;
+// Fotocélula
+unsigned long inicio_fotocelula = 1250;
+unsigned long fim_fotocelula = 1400;
+// Faca
+unsigned long inicio_faca = 600;
+unsigned long fim_faca = 800;
+// Refrigeração
+unsigned long inicio_refrigeracao = 800;
+unsigned long fim_refrigeracao = 1450;
+// Datador
+unsigned long inicio_datador = 0;
+unsigned long fim_datador = 400;
+// Solda Vertical
+unsigned long inicio_soldas = 0;
+unsigned long fim_soldas = 400;
+// Atraso entre resets consecutivos
+unsigned long atraso_resets = ciclo_padrao / 3;

 void setup() {
   Serial.begin(9600);
@@ -110,7 +110,7 @@
   pinMode(bt_geral, BOTAO);
   pinMode(bt_dosador, BOTAO);
   pinMode(bt_datador, BOTAO);
-  pinMode(sensor_reset, BOTAO); // Mudar para Sensor após os testes.
+  pinMode(sensor_reset, BOTAO);  // Mudar para Sensor após os testes.
   // Potenciômetros das Soldas
   pinMode(pot_solda_vertical, SENSOR);
   pinMode(pot_solda_horizontal, SENSOR);
@@ -124,7 +124,6 @@
   pinMode(sensor_painel, BOTAO);
   pinMode(sensor_maquina, BOTAO);

-
   pinMode(geral, SAIDA);
   pinMode(dosador, SAIDA);
   pinMode(datador, SAIDA);
@@ -136,13 +135,15 @@
   resetCompleto();
 }

-
 void loop() {
   modoAlarme();

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

   if (!alarme_ativo) {
     standBy();
@@ -154,9 +155,9 @@

 void standBy() {
   if (stand_by && !alarme_ativo) {
-    acionaGeral(); // Monitora botão Geral
-    acionaDosador(); // Monitora botão Dosador
-    acionaDatador(); // Monitora botão Datador
+    acionaGeral();    // Monitora botão Geral
+    acionaDosador();  // Monitora botão Dosador
+    acionaDatador();  // Monitora botão Datador
     if (maquina_ligada) {
       iniciaTrabalho();
     } else {
@@ -164,20 +165,19 @@
     }
   } else if (!alarme_ativo) {
     escreveSerial("Preparando para iniciar trabalho.");
-    delay(3000); // Espera 3 segundos após energização
-    stand_by = VERDADEIRO; // Libera funcionamento
+    delay(3000);            // Espera 3 segundos após energização
+    stand_by = VERDADEIRO;  // Libera funcionamento
     escreveSerial("Tudo pronto!");
   }
 }

 void iniciaTrabalho() {
   if (!produzindo) {
-    reiniciaCiclo();
-    primeiro_ciclo = millis();
     produzindo = VERDADEIRO;
-  } else if (conta_ciclos >= 3) {
-    ligaFuncao(led_teste_1, "Led Teste 1"); // Exemplo para teste.
-    // ciclo de trabalho
+  }
+  if (conta_ciclos >= 3) {
+    ligaFuncao(led_teste_1, "Led Teste 1");  // Exemplo para teste.
+                                             // ciclo de trabalho
   }
   funcaoReset();
 }
@@ -205,54 +205,102 @@
 }

 void acionaGeral() {
-  btUmClique(bt_geral, &estbt_geral, &estbta_geral, &atr_geral, &maquina_ligada);
+  btUmClique(bt_geral, &estbt_geral, &estbta_geral, &atr_geral,
+             &maquina_ligada);
 }

 void acionaDosador() {
-  btUmClique(bt_dosador, &estbt_dosador, &estbta_dosador, &atr_dosador, &dosador_ligado);
+  btUmClique(bt_dosador, &estbt_dosador, &estbta_dosador, &atr_dosador,
+             &dosador_ligado);
 }

 void acionaDatador() {
   if (maquina_ligada && !alarme_ativo) {
-    btUmClique(bt_datador, &estbt_datador, &estbta_datador, &atr_datador, &datador_ligado);
+    btUmClique(bt_datador, &estbt_datador, &estbta_datador, &atr_datador,
+               &datador_ligado);
   }
 }

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

 void reiniciaCiclo() {
   inicio_ciclo = millis();
+  ciclo_resetado = VERDADEIRO;
+  sensor_resetou = FALSO;
   fotocelula_liberada = FALSO;
   fotocelula_cortou = FALSO;
+}
+
+void sensorReset(){
+  if (ativo(sensor_reset) && reset_liberado){
+    sensor_resetou = VERDADEIRO;
+  }
 }

 void geraPWM(byte pot, unsigned long *inicio, byte saida, String nome) {
@@ -261,7 +309,8 @@
   if (maquina_ligada && !alarme_ativo) {
     if (millis() > *inicio && millis() <= (*inicio + ativo)) {
       liga(saida);
-    } else if (millis() > (*inicio + ativo) && millis() < (*inicio + ciclo_PWM)) {
+    } else if (millis() > (*inicio + ativo) &&
+               millis() < (*inicio + ciclo_PWM)) {
       desliga(saida);
     } else if (millis() >= (*inicio + ciclo_PWM)) {
       *inicio = millis();
@@ -271,16 +320,11 @@
   }
 }

-
 // FERRAMENTAS AUXILIARES

-byte leEntrada(byte pino) {
-  return digitalRead(pino);
-}
-
-void liga(byte saida) {
-  digitalWrite(saida, LIGA);
-}
+byte leEntrada(byte pino) { return digitalRead(pino); }
+
+void liga(byte saida) { digitalWrite(saida, LIGA); }

 void ligaFuncao(byte saida, String texto) {
   if (desligado(saida)) {
@@ -289,9 +333,7 @@
   }
 }

-void desliga(byte saida) {
-  digitalWrite(saida, DESLIGA);
-}
+void desliga(byte saida) { digitalWrite(saida, DESLIGA); }

 void desligaFuncao(byte saida, String texto) {
   if (ligado(saida)) {
@@ -332,7 +374,8 @@
   }
 }

-void btUmClique(byte botao, int *estado, int *est_ant, unsigned long *atr_ant, boolean *funcao) {
+void btUmClique(byte botao, int *estado, int *est_ant, unsigned long *atr_ant,
+                boolean *funcao) {
   byte estado_atual = leEntrada(botao);
   if (estado_atual != *est_ant) {
     *atr_ant = millis();
@@ -364,9 +407,9 @@
   desligaFuncao(dosador, NomeDosador);
   desligaFuncao(datador, NomeDatador);

-  desliga(led_teste_1); // Para testes
-  desliga(led_teste_2); // Para testes
-  desliga(led_teste_3); // Para testes
+  desliga(led_teste_1);  // Para testes
+  desliga(led_teste_2);  // Para testes
+  desliga(led_teste_3);  // Para testes
 }

 void resetCompleto() {
@@ -378,11 +421,10 @@
   desliga(solda_horizontal);
   desliga(solda_datador);

-  desliga(led_teste_1); // Para testes
-  desliga(led_teste_2); // Para testes
-  desliga(led_teste_3); // Para testes
-}
-
+  desliga(led_teste_1);  // Para testes
+  desliga(led_teste_2);  // Para testes
+  desliga(led_teste_3);  // Para testes
+}

 void modoTeste() {
   if (maquina_ligada) {


added sync() function to fix off-by-one sample sync error

--- software/serial_dmm/serial_dmm.ino
+++ software/serial_dmm/serial_dmm.ino
@@ -21,6 +21,11 @@
     this->port = &port;
     digitalWrite(rx_pin, LOW); // turn off internal pullup - use 100k external
     this->port->begin(2400);
+  }
+
+  void sync()
+  {
+    start_frame_seen = false;
   }

   bool poll()
@@ -286,6 +291,7 @@
   if (Serial.available()){
     result_format = Serial.read();
     sample_pending = true;
+    dmm.sync();
   }

   if (dmm.poll() && sample_pending){


заработала передача A0

заработала передача A0

--- serialracoon.ino
+++ serialracoon.ino
@@ -138,10 +138,27 @@

 }

-long int cnt = 0;
+int cnt = 0;
+
+int board = 0;
+
+const int aInPin = A0;
+
+int analogPin = 3;     // potentiometer wiper (middle terminal) connected to analog pin 3
+
+                       // outside leads to ground and +5V
+
+int val = 0;           // variable to store the value read
+
+
+
 void loop()
 {
   int btIn = -1;
+
+
+  val = analogRead(A0);    // read the input pin
+
   if (BTSerial.available() && (btIn = BTSerial.read()) ) {
     Serial.write(btIn);
   }
@@ -166,14 +183,16 @@
     //Serial.print(fromSerialStr);
   }

-
   char out[80];

-  sprintf(out, "test data sequince %d\r\n", cnt++);
-//  BTSerial.write("test data sequince\r\n");
-  BTSerial.write(out);
-  delay(100);
-
+  if (board == 0) {
+    //sprintf(out, "seqid %d;%d;;;\r\n", cnt++, val);
+    sprintf(out, "%d;%d;%d;%d\r\n", cnt, val+0, val+1, val+2);
+    Serial.println(out);
+    BTSerial.write(out);
+    delay(100);
+  }
+  cnt++;
 }


program light three

program light three

Former-commit-id: 3376c5c8c6fc6af973b0eb622a42cf03c725873a

--- LED-control/LED_control/firmware/LightBrick_Jeremy/LightBrick_Jeremy.ino
+++ LED-control/LED_control/firmware/LightBrick_Jeremy/LightBrick_Jeremy.ino
@@ -9,10 +9,10 @@
 #define WIRELESS_MODE_INFRA	1
 #define WIRELESS_MODE_ADHOC	2

-#define light_number 8
+#define light_number 9

 // Wireless configuration parameters ----------------------------------------
-unsigned char local_ip[] = {192,168,0,4}; // IP address of WiShield
+unsigned char local_ip[] = {192,168,0,5}; // IP address of WiShield
 unsigned char gateway_ip[] = {192,168,0,1};	// router or gateway IP address
 unsigned char subnet_mask[] = {255,255,255,0};	// subnet mask for the local network
 char ssid[] = "moodL";		// max 32 bytes


Reading input from two potentiometers

Reading input from two potentiometers

--- SearialInputReading/SearialInputReading.ino
+++ SearialInputReading/SearialInputReading.ino
@@ -1,9 +1,28 @@
-void setup() {
-  // put your setup code here, to run once:
-
-}
-
-void loop() {
-  // put your main code here, to run repeatedly:
-
-}
+   /*This Arduino sketch will read teh values of two potentiometers and a
+     toggle switch, which will be used to control the parameters of an oscillator
+     made with Audio Kit */
+
+     //http://www.nickarner.com
+     //http://www.audiokitio
+
+
+    void setup() {
+      // initialize serial communication at 9600 bits per second:
+      Serial.begin(9600);
+    }
+
+
+    void loop() {
+      // read the input for the first potentiometer
+      int potentiometerOneValue = analogRead(A0);
+      // Convert the analog reading (which goes from 0 - 1023) to a range between 0 and 1
+      float voltageOne = potentiometerOneValue * (1.0 / 1023.0);
+      Serial.println(voltageOne);
+
+      // read the input for the second potentiometer
+      int potentiometerTwoValue = analogRead(A1);
+      // Convert the analog reading (which goes from 0 - 1023) to a range between 0 and 1
+      float voltageTwo = potentiometerTwoValue * (1.0 / 1023.0);
+      Serial.println(voltageTwo);
+
+    }


Add water mass calculation #2

Add water mass calculation #2

--- Node/Node.ino
+++ Node/Node.ino
@@ -62,7 +62,7 @@

   Serial.print("Initializing BMP085/BMP180 sensor... ");
   if (bmp.begin()) {
-    Serial println("Ok");
+    Serial.println("Ok");
   }else{
     Serial.println("Could not find a valid BMP085/BMP180 sensor");
   }
@@ -105,14 +105,30 @@
   Serial.print("Timer Temp: "); Serial.println(RTC.temperature()/4.0);

   si7021_thc thc = sensor.getTempAndRH();
-  Serial.print("Temp: "); Serial.print(thc.celsiusHundredths / 100.0);
-  Serial.print("\tHum: "); Serial.println(thc.humidityPercent);
+  double t = thc.celsiusHundredths / 100.0;
+  double RH = thc.humidityPercent;
+  Serial.print("Temp: "); Serial.print(t);
+  Serial.print("\tHum: "); Serial.println(RH);

-  int32_t pressure = bmp.readPressure();
+  int32_t P = bmp.readPressure() / 100000.0;
   Serial.print("Temp: "); Serial.print(bmp.readTemperature()); // Celsius
-  Serial.print("\tPressure: "); Serial.println(pressure); // Pascals
+  Serial.print("\tPressure: "); Serial.println(P); // Gecto Pascals
+
+  double V = 1.0;
+  double Rv = 461.5;
+  double P0 = 1.0016;
+
+  double T = 273.15 + t;
+  double e_omega = 6.112*exp((17.62*T - 4812.903)/(T - 30.03));
+  double f = P0 + 0.00000315*P - 0.074/P;
+  double e = RH*e_omega*f;
+  double AH = e/(Rv*T);
+  double m = AH*V*1000000.0;
+
+  Serial.print("Water mass[mg]: "); Serial.println(m);

   Serial.flush();
+
   size_t count = 0;
   while (count < 9) {
     delay(50);


#9 update transfer data to MQTT

#9 update transfer data to MQTT

--- Node/Node.ino
+++ Node/Node.ino
@@ -28,7 +28,7 @@
 StaticJsonBuffer<200> jsonBuffer;
 MqttConnector* mqttConnector = NULL;

-JsonObject* sensorsData;
+JsonObject* sensorsData = NULL;

 void register_receive_hooks(MqttConnector* mqtt)
 {
@@ -83,11 +83,11 @@
     JsonObject& data = (*root)["d"];
     //JsonObject& info = (*root)["info"];

-    data["time"] = sensorsData->get("time");
-    data["temperature"] = sensorsData->get("temperature");
-    data["pressure"] = sensorsData->get("pressure");
-    data["humidity"] = sensorsData->get("humidity");
-    data["ppm"] = sensorsData->get("ppm");
+    data["time"] = (*sensorsData)["time"].as<long>();
+    data["temperature"] = (*sensorsData)["temperature"].as<double>();
+    data["pressure"] = (*sensorsData)["pressure"].as<double>();
+    data["humidity"] = (*sensorsData)["humidity"].as<int>();
+    data["ppm"] = (*sensorsData)["ppm"].as<int>();

   }, PUBLISH_EVERY);

@@ -213,10 +213,10 @@
   displayTime();

   tmElements_t tm;
-  RTC.read(tm);
+  Clock.read(tm);
   Serial.print("RTC:      ");
   displayTime(tm);
-  Serial.print("Timer Temp: "); Serial.println(RTC.temperature()/4.0);
+  Serial.print("Timer Temp: "); Serial.println(Clock.temperature()/4.0);

   si7021_thc thc = sensor.getTempAndRH();
   double t = thc.celsiusHundredths / 100.0;
@@ -267,14 +267,15 @@
   sensorsData = &root;

   char dirName[12];
-  sprintf(dirName, "/%.4i/%.2i/%.2i", tmYearToCalendar(tm.Year), tm.Month, tm.Day);
+  snprintf(dirName, 12, "/%.4i/%.2i/%.2i", tmYearToCalendar(tm.Year), tm.Month, tm.Day);
   char fileName[25];
-  sprintf(fileName, "/%s/%.2i.csv", dirName, tm.Hour);
+  snprintf(fileName, 25, "/%s/%.2i.csv", dirName, tm.Hour);

   File dataFile;
   if(!SD.exists(fileName)){
     if(!SD.mkdir(dirName)){
-      Serial.printf("Failed to create directory %s\r\n", dirName);
+      Serial.print("Failed to create directory ");
+      Serial.println(dirName);
       return;
     }
     dataFile = SD.open(fileName, O_WRITE | O_CREAT);
@@ -283,7 +284,9 @@
   }

   dataFile.seek(dataFile.size());
-  dataFile.printf("%i;%i;%i;%.2f;%i;%i\r\n", currentTime, thc.celsiusHundredths, thc.humidityPercent, bmpTemp, p, ppm);
+  char data[100];
+  snprintf(data, 100, "%i;%i;%i;%.2f;%i;%i\r\n", currentTime, thc.celsiusHundredths, thc.humidityPercent, bmpTemp, p, ppm);
+  dataFile.write(data, 100);
   dataFile.close();
   Serial.println();
 }


Delete Pong.ino

Delete Pong.ino

--- Pong/Pong.ino
+++ Pong/Pong.ino
@@ -1,248 +0,0 @@
-#include <SPI.h>
-#include <Adafruit_GFX.h>
-#include <TFT_ILI9163C.h>
-#include "gamebox.h"
-
-#define	BLACK   0x0000
-#define	BLUE    0x001F
-#define	RED     0xF800
-#define	GREEN   0x07E0
-#define CYAN    0x07FF
-#define MAGENTA 0xF81F
-#define YELLOW  0xFFE0
-#define WHITE   0xFFFF
-
-
-
-void setup(void) {
-	Gamebox.begin();
-	startGame(3);
-	showMenu();
-}
-uint8_t difficulty = 0;
-boolean multiplayer = false;
-uint8_t player = 1;
-uint8_t p1_paddle = 100;
-uint8_t p2_paddle = 90;
-uint16_t touches = 0, speed = 1;
-uint8_t ball[] = {106,44};
-int8_t movement[] = {0,0,-1,1};
-uint8_t points[] = {0,0};
-
-void drawField(boolean clear) {
-	if (clear)
-		tft.fillScreen(BLACK);
-	for (uint8_t i = 0; i < 8; i++) {
-		tft.drawLine(63, i*16, 63, i*16+8, WHITE);
-	}
-	tft.setTextSize(3);
-	tft.setTextColor(WHITE);
-	tft.setCursor(40, 10);
-	tft.print(player == 2 ? points[1] : points[0]);
-	tft.setCursor(70, 10);
-	tft.print(player == 1 ? points[1] : points[0]);
-}
-
-void startGame(uint8_t mode) {
-	multiplayer = false;
-	if (mode == 3) {
-		player = Gamebox.startMultiplayer();
-		if (player) multiplayer = true;
-		else return showMenu();
-		drawField(true);
-		tft.setTextSize(4);
-		for (uint8_t i = 3; i > 0; i--) {
-			tft.setTextColor(BLACK);
-			tft.setCursor(54, 48);
-			tft.print(i+1);
-			tft.setTextColor(WHITE);
-			tft.setCursor(54, 48);
-			tft.print(i);
-			delay(950);
-		}
-	} else {
-		difficulty = mode;
-		player = 1;
-	}
-	p1_paddle = 63;
-	p2_paddle = 63;
-	ball[0] = 63;
-	ball[1] = 63;
-	movement[0] = 0;
-	movement[1] = 0;
-	movement[2] = -1;
-	movement[3] = 0;
-	touches = 0;
-	points[0] = 0;
-	points[1] = 0;
-	drawField(true);
-}
-
-void showMenu() {
-	tft.fillScreen(BLACK);
-	tft.setTextSize(3);
-	tft.setTextColor(WHITE);
-	tft.setCursor(30, 10);
-	tft.print("PONG");
-	tft.setTextSize(1);
-	tft.setCursor(0, 50);
-	tft.println("  Easy");
-	tft.println("");
-	tft.println("  Medium");
-	tft.println("");
-	tft.println("  Hard");
-	tft.println("");
-	tft.println("  Multiplayer");
-	uint8_t selected = 0;
-	uint8_t old_sel = 0;
-	tft.fillRect(4, 43, 4, 20, WHITE);
-	while (true) {
-		uint8_t sel = Gamebox.getMovement();
-		if ((sel & 5) != (old_sel & 5)) {
-			tft.fillRect(4, 43+selected*16, 4, 20, BLACK);
-			selected = (selected + ((sel&1)-((sel>>2)&1)) + 4) & 3;
-			tft.fillRect(4, 43+selected*16, 4, 20, WHITE);
-		}
-		old_sel = sel;
-		if (Gamebox.getStartKey()) {
-			return startGame(selected);
-		}
-	}
-
-}
-
-int16_t estimated_pos = 0;
-int8_t hit_diff = 0;
-void loop(void) {
-	if (multiplayer) {
-		if (player == 2) {
-			movement[0] = Gamebox.recvMessage() - p1_paddle;
-			if (!Gamebox.sendMessage(p2_paddle + movement[1])) showMenu();
-		} else {
-			if (!Gamebox.sendMessage(p1_paddle + movement[0])) showMenu();
-			movement[1] = Gamebox.recvMessage() - p2_paddle;
-		}
-	} else {
-		movement[1] = 0;
-		tft.drawPixel(116, estimated_pos, BLACK);
-		if (movement[2] > 0) {
-			if (difficulty == 2) {
-				estimated_pos = abs((ball[1] - 2) + (116 - ball[0]) * movement[3] / movement[2]);
-				while (estimated_pos >= 124) estimated_pos = abs(246 - estimated_pos);
-				estimated_pos += 2;
-				estimated_pos += hit_diff;
-				if (p2_paddle - estimated_pos > 2) movement[1] = -3;
-				else if (estimated_pos - p2_paddle > 2) movement[1] = 3;
-				if (p2_paddle + movement[1] >= 117) movement[1] = 117-p2_paddle;
-				if (p2_paddle + movement[1] <= 10) movement[1] = 10-p2_paddle;
-			} else {
-				if (random(4-difficulty) < 2) {
-					if (p2_paddle - ball[1] > 2) movement[1] = -3;
-					else if (ball[1] - p2_paddle > 2) movement[1] = 3;
-					if (p2_paddle + movement[1] >= 117) movement[1] = 117-p2_paddle;
-					if (p2_paddle + movement[1] <= 10) movement[1] = 10-p2_paddle;
-				}
-			}
-		}
-	}
-
-	tft.fillRect((player == 2 ? (126 - ball[0]) : (ball[0] - 2)), ball[1]-2, 4, 4, BLACK);
-	if (movement[0] != 0)
-		tft.fillRect((player == 2 ? 119 : 4), p1_paddle-10, 4, 20, BLACK);
-	if (movement[1] != 0)
-		tft.fillRect((player == 1 ? 119 : 4), p2_paddle-10, 4, 20, BLACK);
-
-	p1_paddle+=movement[0];p2_paddle+=movement[1];
-	int8_t ball_y = ball[1] + movement[3];
-	if (ball_y < 2) {
-		ball[1] = 2 - ball_y;
-		movement[3] *= -1;
-	} else if (ball_y > 125) {
-		ball[1] = 250 - ball_y;
-		movement[3] *= -1;
-	} else {
-		ball[1] += movement[3];
-	}
-	ball[0] += movement[2];
-
-	if (multiplayer) {
-		if (player == 2) {
-			movement[2] = Gamebox.recvMessage() - ball[0];
-			movement[3] = Gamebox.recvMessage() - ball[1];
-		} else {
-			if (!Gamebox.sendMessage(ball[0] + movement[2])) showMenu();
-			if (!Gamebox.sendMessage(ball[1] + movement[3])) showMenu();
-		}
-	}
-
-
-	tft.fillRect((player == 2 ? (126 - ball[0]) : (ball[0] - 2)), ball[1]-2, 4, 4, WHITE);
-	tft.fillRect((player == 2 ? 119 : 4), p1_paddle-10, 4, 20, WHITE);
-	tft.fillRect((player == 1 ? 119 : 4), p2_paddle-10, 4, 20, WHITE);
-	drawField(false);
-	if (ball[1] <= 2 || ball[1] >= 125) {
-		movement[3] *= -1;
-	}
-	if (ball[0] <= 10 && ball[0] > 6 && movement[2] < 0) {
-		if (p1_paddle+10 >= ball[1] && p1_paddle-10 <= ball[1]) {
-			touches++;
-			speed = (touches >> 2) + 1;
-			movement[2] = speed;
-			movement[3] = (ball[1] - p1_paddle) / 5 * movement[2];
-		}
-	} else if (ball[0] >= 116 && ball[0] < 121 && movement[2] > 0) {
-		if (p2_paddle+10 >= ball[1] && p2_paddle-10 <= ball[1]) {
-			touches++;
-			speed = (touches >> 2) + 1;
-			movement[2] = - speed;
-			movement[3] = (ball[1] - p2_paddle) / 5 * -movement[2];
-			hit_diff = 7 - random(15);
-		}
-	} else if (ball[0] <= 6 || ball[0] >= 122) {
-		tft.fillRect((player == 2 ? (126 - ball[0]) : (ball[0] - 2)), ball[1]-2, 4, 4, BLACK);
-		tft.setTextSize(3);
-		tft.setTextColor(BLACK);
-		tft.fillRect(40,10,50,24,BLACK);
-		points[ball[0] < 64]++;
-		if (points[ball[0] < 64] == 10) {
-			tft.fillScreen(BLACK);
-			tft.setTextSize(3);
-			tft.setTextColor(WHITE);
-			tft.setCursor(40,40);
-			tft.println("You");
-			tft.setCursor(0,64);
-			tft.print((1 + (ball[0] < 64) == player) ? "  won!" : "lost :(");
-			while(!Gamebox.getStartKey());
-			showMenu();
-			return;
-		}
-		movement[3] = 0;
-		movement[2] = 1 - ((ball[0] < 64) * 2);
-		ball[0] = 63;
-		touches = 0;
-		drawField(false);
-	}
-	if ((ball[0] + movement[2] <= 7 && movement[2] < 0)) {
-		movement[3] /= movement[2];
-		movement[2] = min(-1, 7 - ball[0]);
-		movement[3] *= movement[2];
-	}
-	if (ball[0] + movement[2] >= 121 && movement[2] > 0) {
-		movement[3] /= movement[2];
-		movement[2] = max(1, 121 - ball[0]);
-		movement[3] *= movement[2];
-	}
-	delay(20);
-	uint8_t mvmnt = Gamebox.getMovement();
-	movement[player == 2] = ((mvmnt&1)-((mvmnt>>2)&1)) * 3;
-	if (player == 1) {
-		if (p1_paddle + movement[0] >= 117) movement[0] = 117-p1_paddle;
-		if (p1_paddle + movement[0] <= 10) movement[0] = 10-p1_paddle;
-	} else {
-		if (p2_paddle + movement[1] >= 117) movement[1] = 117-p2_paddle;
-		if (p2_paddle + movement[1] <= 10) movement[1] = 10-p2_paddle;
-	}
-	digitalWrite(2, !digitalRead(2));
-}
-
-/**/


fixed duplicate headers

fixed duplicate headers

--- examples/DMASpi_example1/DMASpi_example1.ino
+++ examples/DMASpi_example1/DMASpi_example1.ino
@@ -1,6 +1,6 @@
 #include <WProgram.h>

-#include <SPI.h>
+//#include <SPI.h>

 #include <DmaSpi.h>


moved state checking and init into loop()

--- examples/StandardFirmata/StandardFirmata.ino
+++ examples/StandardFirmata/StandardFirmata.ino
@@ -73,7 +73,10 @@
 /* timer variables */
 unsigned long currentMillis;        // store the current value from millis()
 unsigned long previousMillis;       // for comparison with currentMillis
-int samplingInterval = 50;          // how often to run the main loop (in ms)
+int samplingInterval = 200;          // how often to run the main loop (in ms)
+#define MINIMUM_SAMPLE_DELAY 150
+#define ANALOG_SAMPLE_DELAY 50
+

 /* i2c data */
 struct i2c_device_info {
@@ -153,7 +156,7 @@
 /* -----------------------------------------------------------------------------
  * check all the active digital inputs for change of state, then add any events
  * to the Serial output queue using Serial.print() */
-void checkDigitalInputs(void)
+void checkDigitalInputs(boolean forceSend = false)
 {
   /* Using non-looping code allows constants to be given to readPort().
    * The compiler will apply substantial optimizations if the inputs
@@ -163,7 +166,7 @@
      // Serial.print("Reporting on port "); Serial.print(i); Serial.print(" mask 0x"); Serial.println(portConfigInputs[i], HEX);
       uint8_t x = readPort(i, portConfigInputs[i]);
      // Serial.print("Read 0x"); Serial.println(x, HEX);
-      outputPort(i, x, false);
+      outputPort(i, x, forceSend);
     }
   }
 }
@@ -174,7 +177,7 @@
  */
 void setPinModeCallback(byte pin, int mode)
 {
-  if (pinConfig[pin] == I2C && isI2CEnabled && mode != I2C) {
+  if ((pinConfig[pin] == I2C) && (isI2CEnabled) && (mode != I2C)) {
     // disable i2c so pins can be used for other functions
     // the following if statements should reconfigure the pins properly
     disableI2CPins();
@@ -204,7 +207,7 @@
         digitalWrite(PIN_TO_DIGITAL(pin), LOW); // disable internal pull-ups
       }
       pinConfig[pin] = ANALOG;
-      lastAnalogReads[pin] = -1;
+      lastAnalogReads[PIN_TO_ANALOG(pin)] = -1;
     }
     break;
   case INPUT:
@@ -218,6 +221,9 @@
       }
       pinConfig[pin] = INPUT;

+      // force sending state immediately
+      //delay(10);
+      //checkDigitalInputs(true);
     }
     break;
   case OUTPUT:
@@ -318,7 +324,7 @@
       analogInputsToReport = analogInputsToReport &~ (1 << analogPin);
       Serial.print(F("Stop reporting analog pin #")); Serial.println(analogPin);
     } else {
-      analogInputsToReport = analogInputsToReport | (1 << analogPin);
+      analogInputsToReport |= (1 << analogPin);
       Serial.print(F("Will report analog pin #")); Serial.println(analogPin);
     }
   }
@@ -603,39 +609,19 @@
 }

-aci_evt_opcode_t laststatus, status;
+aci_evt_opcode_t lastBTLEstatus, BTLEstatus;

 void setup()
 {
   Serial.begin(9600);
-  Serial.println("BTLE Firmata test");
+  Serial.println(F("Adafruit BTLE Firmata test"));

   BLEserial.begin();

-  status = laststatus = ACI_EVT_DISCONNECTED;
-  while (status != ACI_EVT_CONNECTED) {
-    BLEserial.pollACI();
-
-    // Ask what is our current status
-    aci_evt_opcode_t status = BLEserial.getState();
-    // If the status changed....
-    if (status != laststatus) {
-      // print it out!
-      if (status == ACI_EVT_DEVICE_STARTED) {
-          Serial.println(F("* Advertising started"));
-      }
-      if (status == ACI_EVT_CONNECTED) {
-          Serial.println(F("* Connected!"));
-          break;
-      }
-      if (status == ACI_EVT_DISCONNECTED) {
-          Serial.println(F("* Disconnected or advertising timed out"));
-      }
-      // OK set the last status change to this one
-      laststatus = status;
-    }
-  }
-
+  BTLEstatus = lastBTLEstatus = ACI_EVT_DISCONNECTED;
+}
+
+void firmataInit() {
   Serial.println(F("Init firmata"));
   //BLE_Firmata.setFirmwareVersion(FIRMATA_MAJOR_VERSION, FIRMATA_MINOR_VERSION);
   //Serial.println(F("firmata analog"));
@@ -653,41 +639,56 @@
   //Serial.println(F("firmata reset"));
   BLE_Firmata.attach(SYSTEM_RESET, systemResetCallback);

-  Serial.println("Begin firmata");
+  Serial.println(F("Begin firmata"));
   BLE_Firmata.begin();
-  systemResetCallback();  // reset to default config
-
-
-}
-
+  systemResetCallback();  // reset to default config
+}
 /*==============================================================================
  * LOOP()
  *============================================================================*/
+
 void loop()
 {
+  // Check the BTLE link, how're we doing?
   BLEserial.pollACI();
-  if (BLEserial.getState() != ACI_EVT_CONNECTED) {
-      Serial.print("!");
-      delay(100);
-      return;
-  }
-
+  // Link status check
+  BTLEstatus = BLEserial.getState();
+
+  // Check if something has changed
+  if (BTLEstatus != lastBTLEstatus) {
+    // print it out!
+    if (BTLEstatus == ACI_EVT_DEVICE_STARTED) {
+        Serial.println(F("* Advertising started"));
+    }
+    if (BTLEstatus == ACI_EVT_CONNECTED) {
+        Serial.println(F("* Connected!"));
+        // initialize Firmata cleanly
+         firmataInit();
+    }
+    if (BTLEstatus == ACI_EVT_DISCONNECTED) {
+        Serial.println(F("* Disconnected or advertising timed out"));
+    }
+    // OK set the last status change to this one
+    lastBTLEstatus = BTLEstatus;
+  }
+
+  // if not connected... bail
+  if (BTLEstatus != ACI_EVT_CONNECTED) {
+    delay(100);
+    return;
+  }
+
+  // For debugging, see if there's data on the serial console, we would forwad it to BTLE
   if (Serial.available()) {
     BLEserial.write(Serial.read());
-
-  }
+  }
+
+  // Onto the Firmata main loop
+
   byte pin, analogPin;
-
-
-// **DEBUG ***
-/*
-  for (uint8_t p=0; p<3; p++) {
-    Serial.print(F("\tport[")); Serial.print(p); Serial.print("] = 0x"); Serial.println(portConfigInputs[p], HEX);
-  }
-*/

   /* DIGITALREAD - as fast as possible, check for changes and output them to the
-   * FTDI buffer using Serial.print()  */
+   * BTLE buffer using Serial.print()  */
   checkDigitalInputs();

   /* SERIALREAD - processing incoming messagse as soon as possible, while still
@@ -700,16 +701,29 @@
    * 60 bytes. use a timer to sending an event character every 4 ms to
    * trigger the buffer to dump. */

+  // make the sampling interval longer if we have more analog inputs!
+  uint8_t analogreportnums = 0;
+  for(uint8_t a=0; a<8; a++) {
+    if (analogInputsToReport & (1 << a)) {
+      analogreportnums++;
+    }
+  }
+
+  samplingInterval = (uint16_t)MINIMUM_SAMPLE_DELAY  + (uint16_t)ANALOG_SAMPLE_DELAY * (1+analogreportnums);
+
   currentMillis = millis();
   if (currentMillis - previousMillis > samplingInterval) {
     previousMillis += samplingInterval;
     /* ANALOGREAD - do all analogReads() at the configured sampling interval */
     for(pin=0; pin<TOTAL_PINS; pin++) {
-      if (IS_PIN_ANALOG(pin) && pinConfig[pin] == ANALOG) {
+      if (IS_PIN_ANALOG(pin) && (pinConfig[pin] == ANALOG)) {
         analogPin = PIN_TO_ANALOG(pin);
+
         if (analogInputsToReport & (1 << analogPin)) {
           int currentRead = analogRead(analogPin);
+
           if ((lastAnalogReads[analogPin] == -1) || (lastAnalogReads[analogPin] != currentRead)) {
+            Serial.print(F("Analog")); Serial.print(analogPin); Serial.print(F(" = ")); Serial.println(currentRead);
             BLE_Firmata.sendAnalog(analogPin, currentRead);
             lastAnalogReads[analogPin] = currentRead;
           }


Feed smoothed input to calibration. Add comments on the individual top-level parameters

--- gas.ino
+++ gas.ino
@@ -6,10 +6,21 @@
 #include <LiquidCrystal.h>
 #include <EEPROM.h>

+// Pin analogico de entrada donde va conectado el gas.
 #define GAS_INPUT A0
+
+// Pin digital de entrada donde va conectado el boton de calibracion.
 #define CALIBRATE_BUTTON 2
+
+// Duracion de la calibracion en segundos.
 #define CALIBRATION_DURATION 10 // seconds
-#define SMOOTHING_FACTOR 0.9
+
+// Valor entre 0 y 1 que suaviza la senyal de gas de entrada.
+// 0 -> suavizado maximo.
+// 1 -> sin suavizado.
+// 0 < x < 1 -> suavizado intermedio.
+#define SMOOTHING_FACTOR 0.3
+
 #define STATE_HEADER 0xcafebabe

 void read_state (CalibratedInput& calibrated_input)
@@ -47,16 +58,10 @@
   print2(lcd, calibration.time_remaining(t));
 }

-void process_input (int input, CalibratedInput& calibrated_input, Smoothed& smoothed_input, LiquidCrystal& lcd)
-{
-  // Map the input to a calibrated range of values.
-  input = calibrated_input(input);
-
-  // Smoothing the input to avoid flickering in the lcd.
-  int smooth_input = int(smoothed_input(input));
-
+void render_input (int input, LiquidCrystal& lcd)
+{
   lcd.setCursor(6,0);
-  print3(lcd, smooth_input);
+  print3(lcd, input);
 }

 LiquidCrystal lcd(7, 6, 8, 9, 10, 11);
@@ -81,16 +86,19 @@
 {
   unsigned long t = millis();
   int calibrate_button = digitalRead(CALIBRATE_BUTTON);
-  int input = read_3v3(GAS_INPUT);
-
+
+  // Smoothing the signal to prevent flickering.
+  int raw_gas = int(smoothed_input(read_3v3(GAS_INPUT)));
+
+  // Calibration.
   if (calibrate_button == HIGH && calibration.state() == Calibration::Idle)
   {
-    calibration.start(t, CALIBRATION_DURATION, input);
+    calibration.start(t, CALIBRATION_DURATION, raw_gas);
   }

   if (calibration.state() == Calibration::Running)
   {
-    calibration.update(t, input, calibrated_input);
+    calibration.update(t, raw_gas, calibrated_input);
     render_calibration(t, lcd, calibration);

     if (calibration.state() == Calibration::Idle) // calibration is done
@@ -99,6 +107,8 @@
       write_state(calibrated_input);
     }
   }
-
-  process_input(input, calibrated_input, smoothed_input, lcd);
+
+  // Output.
+  int calibrated_gas = calibrated_input(raw_gas);
+  render_input(calibrated_gas, lcd);
 }


From prototype 2 beta: processing

From prototype 2 beta: processing

- Remove useless comments
- sincro serial speed with processing

--- Arduino/retouch_accelero.ino
+++ Arduino/retouch_accelero.ino
@@ -24,11 +24,9 @@

 void setup(){

-  Serial.begin(2400);
+  Serial.begin(800);
   xl.begin(10);                   // Setup SPI protocol, issue device soft reset
   xl.beginMeasure();              // Switch ADXL362 to measure mode
-
-  Serial.println("ReAudioguide touch + accelero: test dei sensori");
 }

 void loop(){
@@ -37,15 +35,13 @@

    if(sensorValue2 > threshold){
      if(traccia != 2){
-       Serial.write(2); //Basso,
-       //Serial.print("\n Traccia Ordine basso ");
+       Serial.write(2); //Play the second track: Ordine basso della facciata,
        traccia = 2;
      }
   }
   if(sensorValue > threshold) {
     if(traccia != 1){
-     Serial.write(1); //Piazza,
-     //Serial.print("\n Traccia Piazza ");
+     Serial.write(1); //Play the first track: Piazza,
      traccia = 1;
     }
   }
@@ -53,31 +49,27 @@

   if(XValue > 1100 || XValue < -1100) {
     if(statoplay != 8){
-      Serial.write(8); //Pausa,
-      //Serial.print("\n PAUSA ");
-      statoplay = 8; // ex statoplay
+      Serial.write(8); //Pause mode,
+      statoplay = 8;
       traccia = 0;
     }
   }else{
      if((statoplay != 9)&&(XValue < 600 && XValue > -600)){
-       Serial.write(9); //Play,
-       //Serial.print("\n PLAY ");
-       statoplay=9; // ex statoplay
+       Serial.write(9); //Play mode,
+       statoplay=9; //
        traccia = 0;
      }
   }
   if(YValue > 500) {
     if(YValue > 1200) {
       if(stato != 12){
-         Serial.write(12); //Rewind,
-         //Serial.print("\n REWIND ");
+         Serial.write(12); //Rewind the track,
          stato=12;
       }
     }else{
       if(stato == 12){
         if(YValue < 700) {
-          Serial.write(9); //Play,
-          //Serial.print("\n PLAY ");
+          Serial.write(9); //return in play mode,
           stato=0;
         }
       }
@@ -86,15 +78,13 @@
   if(YValue < -500) {
     if(YValue < -1200) {
       if(stato != 22){
-         Serial.write(22); //Foward,
-         //Serial.print("\n FOWARD ");
+         Serial.write(22); //Foward the track,
          stato=22;
       }
     }else{
       if(stato == 22){
         if(YValue > -700) {
-          Serial.write(9); //Play,
-          //Serial.print("\n PLAY ");
+          Serial.write(9); //return in play mode,
           stato=0;
         }
       }


Updated sensors.ino

Updated sensors.ino

- deleted test function print

--- software/sensors/sensors.ino
+++ software/sensors/sensors.ino
@@ -159,140 +159,136 @@
   delay(2000);
 }

-void loop(){
-    // DISPLAY data
-  Serial.print("Hello \r\n");
-}
-//// BEGIN LOOP
-//void loop() {
-//
-//  // SOIL MOISTURE
-//  digitalWrite(SoilVccPin, HIGH);   // enable sensor
-//  delay(50);  // allow power to settle
-//  unsigned int SoilMoisture = 1023 - (analogRead(SoilMoisturePin)); // read analog voltage then negate so that open circuit -> 0, short circtuit -> 1023
-//  digitalWrite(SoilVccPin, LOW);   // disable sensor
-//
-//
-//  // RGB PHOTOSENSOR
-//  // Read sensor values (16 bit integers)
-//  unsigned int red = RGB_sensor.readRed();
-//  unsigned int green = RGB_sensor.readGreen();
-//  unsigned int blue = RGB_sensor.readBlue();
-//
-//
-//  // SOIL TEMPPERATURE
-//  sensors.requestTemperatures(); // Send the command to get temperatures
-//  signed char SoilTemp = sensors.getTempC(soilThermometer);
-//
-//
-//  // DHT AIR T/RH SENSOR
-//  int chk = DHT.read11(DHT11_PIN);
-//  switch (chk)
-//  {
-//    case DHTLIB_OK:
-//      //               Serial.print("OK,\t");
-//      break;
-//    case DHTLIB_ERROR_CHECKSUM:
-//      Serial.print("Checksum error,\t");
-//      break;
-//    case DHTLIB_ERROR_TIMEOUT:
-//      Serial.print("Time out error,\t");
-//      break;
-//    case DHTLIB_ERROR_CONNECT:
-//      Serial.print("Connect error,\t");
-//      break;
-//    case DHTLIB_ERROR_ACK_L:
-//      Serial.print("Ack Low error,\t");
-//      break;
-//    case DHTLIB_ERROR_ACK_H:
-//      Serial.print("Ack High error,\t");
-//      break;
-//    default:
-//      Serial.print("Unknown error,\t");
-//      break;
-//  }
-//  // display data
-//  signed char AirTemp = DHT.temperature;
-//  unsigned char AirHumidity = DHT.humidity;
-//
-//
-//  //IR PHOTOSENSOR
-//  digitalWrite(IRVccPin, HIGH);   // enable sensor
-//  int photoIR = analogRead(IRPin); // read IR level
-//  digitalWrite(IRVccPin, LOW);   // disable sensor
-//
-//
-//  // construct message
-//  unsigned char msg[13];
-//  msg[0] = (SoilMoisture >> 8) & 0xFF;
-//  msg[1] = SoilMoisture & 0xFF;
-//  msg[2] = (red >> 8) & 0xFF;
-//  msg[3] = red & 0xFF;
-//  msg[4] = (green >> 8) & 0xFF;
-//  msg[5] = green & 0xFF;
-//  msg[6] = (blue >> 8) & 0xFF;
-//  msg[7] = blue & 0xFF;
-//  msg[8] = SoilTemp & 0xFF;
-//  msg[9] = AirTemp & 0xFF;
-//  msg[10] = AirHumidity & 0xFF;
-//  msg[11] = (photoIR >> 8) & 0xFF;
-//  msg[12] = photoIR & 0xFF;
-//
-//  // display msg
-//  /*
-//  for (int i=0; i<sizeof(msg); i++)
-//  {
-//    Serial.print(msg[i], HEX);
-//    Serial.print(", ");
-//  }
-//  Serial.println();
-//*/
-//
-//  // DISPLAY data
-//  Serial.print(SoilMoisture, DEC); // soil moisture level
-//  Serial.print(", ");
-//  Serial.print(red, DEC); // RGB: RED
-//  Serial.print(", ");
-//  Serial.print(green, DEC); // RGB: GREEN
-//  Serial.print(", ");
-//  Serial.print(blue, DEC); // RGB: BLUE
-//  Serial.print(", ");
-//  Serial.print(SoilTemp, DEC);  // soil temperature
-//  Serial.print(", ");
-//  Serial.print(AirTemp, DEC); // Air temperature
-//  Serial.print(", ");
-//  Serial.print(AirHumidity, DEC); // Air Humidity
-//  Serial.print(", ");
-//  Serial.print(photoIR);  // IR level
-//
-//
-//  // finish
-//  Serial.println();
-//  delay(2000);
-//
-//
-//}
-//
-//// FUNCTION DEFINTIONS
-//
-//// soil temperature function to print the temperature for a device
-//void printTemperature(DeviceAddress deviceAddress)
-//{
-//  // method 1 - slower
-//  //Serial.print("Temp C: ");
-//  //Serial.print(sensors.getTempC(deviceAddress));
-//  //Serial.print(" Temp F: ");
-//  //Serial.print(sensors.getTempF(deviceAddress)); // Makes a second call to getTempC and then converts to Fahrenheit
-//
-//  // method 2 - faster
-//  float tempC = sensors.getTempC(deviceAddress);
-//  Serial.print(tempC);
-//  Serial.print(", ");
-//  //  Serial.print(" Temp F: ");
-//  //  Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
-//}
-//
-//// function to print a device address of soil temperature sensor
+// BEGIN LOOP
+void loop() {
+
+  // SOIL MOISTURE
+  digitalWrite(SoilVccPin, HIGH);   // enable sensor
+  delay(50);  // allow power to settle
+  unsigned int SoilMoisture = 1023 - (analogRead(SoilMoisturePin)); // read analog voltage then negate so that open circuit -> 0, short circtuit -> 1023
+  digitalWrite(SoilVccPin, LOW);   // disable sensor
+
+
+  // RGB PHOTOSENSOR
+  // Read sensor values (16 bit integers)
+  unsigned int red = RGB_sensor.readRed();
+  unsigned int green = RGB_sensor.readGreen();
+  unsigned int blue = RGB_sensor.readBlue();
+
+
+  // SOIL TEMPPERATURE
+  sensors.requestTemperatures(); // Send the command to get temperatures
+  signed char SoilTemp = sensors.getTempC(soilThermometer);
+
+
+  // DHT AIR T/RH SENSOR
+  int chk = DHT.read11(DHT11_PIN);
+  switch (chk)
+  {
+    case DHTLIB_OK:
+      //               Serial.print("OK,\t");
+      break;
+    case DHTLIB_ERROR_CHECKSUM:
+      Serial.print("Checksum error,\t");
+      break;
+    case DHTLIB_ERROR_TIMEOUT:
+      Serial.print("Time out error,\t");
+      break;
+    case DHTLIB_ERROR_CONNECT:
+      Serial.print("Connect error,\t");
+      break;
+    case DHTLIB_ERROR_ACK_L:
+      Serial.print("Ack Low error,\t");
+      break;
+    case DHTLIB_ERROR_ACK_H:
+      Serial.print("Ack High error,\t");
+      break;
+    default:
+      Serial.print("Unknown error,\t");
+      break;
+  }
+  // display data
+  signed char AirTemp = DHT.temperature;
+  unsigned char AirHumidity = DHT.humidity;
+
+
+  //IR PHOTOSENSOR
+  digitalWrite(IRVccPin, HIGH);   // enable sensor
+  int photoIR = analogRead(IRPin); // read IR level
+  digitalWrite(IRVccPin, LOW);   // disable sensor
+
+
+  // construct message
+  unsigned char msg[13];
+  msg[0] = (SoilMoisture >> 8) & 0xFF;
+  msg[1] = SoilMoisture & 0xFF;
+  msg[2] = (red >> 8) & 0xFF;
+  msg[3] = red & 0xFF;
+  msg[4] = (green >> 8) & 0xFF;
+  msg[5] = green & 0xFF;
+  msg[6] = (blue >> 8) & 0xFF;
+  msg[7] = blue & 0xFF;
+  msg[8] = SoilTemp & 0xFF;
+  msg[9] = AirTemp & 0xFF;
+  msg[10] = AirHumidity & 0xFF;
+  msg[11] = (photoIR >> 8) & 0xFF;
+  msg[12] = photoIR & 0xFF;
+
+  // display msg
+  /*
+  for (int i=0; i<sizeof(msg); i++)
+  {
+    Serial.print(msg[i], HEX);
+    Serial.print(", ");
+  }
+  Serial.println();
+*/
+
+  // DISPLAY data
+  Serial.print(SoilMoisture, DEC); // soil moisture level
+  Serial.print(", ");
+  Serial.print(red, DEC); // RGB: RED
+  Serial.print(", ");
+  Serial.print(green, DEC); // RGB: GREEN
+  Serial.print(", ");
+  Serial.print(blue, DEC); // RGB: BLUE
+  Serial.print(", ");
+  Serial.print(SoilTemp, DEC);  // soil temperature
+  Serial.print(", ");
+  Serial.print(AirTemp, DEC); // Air temperature
+  Serial.print(", ");
+  Serial.print(AirHumidity, DEC); // Air Humidity
+  Serial.print(", ");
+  Serial.print(photoIR);  // IR level
+
+
+  // finish
+  Serial.println();
+  delay(2000);
+
+
+}
+
+// FUNCTION DEFINTIONS
+
+// soil temperature function to print the temperature for a device
+void printTemperature(DeviceAddress deviceAddress)
+{
+  // method 1 - slower
+  //Serial.print("Temp C: ");
+  //Serial.print(sensors.getTempC(deviceAddress));
+  //Serial.print(" Temp F: ");
+  //Serial.print(sensors.getTempF(deviceAddress)); // Makes a second call to getTempC and then converts to Fahrenheit
+
+  // method 2 - faster
+  float tempC = sensors.getTempC(deviceAddress);
+  Serial.print(tempC);
+  Serial.print(", ");
+  //  Serial.print(" Temp F: ");
+  //  Serial.println(DallasTemperature::toFahrenheit(tempC)); // Converts tempC to Fahrenheit
+}
+
+// function to print a device address of soil temperature sensor
 void printAddress(DeviceAddress deviceAddress)
 {
   for (uint8_t i = 0; i < 8; i++)


Fixed size benchmark after refactoring of MQTT and ThingSpeak.

--- examples/Benchmarks/CosaBenchmarkSizeOf/CosaBenchmarkSizeOf.ino
+++ examples/Benchmarks/CosaBenchmarkSizeOf/CosaBenchmarkSizeOf.ino
@@ -62,8 +62,6 @@
 #include "Cosa/IOStream/Driver/RS485.hh"
 #include "Cosa/IOStream/Driver/UART.hh"
 #include "Cosa/IOStream/Driver/WIO.hh"
-#include "Cosa/IoT/MQTT.hh"
-#include "Cosa/IoT/ThingSpeak.hh"
 #include "Cosa/Interrupt.hh"
 #include "Cosa/Keypad.hh"
 #include "Cosa/LCD.hh"
@@ -161,10 +159,6 @@
   TRACE(sizeof(DNS));
   TRACE(sizeof(HTTP::Client));
   TRACE(sizeof(HTTP::Server));
-  TRACE(sizeof(MQTT::Client));
-  TRACE(sizeof(ThingSpeak::Client));
-  TRACE(sizeof(ThingSpeak::Channel));
-  TRACE(sizeof(ThingSpeak::TalkBack));
   TRACE(sizeof(NTP));
   TRACE(sizeof(SNMP));
   TRACE(sizeof(SNMP::MIB));


Terminate the chunked printDirectory (#6808)

Fixes #2481

Send a 0-len chunk when the directory is completed (in a chunked HTTP
transfer) to terminate the HTTP transfer properly.

--- libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
+++ libraries/ESP8266WebServer/examples/SDWebServer/SDWebServer.ino
@@ -241,6 +241,7 @@
     entry.close();
   }
   server.sendContent("]");
+  server.sendContent(""); // Terminate the HTTP chunked transmission with a 0-length chunk
   dir.close();
 }


Test out some wave files

Test out some wave files

--- EmotionalClothing.ino
+++ EmotionalClothing.ino
@@ -1,6 +1,7 @@
 #include <WaveHC.h>
 #include <WaveUtil.h>

+String fileNames[4] = {"BUGS2.WAV", "DAFFY1.WAV", "BUGS1.WAV", "DAFFY2.WAV"};

 SdReader card;    // This object holds the information for the card
 FatVolume vol;    // This holds the information for the partition on the card
@@ -32,5 +33,16 @@
 }

 void loop() {
+  root.rewind();
+  FatReader file;

+  for (int i = 0; i < 4; i++) {
+    char fileName[fileNames[i].length() + 1];
+    fileNames[i].toCharArray(fileName, fileNames[i].length() + 1);
+
+    file.open(root, fileName);
+    wave.create(file);
+    wave.play();
+    while (wave.isplaying) delay(100);
+  }
 }


Fix #406

Fix #406

--- examples/Boards_WiFi/Arduino_org_UNO_WiFi/Arduino_org_UNO_WiFi.ino
+++ examples/Boards_WiFi/Arduino_org_UNO_WiFi/Arduino_org_UNO_WiFi.ino
@@ -32,7 +32,6 @@
 #define BLYNK_PRINT Serial

-#include <SPI.h>
 #include <WiFiLink.h>
 #include <BlynkSimpleWiFiLink.h>


Add files via upload

Add files via upload

Changed the Base to use elapsedTime instead of millis(). ElapsedTime handles millis() overflow, so the led blinking stuff will still work after >42 days of continuous usage.

--- simu_buttonreader_teensy_base/simu_buttonreader_teensy_base.ino
+++ simu_buttonreader_teensy_base/simu_buttonreader_teensy_base.ino
@@ -17,7 +17,7 @@

 // define led brighness here in percentage
 #define LED_BRIGHTNESS 5
-// for 82-100 ohm series resistor and small 3mm red/green through-hole
+// for 82-120 ohm series resistor and small 3mm red/green through-hole
 // led, 5 % seems fine.
 #define ledOutputValue 255*LED_BRIGHTNESS/100

@@ -31,11 +31,11 @@

 long const int WaitIndicationInterval = 200;
-unsigned long int lastWaitIndicationUpdate = 0;
+elapsedMillis lastWaitIndicationUpdate;

 long const int WaitBatteryInterval = 1000;
-unsigned long int lastBatteryIndicationUpdate = 0;
+elapsedMillis lastBatteryIndicationUpdate;

 void setup() {

@@ -45,7 +45,7 @@
   pinMode(connectionLed, OUTPUT);

   // wake-up blinking
-
+
   digitalWriteFast(connectionLed, HIGH);
   digitalWriteFast(batteryLed, HIGH);
   delay(1000);
@@ -74,8 +74,9 @@
   Serial1.flush(); // flush twice to make sure

   // reset these to known value
-  lastWaitIndicationUpdate = millis();
-  lastBatteryIndicationUpdate = millis();
+  // not needed using elapsedMillis.
+  // lastWaitIndicationUpdate = millis();
+  // lastBatteryIndicationUpdate = millis();
 }

 void loop() {
@@ -131,8 +132,8 @@
 }

 void runWaitBtIndication() {
-  if (millis() > (lastWaitIndicationUpdate + WaitIndicationInterval)) {
-    lastWaitIndicationUpdate = millis();
+  if (lastWaitIndicationUpdate > WaitIndicationInterval) {
+    lastWaitIndicationUpdate = 0;
     if(connectionLedStatus) {
       analogWrite(connectionLed, ledOutputValue);
     } else{
@@ -143,7 +144,9 @@
 }

 void runBatteryIndication() {
-  // blink status led at known interval when battery is low.
+  if(lastBatteryIndicationUpdate > WaitBatteryInterval) {
+    lastBatteryIndicationUpdate = 0;
+    // blink status led at known interval when battery is low.
     if (batteryLow) {
       if(batteryLedStatus) {
         analogWrite(batteryLed, ledOutputValue);
@@ -151,9 +154,10 @@
         analogWrite(batteryLed, 0);
       }
       batteryLedStatus = !batteryLedStatus;
-  } else {
+    } else {
     //make sure it does not stay on!
     analogWrite(batteryLed, 0);
+    }
   }
 }