Retained device

Retained device

--- Photon/Plugins/Relay/examples/relay/relay.ino
+++ Photon/Plugins/Relay/examples/relay/relay.ino
@@ -19,7 +19,15 @@
 #include <IoT.h>
 #include <PatriotRelay.h>

+#define DEV_PTR (Device *)&
+
 IoT *iot;
+
+// Define our "relay" device on pin D0
+// Since duration is 0, no automatic turn off.
+// "retained" means use Backup SRAM to persist state between resets
+retained Relay relay(D0, "relay", 0);
+

 void setup() {
     iot = IoT::getInstance();
@@ -28,7 +36,6 @@
     // Define our "relay" device on pin D7
     // Since no duration is specified, it is set to a
     // default value of 0 meaning no automatic turn off.
-    Relay *relay = new Relay(D7, "relay");
     iot->addDevice(relay);
 }


Optimisation | print g, acc, euler

Optimisation | print g, acc, euler

--- mpuslave/mpuslave.ino
+++ mpuslave/mpuslave.ino
@@ -38,8 +38,15 @@

 void setup()
 {
-  //Configure Serial Port
+    //Configure Serial Port
     Serial.begin(115200);
+    //Echo formulae
+    //Log("accel # %f"  "\t%f"  "\t%f"  "\n", (float)aa.x / 16384 * 2, (float)aa.y / 16384 * 2, (float)aa.z / 16384 * 2);
+    Log("");
+    Serial.print("acc => (float)aa.x / 16384 * 2 || ");
+    //Log("euler # %f\t%f\t%f\n", euler[0] / 3.14159265 * 180, euler[1] / 3.14159265 * 180, euler[2] / 3.14159265 * 180);
+    Log("euler => euler[0] / 3.14159265 * 180");
+
   // join I2C bus (I2Cdev library doesn't do this automatically)
   #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
   	Wire.begin();
@@ -135,17 +142,35 @@
   			mpu.dmpGetAccel(&aa, fifoBuffer);				//Total Acceleration with gravity
   			mpu.dmpGetGravity(&gravity, &q);				//Gravity vector
   			mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);	//Real acceleration without gravity
-  			mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
+  			//mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
   			mpu.dmpGetEuler(euler, &q);
   			//Log("gravity # %f\t%f\t%f\n", gravity.x, gravity.y, gravity.z);
   			//Log("accel # %f"  "\t%f"  "\t%f"  "\n", (float)aa.x / 16384 * 2, (float)aa.y / 16384 * 2, (float)aa.z / 16384 * 2);
   			//Log("ypr # %f\t%f\t%f\n", ypr[0], ypr[1], ypr[2]);
   			//Log("euler # %f\t%f\t%f\n", euler[0] / 3.14159265 * 180, euler[1] / 3.14159265 * 180, euler[2] / 3.14159265 * 180);
-                        Serial.print(euler[0] / 3.14159265 * 180);
+
+                        //Print gravity
+                        Serial.print(gravity.x);
                         Serial.print('\t');
-                        Serial.print(euler[1] / 3.14159265 * 180);
+                        Serial.print(gravity.y);
                         Serial.print('\t');
-                        Serial.print(euler[2] / 3.14159265 * 180);
+                        Serial.print(gravity.z);
+                        Serial.print('\t');
+
+                        //Print acceleration
+                        Serial.print(aa.x);
+                        Serial.print('\t');
+                        Serial.print(aa.y);
+                        Serial.print('\t');
+                        Serial.print(aa.z);
+                        Serial.print('\t');
+
+                        //Print Euler angle
+                        Serial.print(euler[0]);
+                        Serial.print('\t');
+                        Serial.print(euler[1]);
+                        Serial.print('\t');
+                        Serial.print(euler[2]);
                         Serial.print('\t');
                         Serial.println(millis());
   		}


Fix for updateTime

Fix for updateTime

lastT = nowT; was never executed.
This resulted in calling sonar.ping(); without any delay. It was unstable with US-015 sonar module.

--- HC-SR04-RangeFinder/HC-SR04-RangeFinder.ino
+++ HC-SR04-RangeFinder/HC-SR04-RangeFinder.ino
@@ -106,10 +106,9 @@
         val = median(srtValues, ARRAY_SIZE);      // find the median value and use it
         break;
       default:
-        break;
-        lastT = nowT;
+        break;
     }
-
+    lastT = nowT;

     if (Serial.available() > 0) {
       // read the incoming byte:


added fountain pattern

added fountain pattern

--- super_freq/super_freq.ino
+++ super_freq/super_freq.ino
@@ -231,7 +231,7 @@
 byte palette_choice = 0;

 // pattern vars
-byte pattern_choice = 2;
+byte pattern_choice = 3;
 boolean shimmy_even = true;

 void setup() {
@@ -451,7 +451,7 @@
 }

 void shimmy() {
-    // odds then evens
+    // evens then odds
     while (button2State == HIGH) {
         for (int i=0; i < strip.numPixels(); i++) {
             if (shimmy_even) {
@@ -475,6 +475,39 @@
     }
 }

+void fountain() {
+    // start in the middle and grow both sides
+
+    while (button2State == HIGH) {
+
+        // first, turn all the lights off
+        for (int i=0; i < strip.numPixels(); i++) {
+            strip.setPixelColor(i, strip.Color(0, 0, 0));
+        }
+        strip.show();
+
+        for (int i=0; i < (strip.numPixels() / 2); i++) {
+
+            // pattern differs for odd vs even LED lengths
+            // if even we start with the middle 2 LEDs,
+            // for odd just the 1 middle LED
+            if (strip.numPixels() % 2) {
+                // it's an odd number light up the one middle LED
+                strip.setPixelColor(strip.numPixels() / 2 - i, strip_color);
+                strip.setPixelColor(strip.numPixels() / 2 + i, strip_color);
+            } else {
+                // it's an even number we have to start from the middle 2 LEDs
+                strip.setPixelColor(strip.numPixels() / 2 - i - 1, strip_color);
+                strip.setPixelColor(strip.numPixels() / 2 + i, strip_color);
+            }
+            strip.show();
+            delay(60 + (2 * i)); // get progressively slower each iteration
+        }
+
+        button2State = digitalRead(button2Pin);
+    }
+}
+
 void loop() {
     // check for LED count mode
     if (set_LED_count_mode == true) {
@@ -501,7 +534,7 @@
             case 2:
                 shimmy();
             case 3:
-                bullet();
+                fountain();
             case 4:
                 bullet();
             case 5:


src: add support for fade command

src: add support for fade command

--- MqttLEDs/MqttLEDs.ino
+++ MqttLEDs/MqttLEDs.ino
@@ -11,6 +11,7 @@

 #define LED_PIN D6
 #define LED_TOPIC "house/led"
+#define DELAY_MILLIS 50

 WiFiClient wclient;
 ESP8266WiFiGenericClass wifi;
@@ -18,6 +19,63 @@
 const char* OFF = "off";
 const char* RANGE = "range";
 const char* CLEAR_AND_RANGE = "clear+range";
+const char* FADE = "fade";
+
+#define FADE_COMMAND 1
+
+uint8_t current_R = 0;
+uint8_t current_G = 0;
+uint8_t current_B = 0;
+
+void setCurrent(uint8_t R, uint8_t G, int8_t B) {
+  current_R = R;
+  current_B = B;
+  current_B = G;
+}
+
+struct CommandEntry {
+  int command;
+  int range_start;
+  int range_end;
+  uint8_t R;
+  uint8_t G;
+  uint8_t B;
+  int duration;
+  CommandEntry* next_command;
+  CommandEntry* next_in_queue;
+};
+
+CommandEntry* command_queue = nullptr;
+
+void enqueueCommand(struct CommandEntry* command) {
+  command->next_in_queue = nullptr;
+  if (command_queue == nullptr) {
+    command_queue = command;
+    return;
+  }
+  CommandEntry* tail = command_queue;
+  while(tail->next_in_queue != nullptr) {
+    tail = tail->next_in_queue;
+  }
+  tail->next_in_queue = command;
+}
+
+CommandEntry* dequeueHead() {
+  if (nullptr != command_queue) {
+    CommandEntry* head = command_queue;
+    command_queue = command_queue->next_in_queue;
+    return head;
+  }
+  return nullptr;
+}
+
+void clearQueue() {
+  CommandEntry* head = dequeueHead();
+  while(head != nullptr) {
+    delete(head);
+    head = dequeueHead();
+  }
+}

 boolean extractRangeAndTarget(const char* buffer,
                               int* start,
@@ -68,16 +126,38 @@
    int start, end;
    uint8_t R, G, B;

-  if (0 == strcmp(messageBuffer.c_str(), OFF)) {
+  if (0 == strncmp(FADE, messageBuffer.c_str(), strlen(FADE))) {
+    CommandEntry* command = new CommandEntry;
+    if (extractRangeAndTarget(messageBuffer.c_str(),
+                              &command->range_start,
+                              &command->range_end,
+                              strip.numPixels(),
+                              &command->R,
+                              &command->G,
+                              &command->B)) {
+      command->command = FADE_COMMAND;
+      char* next = strtok(nullptr," ");
+      command->duration = atoi(next);
+      command->next_command = nullptr;
+      enqueueCommand(command);
+      Serial.println("Fade enqueued");
+    } else {
+      delete command;
+    }
+  } else if (0 == strcmp(messageBuffer.c_str(), OFF)) {
+    clearQueue();
     for(uint16_t i=0; i <strip.numPixels(); i++) {
       strip.setPixelColor(i, strip.Color(0,0,0));
     }
+    setCurrent(0, 0, 0);
   } else if ((0 == strncmp(RANGE, messageBuffer.c_str(), strlen(RANGE))) ||
              (0 == strncmp(CLEAR_AND_RANGE, messageBuffer.c_str(), strlen(CLEAR_AND_RANGE)))) {
+    clearQueue();
     if (0 == strncmp(CLEAR_AND_RANGE, messageBuffer.c_str(), strlen(CLEAR_AND_RANGE))) {
       for(uint16_t i=0; i <strip.numPixels(); i++) {
         strip.setPixelColor(i, strip.Color(0,0,0));
       }
+      setCurrent(0, 0, 0);
     }

     if (extractRangeAndTarget(messageBuffer.c_str(), &start, &end, strip.numPixels(), &R, &G, &B)) {
@@ -85,9 +165,10 @@
       for(uint16_t i = start; i < end; i++) {
         strip.setPixelColor(i, strip.Color(R, G, B));
       }
+      setCurrent(R, G, B);
     }
   } else {
-    Serial.println("Message Invalid");
+    Serial.println("Message Unknown");
     return;
   }

@@ -97,6 +178,7 @@
 PubSubClient client(mqttServerString, mqttServerPort, callback, wclient);

 void setup() {
+  command_queue = nullptr;
   strip.begin();
   for(uint16_t i=0; i <strip.numPixels(); i++) {
     strip.setPixelColor(i, strip.Color(0,0,0));
@@ -132,7 +214,7 @@
       delay(100);
       return;
     }
-    Serial.println("WiFi connected");
+
   }

   if (!client.connected()) {
@@ -145,5 +227,24 @@
     }
   }

-  delay(100);
-}
+  if (command_queue) {
+    CommandEntry* command = command_queue;
+    if (FADE_COMMAND == command->command) {
+      current_R += (((int)(command->R) - current_R) * DELAY_MILLIS)/command->duration;
+      current_G += (((int)(command->G) - current_G) * DELAY_MILLIS)/command->duration;
+      current_B += (((int)(command->B) - current_B) * DELAY_MILLIS)/command->duration;
+      for(uint16_t i = command->range_start; i <= command->range_end; i++) {
+        strip.setPixelColor(i, strip.Color(current_R, current_G, current_B));
+      }
+      strip.show();
+      if ((command->duration - DELAY_MILLIS) > 0) {
+        command->duration = command->duration - DELAY_MILLIS;
+      } else {
+        // we are done
+        delete(dequeueHead());
+      }
+    }
+  }
+
+  delay(DELAY_MILLIS);
+}


Update mqtt.ino

Update mqtt.ino

--- Mqtt/mqtt.ino
+++ Mqtt/mqtt.ino
@@ -9,8 +9,8 @@
 #define WLAN_PASS  "Your password"

-#define arduino_status "arduino/ac/status"                                       // STATUS  subscribe/publish
-#define arduino_status_response "arduino/ac/status/response"                     //
+#define arduino_status " "                                       // STATUS  subscribe/publish
+#define arduino_status_response " "                     //

 #define arduino_pubsub " "       //   Arduino  subscribe/publish


GPS Test Code

GPS Test Code

Adds LED functionality to GPS test code

--- arduino/archive/GPS_HardwareSerial_Parsing_ModTeensy/GPS_HardwareSerial_Parsing_ModTeensy.ino
+++ arduino/archive/GPS_HardwareSerial_Parsing_ModTeensy/GPS_HardwareSerial_Parsing_ModTeensy.ino
@@ -33,6 +33,8 @@

 String currLatLong;

+const int ledPin = 13;
+
 void setup()
 {
   //while (!Serial);  // uncomment to have the sketch wait until Serial is ready
@@ -64,6 +66,9 @@
   GPSSerial.println(PMTK_Q_RELEASE);

   currLatLong = "null";
+
+  pinMode(ledPin, OUTPUT);
+  digitalWrite(ledPin, LOW);
 }

 void loop() // run over and over again
@@ -110,9 +115,11 @@
       Serial.print("Satellites: "); Serial.println((int)GPS.satellites);

       currLatLong = String(fabs(GPS.latitudeDegrees), 6) + GPS.lat + ", " + String(fabs(GPS.longitudeDegrees), 6) + GPS.lon;
+      digitalWrite(ledPin, HIGH);
     }
     else {
       currLatLong = "null";
+      digitalWrite(ledPin, LOW);
       }
     Serial.print("Output Processed LatLong String: "); Serial.println(currLatLong);
   }


-arduino light work

-arduino light work

--- arduino/src/robotLEDControllerrev2/robotLEDControllerrev2.ino
+++ arduino/src/robotLEDControllerrev2/robotLEDControllerrev2.ino
@@ -43,6 +43,7 @@
 //color data
 uint32_t distanceColor = 0xFF00FF; //start off with the color being purple
 uint32_t allianceColor = 0xFF00FF; //start off with the color being purple
+
 //used for debugging
 int x;
 int incomingByte;


Configure the serial port to use. Prefer native USB port if the Arduino has one.

--- build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
+++ build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
@@ -43,7 +43,9 @@
 // - The SPI functions herein were developed for the AVR910_ARD programmer
 // - More information at http://code.google.com/p/mega-isp

-#include "pins_arduino.h"
+#include "Arduino.h"
+#undef SERIAL
+
 // Use pin 10 to reset the target
 #define RESET     10

@@ -62,6 +64,26 @@
 #define SPI_CLOCK_DIV_MAX	SPI_CLOCK_DIV_128

 #endif
+
+
+// Configure the serial port to use.
+//
+// Prefer the USB virtual serial port (aka. native USB port), if the Arduino has one:
+//   - it does not autoreset (except for the magic baud rate of 1200).
+//   - it is more reliable because of USB handshaking.
+//
+// Leonardo and similar have an USB virtual serial port: 'Serial'.
+// Due and Zero have an USB virtual serial port: 'SerialUSB'.
+//
+// On the Due and Zero, 'Serial' can be used too, provided you disable autoreset.
+// To use 'Serial': #define SERIAL Serial
+
+#ifdef SERIAL_PORT_USBVIRTUAL
+#define SERIAL SERIAL_PORT_USBVIRTUAL
+#else
+#define SERIAL Serial
+#endif
+

 #define HWVER 2
 #define SWMAJ 1
@@ -118,7 +140,7 @@
 #endif

 void setup() {
-  Serial.begin(19200);
+  SERIAL.begin(19200);
   SPI.setDataMode(0);
   SPI.setBitOrder(MSBFIRST);
   // Select the slowest possible clock
@@ -196,14 +218,14 @@

   // light the heartbeat LED
   heartbeat();
-  if (Serial.available()) {
+  if (SERIAL.available()) {
     avrisp();
   }
 }

 uint8_t getch() {
-  while (!Serial.available());
-  return Serial.read();
+  while (!SERIAL.available());
+  return SERIAL.read();
 }
 void fill(int n) {
   for (int x = 0; x < n; x++) {
@@ -238,22 +260,22 @@

 void empty_reply() {
   if (CRC_EOP == getch()) {
-    Serial.print((char)STK_INSYNC);
-    Serial.print((char)STK_OK);
+    SERIAL.print((char)STK_INSYNC);
+    SERIAL.print((char)STK_OK);
   } else {
     error++;
-    Serial.print((char)STK_NOSYNC);
+    SERIAL.print((char)STK_NOSYNC);
   }
 }

 void breply(uint8_t b) {
   if (CRC_EOP == getch()) {
-    Serial.print((char)STK_INSYNC);
-    Serial.print((char)b);
-    Serial.print((char)STK_OK);
+    SERIAL.print((char)STK_INSYNC);
+    SERIAL.print((char)b);
+    SERIAL.print((char)STK_OK);
   } else {
     error++;
-    Serial.print((char)STK_NOSYNC);
+    SERIAL.print((char)STK_NOSYNC);
   }
 }

@@ -380,11 +402,11 @@
 void write_flash(int length) {
   fill(length);
   if (CRC_EOP == getch()) {
-    Serial.print((char) STK_INSYNC);
-    Serial.print((char) write_flash_pages(length));
+    SERIAL.print((char) STK_INSYNC);
+    SERIAL.print((char) write_flash_pages(length));
   } else {
     error++;
-    Serial.print((char) STK_NOSYNC);
+    SERIAL.print((char) STK_NOSYNC);
   }
 }

@@ -451,15 +473,15 @@
   if (memtype == 'E') {
     result = (char)write_eeprom(length);
     if (CRC_EOP == getch()) {
-      Serial.print((char) STK_INSYNC);
-      Serial.print(result);
+      SERIAL.print((char) STK_INSYNC);
+      SERIAL.print(result);
     } else {
       error++;
-      Serial.print((char) STK_NOSYNC);
+      SERIAL.print((char) STK_NOSYNC);
     }
     return;
   }
-  Serial.print((char)STK_FAILED);
+  SERIAL.print((char)STK_FAILED);
   return;
 }

@@ -473,9 +495,9 @@
 char flash_read_page(int length) {
   for (int x = 0; x < length; x += 2) {
     uint8_t low = flash_read(LOW, here);
-    Serial.print((char) low);
+    SERIAL.print((char) low);
     uint8_t high = flash_read(HIGH, here);
-    Serial.print((char) high);
+    SERIAL.print((char) high);
     here++;
   }
   return STK_OK;
@@ -487,7 +509,7 @@
   for (int x = 0; x < length; x++) {
     int addr = start + x;
     uint8_t ee = spi_transaction(0xA0, (addr >> 8) & 0xFF, addr & 0xFF, 0xFF);
-    Serial.print((char) ee);
+    SERIAL.print((char) ee);
   }
   return STK_OK;
 }
@@ -499,34 +521,29 @@
   char memtype = getch();
   if (CRC_EOP != getch()) {
     error++;
-    Serial.print((char) STK_NOSYNC);
+    SERIAL.print((char) STK_NOSYNC);
     return;
   }
-  Serial.print((char) STK_INSYNC);
-  if (memtype == 'F') {
-    result = flash_read_page(length);
-  }
-  if (memtype == 'E') {
-    result = eeprom_read_page(length);
-  }
-  Serial.print(result);
-  return;
+  SERIAL.print((char) STK_INSYNC);
+  if (memtype == 'F') result = flash_read_page(length);
+  if (memtype == 'E') result = eeprom_read_page(length);
+  SERIAL.print(result);
 }

 void read_signature() {
   if (CRC_EOP != getch()) {
     error++;
-    Serial.print((char) STK_NOSYNC);
+    SERIAL.print((char) STK_NOSYNC);
     return;
   }
-  Serial.print((char) STK_INSYNC);
+  SERIAL.print((char) STK_INSYNC);
   uint8_t high = spi_transaction(0x30, 0x00, 0x00, 0x00);
-  Serial.print((char) high);
+  SERIAL.print((char) high);
   uint8_t middle = spi_transaction(0x30, 0x00, 0x01, 0x00);
-  Serial.print((char) middle);
+  SERIAL.print((char) middle);
   uint8_t low = spi_transaction(0x30, 0x00, 0x02, 0x00);
-  Serial.print((char) low);
-  Serial.print((char) STK_OK);
+  SERIAL.print((char) low);
+  SERIAL.print((char) STK_OK);
 }
 //////////////////////////////////////////
 //////////////////////////////////////////
@@ -544,13 +561,13 @@
       break;
     case '1':
       if (getch() == CRC_EOP) {
-        Serial.print((char) STK_INSYNC);
-        Serial.print("AVR ISP");
-        Serial.print((char) STK_OK);
+        SERIAL.print((char) STK_INSYNC);
+        SERIAL.print("AVR ISP");
+        SERIAL.print((char) STK_OK);
       }
       else {
         error++;
-        Serial.print((char) STK_NOSYNC);
+        SERIAL.print((char) STK_NOSYNC);
       }
       break;
     case 'A':
@@ -615,17 +632,16 @@
     // this is how we can get back in sync
     case CRC_EOP:
       error++;
-      Serial.print((char) STK_NOSYNC);
+      SERIAL.print((char) STK_NOSYNC);
       break;

     // anything else we will return STK_UNKNOWN
     default:
       error++;
-      if (CRC_EOP == getch()) {
-        Serial.print((char)STK_UNKNOWN);
-      } else {
-        Serial.print((char)STK_NOSYNC);
-      }
-  }
-}
-
+      if (CRC_EOP == getch())
+        SERIAL.print((char)STK_UNKNOWN);
+      else
+        SERIAL.print((char)STK_NOSYNC);
+  }
+}
+


PID test debug

PID test debug

--- PID_test/PID_test.ino
+++ PID_test/PID_test.ino
@@ -11,13 +11,14 @@
 double whesep= 0.135; // wheel separtion in m
 double whedia= 0.7;   // wheel diameter in m
 int CPR = 40;     // Encoder Count per Revolutions (double of holes using up & down interrupt)
-int period=200;   // sample timer period in ms
-double lv=0, rv=0;// motor speed innumber tics per period
+int period=100;   // sample timer period in ms
+double lv=0., rv=0.;// motor speed innumber tics per period
 int ti=0;         // tic timer counter
 double lOut,rOut,lSet,rSet;   // PID output and demands
-double lkp=1,lki=0,lkd=0;     // Left wheel PID constants
-double rkp=1,rki=0,rkd=0;     // Right wheel PID constants
+double lkp=10,lki=0,lkd=0;     // Left wheel PID constants
+double rkp=10,rki=0,rkd=0;     // Right wheel PID constants
 int kt=1000/period; // number of periods in 1sec
+int rcurrenttime, rlasttime, lcurrenttime, llasttime;

 //PID(&Input, &Output, &Setpoint, Kp, Ki, Kd, Direction)
 PID lPID(&lv, &lOut, &lSet, lkp, lki, lkd, DIRECT);
@@ -27,12 +28,16 @@

 // start of timerCallback
 void tic(void *pArg) {
-  lv=(lmc-lmc0)*kt;    // left instant velocity tic/period
+
+  lv=(lmc-lmc0)*kt+1000./(millis() - llasttime);    // left instant velocity tic/period
   lmc0=lmc;
-  rv=(rmc-rmc0)*kt;    // rv right install velocity
+  rv=(rmc-rmc0)*kt+1000./(millis() - rlasttime);    // rv right install velocity
   rmc0=rmc;
+
   ti+=1;                  // tic counter
-
+  rPID.Compute();
+  lPID.Compute();
+  motion(lOut,rOut,HIGH,HIGH);
 }

 void stop(void){      // Stop both motors
@@ -51,15 +56,26 @@
     } else {
       rdir=-1;
     }
+    if(lpwm>1023)lpwm=1023;
+    if(rpwm>1023)rpwm=1023;
+    if(lpwm<0)lpwm=0;
+    if(rpwm<0)rpwm=0;
     analogWrite(D1, lpwm);
     analogWrite(D2, rpwm);
     digitalWrite(D3, llevel);
     digitalWrite(D4, rlevel);
 }
 void lencode() {          // GPIO ISR Interrupt service routines for encoder changes
+
+  lcurrenttime = millis();
+  //lv = 1000./(lcurrenttime - llasttime);
+  llasttime = lcurrenttime;
   lmc=lmc+ldir;
 }
 void rencode(){
+  rcurrenttime = millis();
+  //rv = 1000./(rcurrenttime - rlasttime);
+  rlasttime = rcurrenttime;
   rmc=rmc+rdir;
 }

@@ -71,16 +87,18 @@
   pinMode(D4, OUTPUT); // 3A,4A aka D4
   pinMode(D5, INPUT); //  Left encoder
   pinMode(D6, INPUT); //  Right encoder
-  attachInterrupt(D5, lencode, CHANGE); // Setup Interrupt
-  attachInterrupt(D6, rencode, CHANGE); // Setup Interrupt
+  //attachInterrupt(D5, lencode, CHANGE); // Setup Interrupt
+  //attachInterrupt(D6, rencode, CHANGE); // Setup Interrupt
+  attachInterrupt(D5, lencode, RISING); // Setup Interrupt
+  attachInterrupt(D6, rencode, RISING); // Setup Interrupt
   sei();                                // Enable interrupts

-  int currentTime = millis();
-  int cloopTime = currentTime;
+  //currentTime = millis();
+  //cloopTime = currentTime;
   os_timer_setfn(&myTimer, tic, NULL);
   os_timer_arm(&myTimer, period, true);   // timer in ms
-  lPID.SetSampleTime(period);
-  rPID.SetSampleTime(period);
+  //lPID.SetSampleTime(period);
+  //rPID.SetSampleTime(period);
   lPID.SetOutputLimits(0, 1023);
   rPID.SetOutputLimits(0, 1023);
   lPID.SetMode(AUTOMATIC);
@@ -102,21 +120,34 @@
       if(c=='s'){
         lSet=gv/10.;
         rSet=gv/10.;
-      }
-      if(c=='p'){
+      } else if(c=='p'){
         lkp=gv/10.;
         rkp=gv/10.;
-      }
-      if(c=='i'){
+        lPID.SetTunings(lkp, lki, lkd);
+        rPID.SetTunings(rkp, rki, rkd);
+      } else if(c=='i'){
         lki=gv/10.;
         rki=gv/10.;
-      }
-      if(c=='d'){
+        lPID.SetTunings(lkp, lki, lkd);
+        rPID.SetTunings(rkp, rki, rkd);
+      } else if(c=='d'){
         lkd=gv/10.;
         rkd=gv/10.;
+        lPID.SetTunings(lkp, lki, lkd);
+        rPID.SetTunings(rkp, rki, rkd);
+      } else {
+        Serial.println("Tunning command not recognized. Use s NNN, p NNN, i NNN, d NNN with NNN=n*10");
       }
       while (Serial.available()) Serial.read();
       c=0;
+      //lPID.SetMode(MANUAL);
+      //rPID.SetMode(MANUAL);
+      //lPID.SetSampleTime(period);
+      //rPID.SetSampleTime(period);
+      //lPID.SetOutputLimits(0, 1023);
+      //rPID.SetOutputLimits(0, 1023);
+      //lPID.SetMode(AUTOMATIC);
+      //rPID.SetMode(AUTOMATIC);
     }
   }
   Serial.print(" lSet: ");
@@ -124,13 +155,13 @@
   Serial.print(" rSet: ");
   Serial.print(rSet);
   Serial.print(" lv:");
-  Serial.print(lv);
+  Serial.print(lv*1000);
   Serial.print(" rv:");
-  Serial.print(rv);
+  Serial.print(rv*1000);
   Serial.print(" lOut:");
-  Serial.print(lOut*4);
+  Serial.print(lOut);
   Serial.print(" rOut:");
-  Serial.print(rOut*4);
+  Serial.print(rOut);
   Serial.print(" lmc:");
   Serial.print(lmc);
   Serial.print(" rmc=");
@@ -143,9 +174,6 @@
   Serial.print(lki);
   Serial.print(" lkd: ");
   Serial.println(lkd);
-  rPID.Compute();
-  lPID.Compute();
-  motion(lOut,rOut,HIGH,HIGH);
   delay(1000);
 }


P & I tweaks

P & I tweaks

--- PID/PID.ino
+++ PID/PID.ino
@@ -33,6 +33,9 @@
 int speed_requested = 0;
 byte pwm_motor_left = 0;
 int speed_motor_left = 0;
+
+//int speed_current = 0;
+//int num_spokes = 5;

 void setup()
 {
@@ -98,10 +101,21 @@

       // No change in light
       // Check for stopped/too slow
+
       ms_per_int = count * sample_interval;
       if (ms_per_int > 700) {
-        count = 0;
-        Input = 0;
+        //count = 0;
+        //Input = 0;
+      }
+
+
+      if (count > 5) {
+      //Input = 0;
+
+      }
+
+      if (count > 0) {
+      //Input = Input / count;
       }
     }


Added new line joystick

Added new line joystick

--- Joystick/Joystick.ino
+++ Joystick/Joystick.ino
@@ -32,6 +32,6 @@
   Serial.print("; ");
   Serial.print("Sel: ");
   Serial.print(digitalRead(joySelPin));
-  Serial.print("; ");
+  Serial.println("; ");
   radio.write((void*)packet, PACKETSIZE, false);
 }


Update SpinCode.ino

Update SpinCode.ino

Removed commented debugging code

--- SpinCode/SpinCode.ino
+++ SpinCode/SpinCode.ino
@@ -30,9 +30,7 @@
   {
     while (1);
   }
-
-  //analogWrite(r,1);
-  //analogWrite(g,1);
+
 }

 void loop()
@@ -45,20 +43,6 @@
   }
   sum = sum >> 3;
   accel_in = (int)sum;
-
-  // assuming accel_in = signed 16 bit input
-  // r -> pwm value for red from 0 -> 255
-  // g -> pwm value for green 0 -> 255
-  // b -> pwm value for blue 0 -> 255
-
-//  accel_in = accel_in + 1;
-
-
-//  for(int i = 0; i < 127; i++)
-//  { analogWrite(g,127-i);
-//    analogWrite(r,i);
-//      delay(10);
-//  }

 accel_in = accel_in & ABS_MASK; // take absolute value of accelerometer data
 masked_in = accel_in & BIT_MASK; // 13 bit mask of accelerometer data


Update Update Update

Update Update Update

--- TimerShot/TimerShot.ino
+++ TimerShot/TimerShot.ino
@@ -13,9 +13,28 @@

 // The one shot pulses are output on Digial pin 3

+/***************************/
+/* PIN CONNECTIONS & NAMES */
+/***************************/
+#define SERVO_PIN 9
+
+/*************/
+/* CONSTANTS */
+/*************/
+#define MIN 740
+#define MAX 2430
+#define BUFLEN 100
+#define MAXF 5
+#define MAXA 45
+#define OFFSET -40

 #define OSP_SET_WIDTH(cycles) (OCR2B = 0xff-(cycles-1))
+
+int pos;
+int maxt = MAX + OFFSET;
+int mint = MIN + OFFSET;
+int mid = round((float)(maxt+mint)/2.0);

 // Setup the one-shot pulse generator and initialize with a pulse width that is (cycles) clock counts long

@@ -26,14 +45,14 @@
               // This keeps anyhting from happeneing while we get set up

   TCNT2 = 0x00;     // Start counting at bottom.
-  OCR2A = 0;      // Set TOP to 0. This effectively keeps us from counting becuase the counter just keeps reseting back to 0.
+  OCR2A = 0;      // Set TOP to 0. This effectively keeps us from counting because the counter just keeps reseting back to 0.
           // We break out of this by manually setting the TCNT higher than 0, in which case it will count all the way up to MAX and then overflow back to 0 and get locked up again.
   OSP_SET_WIDTH(cycles);    // This also makes new OCR values get loaded frm the buffer on every clock cycle.

   TCCR2A = _BV(COM2B0) | _BV(COM2B1) | _BV(WGM20) | _BV(WGM21); // OC2B=Set on Match, clear on BOTTOM. Mode 7 Fast PWM.
   TCCR2B = _BV(WGM22)| _BV(CS20);         // Start counting now. WGM22=1 to select Fast PWM mode 7

-  DDRD |= _BV(3);     // Set pin to output (Note that OC2B = GPIO port PD3 = Arduino Digital Pin 3)
+  DDRD |= _BV(SERVO_PIN);     // Set pin to output (Note that OC2B = GPIO port PD3 = Arduino Digital Pin 3)
 }

 // Setup the one-shot pulse generator
@@ -69,15 +88,24 @@
 {
   // Step though 0-19 cycle long pulses for demo purposes

-  for (uint8_t o = 0; o < 20; o++) {
+  for (pos = mid-100; pos < mid+100; pos++) {

-    OSP_SET_AND_FIRE(o*F_CPU / 1000000);
+    OSP_SET_AND_FIRE(pos*F_CPU / 1000000);

-    while (OSP_INPROGRESS());         // This just shows how you would wait if nessisary - not nessisary in this application.
+    //while (OSP_INPROGRESS());         // This just shows how you would wait if nessisary - not nessisary in this application.

-    _delay_ms(1000);      // Wait a sec to let the audience clap
+    _delay_ms(20);      // Wait a sec to let the audience clap
+
+  }
+
+  for (pos = mid+100; pos > mid-100; pos--) {
+
+    OSP_SET_AND_FIRE(pos*F_CPU / 1000000);
+
+    //while (OSP_INPROGRESS());         // This just shows how you would wait if nessisary - not nessisary in this application.
+
+    _delay_ms(20);      // Wait a sec to let the audience clap

   }

-
 }


不要な変数定義

不要な変数定義


Removed Serial.begin()

Removed Serial.begin()


weiterfahrt hinzuprogrammiert

weiterfahrt hinzuprogrammiert

--- RF_ATtiny85_Lastenaufzug/RF_ATtiny85_Lastenaufzug.ino
+++ RF_ATtiny85_Lastenaufzug/RF_ATtiny85_Lastenaufzug.ino
@@ -68,14 +68,15 @@
  *
  */
 #include <RemoteReceiver.h>
-char version = "1.2";
+
 int RO = PB1; // LOW = Versorge Relais (VCC) mit Spannung HIGH = schalte Spannung ab (PNP Transistor)
 int S1 = PB4; // Relais 1
 int S2 = PB3; // Relais 2
 /*
-int RO = 8;
-int S1 = 9;
-int S2 = 10;
+int RO = 4;
+int S1 = 7;
+int S2 = 8;
+char v[4]="1.2";
 */
 // da bei ATtiny85 bereits alle Pins gebraucht werden, muessen wir uns mit einem Boolean Feld zufrieden geben.
 // die Boolean Felder sind fuer uns sozusagen der Ersatz von 2 zusaetzlichen Input Pins
@@ -86,8 +87,8 @@
 // Boolean Felder Raten.
 boolean floor_og=false;
 boolean floor_eg=false;
-
-char mode[4]; // ein Reservierter Speicher fuer Modus ON / OFF
+boolean chkfix=true;
+
 unsigned long relaistime = 60000L; // Schalte die Relais Versorgungsspannung nach 1min. ab.
 // Wie lange das Relais den Status ON hat bis es wieder abgeschalten wird. Somit kann es
 // einen bestimmten Weg zuruecklegen.
@@ -107,14 +108,20 @@
   digitalWrite(S2, HIGH);
   digitalWrite(RO, HIGH); // Pin auf HIGH Setzen

-  RemoteReceiver::init(0, 0, 3, checkCode, 0); //RemoteReceiver::init(type, interrupt-pin, min-Repeats, callback-function, PulseWidth);
+  RemoteReceiver::init(1, 0, 3, checkCode, 0); //RemoteReceiver::init(type, interrupt-pin, min-Repeats, callback-function, PulseWidth);

   //only for tests
-  //Serial.begin(19200);
-  //Serial.println("Start programm");
-}
-
-void SWRelais(char mode){
+  /*
+  Serial.begin(115200);
+  Serial.print(F("Arduino Lastenaufzug v"));
+  Serial.println(v);
+  Serial.println(F("=========================="));
+  getboolstates();
+  */
+}
+
+
+void SWRelais(char mode[3]){
   /*
    * Powerswitch for relais modul
    */
@@ -131,46 +138,49 @@
     digitalWrite(RO, HIGH);
     ROState=false;
   }
-  //Serial.println(ROState);
-}
-
-void SecRelais1(char mode){
+}
+
+
+void SecRelais1(char mode[3]){
   /*
    * Relais 1 with state check (DOWN)
    */
   if (mode == "ON") {
+    //Serial.println(F("SecRelais1 = mode ON"));
     if (S1State == false && S2State == false) {
+      //Serial.println(F("SecRelais1 = ON, state = true"));
       S1State=true;
-      //liftdown=true;
-      //liftup=false;
       digitalWrite(S1, LOW);
     } else if (S1State == false && S2State == true) {
+      //Serial.println(F("SecRelais1 = ON, state = true"));
       digitalWrite(S2, HIGH);
       S2State=false;
-      //liftup=false;
       delay(80);
       S1State=true;
-      //liftdown=true;
       digitalWrite(S1, LOW);
     } else if (S1State == true && S2State == false) {
       // do nothing
     }
   } else {
+    //Serial.print(F("SecRelais1 mode = "));
+    //Serial.println(mode);
     digitalWrite(S1, HIGH);
     S1State=false;
   }
-  //Serial.println(S1State);
-}
-
-void SecRelais2(char mode){
+}
+
+
+void SecRelais2(char mode[3]) {
   /*
    * Relais 2 with state check (UP)
    */
   if (mode == "ON") {
     if (S2State == false && S1State == false) {
+      //Serial.println(F("SecRelais2 = ON, state = true"));
       S2State=true;
       digitalWrite(S2, LOW);
     } else if (S2State == false && S1State == true) {
+      //Serial.println(F("SecRelais1 = ON, state = true"));
       digitalWrite(S1, HIGH);
       S1State=false;
       delay(80);
@@ -183,26 +193,25 @@
     digitalWrite(S2, HIGH);
     S2State=false;
   }
-  //Serial.println(S2State);
-}
+}
+

 //Callback function is called only when a valid code is received.
 char checkCode(unsigned long receivedCode, unsigned int period){
   //Note: interrupts are disabled. You can re-enable them if needed.

   //print received code
-  //Serial.print("Code = ");
-  //Serial.println(receivedCode);
-
+  /*
+  Serial.print("Code = ");
+  Serial.println(receivedCode);
+  getboolstates();
+  */
+
   if (receivedCode == 531272) {
     task2 = millis();
     //Serial.println("Switch Relais 1 ON");
-    if (floor_og == true && floor_eg == true) {
-      // do nothing
-    } else {
-      SWRelais("ON");
-      SecRelais1("ON");
-    }
+    SWRelais("ON");
+    SecRelais1("ON");

   } else if (receivedCode == 531380) {
     //Serial.println("Switch Relais 2 ON");
@@ -217,58 +226,150 @@
   }
 }

+/*
+void getboolstates(){
+*/
+  /*
+   * print all boolean states
+   */
+  /*
+  Serial.print(F("floor_eg = "));
+  Serial.println(floor_eg);
+  Serial.print(F("floor_og = "));
+  Serial.println(floor_og);
+  Serial.print(F("S1State = "));
+  Serial.println(S1State);
+  Serial.print(F("chkfix = "));
+  Serial.println(chkfix);
+  Serial.print(F("S2State = "));
+  Serial.println(S2State);
+  Serial.print(F("ROState = "));
+  Serial.println(ROState);
+  Serial.println(F("---------------------------"));
+}
+*/

 void loop() {
   unsigned long currmillis = millis();

   // weg von der Winde zum 1.OG
-  if (floor_eg == false && floor_og == false && S2State == true) {
+  if (floor_eg == false && floor_og == false && S1State == true) {
+    /*
+    if ((unsigned long)(currmillis - task2) == 2000){
+      Serial.println(F("start -> 1.OG"));
+    }
+    */
     if ((unsigned long)(currmillis - task2) >= worktime) {
       if ( S1State == true || S2State == true ) {
-        //Serial.println("Switch Relais after worktime OFF");
+        //Serial.println(F("Switch Relais after worktime OFF, start -> 1.OG"));
         SecRelais1("OFF");
         SecRelais2("OFF");
         floor_og=true;
-      }
-    }
-    // weg vom 1.OG nach EG
-  } else if (floor_eg == false && floor_og == true && S2State == true) {
+        //getboolstates();
+      }
+    }
+  }
+  // weg vom 1.OG nach EG
+  else if (floor_eg == false && floor_og == true && S1State == true) {
+    /*
+    if ((unsigned long)(currmillis - task2) == 2000){
+      Serial.println(F("1.OG -> EG"));
+    }
+    */
     if ((unsigned long)(currmillis - task2) >= worktimeto_eg) {
       if ( S1State == true || S2State == true ) {
-        //Serial.println("Switch Relais after worktime OFF");
+        //Serial.println(F("Switch Relais after worktime OFF, 1.OG -> EG"));
         SecRelais1("OFF");
         SecRelais2("OFF");
         floor_eg=true;
-      }
-    }
-    // zueruck auf das 1.OG
-  } else if (floor_eg == true && floor_og == true && S1State == true) {
+        chkfix=true;
+        //getboolstates();
+      }
+    }
+  }
+  // zueruck auf das 1.OG
+  else if (floor_eg == true && floor_og == true && S2State == true) {
+    /*
+    if ((unsigned long)(currmillis - task2) == 2000){
+      Serial.println(F("EG -> 1.OG"));
+    }
+    */
     if ((unsigned long)(currmillis - task2) >= worktimeto_eg) {
       if ( S1State == true || S2State == true ) {
-        //Serial.println("Switch Relais after worktime OFF");
+        //Serial.println(F("Switch Relais after worktime OFF, EG -> 1.OG"));
         SecRelais1("OFF");
         SecRelais2("OFF");
         floor_eg=false;
-      }
-    }
-    // zurueck auf start
-  } else if (floor_eg == false && floor_og == true && S1State == true) {
+        chkfix=false;
+        //getboolstates();
+      }
+    }
+  }
+  // zurueck auf start
+  else if (floor_eg == false && floor_og == true && S2State == true) {
+    /*
+    if ((unsigned long)(currmillis - task2) == 2000){
+      Serial.println(F("1.OG -> start"));
+    }
+    */
     if ((unsigned long)(currmillis - task2) >= worktime) {
       if ( S1State == true || S2State == true ) {
-        //Serial.println("Switch Relais after worktime OFF");
+        //Serial.println(F("Switch Relais after worktime OFF, 1.OG -> start"));
         SecRelais1("OFF");
         SecRelais2("OFF");
         floor_og=false;
+        //getboolstates();
       }
     }
   }
-
+
+  // steuerung weiter verwenden falls auch schon ganz unten ist
+  // allerdings nur 5 Sekunden selbstfahren
+  else if (floor_eg == true && floor_og == true && chkfix == true && S1State == true) {
+    /*
+    if ((unsigned long)(currmillis - task2) == 2000){
+      Serial.println(F("Down run 5 seconds"));
+    }
+    */
+    if ((unsigned long)(currmillis - task2) >= 5000) {
+      if ( S1State == true || S2State == true ) {
+        //Serial.println(F("Switch Relais after worktime OFF, run down 5 sec"));
+        SecRelais1("OFF");
+        SecRelais2("OFF");
+        floor_eg=true;
+        floor_og=true;
+        chkfix=true;
+        //getboolstates();
+      }
+    }
+  }
+  // steuerung weiter verwenden falls auch wenn es schon anscheinend ganz oben ist
+  // allerdings nur 5 Sekunden selbstfahren
+  else if (floor_eg == false && floor_og == false && chkfix == false && S2State == true) {
+    /*
+    if ((unsigned long)(currmillis - task2) == 2000){
+      Serial.println(F("Up run 5 seconds"));
+    }
+    */
+    if ((unsigned long)(currmillis - task2) >= 5000) {
+      if ( S1State == true || S2State == true ) {
+        //Serial.println(F("Switch Relais after worktime OFF, run up 5 sec"));
+        SecRelais1("OFF");
+        SecRelais2("OFF");
+        //floor_eg=false;
+        //floor_eg_fix=false;
+        //getboolstates();
+      }
+    }
+  }
+
   // schalte das Relais nach eingestellter Zeit aus
   if ((unsigned long)(currmillis - task2) >= relaistime) {
     if (ROState == true) {
-      //Serial.println("switch Relais OFF");
+      //Serial.println(F("interrupt Relais Power"));
       SWRelais("OFF");
-    }
-  }
-}
-
+      //getboolstates();
+    }
+  }
+}
+


Return odometry as part of Arduino message string

--- buzzmobile/drive/arduino/src/car_driver/car_driver.ino
+++ buzzmobile/drive/arduino/src/car_driver/car_driver.ino
@@ -107,7 +107,7 @@

       lastCmdTime = millis();
       retMsg[0] = STX;
-      sprintf(retMsg+1, "%05i%05.4f", count, getSteeringAngle());
+      sprintf(retMsg+1, "%05i%05.4f%02.4", count, getSteeringAngle(), getSpeed());
       Serial.println(retMsg);
       count = 0;
     }


before pulling from master

before pulling from master

--- v2/06oct/06oct/06oct.ino
+++ v2/06oct/06oct/06oct.ino
@@ -251,14 +251,14 @@
             searchCount = 0; //reset abandon search count
             pastNear = false;
             attackCount = 0;
-          } else if ((leftDist <= far || perLeftDist <= far)) { // || leftDist - rightDist < -dist) {
+          } else if ((leftDist <= far || perLeftDist <= far) || leftDist - rightDist < -dist) {
             // if opponent within far of the left sensors or if difference within some negative threshold, move left
             state = 2;
             past = 'l'; //set past movement to left
             searchCount = 0; //reset abandon search count because the robot has found an object
             pastNear = false;
             attackCount = 0;
-          } else if ((rightDist <= far || perRightDist <= far)) { // || leftDist - rightDist > dist) {
+          } else if ((rightDist <= far || perRightDist <= far) || leftDist - rightDist > dist) {
             //if opponent within far of the right sensors or if difference within some positive threshold, move right
             state = 3;
             past = 'r'; //set past movement to right


Libraries back to common library folder

Libraries back to common library folder

--- XV_Lidar_Controller.ino
+++ XV_Lidar_Controller.ino
@@ -13,11 +13,11 @@
   The F() macro in the Serial statements tells the compiler to keep your strings in PROGMEM
 */

-#include "libraries/TimerThree/TimerThree.h" // used for ultrasonic PWM motor control
-#include "libraries/PID/PID.h"
+#include <TimerThree.h> // used for ultrasonic PWM motor control
+#include <PID.h>
 #include <EEPROM.h>
-#include "libraries/EEPROMAnything/EEPROMAnything.h"
-#include "libraries/SerialCommand/SerialCommand.h"
+#include <EEPROMAnything.h>
+#include <SerialCommand.h>

 const int N_ANGLES = 360;                                       // # of angles (0..359)
 const int SHOW_ALL_ANGLES = N_ANGLES;                           // value means 'display all angle data, 0..359'


Latest SD changes

Latest SD changes

--- sd-n64/sd-n64.ino
+++ sd-n64/sd-n64.ino
@@ -36,7 +36,7 @@
 #define NEXT 2
 #define SELECT 3

-#define SERIAL_BAUD_RATE 9600
+#define SERIAL_BAUD_RATE 115200

 #define N64_PIN 8
 #define N64_HIGH DDRB &= ~0x01
@@ -127,7 +127,7 @@
   int pos = 0;
   for (m64File = dir.openNextFile(); m64File; m64File = dir.openNextFile()) {
     const char *name = m64File.name();
-    if (!m64File.isDirectory() && extMatches(name)) {
+    if (!m64File.isDirectory() && extMatches(name) && name[0] != '_') {
       if (pos == dirPos) {
         screen.stroke(0,255,0);
         strcpy(n64_raw_dump, name);
@@ -209,11 +209,26 @@
   }
 }

- void mainLoop()
- {
+void logFrame()
+{
+  const unsigned char *dat = (const unsigned char*)(inputBuffer + bufferPos);
+  Serial.write("F:");
+  Serial.print(curFrame + 1);
+  Serial.write(" ");
+  Serial.print(dat[0], HEX);
+  Serial.write(" ");
+  Serial.print(dat[1], HEX);
+  Serial.write(" ");
+  Serial.print(dat[2], HEX);
+  Serial.write(" ");
+  Serial.println(dat[3], HEX);
+}
+
+void mainLoop()
+{
     unsigned char data, addr;
     unsigned long updateTime;
-    unsigned int curPos;
+//    unsigned int curPos;

     // Loop forever if file open failed
     if (!m64OpenSuccess) {
@@ -260,15 +275,23 @@
             n64_send(n64_buffer, 3, 0);
             interrupts();
             screen.println(F("Controller identified"));
+            Serial.println("P:");
             break;
         case 0x01:
             // If the TAS is finished, there's nothing left to do.
-            if (finished)
-                break;
+            if (finished && !bufferOneMore)
+              *(long*)n64_buffer = 0;
+            else
+              *(long*)n64_buffer = *(inputBuffer + bufferPos);

             // blast out the pre-assembled array in n64_buffer
-            n64_send((byte *) (inputBuffer + bufferPos), 4, 0);
+            n64_send(n64_buffer, 4, 0);
             interrupts();
+
+            if (finished)
+              break;
+
+            logFrame();

             // update input buffer and make sure it doesn't take too long
             updateTime = micros();
@@ -283,19 +306,28 @@
             // Record if it took longer than expected
             updateTime = micros() - updateTime;
             if (updateTime > INPUT_BUFFER_UPDATE_TIMEOUT * 1000) {
-                screen.print(F("Input buffer update took to long ("));
+                screen.print(F("Input buffer update took too long ("));
                 screen.print(updateTime / 1000);
                 screen.println(F(" ms)"));
             }

             curFrame++;
-            curPos = (curFrame * screen.width()) / numFrames;
+
+            if (curFrame == numFrames && !finished && 0) {
+              screen.println(F("TAS finished playing"));
+              Serial.println("C:");
+              finished = true;
+              Serial.flush();
+            }
+
+/*            if (!finished)
+              curPos = (curFrame * screen.width()) / numFrames;
             screen.fill(255,0,0);
-/*            while (progressPos < curPos) {
+            while (progressPos < curPos) {
               screen.point(progressPos++, screen.height() - 1);
-            }*/
-            screen.fill(255,255,255);
-
+            }
+            screen.fill(255,255,255);*/
+
             break;
         case 0x02:
             // A read. If the address is 0x8000, return 32 bytes of 0x80 bytes,
@@ -382,6 +414,9 @@
     int version;

     clear();
+
+    Serial.write("M:");
+    Serial.println(n64_raw_dump);

     // Open the file for reading:
     screen.print(F("Opening file '"));
@@ -418,6 +453,15 @@
     screen.println(version);

     screen.stroke(255,0,0);
+
+    m64File.seek(0x018);
+
+    // Open header
+    if (m64File.read(&numFrames, 4) != 4) {
+        m64File.close();
+        screen.println(F("Failed to read frame count"));
+        return false;
+    }

     // Get header size
     switch(version) {
@@ -455,7 +499,10 @@

     m64OpenSuccess = true;

-    numFrames = (m64File.size() - m64File.position()) / 4;
+    numFrames = min(numFrames, (m64File.size() - m64File.position()) / 4);
+
+    Serial.write("N:");
+    Serial.println(numFrames);

     return true;
 }
@@ -509,7 +556,8 @@
     if (bufferEndPos != -1) {
         // Perform one more input then end once the last input data has been queued.
         if (!bufferOneMore) {
-            screen.println(F("TAS finished playing"));
+            screen.println(F("TAS finished playing2"));
+            Serial.println("C:");
             finished = true;
         }
         else if (bufferPos == bufferEndPos)


Update 2018-Firefighter.ino

Update 2018-Firefighter.ino

- Defined "closeToWall" double; how close is too close for the robot to be against the wall of the maze
- Reworked the variables to ensure ultrasonics ping twice

--- 2018-Firefighter/2018-Firefighter.ino
+++ 2018-Firefighter/2018-Firefighter.ino
@@ -44,6 +44,7 @@
 bool hearingStartSound = false;
 bool robotOn = false;
 unsigned long freqCount;
+double closeToWall = 2;

 void moveForward() {
   leftServo.write(180);
@@ -152,30 +153,25 @@
 }

 void startUp(){
-  float rawRight=rightUltrasonic.getDistance();
-  float rawLeft=leftUltrasonic.getDistance();
-  float rawFront=frontLeftUltrasonic.getDistance();
-  float rawBack=backUltrasonic.getDistance();
-
-  float right=calcAvg(rawRight,rawRight);
-  float left=calcAvg(rawLeft,rawLeft);
-  float front=calcAvg(rawFront,rawFront);
-  float back=calcAvg(rawBack,rawBack);
-
-  if(right < 2 && back < 2){
+  float right=calcAvg(rightUltrasonic.getDistance(),rightUltrasonic.getDistance());
+  float left=calcAvg(leftUltrasonic.getDistance(),leftUltrasonic.getDistance());
+  float front=calcAvg(frontLeftUltrasonic.getDistance(),frontRightUltrasonic.getDistance());
+  float back=calcAvg(backUltrasonic.getDistance(),backUltrasonic.getDistance());
+
+  if(right < closeToWall && back < closeToWall){
     turn(90);
   }
-  else if(right < 2 && front < 2){
+  else if(right < closeToWall && front < closeToWall){
     turn(180);
   }
-  else if(front < 2 && left < 2){
+  else if(front < closeToWall && left < closeToWall){
     turn(-90);
   }
   else{
     int a=1;
   }

-  while(rawRight>2){
+  while(rightUltrasonic.getDistance() > closeToWall){
     moveForward();
   }
 }


Speed up transitions if we've been given a new command

--- arduino/blinkytape_orb.ino
+++ arduino/blinkytape_orb.ino
@@ -26,17 +26,29 @@

 void fade(uint8_t new_val, long duration) {
+  if (val == new_val) {
+    return;
+  }
+
   int incr;
   long delay_ms;
+  long change_delay_ms;
   if (val < new_val) {
     incr = 1;
     delay_ms = duration / (new_val - val);
+    if (CHANGE_DURATION / 2 < duration) {
+      change_delay_ms = (CHANGE_DURATION / 2) / (new_val - val);
+    } else {
+      change_delay_ms = delay_ms;
+    }
   } else if (val > new_val) {
     incr = -1;
     delay_ms = duration / (val - new_val);
-  } else {
-    delay(duration);
-    return;
+    if (CHANGE_DURATION / 2 < duration) {
+      change_delay_ms = (CHANGE_DURATION / 2) / (val - new_val);
+    } else {
+      change_delay_ms = delay_ms;
+    }
   }

   for (uint8_t v = val; v != new_val; v += incr) {
@@ -44,7 +56,13 @@
       leds[i] = CHSV(hue, 255, v);
     }
     FastLED.show();
-    delay(delay_ms);
+
+    // check to see if we've been given a new command, if so, hurry things along
+    if (Serial.available() > 0) {
+      delay(change_delay_ms);
+    } else {
+      delay(delay_ms);
+    }
   }

   val = new_val;


Added "serial port on/off"

Added "serial port on/off"

--- arduino.ino
+++ arduino.ino
@@ -48,6 +48,11 @@
 //
 byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

+//
+// Boolean. If false (0) Arduino wont print informations on serial port
+//
+const int SERIAL_PRINT = 0;
+
 /////////////////////////////////////////
 // END USER SETTINGS
 /////////////////////////////////////////
@@ -72,8 +77,11 @@
   pinMode(led, OUTPUT);
   pinMode(servo, OUTPUT);

-  Serial.begin(9600);
-  Serial.print("Starting serial monitor...\n");
+  if(SERIAL_PRINT)
+  {
+    Serial.begin(9600);
+    Serial.print("Starting serial monitor...\n");
+  }

   Ethernet.begin(mac, ip, gateway, submask);

@@ -82,7 +90,8 @@
   // If you have connection problems, try with an higher delay.
   //
   delay(3000);
-  Serial.println("Connecting...\n");
+  if(SERIAL_PRINT)
+    Serial.println("Connecting...\n");
 }

 void loop()
@@ -90,7 +99,8 @@
   digitalWrite(led, 170);

   if (client.connect(server, 80)) {
-    Serial.println("Connection accepted!\n");
+    if(SERIAL_PRINT)
+        Serial.println("Connection accepted!\n");

     //
     // Send the request to the server
@@ -105,7 +115,8 @@
     request();
   }
   else {
-    Serial.println("Connection failed!\n");
+    if(SERIAL_PRINT)
+        Serial.println("Connection failed!\n");
   }

   client.stop();
@@ -122,7 +133,8 @@
   do {
     if (client.available()) {
       char c = client.read();
-      Serial.print(c);
+      if(SERIAL_PRINT)
+        Serial.print(c);
       buffer[i] = c;
       i++;
       if(i >= DIM_BUFFER)
@@ -131,8 +143,11 @@

     // If the server closed the connection
     if (!client.connected()) {
-      Serial.println();
-      Serial.println("\n\nServer disconnected");
+      if(SERIAL_PRINT)
+      {
+        Serial.println();
+        Serial.println("\n\nServer disconnected");
+      }
       go_on = 0;
     }
   } while(go_on);
@@ -175,8 +190,11 @@
   read_value = 10 * (buffer[i] - '0') + (buffer[i + 1] - '0');

   // TODO: maybe use snprintf()?
-  sprintf(stringa, "Value read: %d\n", read_value);
-  Serial.print(stringa);
+  if(SERIAL_PRINT)
+  {
+    sprintf(stringa, "Value read: %d\n", read_value);
+    Serial.print(stringa);
+  }

   digitalWrite(led, LOW);
   analogWrite(servo, read_value * 2.55);


bugfix: no hang if Serial is not available

--- sketch/sketch.ino
+++ sketch/sketch.ino
@@ -76,7 +76,7 @@
  ****************************************************/
 void setup() {
   Serial.begin(14400);
-  while (!Serial);
+  while (!Serial && millis() < nextIdleTick + 2000);
   Serial.println("MusicBox setup");

   // INT pin requires a pullup;


changed to single lap event

changed to single lap event

--- SlotCar.ino
+++ SlotCar.ino
@@ -29,7 +29,7 @@
   startSequence();

   while (1) {
-    if (getEvent(EVENT_LAP_0)) {
+    if (getEvent(EVENT_LAP)) {
       displayUpdate();
     }
     delay(10);


More simple.

More simple.

--- dimmertask.ino
+++ dimmertask.ino
@@ -35,7 +35,7 @@
                            preferences.getUInt( "pwmdepth", LEDC_NUMBER_OF_BIT ) );
   leds.setState( LIGHTS_AUTO );

-  ESP_LOGI( TAG, "Lights running after %.1f seconds.", millis() / 1000.0 );
+  ESP_LOGI( TAG, "Lights running after %i ms.", millis() );

   xLastWakeTime = xTaskGetTickCount();


Added comments to CourseComputer.ino

Added comments to CourseComputer.ino

--- examples/CourseComputer/CourseComputer.ino
+++ examples/CourseComputer/CourseComputer.ino
@@ -1,6 +1,14 @@
 /*
- * Example Arduino sketch
+ * CourseComputer.ino
  *
+ * Example Arduino sketch for MicroGNC library
+ *
+ * Exchanges NMEA sentences among GPS, Serial, and CourseComputer.
+ * Send $GPWPL sentence with waypoint location to the serial.
+ * CourseComputer will compute direct course to the waypoint
+ * from the current location obtained from GPS, and will send it to
+ * the Serial as $GPBWC sentence.
+ *
  * (C) Copyright 2016 Pavel Bobov.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");


Verifying Cosa LCD on ATtinyX5; running CosaLCDspeed on ATtiny85.

--- examples/LCD/CosaLCDspeed/CosaLCDspeed.ino
+++ examples/LCD/CosaLCDspeed/CosaLCDspeed.ino
@@ -25,15 +25,15 @@
 #include "Cosa/Trace.hh"

 // Select the LCD device for the benchmark
-#include "Cosa/LCD/Driver/HD44780.hh"
+// #include "Cosa/LCD/Driver/HD44780.hh"
 // HD44780::MJKDZ port;
 // HD44780::DFRobot port;
 // HD44780 lcd(&port, 20, 4);
-HD44780::Port port;
-HD44780 lcd(&port);
+// HD44780::Port port;
+// HD44780 lcd(&port);

-// #include "Cosa/LCD/Driver/PCD8544.hh"
-// PCD8544 lcd;
+#include "Cosa/LCD/Driver/PCD8544.hh"
+PCD8544 lcd;

 // #include "Cosa/LCD/Driver/ST7565.hh"
 // ST7565 lcd;


2-й вариант

2-й вариант

--- boilers.ino
+++ boilers.ino
@@ -1,4 +1,6 @@
-#define FILE_LOGGER
+//define FAST_PORT
+
+//define FILE_LOGGER

 #ifdef FILE_LOGGER
 #undef SD_CARD
@@ -10,21 +12,29 @@

 #define SERIAL_COMMAND
 #define USE_RTC
+
+#ifdef FAST_PORT
 #define _PWM_PIN_15
 #define _useTimer2
+#endif

 #include <avr/pgmspace.h>

 #ifdef SD_CARD
 #include <SD.h>
 #endif
+
 #ifdef FILE_LOGGER
 #include <FileLogger.h>
 #endif
+
 #include <OneWire.h>
 #include <LedControl.h>
 #include <Wire.h>
+
+#ifdef FAST_PORT
 #include "AnyPCPWM.h"
+#endif

 #ifdef USE_RTC
 #include <RTClib.h>
@@ -263,6 +273,41 @@
 DateTime now;
 #endif

+#ifdef FAST_PORT
+void shiftOutFast(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
+{
+	uint8_t i;
+
+	for (i = 0; i < 8; i++)  {
+		if (bitOrder == LSBFIRST)
+		digitalWriteFast(dataPin, !!(val & (1 << i)));
+		else
+		digitalWriteFast(dataPin, !!(val & (1 << (7 - i))));
+
+		digitalWriteFast(clockPin, HIGH);
+		digitalWriteFast(clockPin, LOW);
+	}
+}
+
+uint8_t shiftInFast(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
+	uint8_t value = 0;
+	uint8_t i;
+
+	for (i = 0; i < 8; ++i) {
+		digitalWriteFast(clockPin, HIGH);
+		if (bitOrder == LSBFIRST)
+		value |= digitalReadFast(dataPin) << i;
+		else
+		value |= digitalReadFast(dataPin) << (7 - i);
+		digitalWriteFast(clockPin, LOW);
+	}
+	return value;
+}
+
+#endif
+
+
+
 void SerialPrint(int cStr){
 	char buffer[30];
 	strcpy_P(buffer, (char*)pgm_read_word(&(string_table[cStr])));
@@ -300,6 +345,7 @@

 // WARNING: address is a page address, 6-bit end will wrap around
 // also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes
+/*
 void i2c_eeprom_write_buffer( int deviceaddress, unsigned int eeaddresspage, byte* data, byte length ) {
 	Wire.beginTransmission(deviceaddress);
 	Wire.write((int)(eeaddresspage >> 8)); // MSB
@@ -312,6 +358,7 @@
 	Wire.endTransmission();
 	delay(10);
 }
+*/

 byte i2c_eeprom_read_byte( int deviceaddress, unsigned int eeaddress ) {
 	byte rdata = 0xFF;
@@ -325,6 +372,7 @@
 }

 // maybe let's not read more than 30 or 32 bytes at a time!
+/*
 void i2c_eeprom_read_buffer( int deviceaddress, unsigned int eeaddress, byte *buffer, int length ) {
 	Wire.beginTransmission(deviceaddress);
 	Wire.write((int)(eeaddress >> 8)); // MSB
@@ -335,6 +383,7 @@
 	for ( c = 0; c < length; c++ )
 	if (Wire.available()) buffer[c] = Wire.read();
 }
+*/

 void clear_led() {
 	int devices=lc.getDeviceCount();
@@ -478,7 +527,7 @@

 	byte i;
 	byte present = 0;
-	uint8_t addr[8];
+	//uint8_t addr[8];
 	uint8_t data[9];
 	char sign;
 	set_led_point(true);
@@ -493,9 +542,9 @@
 	for (int r=0; r<ts_count; r++) {

 		present = ds.reset();
-		memcpy(addr, temp_sensor[r].addr, sizeof(addr));
-
-		ds.select(addr);
+		//memcpy(addr, temp_sensor[r].addr, sizeof(addr));
+
+		ds.select(temp_sensor[r].addr);
 		ds.write(0xBE);         // Read Scratchpad
 		for ( i = 0; i < 9; i++) {           // we need 9 bytes
 			data[i] = ds.read();
@@ -922,11 +971,19 @@
 	return TEMP_ERROR;
 }

+
 void out_relay_state() {
+#ifdef FAST_PORT
+	digitalWriteFast(EXT_CLOCK, LOW);
+	digitalWriteFast(EXT_CLOCK, LOW);
+	shiftOutFast(EXT_DATA_OUT, EXT_CLOCK, MSBFIRST, ~relay_state);
+	digitalWriteFast(EXT_CS, HIGH);
+#else
 	digitalWrite(EXT_CLOCK, LOW);
 	digitalWrite(EXT_CS, LOW);
 	shiftOut(EXT_DATA_OUT, EXT_CLOCK, MSBFIRST, ~relay_state);
 	digitalWrite(EXT_CS, HIGH);
+#endif
 }

 boolean set_boiler_on () {
@@ -1068,11 +1125,19 @@

 byte get_input_data() {
+#ifdef FAST_PORT
+	digitalWriteFast(EXT_CS_IN, LOW);
+	digitalWriteFast(EXT_CLOCK, LOW);
+	digitalWriteFast(EXT_CLOCK, HIGH);
+	digitalWriteFast(EXT_CS_IN, HIGH);
+	byte data = shiftInFast(EXT_DATA_IN, EXT_CLOCK, LSBFIRST);
+#else
 	digitalWrite(EXT_CS_IN, LOW);
 	digitalWrite(EXT_CLOCK, LOW);
 	digitalWrite(EXT_CLOCK, HIGH);
 	digitalWrite(EXT_CS_IN, HIGH);
 	byte data = shiftIn(EXT_DATA_IN, EXT_CLOCK, LSBFIRST);
+#endif
 	return data;
 }

@@ -1304,15 +1369,27 @@
 }

 void setup(void) {
+
+#ifdef FAST_PORT
 	setup_pc_pwm_any();
-	pinMode(EXT_CS_IN, OUTPUT);
+	pinModeFast(EXT_CS_IN, OUTPUT);
+	pinModeFast(EXT_DATA_IN, INPUT);
+	pinModeFast(EXT_CS, OUTPUT);
+	pinModeFast(EXT_CLOCK, OUTPUT);
+	pinModeFast(EXT_DATA_OUT, OUTPUT);
+	digitalWriteFast(EXT_CS_IN, HIGH);
+	digitalWriteFast(EXT_CS, HIGH);
+#else
+	pinMode(EXT_CS_IN, OUTPUT);
+	pinMode(EXT_DATA_IN, INPUT);
+	pinMode(EXT_CS, OUTPUT);
+	pinMode(EXT_CLOCK, OUTPUT);
+	pinMode(EXT_DATA_OUT, OUTPUT);
 	digitalWrite(EXT_CS_IN, HIGH);
-	pinMode(EXT_DATA_IN, INPUT);
-	pinMode(EXT_CS, OUTPUT);
+	digitalWrite(EXT_CS, HIGH);
+#endif
 	//	pinMode(A2, OUTPUT);
-	digitalWrite(EXT_CS, HIGH);
-	pinMode(EXT_CLOCK, OUTPUT);
-	pinMode(EXT_DATA_OUT, OUTPUT);
+
 	set_boiler_off(FORCE);
 	pump_off();
 	Serial.begin(9600);
@@ -1410,10 +1487,10 @@
 		log_data();
 	}

-	analogWriteAny(15, test_val);
+	//		analogWriteAny(15, test_val);
 	//		Serial.println(test_val);
-	test_val--;
-	if (test_val == 0) test_val = 1023;
+	//test_val--;
+	//if (test_val == 0) test_val = 1023;

 	if ((boiler_state & BOILER_TIMER_ON) > 0) {
 		lc.setChar(2, 7, 'b', true);


Enable mixed mode

Enable mixed mode

--- src/move/move.ino
+++ src/move/move.ino
@@ -1,238 +1,107 @@
+// Mixed Mode Sample for Kangaroo
+// Copyright (c) 2013 Dimension Engineering LLC
+// See license.txt for license details.
+#include <SoftwareSerial.h>
 #include <Kangaroo.h>
-#include <AltSoftSerial.h>
+// Arduino TX (pin 11) goes to Kangaroo S1
+// Arduino RX (pin 10) goes to Kangaroo S2
+// Arduino GND         goes to Kangaroo 0V
+// Arduino 5V          goes to Kangaroo 5V (OPTIONAL, if you want Kangaroo to power the Arduino)
+#define TX_PIN 11
+#define RX_PIN 10
+// Mixed mode channels on Kangaroo are, by default, 'D' and 'T'.
+SoftwareSerial  SerialPort(RX_PIN, TX_PIN);
+KangarooSerial  K(SerialPort);
+KangarooChannel Drive(K, 'D');
+KangarooChannel Turn(K, 'T');

-// AltSoftSerial default pins for Arduino Uno
-// Pin 9 (TX) -> Bluetooth RX
-// Pin 8 (RX) -> Bluetooth TX
-AltSoftSerial SerialPort;
+String inputString = "";         // a string to hold incoming data
+boolean stringComplete = false;  // whether the string is complete

-// Pin 1 (TX) -> Kangaroo S1
-// Pin 0 (RX) -> Kangaroo S2
-KangarooSerial KangarooController(Serial);
+void setup()
+{
+  SerialPort.begin(9600);
+  SerialPort.listen();

-KangarooChannel K1(KangarooController, '1', 135);
-KangarooChannel K2(KangarooController, '2', 135);
+  // initialize serial:
+  Serial.begin(9600);
+  // reserve 200 bytes for the inputString:
+  inputString.reserve(200);
+
+  Drive.start();
+  Turn.start();

-void setup() {
-  // Start Kangaroo serial
-  Serial.begin(115200);
-  SerialPort.begin(57600);
+  Serial.write(SerialPort.read());
+
+  Drive.si(0);
+  Turn.si(0);
+}
+void loop()
+{
+  if (stringComplete) {
+    Serial.println(inputString);

-  delay(1000);
+    switch(inputString[0]) {
+      case 'd':
+        Serial.println(inputString.substring(1));
+        Drive.pi(inputString.substring(1).toInt());
+        break;
+      case 't':
+        Serial.println(inputString.substring(1));
+        Turn.pi(inputString.substring(1).toInt());
+        break;
+      default:
+        Serial.println("Command not recognized!");
+        break;
+    }
+    // clear the string:
+    inputString = "";
+    stringComplete = false;
+  }
+}

-  K1.streaming(true);
-  SerialPort.print(K1.start());
-
-  KangarooMonitor k1_home = K1.home().wait();
-  debugMonitor(k1_home);
-
-  K2.streaming(true);
-  SerialPort.print(K2.start());
-  KangarooMonitor k2_home = K2.home().wait();
-  debugMonitor(k2_home);
-
-  debugMonitor(K1.s(100));
-
+/*
+  SerialEvent occurs whenever a new data comes in the
+ hardware serial RX.  This routine is run between each
+ time loop() runs, so using delay inside loop can delay
+ response.  Multiple bytes of data may be available.
+ */
+void serialEvent() {
+  while (Serial.available()) {
+    // get the new byte:
+    char inChar = (char)Serial.read();
+    // add it to the inputString:
+    inputString += inChar;
+    // if the incoming character is a newline, set a flag
+    // so the main loop can do something about it:
+    if (inChar == '\n') {
+      stringComplete = true;
+    }
+  }
 }

 void debugMonitor(KangarooMonitor monitor) {
-  KangarooStatus status = monitor.status();
-
-  SerialPort.print("Monitoring channel: ");
-  SerialPort.println(monitor.name());
-
-  SerialPort.print("Monitor status flags: ");
-  SerialPort.println(status.flags());
-
-  SerialPort.print("Monitor status type: ");
-  SerialPort.println(status.type());
-
-  SerialPort.print("Monitor status value: ");
-  SerialPort.println(status.value());
-
-  SerialPort.println();
+  debugStatus(monitor.status());
 }

-void loop() {
-  if (SerialPort.available()) {
-    char incoming = SerialPort.read();
-    Serial.print(incoming);
-  }
+void debugStatus(KangarooStatus status) {
+  Serial.print("Monitoring channel: ");
+  Serial.println(status.channel());
+
+  Serial.print("Monitor status flags: ");
+  Serial.println(status.flags());
+
+  Serial.print("Monitor status type: ");
+  Serial.println(status.type());

-  if (Serial.available()) {
-    SerialPort.print(Serial.read());
-  }
+  Serial.print("Monitor status value: ");
+  Serial.println(status.value());

+  Serial.print("Monitor status valid: ");
+  Serial.println(status.valid());

-  // long minimum = K1.getMin().value();
-  // K1.p(minimum).wait();
-
-  // delay(250);
-
-  // long maximum = K1.getMax().value();
-  // K1.p(maximum).wait();
+  Serial.print("Monitor status error: ");
+  Serial.println(status.error());

-  // delay(250);
-  // K1.pi(500).wait();
-  // delay(1000);
-}
-// #define ROBOT_NAME "MOBOT"
-
-// // If you haven't configured your device before use this
-// #define BLUETOOTH_SPEED 57600
-// // If you are modifying your existing configuration, use this:
-// // #define BLUETOOTH_SPEED 57600
-
-// #include <SoftwareSerial.h>
-
-// // Swap RX/TX connections on bluetooth chip
-// //   Pin 10 --> Bluetooth TX
-// //   Pin 11 --> Bluetooth RX
-// SoftwareSerial mySerial(10, 11); // RX, TX
-
-
-// /*
-//   The posible baudrates are:
-//     AT+BAUD1-------1200
-//     AT+BAUD2-------2400
-//     AT+BAUD3-------4800
-//     AT+BAUD4-------9600 - Default for hc-06
-//     AT+BAUD5------19200
-//     AT+BAUD6------38400
-//     AT+BAUD7------57600 - Johnny-five speed
-//     AT+BAUD8-----115200
-//     AT+BAUD9-----230400
-//     AT+BAUDA-----460800
-//     AT+BAUDB-----921600
-//     AT+BAUDC----1382400
-// */
-
-
-// void setup()
-// {
-//   Serial.begin(9600);
-//   while (!Serial) {
-//     ; // wait for serial port to connect. Needed for Leonardo only
-//   }
-//   Serial.println("Starting config");
-//   mySerial.begin(BLUETOOTH_SPEED);
-//   delay(1000);
-
-//   // Should respond with OK
-//   mySerial.print("AT");
-//   waitForResponse();
-
-//   // Should respond with its version
-//   mySerial.print("AT+VERSION");
-//   waitForResponse();
-
-//   // Set pin to 0000
-//   mySerial.print("AT+PIN0000");
-//   waitForResponse();
-
-//   // Set the name to ROBOT_NAME
-//   mySerial.print("AT+NAME");
-//   mySerial.print(ROBOT_NAME);
-//   waitForResponse();
-
-//   // Set baudrate to 57600
-//   mySerial.print("AT+BAUD7");
-//   waitForResponse();
-
-//   Serial.println("Done!");
-// }
-
-// void waitForResponse() {
-//   delay(1000);
-//   while (mySerial.available()) {
-//     Serial.write(mySerial.read());
-//   }
-//   Serial.write("\n");
-// }
-
-// void loop() {}
-// Movement Sample for Kangaroo
-// Copyright (c) 2013 Dimension Engineering LLC
-// See license.txt for license details.
-
-// #include <SoftwareSerial.h>
-// #include <Kangaroo.h>
-
-// // Arduino TX (pin 11) goes to Kangaroo S1
-// // Arduino RX (pin 10) goes to Kangaroo S2
-// // Arduino GND         goes to Kangaroo 0V
-// // Arduino 5V          goes to Kangaroo 5V (OPTIONAL, if you want Kangaroo to power the Arduino)
-// #define TX_PIN 9
-// #define RX_PIN 8
-
-// // Independent mode channels on Kangaroo are, by default, '1' and '2'.
-// SoftwareSerial  K_SERIAL(RX_PIN, TX_PIN);
-// KangarooSerial  K(K_SERIAL);
-// KangarooChannel K1(K, '1');
-// KangarooChannel K2(K, '2');
-
-// void setup()
-// {
-//   Serial.begin(9600);
-//   Serial.println("Starting!");
-
-//   K_SERIAL.begin(9600);
-//   K_SERIAL.listen();
-//   Serial.println("Listening on K_SERIAL!");
-
-//   Serial.println("Starting on K_SERIAL!");
-//   K_SERIAL.println("1,start");
-//   Serial.println("units on K_SERIAL!");
-//   K_SERIAL.println("1,units 1000 thousandths = 1024 lines");
-//   Serial.println("Homing on K_SERIAL!");
-//   K_SERIAL.println("1,home");
-//   Serial.println("Getting pos on K_SERIAL!");
-//   K_SERIAL.println("1,getp");
-//   waitForResponse();
-
-//   // delay(2000);
-
-//   // K1.start();
-//   // Serial.println("Kangaroo started!");
-
-//   // K1.home().wait();
-// }
-
-// void waitForResponse() {
-//   delay(1000);
-//   while (K_SERIAL.available()) {
-//     Serial.write(K_SERIAL.read());
-//   }
-//   Serial.write("\n");
-// }
-
-// // .wait() waits until the command is 'finished'. For position, this means it is within the deadband
-// // distance from the requested position. You can also call K1.p(position); without .wait() if you want to command it
-// // but not wait until it gets to the destination. If you do this, you may want to use K1.getP().value()
-// // to check progress.
-// void loop()
-// {
-//   if (Serial.available()) {
-//     char byte = Serial.read();
-//     Serial.write(byte);
-//     K_SERIAL.write(byte);
-//   }
-//   if (K_SERIAL.available()) {
-//     Serial.write(K_SERIAL.read());
-//   }
-//   // Go to the minimum side at whatever speed limit is set on the potentiometers.
-//   // long minimum = K1.getMin().value();
-//   // K1.p(minimum).wait();
-//   // Serial.println("Starting kangaroo!");
-//   // K1.start();
-//   // Serial.println("Kangaroo started!");
-//   // delay(2000);
-
-//   // // Going to the maximum side, limit speed to 1/10th of the range per second
-//   // // (at least 10 seconds of travel time).
-//   // long maximum = K1.getMax().value();
-//   // long speedLimit = (maximum - minimum) / 10;
-//   // K1.p(maximum, speedLimit).wait();
-
-//   // delay(2000);
-// }
+  Serial.println();
+}


Fixed prototype

Fixed prototype

--- arduino/alarm/alarm.ino
+++ arduino/alarm/alarm.ino
@@ -2,7 +2,7 @@
 String light_state;

 void serialEvent();
-void alarm();
+void dim(unsigned long, boolean);

 void dim(unsigned long duration, boolean brighten) {
   double lnb = log(pow(256.0, 1.0 / (float) duration));


Larger buffer for input on message format

--- MagnusCoreNeoPixel_v1.ino
+++ MagnusCoreNeoPixel_v1.ino
@@ -1,6 +1,6 @@
 #include <Adafruit_NeoPixel.h>
 #include <stdlib.h>
-
+#include <string.h>

 // first communication pin for neo pixel string
 #define BASE_PIN 2
@@ -30,7 +30,7 @@

 // Serial I/O
-int8_t command[32];
+int8_t command[128];
 int8_t in_index = 0;

 void start_serial(void)
@@ -114,13 +114,13 @@
     case 'E':
     case 'e':
       owner = enlightened;
-      percent = getPercent(&command[1]);
+      //percent = getPercent(&command[1]);
       Serial.println("OK");
       break;
     case 'R':
     case 'r':
       owner = resistance;
-      percent = getPercent(&command[1]);
+      //percent = getPercent(&command[1]);
       Serial.println("OK");
       break;
     case 'n':


timer割り込みの部分だけ隔離.

timer割り込みの部分だけ隔離.

--- arduino/GeneralIoSerial/GeneralIoSerial.ino
+++ arduino/GeneralIoSerial/GeneralIoSerial.ino
@@ -19,6 +19,12 @@
 struct STR_UINT8_PEAR {
   char* key;
   uint8_t value;
+};
+
+// streamの転送間隔と時間計測に使用するカウンターの構造体.
+struct STREAM_INFO {
+  uint64_t interval_ms;
+  uint64_t counter;
 };

 /**************************************************************************
@@ -54,13 +60,6 @@
 // D0 - D13
 #define DI_MAX_PORT_NUM 14

-struct STREAM_INFO {
-  uint64_t interval_ms;
-  uint64_t counter;
-};
-
-volatile struct STREAM_INFO ai_stream_info[AI_MAX_PORT_NUM];
-volatile struct STREAM_INFO di_stream_info[DI_MAX_PORT_NUM];

 // AI Reference電圧の名前と値を保持するテーブル.
 const struct STR_UINT8_PEAR AI_REF_TBL[] = {
@@ -69,55 +68,6 @@
   {"EXTERNAL", EXTERNAL}
 };

-// 24時間のmsec表現
-
-// タイマ割り込み
-volatile uint32_t timer2_tcnt2 = 0;
-
-void timer2Start(){
-  float prescaler = 0.0;
-
-  TIMSK2 &= ~(1<<TOIE2);
-  TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
-  TCCR2B &= ~(1<<WGM22);
-  ASSR &= ~(1<<AS2);
-  TIMSK2 &= ~(1<<OCIE2A);
-
-  if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) {  // prescaler set to 64
-    TCCR2B |= (1<<CS22);
-    TCCR2B &= ~((1<<CS21) | (1<<CS20));
-    prescaler = 64.0;
-  } else if (F_CPU < 1000000UL) { // prescaler set to 8
-    TCCR2B |= (1<<CS21);
-    TCCR2B &= ~((1<<CS22) | (1<<CS20));
-    prescaler = 8.0;
-  } else { // F_CPU > 16Mhz,  prescaler set to 128
-    TCCR2B |= ((1<<CS22) | (1<<CS20));
-    TCCR2B &= ~(1<<CS21);
-    prescaler = 128.0;
-  }
-
-  timer2_tcnt2 = 256 - (int)((float)F_CPU * 0.001 / prescaler);
-
-  TCNT2 = timer2_tcnt2;
-  TIMSK2 |= (1<<TOIE2);
-}
-
-void timer2Stop(){
-  TIMSK2 &= ~(1<<TOIE2);
-}
-
-ISR(TIMER2_OVF_vect) {
-  TCNT2 = timer2_tcnt2;
-
-  int i = 0;
-  for(; i < AI_MAX_PORT_NUM; ++i){
-    ++ai_stream_info[i].counter;
-  }
-  for(i = 0; i < DI_MAX_PORT_NUM; ++i){
-    ++di_stream_info[i].counter;
-  }
-}
 #endif

 const prog_char ILLEGAL_COMMAND[] PROGMEM       = "Illegal command.";
@@ -134,12 +84,8 @@
 char read_buf[128];
 int buf_index = 0;

-// DI連続転送の有効・無効を管理する. bitが立っていると有効.
-// megaのポート数に対応するため64bitにする.
-//uint64_t di_stream_enable_ports = 0;
-
-//uint16_t ai_stream_enable_ports = 0;
-
+volatile struct STREAM_INFO ai_stream_info[AI_MAX_PORT_NUM];
+volatile struct STREAM_INFO di_stream_info[DI_MAX_PORT_NUM];

 // pinModeの名前と値を保持するテーブル.
 const struct STR_UINT8_PEAR PIN_MODE_TBL[] = {
@@ -804,3 +750,69 @@
 String wraped(char before, String body, char after){
   return before + body + after;
 }
+
+
+
+/**************************************************************************
+                        タイマ割り込みに関するｱﾚ
+**************************************************************************/
+
+volatile uint32_t timer2_tcnt2 = 0;
+
+#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
+/*******************
+  Arduino MEGAとか
+*******************/
+
+
+#else
+/*******************
+  Arduino Unoとか
+*******************/
+void timer2Start(){
+  float prescaler = 0.0;
+
+  TIMSK2 &= ~(1<<TOIE2);
+  TCCR2A &= ~((1<<WGM21) | (1<<WGM20));
+  TCCR2B &= ~(1<<WGM22);
+  ASSR &= ~(1<<AS2);
+  TIMSK2 &= ~(1<<OCIE2A);
+
+  if ((F_CPU >= 1000000UL) && (F_CPU <= 16000000UL)) {  // prescaler set to 64
+    TCCR2B |= (1<<CS22);
+    TCCR2B &= ~((1<<CS21) | (1<<CS20));
+    prescaler = 64.0;
+  } else if (F_CPU < 1000000UL) { // prescaler set to 8
+    TCCR2B |= (1<<CS21);
+    TCCR2B &= ~((1<<CS22) | (1<<CS20));
+    prescaler = 8.0;
+  } else { // F_CPU > 16Mhz,  prescaler set to 128
+    TCCR2B |= ((1<<CS22) | (1<<CS20));
+    TCCR2B &= ~(1<<CS21);
+    prescaler = 128.0;
+  }
+
+  timer2_tcnt2 = 256 - (int)((float)F_CPU * 0.001 / prescaler);
+
+  TCNT2 = timer2_tcnt2;
+  TIMSK2 |= (1<<TOIE2);
+}
+
+void timer2Stop(){
+  TIMSK2 &= ~(1<<TOIE2);
+}
+
+ISR(TIMER2_OVF_vect) {
+  TCNT2 = timer2_tcnt2;
+
+  int i = 0;
+  for(; i < AI_MAX_PORT_NUM; ++i){
+    ++ai_stream_info[i].counter;
+  }
+  for(i = 0; i < DI_MAX_PORT_NUM; ++i){
+    ++di_stream_info[i].counter;
+  }
+}
+
+
+#endif


cosmetic fix

cosmetic fix

--- sketches/Energino/Energino.ino
+++ sketches/Energino/Energino.ino
@@ -19,7 +19,7 @@
  *  #R, resest the configuration to the defaults
  *
  * Serial putput:
- *   #Energino,0,<voltage>,<current>,<power>,<switch>,<samples>,<period>
+ *   #Energino,0,<voltage>,<current>,<power>,<relay>,<samples>,<period>
  *
  * created 24 May 2012
  * by Roberto Riggio


Update to work with the current RF24 library

I have tested against the current RF24 library on January 7, 2020.

--- RF24_demo/transmitter/transmitter.ino
+++ RF24_demo/transmitter/transmitter.ino
@@ -4,29 +4,24 @@
 #include "nRF24L01.h"
 #include "RF24.h"

-#define BAUDRATE 57600
-
 const int led_pin = 8;
 char message = 'A';

-class RF24Test: public RF24
-{
-public: RF24Test(int a, int b): RF24(a,b) {}
-};
-
-RF24Test radio(9,10);
+RF24 radio(9,10);

 // Radio pipe addresses for the 2 nodes to communicate.
 const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

 void setup()
 {
-  Serial.begin(BAUDRATE);
+  Serial.begin(9600);
+  Serial.println("Starting radio...");

   radio.begin();
   radio.openWritingPipe(pipes[0]);
   radio.openReadingPipe(1,pipes[1]);
-  radio.printDetails();
+  Serial.println("Radio started...");
+
 }

 void loop()
@@ -34,8 +29,9 @@
     radio.stopListening();
     Serial.print("Sending:");
     Serial.print(message);
-     Serial.print(" ");
+    Serial.print(" ");
     radio.write( &message, 1 );
+
     // Now, continue listening
     radio.startListening();

@@ -75,4 +71,4 @@
     // Try again  later
     delay(150);

-}+}


Update Otto_BASIC.ino

Update Otto_BASIC.ino

--- Otto_BASIC/Otto_BASIC.ino
+++ Otto_BASIC/Otto_BASIC.ino
@@ -1,7 +1,7 @@
 //----------------------------------------------------------------
 //-- Basic Otto´s setup
 //-- You can add functions, gestures or sounds in loop
-//-- https://github.com/OttoDIY/OttoDIY
+//-- https://github.com/OttoDIY
 //-- CC BY SA (http://ottodiy.com)
 //-- 04 December 2016
 //-- Adapted Pablo García pabloeweb@gmail.com 01 May 2017


Add IR input

Add IR input

--- iot/iot.ino
+++ iot/iot.ino
@@ -1,33 +1,126 @@
 #include <Servo.h>
+#include <IRremote.h>
+#include <Timer.h>

-int led = 13;
+int led_pin = 13;
+int servo_pin = 9;
+int ir_pin = 10;

 Servo servo;
-int servoPos = 0;
+int servo_pos = 0;
+int servo_state = 0;
+int servo_delay = 0;

-void setup() {
+IRrecv irrecv(ir_pin);
+decode_results ir_results;
+
+void setup() {
+  Serial.begin(9600);
+
   // Initialize LED output
-  pinMode(led, OUTPUT);
-
-  servo.attach(9);
+  pinMode(led_pin, OUTPUT);
+
+  // Initialize servo
+  servo.attach(servo_pin);
+
+  // Initialize IR
+  irrecv.enableIRIn();
+
+  Serial.println("Setup complete");
 }

 void loop() {
-  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
-
-  for (servoPos = 0; servoPos < 90; servoPos += 1)
-  {
-    servo.write(servoPos);
-    delay(10);
+  pollButton();
+  //updateServo();
+  delay(10);
+}
+
+void updateServo() {
+  if (servo_state == 0) {
+    if (servo_pos >= 0) {
+      servo_pos -= 1;
+      servo.write(servo_pos);
+    }
   }
-
-  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
-
-  delay(2500);
-
-  for (servoPos = 90; servoPos >= 1; servoPos -= 1)
-  {
-    servo.write(servoPos);
-    delay(10);
+  else if (servo_state == 1) {
+    if (servo_pos <= 90) {
+      servo_pos += 1;
+      servo.write(servo_pos);
+    }
+    else {
+      servo_state = 2;
+      servo_delay = 0;
+    }
+  }
+  else if (servo_state == 2) {
+    if (servo_delay >= 200) {
+      servo_state = 3;
+    }
+    else {
+      servo_delay += 1;
+    }
+  }
+  else if (servo_state == 3) {
+    if (servo_pos >= 0) {
+      servo_pos -= 1;
+      servo.write(servo_pos);
+    }
+    else {
+      servo_state = 1;
+    }
   }
 }
+
+void pollButton() {
+  if (irrecv.decode(&ir_results)) {
+    int ir_response = translateIR();
+    Serial.println("Received IR response" + ir_response);
+
+    if (ir_response == 1) {
+      Serial.println("Servo enabled");
+      digitalWrite(led_pin, HIGH);
+      servo_state = 1;
+    }
+    else if (ir_response == 2) {
+      Serial.println("Servo disabled");
+      digitalWrite(led_pin, LOW);
+      servo_state = 0;
+    }
+
+    irrecv.resume(); // Receive the next value
+  }
+}
+
+int translateIR() {
+  switch(ir_results.value)
+  {
+  case 0xFF30CF:
+    return 1;
+  case 0xFF18E7:
+    return 2;
+  case 0xFF7A85:
+    return 3;
+  case 0xFF10EF:
+    return 4;
+  case 0xFF38C7:
+    return 5;
+  case 0xFF5AA5:
+    return 6;
+  case 0xFF42BD:
+    return 7;
+  case 0xFF4AB5:
+    return 8;
+  case 0xFF52AD:
+    return 9;
+  default:
+    return -1;
+  }
+}
+
+
+
+
+
+
+
+


Removes unused code.

Removes unused code.

Removed the generic index w/ graphs since we will not need them.

--- njmakerday_20160318/njmakerday_20160318.ino
+++ njmakerday_20160318/njmakerday_20160318.ino
@@ -44,12 +44,6 @@
   \

Hello from ESP8266!
\

Uptime: %02d:%02d:%02d
\
-
Uptime Graph
\
-    \
-
Temp Graph
\
-    \
-
Humidity Graph
\
-    \
   \
 ",

@@ -76,24 +70,6 @@

 	server.send ( 404, "text/plain", message );
 	digitalWrite ( ledWiFi, 0 );
-}
-
-void drawUptimeGraph() {
- String out = "";
-  char uptime[100];
-  out += "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"400\" height=\"150\">\n";
-  out += "<rect width=\"400\" height=\"150\" fill=\"rgb(250, 230, 210)\" stroke-width=\"1\" stroke=\"rgb(0, 0, 0)\" />\n";
-  out += "<g stroke=\"black\">\n";
-  int y = rand() % 130;
-  for (int x = 10; x < 390; x+= 10) {
-    int y2 = rand() % 130;
-    sprintf(uptime, "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\" stroke-width=\"1\" />\n", x, 140 - y, x + 10, 140 - y2);
-    out += uptime;
-    y = y2;
-  }
-  out += "</g>\n</svg>\n";
-
-  server.send ( 200, "image/svg+xml", out);
 }

 void handleTemperature() {
@@ -154,9 +130,6 @@
   }

 	server.on ( "/", handleRoot );
-	server.on ( "/uptime.svg", drawUptimeGraph );
-//  server.on ( "/temp.svg", drawTempGraph );
-//  server.on ( "/humidity.svg", drawHumidityGraph );
   server.on ( "/temperature", handleTemperature );
   server.on ( "/humidity", handleHumidity );
 	server.on ( "/inline", []() {


oha_gateway_rf_v0_2: - Shortened field names in JSON message.

--- oha_gateway_rf_v0_2/oha_gateway_rf_v0_2.ino
+++ oha_gateway_rf_v0_2/oha_gateway_rf_v0_2.ino
@@ -11,7 +11,7 @@
    * RF Status LED attached to digital pin 12
    * Serial Status LED attached to digital pin 13

-   Created 17-JAN-2015 by Jon Brule
+   Created 19-JAN-2015 by Jon Brule
 ----------------------------------------------------------------------------- */
 #include <SPI.h>
 #include <RFM69.h>
@@ -166,9 +166,9 @@
   StaticJsonBuffer<200> jsonBuffer;
   JsonObject& root = jsonBuffer.createObject();
   root["type"] = rfMsg.msg.type;
-  root["direction"] = rfMsg.msg.direction;
-  root["source"] = rfMsg.msg.source;
-  root["destination"] = rfMsg.msg.destination;
+  root["dir"] = rfMsg.msg.direction;
+  root["src"] = rfMsg.msg.source;
+  root["dest"] = rfMsg.msg.destination;
   root["rssi"] = rfMsg.msg.rssi;
   JsonArray& data = root.createNestedArray("data");
   for (int i = 0; i < MSG_DATA_LENGTH; i++) {


Restored some neutral code that probably never did anything to begin with.

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

--- zimodem/zstream.ino
+++ zimodem/zstream.ino
@@ -117,9 +117,9 @@
     current->write(c);
     logSocketOut(c);
     current->flush(); // rendered safe by available check
-  }
-  //delay(0);
-  //yield();
+    delay(0);
+    yield();
+  }
 }

 void ZStream::loop()


debug

debug

--- btnLed/src/sketch.ino
+++ btnLed/src/sketch.ino
@@ -15,7 +15,7 @@

 void setup()
 {
-  pinMode(onoffLED, OUTPUT);       // An LED to signal on or off state
+  pinMode(onoffPIN, OUTPUT);       // An LED to signal on or off state
   attachInterrupt(0, ISRbutton, RISING); // Interrupt when button is pressed
   //pinMode(pushbuttonPIN, INPUT);  // A button to switch the LED
 }


Cleanup Bitmaps example removing warnings

--- examples/Bitmaps/Bitmaps.ino
+++ examples/Bitmaps/Bitmaps.ino
@@ -23,8 +23,8 @@
 int led = 13;

 void drawBitmap(int16_t x, int16_t y, const gimp32x32bitmap* bitmap) {
-  for(int i=0; i<bitmap->height; i++) {
-    for(int j=0; j<bitmap->width; j++) {
+  for(unsigned int i=0; i < bitmap->height; i++) {
+    for(unsigned int j=0; j < bitmap->width; j++) {
       rgb24 pixel = { bitmap->pixel_data[(i*bitmap->width + j)*3 + 0],
                       bitmap->pixel_data[(i*bitmap->width + j)*3 + 1],
                       bitmap->pixel_data[(i*bitmap->width + j)*3 + 2] };
@@ -42,9 +42,6 @@
 }

 void loop() {
-  int i;
-  rgb24 *buffer;
-
   matrix.fillScreen({0,0,0});
   // to use drawBitmap, must cast the pointer to pixelmatixlogo as (const gimp32x32bitmap*)
   drawBitmap(0,0,(const gimp32x32bitmap*)&pixelmatixlogo);
@@ -54,8 +51,6 @@
   delay(1000);
   digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
   delay(1000);
-
-  buffer = matrix.backBuffer();

   matrix.fillScreen({0,0,0});
   // can pass &colorwheel in directly as the bitmap source is already gimp32x32bitmap


almost working turning

almost working turning

--- Arduino/Arduino.ino
+++ Arduino/Arduino.ino
@@ -4,7 +4,7 @@
 #include <adk.h>
 #define BUFFSIZE   255
 #define MAX_POWER  400
-#define DELAY 50
+#define DELAY 10

 // Android --> Arduino codes
 #define CMD_NULL_VALUE 0
@@ -66,9 +66,10 @@
 targetRightVelocity = 0,
 currentLeftVelocity = 0,
 currentRightVelocity= 0,
-baseVelocity = 100,
+baseVelocity = 131,
 velocityStep= 5;

+long coldTimerStart;

@@ -90,7 +91,7 @@
 // Debug mode for communication
 bool COM_DEBUG_MODE = false;
 // Debug mode for movment
-bool MOV_DEBUG_MODE = true;
+bool MOV_DEBUG_MODE = false;
 uint8_t inBuffer[BUFFSIZE];
 uint8_t outBuffer[BUFFSIZE];
 char inStringBuffer[BUFFSIZE];
@@ -126,16 +127,18 @@
     char*a;
     if (strlen(a = readFromADK()) > 0) {
       if (decodeCommand(a, &command, &param1, &param2)) {
-        Serial.print("COMMAND: Command "); Serial.print(command); Serial.print(", param1 "); Serial.print(param1); Serial.print(", param2 "); Serial.print(param2); Serial.println(", received and is beign processed!");
+        if (MOV_DEBUG_MODE){
+          Serial.print("COMMAND: Command "); Serial.print(command); Serial.print(", param1 "); Serial.print(param1); Serial.print(", param2 "); Serial.print(param2); Serial.println(", received and is beign processed!");
+        }
         switch (command) {
           case CMD_LEFT:
-          turnLeft(param1);
+          turnLeft(140);//param1
           break;
           case CMD_RIGHT:
-          turnRight(param1);
+          turnRight(140);//param1
           break;
           case CMD_STOP:
-          stop(SOFT);
+          stop(HARD);
           break;
           default:
           stop(SOFT);
@@ -143,31 +146,35 @@
           break;
         }
         lastCommand=command;
-        } else {
+      }
+      else {
+        if (MOV_DEBUG_MODE){
           Serial.print("ERROR: Command "); Serial.print(command); Serial.print(", param1 "); Serial.print(param1); Serial.print(", param2 "); Serial.print(param2); Serial.println(", is not valid!");
         }
-        } else {
-          Serial.print("*");
-        }
-        sendToADK( random(0, 2), random(0, 4) + random(1, 3) * 100, random(150, 152));
       }
-      delay(DELAY);
-    }
-
-    char* readFromADK() {
-      adk.read(&bytesRead, BUFFSIZE, inBuffer);
-      memset(inStringBuffer, 0, BUFFSIZE);
-      if (bytesRead > 0) {
-        memcpy(inStringBuffer, inBuffer, bytesRead);
-        if (COM_DEBUG_MODE) {
-          Serial.print("\nReceiving | ");
-          Serial.print(inStringBuffer);
-          Serial.print(" | ");
-          Serial.print(strlen(inStringBuffer));
-          Serial.println(" bytes incoming");
-        }
-      }
-      delay(DELAY / 10);
+    }
+    else {
+      Serial.print("*");
+    }
+    sendToADK( random(0, 2), random(0, 4) + random(1, 3) * 100, random(150, 152));
+  }
+  delay(DELAY);
+}
+
+char* readFromADK() {
+  adk.read(&bytesRead, BUFFSIZE, inBuffer);
+  memset(inStringBuffer, 0, BUFFSIZE);
+  if (bytesRead > 0) {
+    memcpy(inStringBuffer, inBuffer, bytesRead);
+    if (COM_DEBUG_MODE) {
+      Serial.print("\nReceiving | ");
+      Serial.print(inStringBuffer);
+      Serial.print(" | ");
+      Serial.print(strlen(inStringBuffer));
+      Serial.println(" bytes incoming");
+    }
+  }
+  delay(DELAY / 10);
   return inStringBuffer; // If nothing has been read then return the previously initialized empty array
 }

@@ -284,44 +291,53 @@
   }
 }
 void setSpeedAndGo(int velocityLeft, int velocityRight) {
-  targetLeftVelocity=velocityLeft;
-  targetRightVelocity=velocityRight;
-  if (currentLeftVelocity<targetLeftVelocity){
-    currentLeftVelocity+=velocityStep;
-  }
-  else if (currentLeftVelocity>targetLeftVelocity){
-    currentLeftVelocity-=velocityStep;
-  }
-  if (currentRightVelocity<targetRightVelocity){
-    currentRightVelocity+=velocityStep;
-  }
-  else if (currentRightVelocity>targetRightVelocity){
-    currentRightVelocity-=velocityStep;
-  }
-  releaseBrake(BOTH);
-  analogWrite(PWM_LEFT, currentLeftVelocity);
-  analogWrite(PWM_RIGHT, currentRightVelocity);
-  delay(DELAY);
-}
-
-
-void turnLeft(int velocity){
-  if (lastCommand!=CMD_LEFT){
-    stop(HARD);
-  }
-  setDirection(RIGHT, FORWARD);
-  setDirection(LEFT, BACKWARD);
-  setSpeedAndGo(velocity,velocity);
-}
-
-void turnRight(int velocity){
-  if (lastCommand!=CMD_RIGHT){
-   stop(HARD);
+  releaseBrake(BOTH);
+
+  if (millis()-coldTimerStart>100 ) {
+    if ( currentLeftVelocity<velocityLeft+10 && currentLeftVelocity!=LOW){
+    currentLeftVelocity= currentLeftVelocity+velocityStep/5;
+    }
+    if (currentRightVelocity<velocityRight){
+
+
+    currentRightVelocity= currentRightVelocity+velocityStep/5;
+
+    }
+    analogWrite(PWM_LEFT, currentLeftVelocity);
+    analogWrite(PWM_RIGHT, currentRightVelocity);
+    Serial.println("");
+    Serial.print("Current velocity SX: ");Serial.println(currentLeftVelocity);
+    Serial.print("Current velocity DX: ");Serial.println(currentRightVelocity);
+    Serial.print(analogRead(SNS_LEFT));Serial.print("HHHH");Serial.println(analogRead(SNS_RIGHT));
+    coldTimerStart=millis();
+
+  }
+}
+
+
+  void turnLeft(int velocity){
+    if (lastCommand!=CMD_LEFT){
+      stop(HARD);
+      coldTimerStart=millis();
+      currentLeftVelocity=LOW;
+      currentRightVelocity=baseVelocity;
+    }
+    setDirection(RIGHT, FORWARD);
+    setDirection(LEFT, BACKWARD);
+    setSpeedAndGo(LOW,velocity);
+  }
+
+  void turnRight(int velocity){
+    if (lastCommand!=CMD_RIGHT){
+     stop(HARD);
+     coldTimerStart=millis();
+     currentRightVelocity=LOW;
+     currentLeftVelocity=baseVelocity;
+   }
+   setDirection(RIGHT, BACKWARD);
+   setDirection(LEFT, FORWARD);
+   setSpeedAndGo(velocity,LOW);
  }
- setDirection(RIGHT, BACKWARD);
- setDirection(LEFT, FORWARD);
- setSpeedAndGo(velocity,velocity);
-}

 // with method = HARD = true it uses brakes, otherwise stop by inertia
 void stop(bool method) {
@@ -331,6 +347,7 @@
     analogWrite(PWM_LEFT, LOW);
     analogWrite(PWM_RIGHT, LOW);
     } else{
+      currentRightVelocity=currentLeftVelocity=LOW;
       setSpeedAndGo(LOW,LOW);
     }
     delay(DELAY / 10);