BabelFish: Fixes for Arduino and low memory of ATtiny85

TODO: Fix Ctrl-F1 on ATtiny85

--- Utils/BabelFish/BabelFish.ino
+++ Utils/BabelFish/BabelFish.ino
@@ -27,7 +27,8 @@
 // 3. Forward text from USB to Gigatron as keystrokes
 //    For example to get a long BASIC program loaded into BASIC
 // 4. Controlling the Gigatron over USB from a PC/laptop
-// 5. Pass through of game controller signals
+// 5. Passing through of game controller signals
+// 6. TODO: Receive data from Gigatron and store it
 //
 // Select one of the supported platforms in the Tools->Board menu.
 //
@@ -245,7 +246,7 @@
   #include "tetris.h"
 };

-struct { byte *gt1; char *name; } gt1Files[] = {
+const struct { byte *gt1; char *name; } gt1Files[] = {
   { TinyBASIC_gt1, "Tiny BASIC"               }, // 2702 bytes
   { WozMon_gt1,    "WozMon"                   }, // 595 bytes
 #if maxStorage >= 10000
@@ -336,8 +337,8 @@
   // Open upstream communication
   #if hasSerial
     Serial.begin(115200);
-  #endif
-  doVersion();
+    doVersion();
+  #endif

   // In case we power on together with the Gigatron, this is a
   // good pause to wait for the video loop to have started
@@ -354,10 +355,47 @@
  */
 void loop()
 {
+  // Gigatron vPulse
+  static byte oldValue = 0;
+  critical();
+  byte newValue = receiveBits();
+  nonCritical();
+  if (newValue != oldValue) {
+    #if hasSerial
+      Serial.print(": Got ");
+      Serial.println(newValue);
+    #endif
+    oldValue = newValue;
+  }
+
   // Controller pass through
   #if gameControllerDataPin >= 0
     digitalWrite(gigatronDataPin, digitalRead(gameControllerDataPin));
   #endif
+
+  // PS/2 keyboard events
+  delay(15);                           // Allow PS/2 interrupts for a reasonable window
+  byte key = keyboard_getState();
+  if (key != 255) {
+    byte f = fnKey(key ^ 64);          // Ctrl + function key?
+    if (f) {
+      if (f == 1)
+        doMapping();                   // Ctrl-F1 is help
+      else if (f-2 < arrayLen(gt1Files))
+        doTransfer(gt1Files[f-2].gt1); // Send built-in GT1 file to Gigatron
+    }
+    for (;;) {                         // Focus all attention on PS/2 until state is idle again
+      if (!fnKey(key ^ 64)) {
+        critical();
+        sendFirstByte(key);            // Synchronize with vPulse and send code
+        nonCritical();
+      }
+      if (key == 255)                  // Break after emitting idle state
+        break;
+      delay(15);                       // Allow PS/2 interrupts for a reasonable window
+      key = keyboard_getState();       // This typically returns the same key for a couple of frames
+    }
+  }

   // Commands from upstream USB (PC/laptop)
   #if hasSerial
@@ -376,42 +414,6 @@
       }
     }
   #endif
-
-  // PS/2 keyboard events
-  byte key = keyboard_getState();
-  if (key != 255) {
-    byte f = fnKey(key^64);          // Ctrl + function key?
-    if (f) {
-      if (f == 1)                    // Ctrl-F1 is help
-        doMapping();
-      else if (f-2 < arrayLen(gt1Files))
-        doTransfer(gt1Files[f-2].gt1);// Send built-in GT1 file to Gigatron
-    }
-
-    while (1) {                      // Send to Gigatron until keyboard driver idle
-      critical();
-      sendFirstByte(key);            // Synchronize with vPulse and send code
-      nonCritical();
-
-      if (key == 255)                // Until state is idle again
-        break;
-      delay(15);                     // Allow PS/2 interrupts for a reasonable window
-      key = keyboard_getState();
-    }
-  }
-
-  static byte oldValue = 0;
-  delay(15);                         // Allow PS/2 interrupts for a reasonable window
-  critical();
-  byte newValue = receiveBits();
-  nonCritical();
-  if (newValue != oldValue) {
-    #if hasSerial
-      Serial.print(": Got ");
-      Serial.println(newValue);
-    #endif
-    oldValue = newValue;
-  }
 }

 void prompt()
@@ -505,7 +507,7 @@
     Serial.print(" savedFile=");
     Serial.println(savedFileLength());
     Serial.println(":PROGMEM slots:");
-    for (int i=0; i<arrayLen(gt1Files); i++) {
+    for (byte i=0; i<arrayLen(gt1Files); i++) {
       Serial.print(": P");
       Serial.print(i);
       Serial.print(") ");
@@ -523,7 +525,7 @@
   char text[] = "Ctrl-F1  This help";
   pos = renderLine(pos, text);
   text[9] = 0;
-  for (int i=0; i<arrayLen(gt1Files); i++) {
+  for (byte i=0; i<arrayLen(gt1Files); i++) {
     byte f = i + 2;
     // To save space avoid itoa() or sprintf()
     text[6]      = '0' + f / 10;
@@ -536,7 +538,7 @@
   pos = renderString(pos, getKeymapName());
   pos = renderLine(pos, " (Change with Ctrl-Alt-Fxx)");
   pos = renderString(pos, "Available:");
-  for (int i=0; i<nrKeymaps; i++) {
+  for (byte i=0; i<nrKeymaps; i++) {
     pos = renderString(pos, " ");
     pos = renderString(pos, getKeymapName(i));
   }
@@ -592,7 +594,7 @@
     Serial.flush();
   #endif

-  for (int i=0; i<10; i++) {
+  for (byte i=0; i<10; i++) {
     sendController(~buttonDown, 2);
     delay(50);
   }
@@ -607,7 +609,7 @@
 void doLine(char *line)
 {
   // Pass through the line of text
-  for (int i=0; line[i]; i++) {
+  for (byte i=0; line[i]; i++) {
     sendController(line[i], 1);
     delay(20); // Allow Gigatron software to process key code
   }
@@ -664,44 +666,55 @@
 word renderLine(word pos, char *text)
 {
   pos = renderString(pos, text);
-  return (pos & 0xff00) + 0x600;
+  return (pos & 0xff00) + 0x600; // Goes to new line
 }

 // Render string in Loader screen
 word renderString(word pos, char *text)
 {
-  byte bitmap[160], pixelLine[160], x=0;
-
-  // Render line of text in bitmap
-  for (; *text; text++) {
-
-    // Get pixel data for character
-    int pixels = pgm_read_word(&tinyfont[*text-32]);
-
-    // Render character in bitmap
-    if (pixels >= 0) {
-      bitmap[x++] = 0;                   // Regular position
-      bitmap[x++] = (pixels >> 9)  & 62;
-      bitmap[x++] = (pixels >> 4)  & 62;
-      bitmap[x++] = (pixels << 1)  & 62;
-    } else {
-      bitmap[x++] = 0;                   // Shift down for g, j, p, q, y
-      bitmap[x++] = (pixels >> 10) & 31;
-      bitmap[x++] = (pixels >> 5)  & 31;
-      bitmap[x++] =  pixels        & 31;
-      if (*text == 'j')                  // Special case to dot the j
-        bitmap[x-1] = '.';
+  // Send 6 pixel lines to Gigatron
+  // The ATtiny85 doesn't have sufficient RAM for separate bitmap[] and
+  // pixelLine[] arrays. Therefore the rendering must be redone with each
+  // iteration, followed by an in-place conversion to pixel colors
+
+  byte buf[160];
+  byte *p = pos;
+  byte x;
+  for (byte b=32; b; b>>=1) {
+
+    // (Re-)render line of text in bitmap
+    x = 0;
+    for (byte i=0; text[i]!=0; i++) {
+
+      // Get pixel data for character
+      int pixels = pgm_read_word(&tinyfont[text[i]-32]);
+
+      // Render character in bitmap
+      if (pixels >= 0) {
+        buf[x++] = 0;                   // Regular position
+        buf[x++] = (pixels >> 9)  & 62;
+        buf[x++] = (pixels >> 4)  & 62;
+        buf[x++] = (pixels << 1)  & 62;
+      } else {
+        buf[x++] = 0;                   // Shift down for g, j, p, q, y
+        buf[x++] = (pixels >> 10) & 31;
+        buf[x++] = (pixels >> 5)  & 31;
+        buf[x++] =  pixels        & 31;
+        if (text[i] == 'j')             // Special case to dot the j
+          buf[x-1] = '.';
+      }
     }
-  }
-
-  // Send pixel lines to Gigatron
-  byte *p = pos;
-  for (int b=32; b; b>>=1) {
+
+    // Convert bitmap to pixels
     const byte bgColor = 32; // Blue
     const byte fgColor = 63; // White
-    for (int i=0; i<x; i++)
-      pixelLine[i] = bitmap[i] & b ? fgColor : bgColor;
-    sendGt1Segment(p, x, pixelLine);
+    for (byte i=0; i<x; i++)
+      buf[i] = buf[i] & b ? fgColor : bgColor;
+
+    // Send line of pixels to Gigatron
+    sendGt1Segment(p, x, buf);
+
+    // To next scanline
     p += 256;
   }

@@ -728,24 +741,24 @@
 #endif

   #if hasSerial
-    #define readNext() {\
-      nextByte = gt1 ? pgm_read_byte(gt1++) : nextSerial();\
-      if (nextByte < 0) return;\
-    }
+    #define readNext()\
+      if (gt1)\
+        nextByte = pgm_read_byte(gt1++);\
+      else {\
+        nextByte = nextSerial();\
+        if (nextByte < 0) return;\
+      }
     #define ask(n)\
       if (!gt1) {\
         Serial.print(n);\
         Serial.println("?");\
       }
   #else
-    #define readNext() {\
-      nextByte = pgm_read_byte(gt1++);\
-      if (nextByte < 0) return;\
-    }
+    #define readNext() (nextByte = pgm_read_byte(gt1++))
     #define ask(n)
   #endif

-  byte segment[300] = {0}; // Multiple of N for padding
+  byte segment[256] = {0}; // sendFrame() will read up to index 299 but that's ok

   ask(3);
   readNext();


[Task 18988] editing comments, then pulling to begin major overhaul

--- sketchbook/LCDemoMatrix_edited/LCDemoMatrix_edited.ino
+++ sketchbook/LCDemoMatrix_edited/LCDemoMatrix_edited.ino
@@ -6,6 +6,7 @@
 #include <Ethernet.h>
 #define SS_SD_CARD   4
 #define SS_ETHERNET 10
+
 //String HTTP_req;//     // stores the HTTP request
 // MAC address from Ethernet shield sticker under board
 byte mac[] = { 0x00, 0x1D, 0xFE, 0xEA, 0x39, 0x17 };
@@ -17,10 +18,10 @@
 /*
  Now we need a LedControl to work with.
  ***** These pin numbers will probably not work with your hardware *****
- pin 12 is connected to the DataIn
- pin 11 is connected to the CLK
- pin 10 is connected to LOAD
- 2 is the nu
+ pin 7 is connected to the DataIn
+ pin 6 is connected to the CLK
+ pin 5 is connected to Load.
+ 2 is the # of dispays
  */
 const int DIN_PIN = 7;
 const int CLK_PIN = 6;


Cleanup.

Cleanup.

--- examples/Ethernet/CosaSNMP/CosaSNMP.ino
+++ examples/Ethernet/CosaSNMP/CosaSNMP.ino
@@ -161,15 +161,16 @@
 static const char location[] PROGMEM = "location";

 W5100 ethernet(mac);
-SNMP snmp;
 SNMP::MIB2_SYSTEM mib2(descr, contact, name, location);
 ARDUINO_MIB arduino;
+SNMP snmp;

 void setup()
 {
   uint8_t ip[4] = { IP };
   uint8_t subnet[4] = { SUBNET };

+  // Start watchdog and uart. Use uart for trace output
   uart.begin(9600);
   trace.begin(&uart, PSTR("CosaSNMP: started"));
   Watchdog::begin();
@@ -182,12 +183,10 @@

   // Print the given or default network address
   ethernet.get_addr(ip, subnet);
-  trace.print_P(PSTR("HOSTNAME = "));
-  trace.print_P(hostname);
-  trace.println();
-  trace.print_P(PSTR("IP = "));
+  trace << PSTR("HOSTNAME = ") << hostname << endl;
+  trace << PSTR("IP = ");
   INET::print_addr(trace, ip);
-  trace.println();
+  trace << endl;

   // Print some memory statistics
   TRACE(free_memory());


Use buffer for parts

Use buffer for parts

--- ableton-midi-foot-controller.ino
+++ ableton-midi-foot-controller.ino
@@ -20,6 +20,8 @@
 char sysexBuffer[SYSEX_BUFFER_SIZE];

 #define MAX_ROW_LENGTH 16
+
+char partBuffer[MAX_ROW_LENGTH + 1];

 // LEDs
 const byte ledPin = 13;
@@ -184,12 +186,14 @@
     return;
   }

+  copyToDisplayBuffer(partBuffer, message);
+
   nextPartScheduled = false;
   bars = 0;

   lcd.clear();
   lcd.setCursor(0, 0);
-  lcd.print(message);
+  lcd.print(partBuffer);
 }

 void handleSongSignature(char* messageOriginal) {
@@ -228,12 +232,26 @@
     return;
   }

+  copyToDisplayBuffer(partBuffer, message);
+
   nextPartScheduled = true;
   triggeredElapsed = 0;

   clearLine(1);
   lcd.setCursor(0, 1);
-  lcd.print(message);
+  lcd.print(partBuffer);
+}
+
+void copyToDisplayBuffer(char* displayBuffer, char* message) {
+  displayBuffer[0] = (char)0;
+
+  strncpy(displayBuffer, message, MAX_ROW_LENGTH);
+  byte messageLength = strlen(message);
+  if (messageLength < MAX_ROW_LENGTH) {
+    displayBuffer[messageLength] = (char)0;
+  } else {
+    displayBuffer[MAX_ROW_LENGTH] = (char)0;
+  }
 }

 void handleConfigurationStart() {
@@ -288,13 +306,7 @@
   Serial.println(strings);
 #endif

-  strncpy(songs[index], strings, MAX_ROW_LENGTH);
-  byte lengthOfName = strlen(strings);
-  if (lengthOfName < MAX_ROW_LENGTH) {
-    songs[index][lengthOfName] = (char)0;
-  } else {
-    songs[index][MAX_ROW_LENGTH] = (char)0;
-  }
+  copyToDisplayBuffer(songs[index], strings);
 }

 byte getConfigurationType(char* messageOriginal) {


making output prettier and wiring pump to replay

--- plantstation.ino
+++ plantstation.ino
@@ -113,11 +113,6 @@
   digitalWrite(hygroPower, LOW);
   digitalWrite(waterSensorPower, LOW);
   // Because end
-
-  readAirMeasurements();
-  readSoilMeasurements();
-  readLightResistor();
-
 }

 void loop() {
@@ -126,7 +121,7 @@
   // these happen every minute (or so)
   if (currentMillis - prevMinOneMillis > minOneInterval) {
     prevMinOneMillis = currentMillis;
-
+
     readAirMeasurements();
     readSoilMeasurements();
     readLightResistor();
@@ -141,7 +136,7 @@

     readMoistureSensor();
     readWaterLevelSensor();
-    waterPlantStarts();
+    //waterPlantStarts();
     switchLights();
   }

@@ -155,12 +150,11 @@
 }

 void waterPlantStarts() {
-  // todo - figure out how to send a water pump is on event for log even thou its off at time.
   if (!waterPumpIsOn && waterLevelStatus == "OK" && moistureThreshold > moisturePercent) {
     prevWatering = millis();
     waterPumpIsOn = true;
     digitalWrite(waterPumpPin, HIGH);
-    Console.println("\nWatering started\n");
+    Console.println("\n Watering started\n");
   }
 }

@@ -168,48 +162,42 @@
     if (waterPumpIsOn && currentMillis >= prevWatering + wateringSeconds) {
     waterPumpIsOn = false;
     digitalWrite(waterPumpPin, LOW);
-    Console.println("\nWatering stopped\n");
+    Console.println("\n Watering stopped\n");
   } else if (waterPumpIsOn && moistureThreshold < moisturePercent) {
     waterPumpIsOn = false;
     digitalWrite(waterPumpPin, LOW);
-    Console.println("\nWatering stopped\n");
+    Console.println("\n Watering stopped\n");
   } else if (waterPumpIsOn && waterLevelStatus == "LOW") {
     waterPumpIsOn = false;
     digitalWrite(waterPumpPin, LOW);
-    Console.println("\nWatering stopped\n");
+    Console.println("\n Watering stopped\n");
   }
 }

 void switchLights() {
   if (lightOnThreshold > lightPercent && !lightIsOn) {
-    Console.println("\nArtificial lights on.\n");
+    Console.println("\n Turning lights on.\n");
     digitalWrite(lightSwitchPin, HIGH);
     lightIsOn = true;
   }
   if (lightOnThreshold < lightPercent && lightIsOn) {
-    Console.println("\nArtificial lights off.\n");
+    Console.println("\n Turning lights off.\n");
     digitalWrite(lightSwitchPin, LOW);
     lightIsOn = false;
   }
 }

 void readLightResistor() {
-  Console.println("\nReading light sensor.");
   lightResistorVal = analogRead(lightPin);
   lightPercent = map(lightResistorVal, lightMinVal, lightMaxVal, 0, 100);
-  Console.print("Light Percent: ");
-  Console.println(lightPercent);
 }

 void readMoistureSensor() {
-  Console.println("\nReading moisture sensor.");
   digitalWrite(hygroPower, HIGH);
   delay(1000); // nasty hack to wait for moisture drivers
   moistureSensorVal = analogRead(hygroPin);
   digitalWrite(hygroPower, LOW);
-  moisturePercent = reversemap(moistureSensorVal, moistureMinVal, moistureMaxVal, 0, 100);
-  Console.print("Moisture Percent: ");
-  Console.println(moisturePercent);
+  moisturePercent = map(moistureSensorVal, moistureMinVal, moistureMaxVal, 0, 100);

   // moistureStatus
   if (moistureSensorVal > 0 && moistureSensorVal < 300) {
@@ -225,26 +213,20 @@
 }

 void readWaterLevelSensor() {
-  Console.println("\nReading Water Level.");
   digitalWrite(waterSensorPower, HIGH);
   delay(1000); // nasty hack to wait for moisture drivers
   waterLevelVal = analogRead(waterSensorPin);
   digitalWrite(waterSensorPower, LOW);
   waterLevelPercent = map(waterLevelVal, waterMinVal, waterMaxVal, 0, 100);
-  Console.print("Water Level Percent: ");
-  Console.println(waterLevelPercent);

   if (waterLevelPercent < waterLevelThreshold) {
    waterLevelStatus = "LOW";
   } else {
    waterLevelStatus = "OK";
   }
-  Console.print("Water level is: ");
-  Console.println(waterLevelStatus);
 }

 void readAirMeasurements() {
-  Console.println("\nReading air measurements.");
   am.humidityAir = myDHT.readHumidity();
   am.tempAirC = myDHT.readTemperature();
   am.tempAirF = myDHT.readTemperature(true);
@@ -253,16 +235,10 @@
   if (am.humidityAir == 0  && am.tempAirC == 0) {
     Console.println("Failed to read from DHT sensor.");
   }
-  Console.print("Air temp F is: ");
-  Console.println(am.tempAirF);
-  Console.print("Humidity is: ");
-  Console.println(am.humidityAir);
-  Console.print("Heat Index is: ");
-  Console.println(am.heatIndex);
 }

 void readSoilMeasurements() {
-  Console.println("\nReading soil measurements.");
+//  Console.println("\nReading soil measurements.");
   byte data[12];
   byte addr[8];

@@ -300,13 +276,10 @@
   float tempRead = ((MSB << 8) | LSB); //using two's compliment
   sm.tempSoilC = tempRead / 16;
   sm.tempSoilF = sm.tempSoilC*9/5+32;
-
-  Console.print("Soil temp F is: ");
-  Console.println(sm.tempSoilF);
 }

 void sendToKeen() {
-  Console.print("\nSending data to Keen.io.");
+  Console.print("\n Sending data to Keen.io");
   String my_output = "{";
   // strings
   my_output += "\"AppId\":\"";                      my_output += appId;             my_output += "\"";
@@ -351,27 +324,31 @@
 void outputEvent() {
   String my_output = "\n";
   // strings
-  //my_output += "AppId:";                        my_output += appId;
-  //my_output += ";Location:";                    my_output += location;
-  my_output += ";WaterLevelStatus:";            my_output += waterLevelStatus;
-  my_output += ";MoistureStatus:";               my_output += moistureStatus;
+  my_output += " App Id\t\t\t";        my_output += appId;               my_output +="\n";
+  my_output += " Location\t\t";        my_output += location;            my_output +="\n";
+  my_output += " Water Level\t\t";     my_output += waterLevelStatus;    my_output +="\n";
+  my_output += " Moisture\t\t";         my_output += moistureStatus;      my_output +="\n";
   // numerics
-  //my_output += ";AirTemperatureCelcius:";       my_output += am.tempAirC;
-  my_output += ";AirTemperatureFahrenheit:";    my_output += am.tempAirF;
-  my_output += ";HeatIndex:";                   my_output += am.heatIndex;
-  my_output += ";HumidityPercent:";             my_output += am.humidityAir;
-  my_output += ";LightPercent:";                my_output += lightPercent;
-  my_output += ";LightValue:";                  my_output += lightResistorVal;
-  my_output += ";LightIsOn:";                   my_output += lightIsOn;
-  my_output += ";MoisturePercent:";             my_output += moisturePercent;
-  my_output += ";MoistureValue:";               my_output += moistureSensorVal;
-  //my_output += ";ProbeTemperatureCelcius:";     my_output += sm.tempSoilC;
-  my_output += ";ProbeTemperatureFahrenheit:";  my_output += sm.tempSoilF;
-  my_output += ";WaterLevelPercent:";           my_output += waterLevelPercent;
-  my_output += ";WaterLevelValue:";             my_output += waterLevelVal;
-  my_output += ";WaterPumptIsOn:";              my_output += waterPumpIsOn;
+  my_output += " Air Temp C\t\t";      my_output += am.tempAirC;         my_output +="\n";
+  my_output += " Air Temp F\t\t";      my_output += am.tempAirF;         my_output +="\n";
+  my_output += " Heat Index\t\t";      my_output += am.heatIndex;        my_output +="\n";
+  my_output += " Humidity %\t\t";      my_output += am.humidityAir;      my_output +="\n";
+  my_output += " Light %\t\t";        my_output += lightPercent;        my_output +="\n";
+  my_output += " Light Val\t\t";       my_output += lightResistorVal;    my_output +="\n";
+  my_output += " Light Is On\t\t";     my_output += lightIsOn;           my_output +="\n";
+  my_output += " Moisture %\t\t";      my_output += moisturePercent;     my_output +="\n";
+  my_output += " Moisture\t\t";        my_output += moistureSensorVal;   my_output +="\n";
+  my_output += " Probe Temp C\t\t";    my_output += sm.tempSoilC;        my_output +="\n";
+  my_output += " Probe Temp F\t\t";    my_output += sm.tempSoilF;        my_output +="\n";
+  my_output += " Water Level %\t\t";   my_output += waterLevelPercent;   my_output +="\n";
+  my_output += " Water Level Val\t";   my_output += waterLevelVal;       my_output +="\n";
+  my_output += " Water Pump Is On\t";  my_output += waterPumpIsOn;       my_output +="\n";

-  Console.println(my_output);
+  Console.println();
+  Console.println();
+  Console.println(millis());
+  Console.print("--------------------------------------------------");
+  Console.print(my_output);
 }

 long reversemap(long x, long in_min, long in_max, long out_min, long out_max)


fetch RPM from CAN

fetch RPM from CAN

--- main/main.ino
+++ main/main.ino
@@ -124,7 +124,7 @@
   lcd.createChar(4, fill5);

   lcd.begin(20, 4);
-  lcd.print("MAP");
+  lcd.print("RPM");
   lcd.setCursor(0, 2);
   lcd.print("TGT");

@@ -148,8 +148,8 @@
     draw_bar(engine_tgt.currentValue, 3, 10.0, 20.0);

     lcd.setCursor(4, 0);
-    lcd.print(engine_map.currentValue);
-    draw_bar(engine_map.currentValue, 1, 97.0, 99.0);
+    lcd.print(engine_rpm.currentValue);
+    draw_bar(engine_rpm.currentValue, 1, 0.0, 6500.0);

   }

@@ -166,8 +166,8 @@
         switch(canId) {
           case 1512:
             engine_map.currentValue = ((buf[0] * 256) + buf[1]) / 10.0;
-            //Serial.println(buf[1]);
-            //Serial.println("=====");
+            engine_rpm.currentValue = buf[2] * 256 + buf[3];
+            Serial.println(engine_rpm.currentValue);
             break;
           case 1513:


Faster baud change on at+print

Faster baud change on at+print

git-svn-id: d8bfcd070c2c81762cca1b3912331324182919ba@19254 0d6f1817-ed0e-0410-87c9-987e46238f29

--- zimodem/zprint.ino
+++ zimodem/zprint.ino
@@ -193,6 +193,8 @@
     free(workBuf);
     return ZERROR;
   }
+  checkOpenConnections();
+  checkBaudChange();
   pdex=0;
   coldex=0;
   currentExpiresTimeMs = millis()+5000;


Implement touch events probably

Implement touch events probably

--- mouse_rat.ino
+++ mouse_rat.ino
@@ -28,8 +28,13 @@
 float xRange[] = {0,0};
 float yRange[] = {0,0};

-uint16_t lasttouched = 0;
-uint16_t currtouched = 0;
+const int MOUSE_LEFT_PIN = 10,
+          MOUSE_MID_PIN   = 8,
+          MOUSE_RIGHT_PIN = 6;
+
+uint16_t lasttouched = 0,
+         currtouched = 0;
+

 // Configures the gain and integration time for the TSL2561
 void configureSensor(void) {
@@ -52,17 +57,20 @@
   //lsm.setupGyro(lsm.LSM9DS0_GYROSCALE_2000DPS);
 }

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

   dof_setup();
   mpr_setup();
 }
+

 void loop(void) {
   dof_loop();
   mpr_loop();
 }
+

 void mpr_setup() {
   // needed to keep leonardo/micro from starting too fast!
@@ -80,6 +88,7 @@
   Serial.println("MPR121 found!");
 }

+
 void dof_setup() {
   if(!lsm.begin()) { while(1); }

@@ -92,6 +101,7 @@
   lsm.getEvent(&accel, &mag, &gyro, &temp);
 }

+
 void dof_loop() {
   /* Get a new sensor event */
   sensors_event_t accel, mag, gyro, temp;
@@ -113,6 +123,7 @@
   Mouse.move(mx, my, 0);
   delay(5);
 }
+

 void mpr_loop() {
   // Get the currently touched pads
@@ -122,23 +133,51 @@
   lasttouched = currtouched;
 }

+
 void checkTouch() {
   for (uint8_t i=0; i < 12; i++) {
-    // it if *is* touched and *wasnt* touched before, alert!
+    // it if /is/ touched and /wasn't/ touched before, alert!
     if ( (currtouched & _BV(i)) && !(lasttouched & _BV(i)) ) touchHandler(i);

-    // if it *was* touched and now *isnt*, alert!
+    // if it /was/ touched and now /isn't/, alert!
     if ( !(currtouched & _BV(i)) && (lasttouched & _BV(i)) ) releaseHandler(i);
   }
 }

+
 void touchHandler(int id) {
+  Serial.print(id); Serial.println(" touched");
+
+  switch(id) {
+    case MOUSE_LEFT_PIN:
+      Mouse.press(MOUSE_LEFT);
+      break;
+    case MOUSE_MID_PIN:
+      Mouse.press(MOUSE_MIDDLE);
+      break;
+    case MOUSE_RIGHT_PIN:
+      Mouse.press(MOUSE_RIGHT);
+      break;
+  }
+}
+
+
+void releaseHandler(int id) {
   Serial.print(id); Serial.println(" released");
-}
-
-void releaseHandler(int id) {
-  Serial.print(id); Serial.println(" touched");
-}
+
+  switch(id) {
+    case MOUSE_LEFT_PIN:
+      Mouse.release(MOUSE_LEFT);
+      break;
+    case MOUSE_MID_PIN:
+      Mouse.release(MOUSE_MIDDLE);
+      break;
+    case MOUSE_RIGHT_PIN:
+      Mouse.release(MOUSE_RIGHT);
+      break;
+  }
+}
+

 void calibrate(float x, float y) {
    xRange[0] = min(xRange[0], x);
@@ -154,9 +193,11 @@
    Serial.print(yRange[0]); Serial.print(", "); Serial.println(yRange[1]);
 }

+
 float clamp(float value, float min_, float max_) {
   return (value < min_) ? min_ : (value > max_) ? max_ : value;
 }
+

 void displaySensorDetails(void) {
   sensor_t accel, mag, gyro, temp;


Update tinker-x042-laddstation.ino

Update tinker-x042-laddstation.ino

--- laddstation/tinker-x042-laddstation.ino
+++ laddstation/tinker-x042-laddstation.ino
@@ -31,48 +31,6 @@

 /* This function loops forever --------------------------------------------*/
 void loop()
- {
-    Serial1.print("t0.txt=\"25.4°C\"");
-    Serial1.write(0xff);
-    Serial1.write(0xff);
-    Serial1.write(0xff);
-
-  delay(1000);
-
-    Serial1.print("t0.txt=");
-    Serial1.write(0x22);
-    Serial1.print(batteryVoltage,1);
-    Serial1.write(0x22);
-
-
-
-    Serial1.write(0xff);
-    Serial1.write(0xff);
-    Serial1.write(0xff);
-
-
-  delay(1000);
-
-  // check to see what the value of the photoresistor is and store it in the int variable analogvalue
-    analogvalue = analogRead(A0);
-    temp = analogvalue*2;
-    batteryVoltage = temp/112;
-
-
-    if (analogvalue>2000) {
-        digitalWrite(D3,HIGH);
-
-    }
-    else if (analogvalue<2000) {
-        digitalWrite(D3,LOW);
-    }
-    else {
-
-    }
-
-}
-
-

 /*******************************************************************************
  * Function Name    :
@@ -86,6 +44,49 @@
  * attribut         :   txt
  ******************************************************************************/

+{
+    Serial1.print("t0.txt=\"25.4°C\"");
+    Serial1.write(0xff);
+    Serial1.write(0xff);
+    Serial1.write(0xff);
+
+  delay(1000);
+
+    Serial1.print("t0.txt=");
+    Serial1.write(0x22);
+    Serial1.print(batteryVoltage,1);
+    Serial1.write(0x22);
+
+
+
+    Serial1.write(0xff);
+    Serial1.write(0xff);
+    Serial1.write(0xff);
+
+
+  delay(1000);
+
+  // check to see what the value of the photoresistor is and store it in the int variable analogvalue
+    analogvalue = analogRead(A0);
+    temp = analogvalue*2;
+    batteryVoltage = temp/112;
+
+
+    if (analogvalue>2000) {
+        digitalWrite(D3,HIGH);
+
+    }
+    else if (analogvalue<2000) {
+        digitalWrite(D3,LOW);
+    }
+    else {
+
+    }
+
+}
+
+
+
 /*******************************************************************************
  * Function Name  : tinkerDigitalRead
  * Description    : Reads the digital value of a given pin


Reorder #defines, save SRAM, compute MAX_FRAMES, restore all settings

Make the file more user-friendly, laying out the various sections of
defines.
Use the F("") macro to store all those strings in PROGMEM, awesome.
Compute MAX_FRAMES based on NUM_LEDS, SRAM_SIZE, and an arbitrary
VAR_ALLOWANCE that may need to expand later.
If there's a problem with the settings object we get, restore from the
previous. Avoids weirdness.

--- blume.ino
+++ blume.ino
@@ -3,7 +3,14 @@
 #include <EEPROM.h>
 #include <FastLED.h>

-
+// These settings change per project!
+#define NUM_LEDS    18
+#define BASE_WIDTH  1
+// If true, adds 1 to BASE_WIDTH for every other row
+#define STAGGERED   false
+
+// Only change these settings if you're wired to different pins, using a non-APA102 chipset,
+// using a different COLOR_ORDER for RGB, etc.
 #define DATA_PIN_0    A0
 #define DATA_PIN_1    A1
 #define CLOCK_PIN_0   5
@@ -20,17 +27,20 @@
 #define LED_SETTINGS_1 CHIPSET, CLOCK_PIN_1, DATA_PIN_0, COLOR_ORDER
  */

+
+// EVERYTHING BELOW HERE WON'T CHANGE FOR A NORMAL PROJECT.
+
+
 #define EEPROM_SAVE_TIMEOUT_MS 5000
 #define EEPROM_START_POINTER_ADDR 0x0

-#define NUM_LEDS    18
-#define BASE_WIDTH  1
-// If true, adds 1 to BASE_WIDTH for every other row
-#define STAGGERED   false
-// Varies by NUM_LEDS to ensure not overloading SRAM
-#define MAX_FRAMES 64
-
 CRGB leds[NUM_LEDS];
+
+// Calculate max number of frames we can store in SRAM
+#define SRAM_SIZE 2048
+// Assume we need this much for everything else
+#define VAR_ALLOWANCE 600
+#define MAX_FRAMES ((SRAM_SIZE - VAR_ALLOWANCE) / NUM_LEDS)

 int width;
 int height;
@@ -103,16 +113,16 @@
   FastLED.setBrightness(255);
   fill_solid(leds, NUM_LEDS, 0xFF0000);
   FastLED.delay(1000);
-  Serial.println("did the thing");
+  Serial.println(F("did the thing"));
   fill_solid(leds, NUM_LEDS, 0x00FF00);
   FastLED.delay(1000);
-  Serial.println("yep");
+  Serial.println(F("yep"));
   fill_solid(leds, NUM_LEDS, 0x0000FF);
   FastLED.delay(1000);
-  Serial.println("done");
+  Serial.println(F("done"));
   fill_solid(leds, NUM_LEDS, 0x000000);
   FastLED.delay(1000);
-  Serial.println("clear");
+  Serial.println(F("clear"));
   */
 }

@@ -183,21 +193,21 @@
     return;
   }
   if (!Serial.find("!")) {
-    Serial.println("no !");
+    Serial.println(F("no !"));
     return;
   }
   //Serial.println("found !");
   byte len;
   if (!Serial.readBytes(&len, 1)) {
-    Serial.println("no len");
-  }
-  //Serial.print("len=");
+    Serial.println(F("no len"));
+  }
+  //Serial.print(F("len="));
   //Serial.println(len);
   if (!len) {
     // Special case: no length means primary is asking a question.
     byte question;
     if (!Serial.readBytes(&question, 1)) {
-      Serial.println("no question");
+      Serial.println(F("no question"));
     } else {
       if (question == 'D') {
         // Send dimensions.
@@ -208,10 +218,10 @@
     return;
   }

-  byte previousMode = settings.mode;
-  byte previousHue = settings.hue;
+  SavedSettings previous = settings;
   if (!Serial.readBytes((byte*)&settings, min(sizeof(settings), len))) {
-    Serial.println("failed to read len bytes");
+    Serial.println(F("failed to read len bytes"));
+    settings = previous;
     return;
   }
   if (settings.mode == 'P') {
@@ -219,24 +229,23 @@
     settings.hue = min(settings.hue, MAX_FRAMES);
     if (settings.hue) {
       if (!Serial.readBytes(ledFrames, settings.hue * NUM_LEDS)) {
-        Serial.print("failed to read ");
+        Serial.print(F("failed to read "));
         Serial.print(settings.hue);
-        Serial.println(" image frames");
+        Serial.println(F(" image frames"));
+        settings = previous;
       }
-    } else if (previousMode == 'P') {
+    } else if (previous.mode == 'P') {
       // Special case: frame count of 0 means no frames sent.
       // The mode must have already been 'P' for this to work.
-      settings.hue = previousHue;
+      settings.hue = previous.hue;
     } else {
       Serial.println("Can't modify frame timing without image frames first");
-      // This is an error case; restore as much as we had before as possible.
-      settings.mode = previousMode;
-      settings.hue = previousHue;
+      settings = previous;
     }
   }

   /*Serial.print(len);
-  Serial.print(" -> ");*/
+  Serial.print(F(" -> "));*/
   // We have new settings! Apply them.
   restoreFromSettings();
   // Plan to save this if we don't get any more data
@@ -251,12 +260,12 @@
     // Uses update() so only rewrites if necessary
     EEPROM.put(eepromStart, settings);
     saveTarget = 0;
-    //Serial.println("SAVED!");
+    //Serial.println(F("SAVED!"));
   }
 }

 void restoreFromSettings() {
-  /*Serial.print("settings: ");
+  /*Serial.print(F("settings: "));
   Serial.print(settings.brightness);
   Serial.print(',');
   Serial.print(settings.mode);
@@ -284,7 +293,7 @@
   } else if (settings.mode == 'P') {
     runPixels(true);
   } else {
-    Serial.print("Unknown mode: ");
+    Serial.print(F("Unknown mode: "));
     Serial.println(settings.mode);
   }
 }


Turn on/off digital pins instead of using tone that don't work on multiple pin in same time

--- vibrate/vibrate.ino
+++ vibrate/vibrate.ino
@@ -1,23 +1,26 @@
 /*
+Copyright Ahmed Mansour 2016

-
- Plays tones on digital pins 6 (P1_4)
-
-
- http://arduino.cc/en/Tutorial/Tone4
+ Turn on/off digital pins 6 (P1_4)
+ Turn on/off digital pins 7 (P1_5)

  */
-//int frequency = 31000; // 31kHz Ultrasound
-int frequency = 9000;
+
 void setup() {
-
+  // initialize the digital pin as an output.
+  pinMode(6, OUTPUT);
+  // initialize the digital pin as an output.
+  pinMode(7, OUTPUT);
 }

 void loop() {

-  // play a note on pin 6 for 200 ms:
-  tone(6, frequency, 200);
+  digitalWrite(6, HIGH);
+  digitalWrite(7, HIGH);
+  delay(200);
+
+  digitalWrite(6, LOW);
+  digitalWrite(7, LOW);
   delay(200);

-
 }


Max 30 s period works, very strange

Max 30 s period works, very strange

--- src/MQTT-monitor.ino
+++ src/MQTT-monitor.ino
@@ -89,7 +89,7 @@
 unsigned long lastrun = millis();
 int state = 0;
 //#define PERIOD 5*60*1000
-#define PERIOD 15*1000
+#define PERIOD 30*1000

 bool bme_status;

@@ -151,7 +151,7 @@
   mqtt.setServer(broker, 1883);
   mqtt.setCallback(mqttCallback);

-  bme_status = bme.begin();
+  //  bme_status = bme.begin();
   //  Watchdog.reset();
 }

@@ -169,43 +169,73 @@
 }

 void loop() {
-
-  if (mqtt.connected()) {
-    if (millis() > (lastrun + PERIOD)) {
-      switch(state) {
-      case 0:
-	senddht22(Makuuhuone, topicMakuuhuone);
-	state++;
-	break;
+
+  Serial.print("millis ");
+  Serial.println(millis());
+  //  if (mqtt.connected()) {
+  if (millis() > (lastrun + PERIOD)) {
+      if (mqtt.connect("Karttula", mqtt_user, mqtt_pass)) {
+
+	switch(state) {
+	case 0:
+	  senddht22(Makuuhuone, topicMakuuhuone);
+	  state++;
+	  break;
+
+	case 1:
+	  sendbme(topicOlohuone);
+	  state++;
+	  break;
+
+	case 2:
+	  senddht22(WC, topicWC);
+	  state++;
+	  break;
+
+	case 3:
+	  senddht22(Vierashuone, topicVierashuone);
+	  state = 0;
+	  lastrun = millis();
+	}
+      } else {
+	// Restart takes quite some time
+	// To skip it, call init() instead of restart()
+	Serial.println("Initializing modem...");
+	modem.restart();

-      case 1:
-	sendbme(topicOlohuone);
-	state++;
-	break;
-
-      case 2:
-	senddht22(WC, topicWC);
-	state++;
-	break;
-
-      case 3:
-	senddht22(Vierashuone, topicVierashuone);
-	state = 0;
-	lastrun = millis();
+	// Unlock your SIM card with a PIN
+	//modem.simUnlock("1234");
+
+	Serial.print("Waiting for network...");
+	if (!modem.waitForNetwork()) {
+	  Serial.println(" fail");
+	  while (true);
+	}
+	Serial.println(" OK");
+
+	Serial.print("Connecting to ");
+	Serial.print(apn);
+	if (!modem.gprsConnect(apn, user, pass)) {
+	  Serial.println(" fail");
+	  while (true);
+	}
+	Serial.println(" OK");
       }
     }
+
     delay(1000);
     mqtt.loop();
-  } else {
-    // Reconnect every 10 seconds
-    unsigned long t = millis();
-    if (t - lastReconnectAttempt > 10000L) {
-      lastReconnectAttempt = t;
-      if (mqttConnect()) {
-        lastReconnectAttempt = 0;
-      }
-    }
-  }
+  /* } else { */
+  /*   // Reconnect every 10 seconds */
+  /*   unsigned long t = millis(); */
+  /*   if (t - lastReconnectAttempt > 10000L) { */
+  /*     lastReconnectAttempt = t; */
+  /*     if (mqttConnect()) { */
+  /*       lastReconnectAttempt = 0; */
+  /*     } */
+  /*   } */
+  /* } */
+
   //  Watchdog.reset();

 }
@@ -253,9 +283,10 @@
 void sendbme(char* topic) {
   float temperature = 0;
   float humidity = 0;
+  bme_status = bme.begin();
   size_t len = strlen(topic);
-    Serial.print("BME status ");
-   Serial.println(bme_status);
+  Serial.print("BME status ");
+  Serial.println(bme_status);

   if (bme_status) {
     strcpy(topicbuffer,topic);


Start working on LED

Start working on LED

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -14,6 +14,11 @@
 // SENSORS
 long gyroX, gyroY, gyroZ;
 float rotX, rotY, rotZ;
+
+//orientation of MPU
+int prevX = 0;
+int prevY = 0;
+int prevZ = 0;

 // VARIABLES
 // Default positions for servos
@@ -23,12 +28,6 @@
 int pos4 = 0;
 int pos5 = 0;

-//orientation of MPU
-
-int prevX = 0;
-int prevY = 0;
-int prevZ = 0;
-
 int ByteReceived;   // store byte recieved via serial

 bool stabilizingOn = false;       // stores wheter self-stabilizing is on.
@@ -44,6 +43,12 @@
 bool servosFault = true;
 bool sensorsFault = true;
 bool arduinoFault = true;
+
+enum ledState {
+  off,
+  blinking,
+  on
+};

 // CONSTANTS

@@ -129,7 +134,7 @@
   upDown.write(pos5);

   // Set up LED
-  // Nothing here yet
+  pinMode(LED_PIN, OUTPUT);
 }

 // UPDATE


Best run tilll now

Best run tilll now

--- zippy_the_road_runner.ino
+++ zippy_the_road_runner.ino
@@ -2,7 +2,7 @@
 #include <Motor.h>
 #include "QTRSensors_teensy3.h"

-#define BLUETOOTH Serial1
+#define BLUETOOTH Serial

 #define ON_LINE(sensor)((sensor<COMPARE))
 #define OVERSHOOT_LINE_TIME 50
@@ -236,12 +236,12 @@

 	// Mode 1 for simplifying path
-	if (MODE == 1)
-		simplifyPath();
+	//if (MODE == 1)
+		//simplifyPath();

 	// Mode 2 for running on simplified path
-	if (MODE == 2)
-		runSimplifiedPath();
+	//if (MODE == 2)
+		//runSimplifiedPath();

 }

@@ -375,11 +375,21 @@
 			LED_LEFT_ON;
 			LED_RIGHT_ON;

+			BLUETOOTH.println(" :) ");
 			BLUETOOTH.println(path);
 			BLUETOOTH.println("END OF MAPPING MODE");

-				motorLeft.write(512);
-				motorRight.write(512);
+			DISABLE_STANDBY;
+			motorLeft.stop();
+			motorRight.stop();
+			while (1)
+			{
+				BLUETOOTH.println(" :) ");
+				BLUETOOTH.println(path);
+			}
+
+				//motorLeft.write(512);
+				//motorRight.write(512);
 				//delay(50);
 			LED_LEFT_OFF;
 			LED_RIGHT_OFF;
@@ -417,7 +427,7 @@

 		char direction = selectTurn(foundLeft, foundRight, foundStraight);
-		turn(direction, SPEED_TURN, 250);
+		turn(direction, SPEED_TURN, 300);

 		// L 90 Turn OR R 90 Turn
 		if ((foundLeft || foundRight) && !foundStraight)


Update main.ino

Update main.ino


use struct to draw bar, tweak clt

use struct to draw bar, tweak clt

--- main/main.ino
+++ main/main.ino
@@ -77,7 +77,7 @@
 EngineVariable calc_vac     = {"VAC", "VACUUM", 0.0, 0.0, -200.0, 100.0, "HG"};
 EngineVariable calc_bst     = {"BST", "BOOST", 0.0, 0.0, 0.0, 50.0, "PSI"};
 EngineVariable engine_rpm   = {"RPM", "RPM", 0.0, 0.0, 0.0, 6500.0, ""};
-EngineVariable engine_clt   = {"CLT", "TEMP", 0.0, 0.0, 20.0, 250.0, ""};
+EngineVariable engine_clt   = {"CLT", "TEMP", 0.0, 0.0, 160.0, 240.0, ""};
 EngineVariable engine_tps   = {"TPS", "THROTTLE", 0.0, 0.0, 0.0, 100.0, "%"};
 EngineVariable engine_pw1   = {"PW1", "PULSE WIDTH 1", 0.0, 0.0, 0.0, 50.0, "MS"};
 EngineVariable engine_pw2   = {"PW2", "PULSE WIDTH 2", 0.0, 0.0, 0.0, 50.0, "MS"};
@@ -145,11 +145,11 @@
     lastMillis = currentMillis;
     lcd.setCursor(4, 2);
     lcd.print(engine_tgt.currentValue);
-    draw_bar(engine_tgt.currentValue, 3, 10.0, 20.0);
+    draw_bar(engine_tgt, 3);

     lcd.setCursor(4, 0);
     lcd.print(engine_clt.currentValue);
-    draw_bar(engine_clt.currentValue, 1, 20.0, 250.0);
+    draw_bar(engine_clt, 1);

   }

@@ -193,13 +193,20 @@

 }

-void draw_bar(double value, int row, double minimum, double maximum) {
+void draw_bar(EngineVariable engineVar, int row) {
   lcd.setCursor(0, row);
   lcd.write("                    ");
   lcd.setCursor(0, row);
-  int bars = ((value - minimum) * 100) / (maximum - minimum);
+  int bars = ((engineVar.currentValue - engineVar.minimum) * 100) / (engineVar.maximum - engineVar.minimum);
   int fullBars = bars/5;
   int partialBars = bars % 5;
+
+  //prevent graph overrun
+  if(fullBars >= 20) {
+    fullBars = 20;
+    partialBars = 0;
+  }
+
   lcd.setCursor(0, row);
   for(int i = 0; i < fullBars; i++) {
     lcd.write(byte(4));


random instrument color on startup

random instrument color on startup

--- ptw-wheel.ino
+++ ptw-wheel.ino
@@ -1,4 +1,5 @@
 #include <Adafruit_NeoPixel.h>
+#include <HSBColor.h>

 // Arduino Nano v2.x, v3.x

@@ -35,10 +36,10 @@
 int i_color_r = 255;
 int i_color_g = 0;
 int i_color_b = 0;
-float instrument_brightness = 0.1;
+float instrument_brightness = 1.0;
 // use oneshot only
-float instrument_brightness_alt = 0.1;
-float instrument_brightness_min = 0.1;
+float instrument_brightness_alt = 1.0;
+float instrument_brightness_min = 1.0;

 // effect color
 int e_color_r = 0;
@@ -57,10 +58,44 @@
   strip.begin();
   strip.show(); // Initialize all pixels to 'off'
   Serial.begin(9600);
+  randomSeed(analogRead(0));

   // startup animation
   rainbow(2);
   colorWipe(0, 2);
+
+  // random instrument color
+  int rand = random(6);
+  float h, s;
+  if(rand < 1) {
+    h = 0.412;
+    s = 1.0;
+  }
+  else if(rand < 2) {
+    h = 0.678;
+    s = 1.0;
+  }
+  else if(rand < 3) {
+    h = 0.893;
+    s = 1.0;
+  }
+  else if(rand < 4) {
+    h = 0.0;
+    s = 1.0;
+  }
+  else if(rand < 5) {
+    h = 0.412;
+    s = 1.0;
+  }
+  else {
+    h = 0.19;
+    s = 1.0;
+  }
+  int rgb[] = {255,255,255};
+  H2R_HSBtoRGB((int)(h*360.0), (int)(s*100.0), 100, rgb);
+  i_color_r = rgb[0];
+  i_color_g = rgb[1];
+  i_color_b = rgb[2];

   updateLED();
 }
@@ -258,8 +293,8 @@
   uint32_t _r = constrainValue(i_color_r);
   uint32_t _g = constrainValue(i_color_g);
   uint32_t _b = constrainValue(i_color_b);
-  uint32_t instrument_color = multiplicateBrightness(_r, _g, _b, instrument_brightness);
-  int32_t instrument_color_alt = multiplicateBrightness(_r, _g, _b, instrument_brightness_alt);
+  uint32_t instrument_color = multiplicateBrightness(_r, _g, _b, min(instrument_brightness,0.5));
+  int32_t instrument_color_alt = multiplicateBrightness(_r, _g, _b, min(instrument_brightness_alt, 0.5));

   _r = constrainValue(e_color_r);
   _g = constrainValue(e_color_g);


Has a min/max range where the temperature can not be set in

--- remote_thermostat/remote_thermostat.ino
+++ remote_thermostat/remote_thermostat.ino
@@ -1,4 +1,4 @@
-#include <PubSubClient.h>
+#include <PubSubClient.h>
 #include <ESP8266WiFi.h>
 #include <DHT.h>
 #include <EEPROM.h>
@@ -8,9 +8,11 @@
 #define PASSWORD "pwd"

 #define DEFAULT_TARGET_TEMP 19
+#define MAX_TEMP 29
+#define MIN_TEMP 2

-#define COOL_PIN 13
-#define HEAT_PIN 14
+#define COOL_PIN 14
+#define HEAT_PIN 13
 #define DHTPIN 12

 #define TEMPERATURE_CONTROL_RANGE 1
@@ -32,37 +34,37 @@
 RelayrClient remoteClient;

 float readTemp() {
-  return dht.getTemperature();
+    return dht.getTemperature();
 }

 void cool() {
     lastCoolingTime = lastCoolingTime < 1 ? millis() : lastCoolingTime;

    if (millis() - lastCoolingTime > COMPRESSER_DELAY) {
-     digitalWrite(COOL_PIN, LOW);
+     digitalWrite(COOL_PIN, HIGH);
      lastCoolingTime = millis();
    }

-   digitalWrite(HEAT_PIN, HIGH);
+   digitalWrite(HEAT_PIN, LOW);
 }

 void heat() {
-  digitalWrite(HEAT_PIN, LOW);
-  digitalWrite(COOL_PIN, HIGH);
+  digitalWrite(HEAT_PIN, HIGH);
+  digitalWrite(COOL_PIN, LOW);
   lastCoolingTime = 0;
 }

 void stop() {
   lastCoolingTime = 0;
-  digitalWrite(HEAT_PIN, HIGH);
-  digitalWrite(COOL_PIN, HIGH);
+  digitalWrite(HEAT_PIN, LOW);
+  digitalWrite(COOL_PIN, LOW);
 }

 void control(float temp) {
-  if (temp + TEMPERATURE_CONTROL_RANGE < targetTemp) {
+  if (temp + TEMPERATURE_CONTROL_RANGE < targetTemp && targetTemp < MAX_TEMP) {
     heating = true;
     cooling = false;
-  } else if (temp - TEMPERATURE_CONTROL_RANGE > targetTemp) {
+  } else if (temp - TEMPERATURE_CONTROL_RANGE > targetTemp && targetTemp > MIN_TEMP) {
     heating = false;
     cooling = true;
   } else {
@@ -73,9 +75,11 @@

 void setTargetTemp(float message) {
   Serial.println("set target" + String(message));
-  targetTemp = message;
-  EEPROM.put(eeAddress, targetTemp);
-  EEPROM.commit();
+  if (MIN_TEMP < message < MAX_TEMP) {
+    targetTemp = message;
+    EEPROM.put(eeAddress, targetTemp);
+    EEPROM.commit();
+  }
 };

 void setup() {
@@ -89,8 +93,8 @@

     pinMode(HEAT_PIN, OUTPUT);
     pinMode(COOL_PIN, OUTPUT);
-    digitalWrite(HEAT_PIN, HIGH);
-    digitalWrite(COOL_PIN, HIGH);
+    digitalWrite(HEAT_PIN, LOW);
+    digitalWrite(COOL_PIN, LOW);

     publishingPeriod = publishingPeriod > 200 ? publishingPeriod : 200;

@@ -103,7 +107,8 @@

 void loop() {
   float temp = readTemp();
-
+  Serial.println("--- Control --- Temp");
+
   control(temp);

   if (heating) {
@@ -118,7 +123,7 @@
     remoteClient.loop();

     if (millis() - lastPublishTime > publishingPeriod) {
-      lastPublishTime = millis();
+      lastPublishTime = millis();
       remoteClient.publishTemperature(temp);
       delay(200);
       remoteClient.publishSetTemperature(targetTemp);


Fixed #16 (compilation error)

Fixed #16 (compilation error)

--- Helper_Functions.ino
+++ Helper_Functions.ino
@@ -16,25 +16,25 @@
 	penServo.write(penState);
 }

-void inline loadPenPosFromEE() {
+inline void loadPenPosFromEE() {
 	penUpPos = eeprom_read_word(penUpPosEEAddress);
 	penDownPos = eeprom_read_word(penDownPosEEAddress);
 	penState = penUpPos;
 }

-void inline storePenUpPosInEE() {
+inline void storePenUpPosInEE() {
 	eeprom_update_word(penUpPosEEAddress, penUpPos);
 }

-void inline storePenDownPosInEE() {
+inline void storePenDownPosInEE() {
 	eeprom_update_word(penDownPosEEAddress, penDownPos);
 }

-void inline sendAck(){
+inline void sendAck(){
 	Serial.print("OK\r\n");
 }

-void inline sendError(){
+inline void sendError(){
 	Serial.print("unknown CMD\r\n");
 }


reader for dorm 4 working

reader for dorm 4 working

--- Margoulineur2000.ino
+++ Margoulineur2000.ino
@@ -295,9 +295,11 @@
             nfc.PrintHexChar(nfc_handler.data, 16);
             if (!mode)
             {
-                nfc_handler.offset = dormitory == 4 ? 1 : 7;
+                nfc_handler.offset = dormitory == 4 ? 0 : 7;
                 if (nfc_handler.currentblock == 24)
-                    nfc_handler.currentBalance = (nfc_handler.data[nfc_handler.offset - 1] * 256) + nfc_handler.data[nfc_handler.offset];
+                    nfc_handler.currentBalance = dormitory == 4 ?
+                     (nfc_handler.data[nfc_handler.offset + 1] * 256) + nfc_handler.data[nfc_handler.offset] :
+                     (nfc_handler.data[nfc_handler.offset - 1] * 256) + nfc_handler.data[nfc_handler.offset];
             }
             else
             {


Delete OBSIDEM_NEW_GAME.ino

Delete OBSIDEM_NEW_GAME.ino

--- OBSIDEM_NEW_GAME.ino
+++ OBSIDEM_NEW_GAME.ino
@@ -1,413 +0,0 @@
-#include <SPI.h>
-#include "Mfrc522.h"
-
-
-
-
-//r1 pins
-#define r1_shield_pin 6
-#define r1_bust_pin 2
-#define r1_motor_relay_pin 18
-#define r1_motor_mosfet_pin 40
-#define r1_large_frame_pin 39
-#define r1_pedestal_pin 38
-
-//r2 pins
-#define r2_houselight_pin 37
-#define r2_uv_pin 36
-#define r2_entry_door_pin 24
-#define r2_exit_door_pin 11
-#define r2_laserrx1_pin 28
-#define r2_laserrx2_pin 27
-#define r2_laserrx3_pin 26
-#define r2_laserrx4_pin 25
-#define r2_door_lights_pin 19
-
-//r3 pins
-#define r3_picture_pin 13
-#define r3_g1_pin 34
-#define r3_g2_pin 33
-#define r3_g3_pin 32
-#define r3_g4_pin 31
-#define r3_shield_pin 23
-#define r3_statue_orientation_pin 8
-
-
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-class Room1
-{
-public:
-
-int off_state;
-
-  Room1()
-{
- pinMode(r1_shield_pin,INPUT_PULLDOWN);
- pinMode(r1_bust_pin,INPUT);
- pinMode(r1_motor_relay_pin,OUTPUT);
- pinMode(r1_motor_mosfet_pin,OUTPUT);
- pinMode(r1_large_frame_pin,OUTPUT);
- pinMode(r1_pedestal_pin,OUTPUT);
- calibrate_bust();
-}
-
-//r1 functions
-bool check_shield()
-{
-  return (digitalRead(r1_shield_pin));
-}
-
-void calibrate_bust()
-{
-  off_state = analogRead(r1_bust_pin);
-}
-
-bool check_bust()
-{
-  if (analogRead(r1_bust_pin) > 200)
-    return true;
-  else
-    return false;
-}
-
-void set_pedestal(bool state)
-{
-  digitalWrite(r1_pedestal_pin,state);
-}
-
-void set_frame(bool state)
-{
-  digitalWrite(r1_large_frame_pin,state);
-}
-
-void activate_slider(bool direction)
-{
-  digitalWrite(r1_motor_relay_pin,direction);
-  digitalWrite(r1_motor_mosfet_pin,true);
-  delay (5000);
-  digitalWrite(r1_motor_mosfet_pin,false);
-}
-};
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-class Room2
-{
-public:
-
-Room2()
-{
-pinMode(r2_houselight_pin,OUTPUT);
-pinMode(r2_uv_pin,OUTPUT);
-pinMode(r2_entry_door_pin,INPUT_PULLDOWN);
-pinMode(r2_exit_door_pin,OUTPUT);
-pinMode(r2_laserrx1_pin,INPUT);
-pinMode(r2_laserrx2_pin,INPUT);
-pinMode(r2_laserrx3_pin,INPUT);
-pinMode(r2_laserrx4_pin,INPUT);
-pinMode(r2_door_lights_pin, OUTPUT);
-calibrate_laserrx();
-}
-//room2 objects
-const int code[4] =  {1,2,3,4};
-int puzzle_state = 0;
-int avg_base_value;
-//
-
-//
-//r2_functions
-void set_houselights (bool status)
-{
-  digitalWrite(r2_houselight_pin, status);
-}
-
-void set_uv (bool status)
-{
-  digitalWrite(r2_uv_pin, status);
-}
-
-void set_door_lights(int intensity)
-{
-  analogWrite(r2_door_lights_pin,intensity);
-}
-
-bool get_entry_door_status()
-{
-  return (digitalRead(r2_entry_door_pin));
-}
-
-void set_exit_door(bool status)
-{
-  digitalWrite(r2_exit_door_pin,status);
-}
-
-int calibrate_laserrx()
-{
-  int avg = 0;
-  avg = analogRead(r2_laserrx1_pin) + analogRead(r2_laserrx2_pin) + analogRead(r2_laserrx3_pin) + analogRead(r2_laserrx4_pin);
-  avg /= 4;
-  return avg;
-}
-
-
-bool check_laser_rx (int laser_number)
-{
-  int rx_value;
-  switch(laser_number)
-  {
-  case 1: rx_value = analogRead(r2_laserrx1_pin);
-  case 2: rx_value = analogRead(r2_laserrx2_pin);
-  case 3: rx_value = analogRead(r2_laserrx3_pin);
-  case 4: rx_value = analogRead(r2_laserrx4_pin);
-  }
-  if (rx_value > avg_base_value)
-    return true;
-  else
-    return false;
-}
-
-int check_laser_puzzle()
-{
-  if (puzzle_state == 0 && (check_laser_rx(code[0])))
-    {
-    puzzle_state = 1;
-    set_door_lights(63);
-    delay (500);
-    }
-
-  if (puzzle_state == 1 && (check_laser_rx(code[1])))
-    {
-    puzzle_state = 2;
-    set_door_lights(126);
-    delay(500);
-    }
- /* else
-  {
-    puzzle_state = 0;
-    set_door_lights(0);
-  }*/
-
-  if (puzzle_state == 2 && (check_laser_rx(code[2])))
-    {
-      puzzle_state = 3;
-      set_door_lights(189);
-      delay(500);
-    }
-  /*else
-  {
-    puzzle_state = 0;
-    set_door_lights(0);
-  }*/
-
-  if (puzzle_state == 3 && (check_laser_rx(code[3])))
-    {
-      puzzle_state = 4;
-      set_door_lights(255);
-      delay(500);
-    }
-  /*else
-    {
-    puzzle_state = 0;
-    set_door_lights(0);
-    }*/
-
-
-
-  return puzzle_state;
-}
-
-};
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-class Room3
-{
-public:
-
-Room3()
-{
-pinMode(r3_picture_pin,INPUT);
-pinMode(r3_g1_pin, OUTPUT);
-pinMode(r3_g2_pin,OUTPUT);
-pinMode(r3_g3_pin,OUTPUT);
-pinMode(r3_g4_pin,OUTPUT);
-pinMode(r3_shield_pin,INPUT_PULLDOWN);
-pinMode(r3_statue_orientation_pin,INPUT_PULLDOWN);
-}
-
-
-
-bool check_pictures()
-{
-  return (digitalRead(r3_picture_pin));
-}
-
-void set_glyph(int glyph, bool status)
-{
-  switch (glyph)
-  {
-  case 1: digitalWrite(r3_g1_pin,status);
-  case 2: digitalWrite(r3_g2_pin,status);
-  case 3: digitalWrite(r3_g3_pin,status);
-  case 4: digitalWrite(r3_g4_pin,status);
-  }
-}
-
-bool check_shield()
-{
-  return(digitalRead(r3_shield_pin));
-}
-
-bool check_statue_orientation()
-{
-  return(digitalRead(r3_statue_orientation_pin));
-}
-};
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-class RFID_EFFECTS
-{
-private:
-Mfrc522 * rfid [6];
-unsigned char codes [6][5];
-
-public:
-RFID_EFFECTS()
-{
-  SPI.begin();
-  for (int i = 0; i < 6 ; i++)
-  {
-    rfid[i] = new Mfrc522(i);
-    rfid[i]->Init();
-  }
-}
-
-void set_codes()
-  {
-    unsigned char temp[16];
-    for (int i = 0 ; i < 6 ; i++)
-    {
-      if ( rfid[i]->Request(PICC_REQIDL, temp) == '0' )
-      {
-        if (rfid[i]->Anticoll(temp) == '0')
-        {
-          for(int j = 0 ; i < 5 ; i++)
-          {
-          codes[i][j] = temp[j];
-          }
-        }
-      }
-    }
-  }
-
-bool get_codes()
-{
-  bool compare = true;
-  unsigned char temp[16];
-    for (int i = 0 ; i < 6 ; i++)
-    {
-      if ( rfid[i]->Request(PICC_REQIDL, temp) == '0' )
-      {
-        if (rfid[i]->Anticoll(temp) == '0')
-        {
-         for (int j = 0 ; i < 6 ; i++)
-         {
-
-            if (codes[i][j] == temp[j])
-              compare &= true;
-              else
-              compare &= false;
-
-         }
-        }
-      }
-    }
-}
-
-
-
-};
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-//////////////////////////////////////////////////////////////////////////////
-//status registers
-int status = 0;
-/*
- 0 = standby
- 1 = room1
- 2 = room2
- 3 = room3
- 4 = game over
- 5 = reset1
- 6 = reset2
- 7 = manual test
- */
-
-
-void serial_readin()
-{
-  String serial_in = "NULL";
-  if (Serial.available())
-  serial_in = Serial.readString();
-  else
-  serial_in = "NULL";
-
-    if (serial_in == "status = 0")
-    status = 0;
-
-    if (serial_in == "status = 1")
-    status = 1;
-
-    if (serial_in == "status = 2")
-    status = 2;
-
-    if (serial_in == "status = 3")
-    status = 3;
-
-    if (serial_in == "status = 4")
-    status = 4;
-
-    if (serial_in == "status = 5")
-    status = 5;
-
-    if (serial_in == "status = 6")
-    status = 6;
-
-    if (serial_in == "status = 7")
-    status = 7;
-
-    if (serial_in == "reset_1")
-    status = 5;
-
-    if (serial_in == "reset_2")
-    status = 6;
-
-    if (serial_in == "set_rfid")
-    status = 7;
-
-
-}
-
-
-
-
-
-
-
-
-void setup() {
-  // put your setup code here, to run once:
-Serial.begin(9600);
-Room1 room1;
-Room2 room2;
-Room3 room3;
-
-}
-
-void loop() {
-  // put your main code here, to run repeatedly:
-  ;
-}


Updating LCD driver size for SR4W port adapter.


implemented button, removed display glitch when tone is activated

--- examples/led8x8display/led8x8display.ino
+++ examples/led8x8display/led8x8display.ino
@@ -57,10 +57,6 @@
 #define DATA 14
 #define DELAYTIME 1 // microseconds to wait after setting pin

-// default launchpad pins (note: they overlap with the default connection of the booster pack!)
-#define SWITCH 4
-#define LED1 2
-#define LED2 14

 // The string to display:
 const char *str = "}} Hello  World... }}";
@@ -77,11 +73,18 @@
 void setup()
 {
   pinMode(BUZ1, OUTPUT);
-  pinMode(BUZ2, OUTPUT);
+  pinMode(BUZ2, OUTPUT); // note: also switch
   pinMode(CLOCK, OUTPUT);
   pinMode(DATA, OUTPUT);
   pinMode(LATCH, OUTPUT);
+  pinMode(PUSH2, INPUT_PULLUP);
   analogReference(INTERNAL1V5);
+}
+
+// Read switch status
+boolean button()
+{
+  return digitalRead(PUSH2) == 0;
 }

 // send 16 bits to LED tile (bits 0..7 are column, 8..15 are row)
@@ -162,7 +165,7 @@
 **/
 void loop()
 {
-  int a =0, i=0, j=0, now, avg, prev, val;
+  int a =0, i=0, j=0, now=0, avg=0, prev=0, val=0;
   sineWave();
   for(i=0;i<20;i++)
    tone(500*i);
@@ -178,7 +181,9 @@
       if ( now < 0 ) now = -now;
       avg = (15 * avg + now) / 16;
       val = ABS(avg-prev);
-      shiftLeft(  128>>val );
+      shiftLeft(  128>>val );
+      if ( button() )
+        avg = 0;
       tone(100*val);
       prev = avg;
     }
@@ -215,6 +220,7 @@
       else
       {
         shiftLeft(0); // blank line
+        sendImage(image);
         tone(500);
       }
       if ( ++j > 5 ) // next character


Updated arduino sketch

Updated arduino sketch

--- Udoo_Neo_Serial/Udoo_Neo_Serial.ino
+++ Udoo_Neo_Serial/Udoo_Neo_Serial.ino
@@ -33,12 +33,15 @@
   Serial.begin(115200);
   pinMode(PIR,INPUT);
   pinMode(LED1,OUTPUT);
+  timer1.time = 2000;
+  emailDelay.time = 60000;
   intToStr = (unsigned char*) malloc (sizeof(int)/sizeof(unsigned char));
   if(intToStr != NULL) memset(&intToStr,0,sizeof(int)/sizeof(unsigned char));
   memset(&buff,0,BUFFER_MAX);
 }

 void loop() {
+
   /*
   if(Serial.available()>0){
     byte bytes = readSerial(buff);
@@ -49,17 +52,16 @@

   if(digitalRead(PIR)==HIGH){
     digitalWrite(LED1,HIGH);
+
+    if(!motionDetected){         // One Shot
+      sendCommand(":Debug","Taking photo");
+      //sendCommand(":Webcam","foto00.jpeg");
+      sendCommand(":EmailPhoto","jerullan@yahoo.com,Security Alert,Motion triggered alarm!");
+      motionDetected = true;
+      resetTimer(&emailDelay);
+    }

     if(timerDone(&timer1)){
-
-      if(!motionDetected){         // One Shot
-        sendCommand(":Debug","Taking photo");
-        sendCommand(":Webcam","capture00.jpeg");
-        //sendCommand(":EmailPhoto","jerullan@yahoo.com,Security Alert,Motion triggered alarm!");
-        motionDetected = true;
-        resetTimer(&emailDelay);
-      }
-
       String message = "Motion Detected ";
       message += (millis()-emailDelay.last)/1000;
       sendCommand(":Debug",message);


Update EraseEEPROM.ino

Update EraseEEPROM.ino

--- examples/EraseEEPROM/EraseEEPROM.ino
+++ examples/EraseEEPROM/EraseEEPROM.ino
@@ -6,18 +6,15 @@
 {
   #ifdef ESP8266
   Serial.begin(115200);
+  EEPROM.begin(4); // Only one byte cleared, but 4 is the minimum for begin()
   #else
   Serial.begin(9600);
-  #endif
-
-  #ifdef ESP8266
-  EEPROM.begin(4); // Only one byte cleared, but 4 is the minimum for begin()
   #endif

   EEPROM.write(EEPROM_OFFSET, 0);

   #ifdef ESP8266
-  EEPROM.commit();
+  EEPROM.end();
   #endif

   Serial.println("Done.");


remove Arduino.h header include

remove Arduino.h header include

the Arduino.h is deprecated as the new linux_userspace.h is
included by default on the builds.

--- arduino-makefile/examples/HelloWorldUserspace/HelloWorldUserspace.ino
+++ arduino-makefile/examples/HelloWorldUserspace/HelloWorldUserspace.ino
@@ -4,7 +4,6 @@
  *
  *
  */
-#include "Arduino.h"

 void setup() {
 	printf("hello, world!\n");


charger dont care about these

charger dont care about these

Signed-off-by: Robert Nelson <d6c41255011d14bfa93d8562b946ca186cfa0c7b@gmail.com>

--- BatteryCharger/BatteryCharger.ino
+++ BatteryCharger/BatteryCharger.ino
@@ -19,18 +19,10 @@
 float shuntvoltage_A = 0;
 float busvoltage_A = 0;
 float current_mA_A = 0;
-float loadvoltage_A = 0;

 float shuntvoltage_B = 0;
 float busvoltage_B = 0;
 float current_mA_B = 0;
-float loadvoltage_B = 0;
-
-//with xbee on
-float shuntvoltage_C = 0;
-float busvoltage_C = 0;
-float current_mA_C = 0;
-float loadvoltage_C = 0;

 void setup () {
 	//clock_prescale_set(clock_div_4);
@@ -57,7 +49,6 @@
 	//Print readings every second
 	if (millis() - lastSecond >= 10000)
 	{
-
 		lastSecond += 10000;

 		shuntvoltage_A = ina219_A.getShuntVoltage_mV();
@@ -84,10 +75,6 @@
 		Serial.print(current_mA_A);
 		Serial.println("mA*");

-		shuntvoltage_C = ina219_A.getShuntVoltage_mV();
-		busvoltage_C = ina219_A.getBusVoltage_V();
-		current_mA_C = ina219_A.getCurrent_mA();
-
 		Serial.print("$CHARGER:");
 		Serial.print(counter);
 		Serial.print(":BusVolt:");
@@ -98,18 +85,6 @@
 		Serial.print(counter);
 		Serial.print(":Current:");
 		Serial.print(current_mA_B);
-		Serial.println("mA*");
-
-		Serial.print("$LOADXB:");
-		Serial.print(counter);
-		Serial.print(":BusVolt:");
-		Serial.print(busvoltage_C);
-		Serial.println("V*");
-
-		Serial.print("$LOADXB:");
-		Serial.print(counter);
-		Serial.print(":Current:");
-		Serial.print(current_mA_C);
 		Serial.println("mA*");
 		Serial.println("");


Update DigestAuthorization.ino (#6029)

Update DigestAuthorization.ino (#6029)

Fix WiFiClient vs. HttpClient declaration order

--- libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino
+++ libraries/ESP8266HTTPClient/examples/DigestAuthorization/DigestAuthorization.ino
@@ -98,9 +98,8 @@
 }

 void loop() {
-  HTTPClient http;
-
   WiFiClient client;
+  HTTPClient http; //must be declared after WiFiClient for correct destruction order, because used by http.begin(client,...)

   Serial.print("[HTTP] begin...\n");


Refactored code, moved MATH out of max() parameters (see docs)

--- humidity_simple/humidity_simple.ino
+++ humidity_simple/humidity_simple.ino
@@ -1,13 +1,12 @@
 #include <Time.h>

-const int relaisPin =  11;
+const int relayPin =  11;
 const int sensorPin = A0;    // select the input pin for the potentiometer
 const int MINHUMIDITY = 0;
 const int MAXHUMIDITY = 1023;
 const int milliseconds_sleep = 5000;
 const int avg_decay = 0.00001;
 const int deviation_decay = 0.01;
-int sensorValue = 0;  // variable to store the value coming from the sensor
 int thresholdLow = 0;
 int thresholdHigh = 0;
 int avg = 0;
@@ -16,7 +15,7 @@
 int startup_seconds = 900; // sensor needs to settle for 15 minutes

 int get_humidity() {
-  sensorValue = analogRead(sensorPin);
+  int sensorValue = analogRead(sensorPin);

   // sensor value is high when humidity is low, this is
   // counterintuitive (it's a dryness sensor!), so we
@@ -27,9 +26,9 @@
 void setup() {
   // initialize the 11 pin as an output:
   Serial.begin(9600);
-  pinMode(relaisPin, OUTPUT);
+  pinMode(relayPin, OUTPUT);
   pinMode(sensorPin, INPUT);
-  digitalWrite(relaisPin, HIGH);
+  digitalWrite(relayPin, HIGH);
   avg = get_humidity();
 }

@@ -44,8 +43,9 @@
     // decay the old value, combine with the new (reverse decay)
     avg = avg * (1.0 - avg_decay) + humidity * avg_decay;
   }
-  int cur_deviation = max(deviation, humidity - avg);
-  deviation = deviation * (1.0 - deviation_decay) + cur_deviation * deviation_decay;
+  int cur_deviation = humidity - avg;
+  int max_deviation = max(deviation, cur_deviation);
+  deviation = deviation * (1.0 - deviation_decay) + max_deviation * deviation_decay;
   thresholdLow = avg + deviation / 3;
   thresholdHigh = avg + 2 * deviation / 3;

@@ -62,12 +62,12 @@
   Serial.println(avg + deviation);

   // switch the relays!
-  if (sensorValue < thresholdLow) {
+  if (humidity < thresholdLow) {
     // HIGH means setting the relay to NC
-    digitalWrite(relaisPin, HIGH);
-  } else if (sensorValue > thresholdHigh) {
+    digitalWrite(relayPin, HIGH);
+  } else if (humidity > thresholdHigh) {
     // LOW means setting the relay to NO
-    digitalWrite(relaisPin, LOW);
+    digitalWrite(relayPin, LOW);
   }
   delay(milliseconds_sleep);
 }


updated

updated

--- jenny5-firmware/jenny5-firmware.ino
+++ jenny5-firmware/jenny5-firmware.ino
@@ -12,7 +12,7 @@

 char is_command_running;

-char firmware_version[] = "2015.11.11.3";
+char firmware_version[] = "2015.11.11.4";

 AccelStepper *steppers[num_motors];

@@ -33,6 +33,7 @@
   reset_pins();

   Serial.begin(9600); //Open Serial connection
+
   Serial.print("Jenny 5 firmware version: ");
   Serial.print(firmware_version);
   Serial.println();
@@ -47,7 +48,7 @@

   Serial.println();

-  current_buffer[0] = 0;
+  current_buffer[0] = 0;//'\0';
   is_command_running = 0;
 }
 //--------------------------------------------------------------------------------------------
@@ -69,7 +70,7 @@
         Serial.println();
       #endif

-      // parse from the beginning until I find a M, D, S or A
+      // parse from the beginning until I find a M, D, L, S, A, P, B, U
       int buffer_length = strlen(current_buffer);
       for (int i = 0; i < buffer_length; i++)
         if (current_buffer[i] >= 'A' && current_buffer[i] <= 'Z' || current_buffer[i] >= 'a' && current_buffer[i] <= 'z'){// a command
@@ -135,7 +136,7 @@
       is_one_motor_running = true;
     }
     else{
-      steppers[m]->setCurrentPosition(0);
+      steppers[m]->setCurrentPosition(0);
     }
   if (!is_one_motor_running)
     is_command_running = 0;


fixed some bugs with disabling, turn on LED when servos active

--- src/org/ine/telluride/jaer/tell2022/GoingFishingFirmware/GoingFishingFirmware.ino
+++ src/org/ine/telluride/jaer/tell2022/GoingFishingFirmware/GoingFishingFirmware.ino
@@ -7,35 +7,40 @@
 byte bytes[3];

 void setup() {
+  pinMode(LED_BUILTIN, OUTPUT);
+  Serial.begin(115200);
   theta.attach(12);
   z.attach(9);
-
-  Serial.begin(115200);
-  delay(1000);
+  digitalWrite(LED_BUILTIN, HIGH);
+  theta.write(90);
+  z.write(90);
+  delay(300);
   theta.detach();
   z.detach();
-
+  digitalWrite(LED_BUILTIN, LOW);
 }

 void loop() {
   while (Serial.available() < 3)
     return;
-  if (Serial.readBytes(bytes, 3) == 3) {
-    bool disable = bytes[0];
-    int thetaDeg = bytes[1];
-    int zDeg = bytes[2];
-    if (disable) {
-      disabled = true;
-      theta.detach();
-      z.detach();
-    } else {
-      if (disabled) {
-        theta.attach(12);
-        z.attach(9);
-        disabled = false;
-      }
-      theta.write(thetaDeg);
-      z.write(zDeg);
+  if (Serial.readBytes(bytes, 3) < 3)
+    return;
+  bool disable = bytes[0];
+  int thetaDeg = bytes[1];
+  int zDeg = bytes[2];
+  if (disable) {
+    disabled = true;
+    theta.detach();
+    z.detach();
+    digitalWrite(LED_BUILTIN, LOW);
+  } else {
+    if (disabled) {
+      theta.attach(12);
+      z.attach(9);
+      disabled = false;
+      digitalWrite(LED_BUILTIN, HIGH);
     }
+    theta.write(thetaDeg);
+    z.write(zDeg);
   }
 }


main: cleanup all begin()s

main: cleanup all begin()s

--- src/main.ino
+++ src/main.ino
@@ -20,19 +20,16 @@
 {
     bool clear = true;
     char *banner;
+    String r = ESP.getResetReason();

     expand.begin();
-
-    String r = ESP.getResetReason();
+    Serial.begin(9600);
     SPIFFS.begin();
+    display.begin();

     if (r == "Deep-Sleep Wake") {
         clear = false;
     }
-
-    Serial.begin(9600);
-
-    display.begin();

     if (!load_config()) {
         banner = strdup("NO CONFIG");


Improve firmware; rewrite for Bean

Improve firmware; rewrite for Bean

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

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

     sensors.begin();
     if (!sensors.getAddress(thermometer, 0)) {
@@ -34,37 +34,59 @@

 void loop()
 {
-    // Wait for serial data
-    while (!Serial.available());
+    // Sleep if there are no incoming commands
+    if (!Serial.available()) {
+        Bean.sleep(20000);
+    }
+
+    Bean.setLed(0, 0, 255);
+
     byte cmd = Serial.read();
-    if (cmd == '0') {
+
+    if (cmd == 0x00) {
         // 0: Get status
         // Send the command to get temperatures
         sensors.requestTemperatures();
-        // Print the received temperature
-        Serial.print("Enabled: ");
-        Serial.print(enabled);
-        Serial.print(", temp F: ");
-        Serial.print(temperature());
-        Serial.print(", target F: ");
-        Serial.println(targetTempF);
-    } else if (cmd == '1') {
-        // 1: Turn on heater
+
+        // Return 0x00, current temp, target temp, 0xFF
+        Serial.write(0x00);
+        Serial.write((int)temperature());
+        Serial.write(targetTempF);
+        Serial.write(0xFF);
+
+    } else if (cmd == 0x01) {
+        // 1: Enable heater
         enabled = true;
-        Serial.println("Heater on");
-    } else if (cmd == '2') {
-        // 2: Turn off heater
+
+        // Return 0x01, 0xFF
+        Serial.write(0x01);
+        Serial.write(0xFF);
+
+    } else if (cmd == 0x02) {
+        // 2: Disable heater
         enabled = false;
-        Serial.println("Heater off");
-    } else if (cmd == '3') {
+
+        // Return 0x02, 0xFF
+        Serial.write(0x02);
+        Serial.write(0xFF);
+
+    } else if (cmd == 0x03) {
         // 3: Set target temperature
         while (!Serial.available());
         targetTempF = Serial.read();
-        Serial.print("Set temp to ");
-        Serial.println(targetTempF);
+
+        // Return 0x03, target temp, 0xFF
+        Serial.write(0x03);
+        Serial.write(targetTempF);
+        Serial.write(0xFF);
+
     } else {
+        // Flush incoming buffer
         while (Serial.available()) {
             Serial.read();
         }
     }
+
+    Bean.setLed(0, 0, 0);
+
 }


Remove unused code

Remove unused code

--- midicontroller.ino
+++ midicontroller.ino
@@ -21,8 +21,6 @@
 const byte numberOfChannelButtons = 2;
 const byte ledPins[] = {/*10, 11, 12,*/ 14, 15, 16};
 Button channelButtons[numberOfChannelButtons];
-boolean channelButtonStates[numberOfChannelButtons];
-boolean channelButtonDown[numberOfChannelButtons];

 const byte bankDownPin = 6;
 const byte bankUpPin = 7;
@@ -83,20 +81,9 @@
   playButton.init(playPin);
 }

-void initButton(byte pin, Bounce *button, boolean *state, boolean *down) {
-  pinMode(pin, INPUT_PULLUP);
-  (*button).attach(pin);
-  (*button).interval(10);
-  *state = false;
-  *down = false;
-}
-
 void setupLeds() {
   pinMode(ledPin, OUTPUT);
-  pinMode(bpmLed, OUTPUT);
-  for (byte i = 0; i < numberOfChannelButtons; i++) {
-    pinMode(ledPins[i], OUTPUT);
-  }
+  pinMode(bpmLed, OUTPUT);
 }


both circuits detecting connections

both circuits detecting connections

--- arduino/modularsynth/modularsynth.ino
+++ arduino/modularsynth/modularsynth.ino
@@ -56,7 +56,7 @@
   int i,j,k,m;

   // supply 5V to each "write" demultiplexer in turn
-  for(i=0;i<4;i++) {
+  for(i=0;i<8;i++) {
     digitalWrite(DEMUX_SELECT_1,bitRead(i,0));
     digitalWrite(DEMUX_SELECT_2,bitRead(i,1));
     digitalWrite(DEMUX_SELECT_3,bitRead(i,2));
@@ -74,7 +74,7 @@
         digitalWrite(READ_SELECT_3,bitRead(k,2));

         // read from each multiplexer in turn
-        for(m=0;m<4;m++) {
+        for(m=0;m<8;m++) {
           if(i*8+j<m*8+k) {
             if(digitalRead(READ_MUX_PINS[m])==HIGH) {
               Serial.print(i*8 + j);


send sensible pixel data

send sensible pixel data

--- arduino/led_matrix/led_matrix.ino
+++ arduino/led_matrix/led_matrix.ino
@@ -22,8 +22,8 @@
   for (y = 0; y < HEIGHT; y++) {
     for (x = 0; x < WIDTH; x++) {
       while (Serial.available() < 3);
+      g = Serial.read();
       r = Serial.read();
-      g = Serial.read();
       b = Serial.read();
       if (y % 2 == 0) {
         xx = x;


More Comments

More Comments

--- multi_point_led/multi_point_led.ino
+++ multi_point_led/multi_point_led.ino
@@ -28,6 +28,7 @@
   int on_pixel;
   int off_pixel;
   int num_pixels_on = 2;
+  //This leaves 2 pixels on at all times:
   for(int i=0;i < NUMPIXELS;i++){
     on_pixel = i;
     off_pixel = i - num_pixels_on;
@@ -43,11 +44,11 @@
     if (off_pixel > NUMPIXELS){
       off_pixel -= NUMPIXELS;
     }
-    pixels.setPixelColor(on_pixel, pixels.Color(255,255,255)); // Moderately bright green color.
-    pixels.show(); // This sends the updated pixel color to the hardware.
-    pixels.setPixelColor(off_pixel, pixels.Color(0,0,0)); // Moderately bright green color.
-    pixels.show(); // This sends the updated pixel color to the hardware.
-    delay(delayval); // Delay for a period of time (in milliseconds).
+    pixels.setPixelColor(on_pixel, pixels.Color(255,255,255));
+    pixels.show();
+    pixels.setPixelColor(off_pixel, pixels.Color(0,0,0));
+    pixels.show();
+    delay(delayval);
   }
 }


Update arduino_client

Update arduino_client

--- Arduino/arduino_client/arduino_client.ino
+++ Arduino/arduino_client/arduino_client.ino
@@ -1,10 +1,154 @@
+#include <NewPing.h>
+#include <Servo.h>
+
+#define SONAR_NUM      2 // Number of sensors.
+#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.
+#define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).
+
+unsigned long pingTimer[SONAR_NUM]; // Holds the times when the next ping should happen for each sensor.
+unsigned int cm[SONAR_NUM];         // Where the ping distances are stored.
+uint8_t currentSensor = 0;          // Keeps track of which sensor is active.
+
+// Declare L298N Dual H-Bridge Motor Controller directly since there is not a library to load.
+
+// Motor A
+uint8_t dir1PinA = 2;
+uint8_t dir2PinA = 3;
+int speedPinA = 4; // Needs to be a PWM pin to be able to control motor speed
+
+// Motor B
+uint8_t dir1PinB = 5;
+uint8_t dir2PinB = 6;
+int speedPinB = 7; // Needs to be a PWM pin to be able to control motor speed
+
+const int servoPin = 6; // the digital pin used for the first servo
+
+NewPing sonar[SONAR_NUM] = {     // Sensor object array.
+  NewPing(22, 23, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
+  NewPing(24, 25, MAX_DISTANCE),
+};
+
+Servo servo;  // create servo object to control a servo
+
 void setup() {
+  // initialize serial communication @ 115200 baud
   Serial.begin(115200);
+
+  pinMode(dir1PinA,OUTPUT);
+  pinMode(dir2PinA,OUTPUT);
+  pinMode(speedPinA,OUTPUT);
+  pinMode(dir1PinB,OUTPUT);
+  pinMode(dir2PinB,OUTPUT);
+  pinMode(speedPinB,OUTPUT);

+  servo.attach(servoPin);  // attaches the servo on pin 9 to the servo object
+  servo.write(0);
+  pingTimer[0] = millis() + 75;           // First ping starts at 75ms, gives time for the Arduino to chill before starting.
+  for (uint8_t i = 1; i < SONAR_NUM; i++) // Set the starting time for each sensor.
+    pingTimer[i] = pingTimer[i - 1] + PING_INTERVAL;
 }

 void loop() {
-  Serial.println("Hello, World");
-  delay(2000);
+  for (uint8_t angle = 15; angle <= 165; angle++) {
+    // write servo angle position
+    servo.write(angle);
+
+    for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
+      if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
+        pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
+        if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
+        sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
+        currentSensor = i;                          // Sensor being accessed.
+        cm[currentSensor] = 0;                      // Make distance zero in case there's no ping echo for this sensor.
+        sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
+      }
+    }

+    // Other code that *DOESN'T* analyze ping results can go here.
+    doStaff(); // All logic controller is implemented here
+    delay(30); // delay for 30 ms
+  }
+
+  for (uint8_t angle = 165; angle > 15; angle--) {
+    // write servo angle position
+    servo.write(angle);
+
+    // ping ultrasonic sensor
+    for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through all the sensors.
+      if (millis() >= pingTimer[i]) {         // Is it this sensor's time to ping?
+        pingTimer[i] += PING_INTERVAL * SONAR_NUM;  // Set next time this sensor will be pinged.
+        if (i == 0 && currentSensor == SONAR_NUM - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results.
+        sonar[currentSensor].timer_stop();          // Make sure previous timer is canceled before starting a new ping (insurance).
+        currentSensor = i;                          // Sensor being accessed.
+        cm[currentSensor] = 0;                      // Make distance zero in case there's no ping echo for this sensor.
+        sonar[currentSensor].ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
+      }
+    }
+
+    // Other code that *DOESN'T* analyze ping results can go here.
+    doStaff(); // All logic controller is implemented here
+    delay(30); // delay for 30 ms
+  }
 }
+
+void echoCheck() { // If ping received, set the sensor distance to array.
+  if (sonar[currentSensor].check_timer())
+    cm[currentSensor] = sonar[currentSensor].ping_result / US_ROUNDTRIP_CM;
+}
+
+void oneSensorCycle() { // Sensor ping cycle complete, do something with the results.
+  // The following code would be replaced with your code that does something with the ping results.
+  for (uint8_t i = 0; i < SONAR_NUM; i++) {
+    Serial.print(i);
+    Serial.print("=");
+    Serial.print(cm[i]);
+    Serial.print("cm ");
+  }
+  Serial.println();
+}
+
+void doStaff() {
+  uint8_t serIn = 0;
+  if (Serial.available()) {
+    serIn = Serial.read();
+  }
+
+  switch (serIn) {
+    case 1:
+      // move robot forward
+      goForward();
+      break;
+    case 2:
+      // move robot backward
+      goBackward();
+      break;
+    case 3:
+      // move robot to left direction
+      goLeft();
+      break;
+    case 4:
+      // move robot to right direction
+      goRight();
+      break;
+    default:
+      // default state
+      break;
+  }
+}
+
+void goForward() {
+  // move robot forward
+}
+
+void goBackward() {
+  // move robot backward
+}
+
+void goLeft() {
+  // move robot left direction
+}
+
+void goRight() {
+  // move robot right direction
+}
+


Ok, back to mike-dev.  Git is a fin useless shitpile.  Cost me a half-hour.

--- src/Tower/Tower.ino
+++ src/Tower/Tower.ino
@@ -233,6 +233,7 @@
   if ( networkTimeout.check() ) {
     Serial << F("Network timeout.") << endl;
     networkTimedOut = true;
+    Serial << F("Free RAM: ") << freeRam() << endl;
   }
   if( systemResetFlag ) {
     resetTestPattern();
@@ -255,7 +256,9 @@
 boolean systemReseted() {
   // with EMI, be very sure.
   Metro readTime(DEBOUNCE_TIME);
+  readTime.interval(DEBOUNCE_TIME);
   readTime.reset();
+
   while( !readTime.check() ) systemReset.update();

   // at system power up, relay is open, meaning pin will read HIGH.
@@ -519,6 +522,8 @@
 // alternative to delay(), non-blocking
 void myDelay(unsigned long delayTime) {
   Metro delayFor(delayTime);
+  delayFor.interval(delayTime);
+  delayFor.reset();

   while( ! delayFor.check() ) {
     // insert any mission-critical operations here
@@ -526,5 +531,9 @@
   }
 }

-
-
+int freeRam () {
+  extern int __heap_start, *__brkval;
+  int v;
+  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
+}
+


No DEBUG

No DEBUG

--- DigitalSynthVRA8Px/DigitalSynthVRA8Px.ino
+++ DigitalSynthVRA8Px/DigitalSynthVRA8Px.ino
@@ -1,4 +1,4 @@
-#define DEBUG
+//#define DEBUG

 #include "common.h"
 #include "synth.h"


last execution instead of delay

last execution instead of delay

--- src/basic/basic.ino
+++ src/basic/basic.ino
@@ -14,6 +14,8 @@
 // The TinyGPS++ object
 TinyGPSPlus gps;

+int lastExecutionMillis = 0;
+int lastSendMillis = 0;
 // Setup routine runs once when you press reset
 void setup() {
   pinMode(13, OUTPUT);
@@ -49,29 +51,35 @@
   Serial.println("Initialized GPS");

   led_off();
-  delay(2000);
 }

 // the loop routine runs over and over again forever:
 void loop() {
-  Serial.println("starting loop...");
+  int currentMillis = millis();
+
+  //if(currentMillis - lastExecutionMillis < 5000){
+  //  return;
+  //}
+  lastExecutionMillis = currentMillis;
   led_on();
-  while (gpsSerial.available() > 0){
+  int available = gpsSerial.available();
+  if(available == 0)
+    return;
+  Serial.println("available bytes from gps: " + String(available, DEC));
+  while (available > 0){
     if (gps.encode(gpsSerial.read())){
       displayInfo();
-      if (gps.location.isValid()){
+      if (gps.location.isValid() && currentMillis - lastSendMillis > 30000){
         transmit_coords(gps.location.lat(), gps.location.lng());
-        delay(5000);
-        break;
       }
+      break;
     }
+    available = gpsSerial.available();
   }
   if(receivedBikeKillSignal()){
     Serial.println("Deactivating Bike...");
   }
-  Serial.println("end of loop...");
   led_off();
-  delay(5000);
 }

 boolean receivedBikeKillSignal() {
@@ -84,6 +92,7 @@
 }

 void transmit_coords(double float_latitude, double float_longitude){
+  Serial.println("Transimitting coords...");
   uint8_t coords[6]; // 6*8 bits = 48
   int32_t lat = float_latitude * 10000;
   int32_t lon = float_longitude * 10000;


modified framework

modified framework

--- task6/task6.ino
+++ task6/task6.ino
@@ -3,19 +3,68 @@
 //Created by Yuhan Long
 //this work belongs to evolutus
 //all right reserved
-void dsetup(){
-
- //for setup code of pins and interrupts.
+#include <TimerOne.h>
+
+
+
+//int BUTTON=;
+//int SLOT=;
+
+
+public char time200 = 0;
+//public char time4 = 0;
+
+void timerInterrupt(){
+  //read switch at a granulartiy of 0.02s
+  //take serial communication every 0.1s
+  static int timer_count = 0;
+
+  timer_count++;
+  if(timer_count % 4 == 0) {
+    //0.02 second reached
+    ButtonBuf = ButtonBuf * 2 + digitalRead(BUTTON);
+    SlotBuf = SlotBuf *2 + digitalRead(SLOT);
+    }
+  if(timer_count ==200) {
+    //0.1 secound reached
+    time200 = 1;
+    timer_count = 0;
+    }
 }

-void timerInterrup(){
-  //read all sensor,
-  //send new comments to motors,
+void setup(){
+ //for setup code of pins and interrupts.
+ Timer1.initialize(5000);//set the timer interrupt at 100ms
+ Timer1.attachInterrupt(timerInterrupt);
+ Serial.begin(9600);
+
+ pinMode(BUTTON, INPUT);
+ pinMode(SLOT, INPUT);

 }

+void sendData(){
+  //send IR distance to computer
+  //send Sonor distance to computer
+  //send Slotswtch action & button action
+}
+
+void readSensor(){
+  //receive IR distence
+  //receive Sonor distance
+}
+
+
 void loop(){
   //read the serial input and report data to the server.
-
+  if(time200 = 1){
+    readSensor();
+    sendData();
+    timer200 = 0;
+    }
+  //Check serial port
+
+  //apply the command on motor
+
 }


revert

revert

--- d_BacpacCommands.ino
+++ d_BacpacCommands.ino
@@ -210,7 +210,7 @@
       Serial.println("");
     }
     buf[0] = 0x83; buf[1] = 'S'; buf[2] = 'R'; buf[3] = RECV(3);
-    if (buf[3] == 1) {
+    if (buf[3] == 1 && (!isMaster || td[TD_MODE] != MODE_TIMELAPSE)) {
       delay(1000); // start of a capture requres additional delay
     }
     delay(140);


Add simple code to test the speaker

Add simple code to test the speaker

--- timer/timer.ino
+++ timer/timer.ino
@@ -25,6 +25,8 @@
   Serial.println("Starting up!");

   buttons.setup();
+
+  pinMode(PIN_SPEAKER, OUTPUT);

   countdown_ends = 0;
   countdown_duration = 900000; // 15 mins in ms
@@ -74,6 +76,9 @@

 void change_to_state(int new_state) {
+
+  noTone(PIN_SPEAKER);
+
   if (new_state == STATE_WAITING) {
     current_state = STATE_WAITING;
   } else if (new_state == STATE_RUNNING) {
@@ -128,10 +133,17 @@
   pulser.pulse();
   display.display_time( time_remaining / 1000 );

+
   running_state_loop_buttons(button);
 }

 void beeping_state_loop (int button) {
+
+  if (millis() % PULSER_FLASH_PERIOD > PULSER_FLASH_PERIOD / 2 ) {
+    tone(PIN_SPEAKER, 400);
+  } else {
+    noTone(PIN_SPEAKER);
+  }

   pulser.flash();
   display.display_time( 0 );


Update LineFollower.ino

Update LineFollower.ino

--- DolonCSE/LineFollower/LineFollower.ino
+++ DolonCSE/LineFollower/LineFollower.ino
@@ -8,7 +8,7 @@
  */

-#include <Motor.h>
+#include "Motor.h"
 #define baud 9600
 #define spd 255
 #define del 500


Corrected hostname setting for OTA.

Corrected hostname setting for OTA.

--- src/_ota.ino
+++ src/_ota.ino
@@ -19,7 +19,7 @@
  */
 void setupOTA() {
   ArduinoOTA.setPort(OTA_PORT);
-  ArduinoOTA.setHostname(DEVICE_ID);
+  ArduinoOTA.setHostname(getDeviceID());
   ArduinoOTA.setPassword(OTA_PASSWORD);

   ArduinoOTA.onStart([]() { DEBUGLOG("[OTA] Start\n"); });


add data from Date header as Date and Time infoscreen

--- firmwetter/firmwetter.ino
+++ firmwetter/firmwetter.ino
@@ -8,6 +8,7 @@
 #define MIDDLE_LENGTH    14

 String wetter;
+String dateHeader;

 struct Line {
   String _name;
@@ -22,11 +23,9 @@
   Line _lines[5];
 };

-#define SCREENS   4
+#define SCREENS   2

 Infoscreen inf[SCREENS] = {
-  { "krefeld", "Zwingenbergstr", "", {} },
-  { "krefeld", "Heyenbaumstr", "", {} },
   { "Duesseldorf", "Uni-Mitte", "", {} },
   { "Duesseldorf", "Botanischer-Garten", "", {} }
 };
@@ -62,6 +61,7 @@
 SSD1306Spi        display(D0, D2, D8);

 ESP8266WiFiMulti  WiFiMulti;
+HTTPClient http;

 void extractP(int id) {
   String cutting;
@@ -106,8 +106,10 @@
   delay(500);
   display.init();
   display.flipScreenVertically();
-  display.setFont(DejaVu_Sans_Condensed_8);
+  const char* headerNames[] = { "Date", "Content-Type" };
+  http.collectHeaders(headerNames, 2);
 }
+

 void loop() {
   if (seccount < 1) {
@@ -115,8 +117,6 @@

     // wait for WiFi connection
     if((WiFiMulti.run() == WL_CONNECTED)) {
-        HTTPClient http;
-
         for (int j = 0; j < SCREENS; ++j) {
           http.begin(
             String("https://vrrf.finalrewind.org/")+inf[j]._ort+String("/")+inf[j]._stop+String(".html?frontend=html"),
@@ -135,21 +135,34 @@
         http.begin("http://dummer.click/_p/wdrWetter/?text=true");
         int httpCode = http.GET();
         // httpCode will be negative on error
-        if(httpCode > 0 && httpCode == HTTP_CODE_OK) wetter = http.getString();
+        if (httpCode > 0 && httpCode == HTTP_CODE_OK) {
+          dateHeader = http.header("Date");
+          wetter = http.getString();
+        }
         http.end();
     }
   }

   display.clear();

-  display.setTextAlignment(TEXT_ALIGN_LEFT);
-
   if (infoScreen == SCREENS) {

+    display.setTextAlignment(TEXT_ALIGN_LEFT);
+    display.setFont(DejaVu_Sans_Condensed_8);
     display.drawStringMaxWidth(0, 3, 128, wetter);
+
+  } else if (infoScreen == (SCREENS+1)) {
+
+    display.setTextAlignment(TEXT_ALIGN_CENTER);
+    display.setFont(ArialMT_Plain_16);
+    display.drawString(64, 4, dateHeader.substring(0,11));
+    display.setFont(ArialMT_Plain_24);
+    display.drawString(64, 36, dateHeader.substring(17,22) + String(" ") + dateHeader.substring(25));

   } else {

+    display.setTextAlignment(TEXT_ALIGN_LEFT);
+    display.setFont(DejaVu_Sans_Condensed_8);
     display.drawString(0, 0, inf[infoScreen]._stop);

     display.setTextAlignment(TEXT_ALIGN_RIGHT);
@@ -170,6 +183,5 @@
   delay(1000);
   --seccount;
   if (seccount%5 == 0) infoScreen++;
-  if (infoScreen > SCREENS) infoScreen=0;
+  if (infoScreen > (SCREENS+1)) infoScreen=0;
 }
-


fix comments on spaceship example

fix comments on spaceship example

The comments explaining the if..else part were mistaken.

--- build/shared/examples/10.StarterKit/p02_SpaceshipInterface/p02_SpaceshipInterface.ino
+++ build/shared/examples/10.StarterKit/p02_SpaceshipInterface/p02_SpaceshipInterface.ino
@@ -44,7 +44,7 @@
   switchstate = digitalRead(2);

   // if the button is not pressed
-  // blink the red LEDs
+  // turn on the green LED and off the red LEDs
   if (switchstate == LOW) {
     digitalWrite(3, HIGH); // turn the green LED on pin 3 on
     digitalWrite(4, LOW);  // turn the red LED on pin 4 off
@@ -52,7 +52,7 @@
   }
   // this else is part of the above if() statement.
   // if the switch is not LOW (the button is pressed)
-  // the code below will run
+  // turn off the green LED and blink alternatively the red LEDs
   else {
     digitalWrite(3, LOW);  // turn the green LED on pin 3 off
     digitalWrite(4, LOW);  // turn the red LED on pin 4 off


servoFix handle on Arduino

servoFix handle on Arduino

--- arduino/rcController/rcController.ino
+++ arduino/rcController/rcController.ino
@@ -27,7 +27,7 @@
 const int MIN_ENGINE_SPEED = 80;

 // cmd:
-// ^ [1|2] [0-100] | [1|2] [0-100] [0-100]$
+// ^ [1|2] [0-100] | [1|2] [0-100] [-50 - 50]$
 // ^direction speed | side   angle  servo-fix$
 char START_CMD_CHAR = '^';
 char END_CMD_CHAR = '$';
@@ -43,7 +43,7 @@
   bluetooth.begin(9600);
   servo.attach(servoPin);

-  setServo(side, angle);
+  setServo(side, angle, servoFix);
   setDirectionPins(direction);
   setEnginePower(direction, speed);
 }
@@ -62,7 +62,7 @@

   int newSide = bluetooth.parseInt();
   int newAngle = bluetooth.parseInt();
-  int servoFix = bluetooth.parseInt();
+  int newServoFix = bluetooth.parseInt();
   if (bluetooth.read() != END_CMD_CHAR) return;

   // Validation
@@ -81,15 +81,16 @@
   Serial.print(" ");
   Serial.print(newAngle);
   Serial.print(" ");
-  Serial.print(servoFix);
+  Serial.print(newServoFix);
   Serial.println(END_CMD_CHAR);

   // Side or angle has changed
-  if (side != newSide || angle != newAngle) {
-    setServo(newSide, newAngle);
+  if (side != newSide || angle != newAngle || servoFix != newServoFix) {
+    setServo(newSide, newAngle, newServoFix);

     side = newSide;
     angle = newAngle;
+    servoFix = newServoFix;
     Serial.println("Servo moved");
   }

@@ -121,7 +122,7 @@
   }
 }

-void setServo(int side, int angle) {
+void setServo(int side, int angle, int servoFix) {
   int servoPwm = getServoPwm(side, angle, servoFix);
   servo.write(servoPwm);
 }


Array averaging finally works. Variable trial accuracy now!

--- arduino_distance/arduino_distance.ino
+++ arduino_distance/arduino_distance.ino
@@ -6,6 +6,7 @@

 #include <Wire.h>
 #include <VL53L0X.h>
+#define average_trials 3

 VL53L0X sensor;

@@ -20,37 +21,36 @@

 void loop()
 {
-  int a;
-  int lidar_array[3];
+  int avg;
+  int lidar_array[average_trials];
   populate_lidar_array(lidar_array);
-  a = average_lidar_array(lidar_array);
-  Serial.print(a);
+  avg = average_lidar_array(lidar_array);
+  Serial.print(avg);
   Serial.println();
 }

 int populate_lidar_array(int lidar_array[])
 {
-  int i;
-  int len = sizeof(lidar_array);
-  for (i = 0; i = (len-1); i = i +1)
+  for (int i = 0; i < average_trials; i = i +1)
   {
-    lidar_array[i] = sensor.readRangeSingleMillimeters();
+    lidar_array[i] = get_distance();
   }
 }

 int average_lidar_array(int lidar_array[])
 {
-  int i;
-  int len = sizeof(lidar_array);
   int sum = 0;
-  for (i = 0; i = (len-1); i = i + 1)
+  for (int i = 0; i < average_trials; i = i + 1)
   {
     sum += lidar_array[i];
   }
   int result;
-  result = ((float) sum) / len;
+  result = ((float) sum) / average_trials;
   return result;
 }

-
+int get_distance()
+{
+  return sensor.readRangeSingleMillimeters();
+}


Format while loops

Format while loops

--- src/Garbo.ino
+++ src/Garbo.ino
@@ -1,9 +1,9 @@
 #include <Bridge.h>
 #include <Process.h>

+#include "./dht.h"
 #include "./sampling.h"
 #include "./utils.h"
-#include "./dht.h"

 #define DHT_DEBUG

@@ -18,7 +18,8 @@
   Bridge.begin();

   DEBUG_PRINTLN("Checking connectivity... ");
-  while (!isConnectedToInternet(&p));
+  while (!isConnectedToInternet(&p)) {
+  }
   DEBUG_PRINTLN("Connected");

   DEBUG_PRINTLN("Syncing clock...");
@@ -28,11 +29,12 @@
     DEBUG_PRINTLN("BMP180 init success");
   } else {
     DEBUG_PRINTLN("BMP180 init failed");
-    while(1);
+    while (1) {
+    }
   }

   dht.begin();
-
+
   // Initialize light sensor
   tsl.enableAutoRange(true);
   tsl.setIntegrationTime(TSL2561_INTEGRATIONTIME_13MS);
@@ -42,19 +44,21 @@
 void loop() {
   WeatherSample sample;
   sampleWeather(&sample);
-
+
   p.begin("curl");
   p.addParameter("-i");
   p.addParameter("-XPOST");
   p.addParameter("http://192.168.178.37:8086/write?db=garbo");
   p.addParameter("-d "
-    "humidity,node=pluto value=" + String(sample.humidity) + "\n"
-    "temperature,node=pluto value=" + String(sample.temperature) + "\n"
-    "pressure,node=pluto value=" + String(sample.pressure) + "\n"
-    "light,node=pluto value=" + String(sample.light) + "\n"
-  );
+                 "humidity,node=pluto value=" +
+                 String(sample.humidity) + "\n"
+                                           "temperature,node=pluto value=" +
+                 String(sample.temperature) + "\n"
+                                              "pressure,node=pluto value=" +
+                 String(sample.pressure) + "\n"
+                                           "light,node=pluto value=" +
+                 String(sample.light) + "\n");
   p.run();

   delay(10000);
 }
-


Remove a String from function handleSPIFFSfile().

Probably the compiler already optimized it away, but hey...

--- webserver.ino
+++ webserver.ino
@@ -118,8 +118,7 @@
       return true;
     };
     File file = SPIFFS.open( path, "r" );
-    String contentType = getContentType( path );
-    size_t sent = webServer.streamFile( file, contentType );
+    size_t sent = webServer.streamFile( file, getContentType( path ) );
     file.close();
     return true;
   }


Remove uneeded header

Remove uneeded header

--- iDONT.ino
+++ iDONT.ino
@@ -4,8 +4,6 @@
 #include <DNSServer.h>            //Local DNS Server used for redirecting all requests to the configuration portal
 #include <ESP8266WebServer.h>     //Local WebServer used to serve the configuration portal
 #include <WiFiManager.h>          //https://github.com/kentaylor/WiFiManager WiFi
-#include <ESP8266WebServer.h>
-

 WiFiServer* pWifiServer;
 unsigned char btnState;


Last changes

Last changes

--- test_lcd.ino
+++ test_lcd.ino
@@ -1,3 +1,6 @@
+#include <SPI.h>
+#include <SparkFunMAX31855k.h>
+
 #include <SPI.h>
 #include <TFT.h>
 #include <PID_v1.h>
@@ -7,11 +10,11 @@
 #include "TempSensor.h"
 #include "Label.h"

-#define CS   10
-#define DC   9
-#define RESET  8
-
-#define RATE 100L
+#define TFT_CS    19
+#define TFT_DC    9
+#define TFT_RESET 8
+
+#define TC_CS     10

 enum ButtonsEnum
 {
@@ -21,71 +24,6 @@
   DownButton = 4,
   RightButton = 8
 };
-
-/*
-  class TextBox : public Label
-  {
-  public:
-    TextBox(const Point &pt, const Color &foreColor)
-      : Label(pt, foreColor), _currentPart(-1)
-    {
-      // Nothing to do...
-    }
-
-    virtual void draw(TFT &hw)
-    {
-      Label::draw(hw);
-
-      if (_currentPart >= 0)
-      {
-        int x =
-        hw.noStroke();
-        hw.fill(_foreColor.r, _foreColor.g, _foreColor.b);
-        hw.rect(_position.x + _fontSize * 5, _position.y, _fontSize * 5, _fontSize * 8);
-        hw.noFill();
-        hw.setTextSize(_fontSize);
-        hw.stroke(_backColor.r, _backColor.g, _backColor.b);
-        hw.text(charBuffer, _position.x + _fontSize * 5 * _currentPart, _position.y);
-      }
-    }
-
-    void setEditMode(bool edition)
-    {
-      if (edition && _currentPart < 0)
-      {
-        _currentPart = 0;
-      }
-      else
-      {
-        _currentPart = -1;
-      }
-    }
-
-    void moveLeft()
-    {
-
-    }
-
-    void moveRight()
-    {
-
-    }
-
-    void next()
-    {
-
-    }
-
-    void previous()
-    {
-
-    }
-
-  private:
-    int _currentPart;
-    float _value;
-  };*/
-

 class Screen
 {
@@ -131,6 +69,18 @@
       if (_editDigit >= 0) {
         _editLabel.draw(hw);
       }
+
+      hw.stroke(255, 255, 255);
+      if (_aliveFlag)
+      {
+        hw.fill(255, 255, 255);
+      }
+      else
+      {
+        hw.fill(0, 0, 0);
+      }
+      hw.rect(150, 120, 8, 8);
+      _aliveFlag = !_aliveFlag;
     }

     void setOutput(float output)
@@ -204,57 +154,6 @@
       _editDigit = -1;
       _editLabel.setValue(_editDigit);
     }
-
-    /*
-      void editConsign(float consign)
-      {
-      _editPos = 0;
-      _editValue = consign;
-
-      refreshEditConsign();
-      }
-
-      int editDigit()
-      {
-      return (int)(_editValue * pow(10, _editPos + 1)) % 10;
-      }
-
-      void refreshEditConsign()
-      {
-      int digit = ;
-      _editLabel.setValue(digit);
-      Point pt(_consignLabel.position());
-      pt.x = _editLabel.fontSize() * 6 * (_consignLabel.value().length() - (_editPos + 1));
-      _editLabel.setPosition(pt);
-      }
-
-      void moveEditPos()
-      {
-      _editPos = (_editPos + 1);
-      refreshEditConsign();
-      }
-
-      void incEditValue()
-      {
-      _editDigit = (_editDigit + 1) % 10;
-      _editLabel.setValue(_editDigit);
-      }
-
-      void decEditValue()
-      {
-      _editDigit--;
-      if (_editDigit < 0)
-      {
-        _editDigit = 10 + _editDigit;
-      }
-      _editLabel.setValue(_editDigit);
-      }
-
-      float editValue()
-      {
-      return _editValue;
-      }
-    */

   private:
     Label _consignLabel;
@@ -262,6 +161,7 @@
     Label _currentTempLabel;
     Label _outputLabel;
     short _editDigit;
+    bool _aliveFlag;
 };

 #define DEBOUNCE_DELAY 50
@@ -366,9 +266,9 @@
     KeyPad()
     {
       _buttons[0] = new Button(2);
-      _buttons[1] = new Button(3);
-      _buttons[2] = new Button(4);
-      _buttons[3] = new Button(5);
+      _buttons[1] = new Button(4);
+      _buttons[2] = new Button(5);
+      _buttons[3] = new Button(6);
     }

     void loop()
@@ -494,18 +394,16 @@
     Program()
       : _p(2), _i(5), _d(1),
         _input(0), _output(0), _consign(0),
-        _tft(CS, DC, RESET),
-        _tempSensor(A1, 3300.0f),
-        _pid(&_input, &_output, &_consign, _p, _i, _d, DIRECT)
+        _tft(TFT_CS, TFT_DC, TFT_RESET),
+        _pid(&_input, &_output, &_consign, _p, _i, _d, DIRECT),
+        _tc(TC_CS)
     {
       // Nothing to do...
     }

     void setup() {
-      Serial.begin(9600);
-
-      analogReference(EXTERNAL);
-
+      Serial.begin(57600);
+
       _tft.begin();
       _tft.background(0, 0, 0);

@@ -516,7 +414,7 @@
       _output = 0.0;
       _consign = 32.0;

-      myservo.attach(6);
+      myservo.attach(3);

       _state = prg::Idle;
     }
@@ -545,10 +443,10 @@
     }

     void longTask() {
-      _tempSensor.loop();
-
-      _input = _tempSensor.value();
+      _input = _tc.readTempC();
       _pid.Compute();
+
+      Serial.println(_input);

       myservo.write((int)_output);

@@ -566,10 +464,10 @@
     double _consign;
     double _output;
     TFT _tft;
-    TempSensor _tempSensor;
     Screen _mainScreen;
     KeyPad _keyPad;
     PID _pid;
+    SparkFunMAX31855k _tc;
     prg::StateEnum _state;
 };


number display is now a long

number display is now a long

--- range/arduino/led_8seg/led_8seg.ino
+++ range/arduino/led_8seg/led_8seg.ino
@@ -37,14 +37,15 @@
     0b11111110, //8
     0b11100110, //9
     0b00000001, //dot
+    0b00000000, //off
   };

 boolean run_flag = false;
 unsigned long counter = 0UL;
-int timer = TIMER_DEFAULT;
+long timer = TIMER_DEFAULT;

 // prototype for defalt decimal places for display
-void displayTime(int number, int decimalplaces = DECIMAL_PLACES);
+void displayTime(long number, int decimalplaces = DECIMAL_PLACES);

 void setup() {
   Serial.begin(BAUD);
@@ -105,7 +106,7 @@
     }

     if (character == 'D' || character == 'd') {
-      int number = Serial.parseInt();
+      long number = Serial.parseInt();
       displayTime(number, 0);
     }
   }
@@ -124,7 +125,7 @@
 }

-void displayTime(int number, int decimal_places) {
+void displayTime(long number, int decimal_places) {
   digitalWrite(LE,LOW);
   // calculate each digit for sending
   for (byte i=0; i<DIGITS; i++) {
@@ -132,6 +133,8 @@
     if (i == decimal_places) {
       // add decimal place if specified digit
       shiftOut(SDO, CLK, LSBFIRST, segments[output] | segments[10]);
+    } else if (number == 0) {
+      shiftOut(SDO, CLK, LSBFIRST, segments[11]);
     } else {
       shiftOut(SDO, CLK, LSBFIRST, segments[output]);
     }