More AT enhancements:  Can now do things like ate0&k1dtbbs.domain.com or ate0d#9 for phone book dial

--- MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
+++ MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
@@ -1368,6 +1368,12 @@
 {
     boolean petscii_mode_guess = false;
     byte errors = 0;
+    boolean dialed_out = 0;
+    // Phonebook dial
+    char numString[2];
+    char address[ADDR_HOST_SIZE];
+    int phoneBookNumber;
+
     // Simple PETSCII/ASCII detection

     if (((Modem_CommandBuffer[0] == 'A') && (Modem_CommandBuffer[1] == 'T')))
@@ -1432,7 +1438,7 @@
         {
             Modem_PrintERROR();
         }
-    }
+    }/*
     else if (strncmp(Modem_CommandBuffer, ("ATD#"), 4) == 0)
     {
         // Phonebook dial
@@ -1449,8 +1455,8 @@
         }
         else
             Modem_PrintERROR();
-    }
-    else if (   // This needs to be revisited
+    }*/
+    /*else if (   // This needs to be revisited
         strncmp(Modem_CommandBuffer, ("ATDT "), 5) == 0 ||
         strncmp(Modem_CommandBuffer, ("ATDP "), 5) == 0 ||
         strncmp(Modem_CommandBuffer, ("ATD "), 4) == 0
@@ -1463,7 +1469,7 @@
     {
         Modem_Dialout(strstr(Modem_CommandBuffer, "ATDT") + 4);
         Modem_ResetCommandBuffer();  // This avoids port# string fragments on subsequent calls
-    }
+    }*/
     /*else if ((strcmp(Modem_CommandBuffer, ("ATH0")) == 0 || strcmp(Modem_CommandBuffer, ("ATH")) == 0))
     {
         Modem_Disconnect();
@@ -1736,6 +1742,46 @@
                 }
                 break;

+
+                // Dialing should come last..
+                // TODO:  Need to allow for spaces after D, DT, DP.  Currently fails.
+                case 'D':
+                switch(Modem_CommandBuffer[i])
+                {
+                    case 'T':
+                    case 'P':
+                    Modem_Dialout(&Modem_CommandBuffer[i+1]);
+                    dialed_out = 1;
+                    i = COMMAND_BUFFER_SIZE-3;    // Make sure we don't try to process any more...
+                    break;
+
+                    case '#':
+                    // Phonebook dial
+                    //char numString[2];
+                    numString[0] = Modem_CommandBuffer[i+1];
+                    numString[1] = '\0';
+                    //char address[ADDR_HOST_SIZE];
+
+                    //int phoneBookNumber = atoi(numString);
+                    phoneBookNumber = atoi(numString);
+                    if (phoneBookNumber >= 1 && phoneBookNumber <= ADDR_HOST_ENTRIES)
+                    {
+                        strncpy(address,readEEPROMPhoneBook(ADDR_HOSTS + ((phoneBookNumber-1) * ADDR_HOST_SIZE)).c_str(),ADDR_HOST_SIZE);
+                        Modem_Dialout(address);
+                        dialed_out = 1;
+                    }
+                    else
+                        errors++;
+                    break;
+
+                    default:
+                    Modem_Dialout(&Modem_CommandBuffer[i]);
+                    dialed_out = 1;
+                    i = COMMAND_BUFFER_SIZE-3;    // Make sure we don't try to process any more...
+                    break;
+                }
+                break;
+
                 case '\n':
                 case '\r':
                 break;
@@ -1820,10 +1866,12 @@
             Modem_S0_AutoAnswer = atoi(temp);
         }*/

-        if (errors)
-            Modem_PrintERROR();
-        else
-            Modem_PrintOK();
+        if (!dialed_out) {    // Should add error checking to calls to Modem_Dialout(), Connect() etc.
+            if (errors)
+                Modem_PrintERROR();
+            else
+                Modem_PrintOK();
+        }
     }
     else
     {


Code formatting

Code formatting

--- ArduinoAudioSpectrumAnalyzer.ino
+++ ArduinoAudioSpectrumAnalyzer.ino
@@ -15,54 +15,54 @@
 #include "Test_signal.h"

 #ifndef _PDQ_ST7735H_
-  #define TFT_RST 0  // you can also connect this to the Arduino reset, in which case, set this #define pin to 0!
-  Adafruit_ST7735 tft = Adafruit_ST7735(ST7735_CS_PIN,  ST7735_DC_PIN, TFT_RST);
+#define TFT_RST 0  // you can also connect this to the Arduino reset, in which case, set this #define pin to 0!
+Adafruit_ST7735 tft = Adafruit_ST7735(ST7735_CS_PIN, ST7735_DC_PIN, TFT_RST);
 #else
-  PDQ_ST7735 tft;
+PDQ_ST7735 tft;
 #endif

 void setup()
 {
-  // TODO:
-  // TIMSK0 = 0; // turn off timer0 for lower jitter
-  setupADC();
+	// TODO:
+	// TIMSK0 = 0; // turn off timer0 for lower jitter
+	setupADC();

-  // Use this initializer (uncomment) if you're using a 1.44" TFT
-  tft.initR(ST7735_INITR_144GREENTAB);   // initialize a ST7735S chip, black tab
-  tft.fillScreen(ST7735_BLACK);
-  tft.setTextWrap(false);
+	// Use this initializer (uncomment) if you're using a 1.44" TFT
+	tft.initR(ST7735_INITR_144GREENTAB);   // initialize a ST7735S chip, black tab
+	tft.fillScreen(ST7735_BLACK);
+	tft.setTextWrap(false);
 }

 void setupADC()
 {
-  cli();
-
-  ADCSRA = 0;
-  ADCSRB = 0; // Free running mode - no specific trigger
-
-  // See http://www.robotplatform.com/knowledge/ADC/adc_tutorial_3.html
-  // Leaving ADLAR cleared for the default right-justification and MUX3 though MUX0 bits cleared for only A0 input
-  // Setting the standard 5V reference.
-  ADMUX = 1 << REFS0;
-
-  // set a2d prescaled factor to 32
-  // 16 MHz / 32 = 500 KHz, for sampling rate of 500 000 / 13 = 38461.54 Hz
-  // XXX: this will not work properly for other clock speeds, and
-  // this code should use F_CPU to determine the prescaled factor.
+	cli();

-  // See http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogRead.html for how prescaling is encoded. Basically, it's a list of factors from 1 to 128
-  // 32 is 6th in the list, so it's 101
-  setBit(ADCSRA, ADPS2);
-  clearBit(ADCSRA, ADPS1);
-  setBit(ADCSRA, ADPS0);
+	ADCSRA = 0;
+	ADCSRB = 0; // Free running mode - no specific trigger

-  // See http://www.robotplatform.com/knowledge/ADC/adc_tutorial_2.html for ADCSRA reference
-  setBit(ADCSRA, ADATE); //enabble auto trigger
-  setBit(ADCSRA, ADEN); //enable ADC
-  setBit(ADCSRA, ADIE); //enable ADC interrupt
-  setBit(ADCSRA, ADSC); //start ADC
-
-  sei();
+	// See http://www.robotplatform.com/knowledge/ADC/adc_tutorial_3.html
+	// Leaving ADLAR cleared for the default right-justification and MUX3 though MUX0 bits cleared for only A0 input
+	// Setting the standard 5V reference.
+	ADMUX = 1 << REFS0;
+
+	// set a2d prescaled factor to 32
+	// 16 MHz / 32 = 500 KHz, for sampling rate of 500 000 / 13 = 38461.54 Hz
+	// XXX: this will not work properly for other clock speeds, and
+	// this code should use F_CPU to determine the prescaled factor.
+
+	// See http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogRead.html for how prescaling is encoded. Basically, it's a list of factors from 1 to 128
+	// 32 is 6th in the list, so it's 101
+	setBit(ADCSRA, ADPS2);
+	clearBit(ADCSRA, ADPS1);
+	setBit(ADCSRA, ADPS0);
+
+	// See http://www.robotplatform.com/knowledge/ADC/adc_tutorial_2.html for ADCSRA reference
+	setBit(ADCSRA, ADATE); //enabble auto trigger
+	setBit(ADCSRA, ADEN); //enable ADC
+	setBit(ADCSRA, ADIE); //enable ADC interrupt
+	setBit(ADCSRA, ADSC); //start ADC
+
+	sei();
 }

 volatile uint16_t maxSampleValue = 0;
@@ -75,68 +75,68 @@

 ISR(ADC_vect) //when new ADC value ready
 {
-  if (samplingWindowFull)
-    return;
-
-  const uint16_t sample = ADCL | ((uint16_t)ADCH << 8); // Somehow it is required that ADCL is read before ADCH, or it won't work!
+	if (samplingWindowFull)
+		return;
+
+	const uint16_t sample = ADCL | ((uint16_t)ADCH << 8); // Somehow it is required that ADCL is read before ADCH, or it won't work!
 #ifndef USE_TEST_SIGNAL
-  fht_input[currentSampleIndex] = sample - 512; // fht_input is signed! Skipping this step will result in DC offset
+	fht_input[currentSampleIndex] = sample - 512; // fht_input is signed! Skipping this step will result in DC offset
 #endif

-  ++currentSampleIndex;
+	++currentSampleIndex;

-  constexpr uint16_t k = 8;
-  averageSampleValue = (averageSampleValue * (k - 1) + sample) / k;
+	constexpr uint16_t k = 8;
+	averageSampleValue = (averageSampleValue * (k - 1) + sample) / k;

-  if (currentSampleIndex == SamplingWindowSize)
-  {
-    currentSampleIndex = 0;
-    samplingWindowFull = true;
-  }
-
-  if (sample > maxSampleValue)
-    maxSampleValue = sample;
-  else if (sample < minSampleValue)
-    minSampleValue = sample;
+	if (currentSampleIndex == SamplingWindowSize)
+	{
+		currentSampleIndex = 0;
+		samplingWindowFull = true;
+	}
+
+	if (sample > maxSampleValue)
+		maxSampleValue = sample;
+	else if (sample < minSampleValue)
+		minSampleValue = sample;
 }

 void loop()
 {
-  if (samplingWindowFull)
-  {
-	// No-op if USE_TEST_SIGNAL is not defined
-	generateTestSignal(1000 /* Hz */, 1024, 32);
+	if (samplingWindowFull)
+	{
+		// No-op if USE_TEST_SIGNAL is not defined
+		generateTestSignal(1000 /* Hz */, 1024, 32);

-    runFHT();
-    updateScreen();
-    delay(67);
-    samplingWindowFull = false; // Allow the new sample set to be collected - only after the delay. Else the sample set would be 60 ms stale by the time we get to process it.
-  }
+		runFHT();
+		updateScreen();
+		delay(67);
+		samplingWindowFull = false; // Allow the new sample set to be collected - only after the delay. Else the sample set would be 60 ms stale by the time we get to process it.
+	}
 }

 #define RGB_to_565(R, G, B) static_cast<uint16_t>(((R & 0xF8) << 8) | ((G & 0xFC) << 3) | (B >> 3))

 inline void updateScreen()
 {
-  //tft.fillRect(0, 0, 100, 55, ST7735_BLACK);
+	//tft.fillRect(0, 0, 100, 55, ST7735_BLACK);
 	tft.fillScreen(RGB_to_565(0, 0, 0));

-  // Symbol heights depending on text size: 1 - 10(?), 2 - 15, 3 - 25
+	// Symbol heights depending on text size: 1 - 10(?), 2 - 15, 3 - 25

-  tft.setTextSize(2);
-  tft.setTextColor(RGB_to_565(0, 200, 255));
-  tft.setCursor(0, 0);
-  tft.print(minSampleValue);
+	tft.setTextSize(2);
+	tft.setTextColor(RGB_to_565(0, 200, 255));
+	tft.setCursor(0, 0);
+	tft.print(minSampleValue);

-  tft.setTextColor(RGB_to_565(255, 0, 10));
-  tft.setCursor(45, 0);
-  tft.print(maxSampleValue);
+	tft.setTextColor(RGB_to_565(255, 0, 10));
+	tft.setCursor(45, 0);
+	tft.print(maxSampleValue);

-  tft.setTextColor(RGB_to_565(0, 255, 10));
-  tft.setCursor(90, 0);
-  tft.print(averageSampleValue);
+	tft.setTextColor(RGB_to_565(0, 255, 10));
+	tft.setCursor(90, 0);
+	tft.print(averageSampleValue);

-  assert(FHT_N == 256);
-  for (int i = 1; i < 128; ++i) // What's the deal with bin 0?
-	tft.drawFastVLine(i, 128 - fht_log_out[i] / 2, fht_log_out[i] / 2, RGB_to_565(255, 255, 200));
+	assert(FHT_N == 256);
+	for (int i = 1; i < 128; ++i) // What's the deal with bin 0?
+		tft.drawFastVLine(i, 128 - fht_log_out[i] / 2, fht_log_out[i] / 2, RGB_to_565(255, 255, 200));
 }


Modify JSON data to send to serial

Modify JSON data to send to serial

--- Sensors/GpsDataToSerial/GpsDataToSerial.ino
+++ Sensors/GpsDataToSerial/GpsDataToSerial.ino
@@ -138,11 +138,11 @@
           if(sAlt == "")
             sAlt = "0";

-          String geo = "{\"latitude\":" + sLat + ",\"latd\":" + sLatd + ",\"longitude\":" + sLong + ",\"longd\":" + sLongd + ",\"altitude\":" + sAlt + ",\"T\":" + currentTemperature + ",\"P\":" + currentPressure + ",\"H\":" + currentHumidity + "}";
+          String data = "{\"latitude\":\"" + sLat + "\",\"latd\":\"" + sLatd + "\",\"longitude\":\"" + sLong + "\",\"longd\":\"" + sLongd + "\",\"altitude\":\"" + sAlt + "\",\"T\":\"" + currentTemperature + "\",\"P\":\"" + currentPressure + "\",\"H\":\"" + currentHumidity + "\"}";

           Serial.println("#");
           delay(50);
-          Serial.println(geo);
+          Serial.println(data);
           delay(50);
           Serial.println("#");
           delay(50);


Remove dead code

Remove dead code


Adding some fun to the Ultrasonic range module example.

--- examples/Drivers/CosaHCSR04/CosaHCSR04.ino
+++ examples/Drivers/CosaHCSR04/CosaHCSR04.ino
@@ -38,18 +38,23 @@

 // Use the ST7735R TFT display or the trace iostream
 #ifdef USE_TFT
+
 #undef putchar
 #include "Cosa/SPI/ST7735R.hh"
 #include "Cosa/IOStream.hh"
 #include "Cosa/Font/FixedNums8x16.hh"
-#include "Cosa/Font/System5x7.hh"
+#include "Cosa/Icon/arduino_icon_96x32.h"
+
 ST7735R tft;
 IOStream cout(&tft);
 uint16_t RED, GREEN, BLUE, YELLOW, CYAN, GRAY;
+
 #else
+
 #include "Cosa/Pins.hh"
 #include "Cosa/Trace.hh"
 OutputPin ledPin(13);
+
 #endif

 void setup()
@@ -58,7 +63,8 @@
   // Start display and initiate text scale and port
   tft.begin();
   tft.set_text_scale(4);
-  tft.set_text_port(10, 40, tft.WIDTH - 20, tft.HEIGHT - 40);
+  tft.set_font(&fixednums8x16);
+  tft.set_orientation(Canvas::LANDSCAPE);
   RED = tft.shade(Canvas::RED, 75);
   YELLOW = tft.shade(Canvas::YELLOW, 75);
   GREEN = tft.shade(Canvas::GREEN, 75);
@@ -104,15 +110,16 @@
     else if (distance < 400) tft.set_canvas_color(CYAN);
     else                     tft.set_canvas_color(GRAY);
     tft.fill_screen();
-    tft.set_cursor(10, 10);
-    tft.set_text_scale(4);
-    tft.set_font(&system5x7);
-    cout.printf_P(PSTR("%d\nmm"), distance);
-
-    tft.set_text_scale(1);
-    tft.set_cursor(10, 120);
-    tft.set_font(&fixednums8x16);
-    cout.printf_P(PSTR("%d"), distance);
+    if (distance < 50 || distance > 2000) {
+      uint8_t saved = tft.get_text_scale();
+      tft.set_text_scale(1);
+      tft.draw_icon((tft.WIDTH-96)/2, (tft.HEIGHT-32)/2, arduino_icon_96x32);
+      tft.set_text_scale(saved);
+    }
+    else {
+      tft.set_cursor(10, 35);
+      cout.printf_P(PSTR("%d"), distance);
+    }
 #else
     TRACE(distance);
 #endif


More helpful information

More helpful information

Print an FPGA Image line that matches what gets selected in the Arduino
IDE under Tools->FPGA Image.
Add printing a message at 1/2 speed and 2x speed to help people figure
out cases where the wrong MHz is selected in Tools->FPGA image.

--- examples/GetXLR8Version/GetXLR8Version.ino
+++ examples/GetXLR8Version/GetXLR8Version.ino
@@ -5,16 +5,39 @@
  Alorium Technology (info@aloriumtech.com)
  Reports information about the FPGA design currently
   loaded on the XLR8 board
+ Set serial monitor to 115200 baud
 */

 #define SAMPLES 129
 volatile uint8_t index;
 volatile uint16_t timestamp[SAMPLES];
+XLR8Info myXLR8;

 void setup() {
-  XLR8Info myXLR8;
+  // Try a couple "wrong speeds" to help people figure out if they have a
+  //  Tools->FPGA Image selection that doesn't match what's actually on the board
+  //
+  Serial.begin(57600);
+  Serial.println("***************");
+  Serial.println("Error, Change Tools->FPGA Image to a selection with the following MHz");
+  printImageName(Serial);
+  Serial.println("***************");
+  Serial.flush();
+  Serial.begin(230400);
+  Serial.println();
+  Serial.println("***************");
+  Serial.println("Error, Change Tools->FPGA Image to a selection with the following MHz");
+  printImageName(Serial);
+  Serial.println("***************");
+  Serial.flush();
   Serial.begin(115200);
+  Serial.println();
+  Serial.println();
+  Serial.println("***************");
+  printImageName(Serial);
+  Serial.println("***************");
+  Serial.flush();
   Serial.print("XLR8 Hardware Version Number = ");
   Serial.println(myXLR8.getXLR8Version());
   if (myXLR8.isVersionMixed()) {Serial.println("  Mixed version, lowest reported");}
@@ -87,3 +110,13 @@
   }
 }

+void printImageName(Stream &s) {
+  s.print("FPGA Image: ");
+  s.print(myXLR8.getClockMHz());
+  s.print(" MHz ");
+  if (myXLR8.hasXLR8FloatAddSubMult()) {s.print(F("Float "));}
+  if (myXLR8.hasXLR8Servo())           {s.print(F("Servo "));}
+  if (myXLR8.hasXLR8NeoPixel())        {s.print(F("NeoPixel "));}
+  s.print(" 1.0.");
+  s.println(myXLR8.getXLR8Version());
+}


リクエストの処理をintervalに対応させた.

リクエストの処理をintervalに対応させた.

--- arduino/GeneralIoSerial/GeneralIoSerial.ino
+++ arduino/GeneralIoSerial/GeneralIoSerial.ino
@@ -54,6 +54,13 @@
 // 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[] = {
@@ -61,6 +68,56 @@
   {"INTERNAL", INTERNAL},
   {"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.";
@@ -79,9 +136,9 @@

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

 // pinModeの名前と値を保持するテーブル.
@@ -149,20 +206,12 @@

   /*
     DI連続転送ON
-    format   => stream/di/on/{port}
-    {port} => 連続転送を有効にするポート番号
-    example  => stream/di/on/1
-
-     streamのレスポンス
-
-     streamのレスポンスはeventとして定義する
-
-     {"event":"di", "datas":[
-        {"msg":"OK","port":[port],"val":[val]},
-        {"msg":"OK","port":[port],"val":[val]},
-        ...
-        {"msg":"OK","port":[port],"val":[val]}
-     ]}
+    format  => stream/di/on/{port}?interval={msec}
+    {port}  => 連続転送を有効にするポート番号
+    {msec}  => DIポート読み取り間隔(ミリ秒)
+    example => stream/di/on/1?interval=1000
+
+
    */
   {"stream/di/on/", &streamDiOnTask},

@@ -176,8 +225,9 @@

   /*
     AI連続転送ON
-    format   => stream/ai/on?{ports}
+    format   => stream/ai/on/{port}?interval={msec}
     {port} => 連続転送を有効にするポート番号
+    {msec}  => AIポート読み取り間隔(ミリ秒)
     example  => stream/ai/on/1
    */
   {"stream/ai/on/", &streamAiOnTask},
@@ -227,6 +277,8 @@

   Serial.begin(115200);
   Serial.println("READY");
+  pinMode(13, OUTPUT);
+  timer2Start();
 }

 void loop() {
@@ -254,6 +306,7 @@

   // enabledがtrueかつ、portsのどれか一つが有効になっていれば
   // 変換を行う
+  /*
   if( di_stream_enable_ports != 0){
     Serial.print(eventResponseHeader("di"));
     bool first = true;
@@ -285,6 +338,7 @@
     }
     Serial.println("]}");
   }
+  */
 }

 String eventResponseHeader(String event){
@@ -308,7 +362,7 @@
 String switchPinModeTask(String portWithQuery){

   String valQuery;
-  int port;
+  uint8_t port;

   String error = checkPortWithQuery(portWithQuery, &port, &valQuery);

@@ -340,7 +394,7 @@
   return NULL;
 }

-String checkPortWithQuery(String portWithQuery, int *port, String *query){
+String checkPortWithQuery(String portWithQuery, uint8_t *port, String *query){

   int at = 0;
   String error = checkHasQuery(portWithQuery, &at);
@@ -358,7 +412,37 @@
   return NULL;
 }

-String checkPortWithValue(String portWithValue, int *port, int *val){
+
+// {port}?interval={msec}なクエリーを分解.
+String checkPortWithInterval(String portWithInterval, uint8_t *port, uint64_t *interval){
+
+  String intervalQuery;
+
+  String error = checkPortWithQuery(portWithInterval, port, &intervalQuery);
+  if(error){
+    return error;
+  }
+
+  // intervalが指定されていなかったらintervalを1にする.
+  if(intervalQuery.startsWith("interval=")){
+    intervalQuery.replace("interval=", "");
+    // intervalに整数以外が指定されていたらエラー
+    if(isInt(intervalQuery)){
+      *interval = strToUInt64(intervalQuery);
+      // 0はサンプリング停止なので1に書き換える.
+      if(*interval == 0){
+        *interval = 1;
+      }
+    }else{
+      return NgReturnJson(ILLEGAL_VALUE);
+    }
+  }else{
+    *interval = 1;
+  }
+  return NULL;
+}
+
+String checkPortWithValue(String portWithValue, uint8_t *port, int *val){

   String valQuery;

@@ -393,7 +477,7 @@
    で入ってくる.
  */
 String aoWriteTask(String portWithValue){
-  int port = 0;
+  uint8_t port = 0;
   int val = 0;

   String error = checkPortWithValue(portWithValue, &port, &val);
@@ -407,7 +491,7 @@

 String doWriteTask(String portWithValue){
-  int port = 0;
+  uint8_t port = 0;
   int val = 0;

   String error = checkPortWithValue(portWithValue, &port, &val);
@@ -486,7 +570,35 @@
 }

-String streamDiOnTask(String query){
+String streamDiOnTask(String portWithInterval){
+
+  uint64_t interval;
+  uint8_t port;
+
+  String error = checkPortWithInterval(portWithInterval, &port, &interval);
+  if(error){
+    return error;
+  }
+
+  if(port >= DI_MAX_PORT_NUM){
+    return NgReturnJson(ILLEGAL_PORT_NUMBER);
+  }
+
+  di_stream_info[port].interval_ms = interval;
+  di_stream_info[port].counter = 0;
+
+  // TODO: stream用のレスポンスを考える.
+  return okIoJson(port, 1);
+}
+
+String streamDiOffTask(String query){
+
+  if(query == "all"){
+    for(uint8_t i = 0; i < DI_MAX_PORT_NUM; i++){
+      di_stream_info[i].interval_ms = 0;
+    }
+    return okIoJson(0xff, 0);
+  }

   String error = checkPortQuery(query);
   if(error){
@@ -494,15 +606,40 @@
   }

   uint8_t port = strToInt(query);
-  bitSet(di_stream_enable_ports, port);
+  if(port >= DI_MAX_PORT_NUM){
+    return NgReturnJson(ILLEGAL_PORT_NUMBER);
+  }
+  di_stream_info[port].interval_ms = 0;
+
+  return okIoJson(port, 0);
+}
+
+String streamAiOnTask(String portWithInterval){
+
+  uint64_t interval;
+  uint8_t port;
+
+  String error = checkPortWithInterval(portWithInterval, &port, &interval);
+  if(error){
+    return error;
+  }
+
+  if(port >= AI_MAX_PORT_NUM){
+    return NgReturnJson(ILLEGAL_PORT_NUMBER);
+  }
+
+  ai_stream_info[port].interval_ms = interval;
+  ai_stream_info[port].counter = 0;

   return okIoJson(port, 1);
 }

-String streamDiOffTask(String query){
+String streamAiOffTask(String query){

   if(query == "all"){
-    di_stream_enable_ports = 0;
+    for(uint8_t i = 0; i < AI_MAX_PORT_NUM; i++){
+      ai_stream_info[i].interval_ms = 0;
+    }
     return okIoJson(0xff, 0);
   }

@@ -512,38 +649,10 @@
   }

   uint8_t port = strToInt(query);
-  bitClear(di_stream_enable_ports, port);
-
-  return okIoJson(port, 0);
-}
-
-String streamAiOnTask(String query){
-
-  String error = checkPortQuery(query);
-  if(error){
-    return error;
-  }
-
-  uint8_t port = strToInt(query);
-  bitSet(ai_stream_enable_ports, port);
-
-  return okIoJson(port, 1);
-}
-
-String streamAiOffTask(String query){
-
-  if(query == "all"){
-    ai_stream_enable_ports = 0;
-    return okIoJson(0xff, 0);
-  }
-
-  String error = checkPortQuery(query);
-  if(error){
-    return error;
-  }
-
-  uint8_t port = strToInt(query);
-  bitClear(ai_stream_enable_ports, port);
+  if(port >= AI_MAX_PORT_NUM){
+    return NgReturnJson(ILLEGAL_PORT_NUMBER);
+  }
+  ai_stream_info[port].interval_ms = 0;

   return okIoJson(port, 0);
 }


Sane baton stuff

Sane baton stuff

--- baton/baton.ino
+++ baton/baton.ino
@@ -9,7 +9,7 @@
 int fps = 30;
 int power_in_milliamps = 7000;

-#define NUM_LEDS 1500         // Number of LED's.
+#define NUM_LEDS 300         // Number of LED's.
 struct CRGB leds[NUM_LEDS];   // Initialize our LED array.

 #define BEAUTIFUL_SPARKLES 1
@@ -23,21 +23,21 @@
 #define RAIN 9

 int maxPatternId = 9;
-int rotationInSeconds = 5;
+int rotationInSeconds = 20;

 // If we're testing one pattern, use holdPattern as true and the patternId as the starting pattern.
-bool holdPattern = true;
-int patternId = WORMS;
+bool holdPattern = false;
+int patternId = BEAUTIFUL_SPARKLES;

 // Set up LEDs, fade them all to black.
 void setup() {
   Serial.begin(57600);

   // WS2812
-  //  LEDS.addLeds<WS2812B, 7, GRB>(leds, NUM_LEDS);
+    LEDS.addLeds<WS2812B, 7, GRB>(leds, NUM_LEDS);

   // APA102
-  FastLED.addLeds<APA102, BGR>(leds, NUM_LEDS);
+//  FastLED.addLeds<APA102, BGR>(leds, NUM_LEDS);
   pinMode(7, OUTPUT);
   digitalWrite(7, HIGH);  // enable access to LEDs


Fixed the first example to match the new comms interface

--- examples/example0_blink/example0_blink.ino
+++ examples/example0_blink/example0_blink.ino
@@ -29,7 +29,7 @@
     Module* modules[] = { &LED };

     // Initialise the communication protocol.
-    comms.setup(modules);
+    comms.setup(modules, sizeof(modules)/sizeof(modules[0]));

     Serial.println("Finished set up");
 }


Added more functionality

Added more functionality

--- sequencer.ino
+++ sequencer.ino
@@ -1,5 +1,8 @@
-const int DIFFERENT_VALUES = 2;
+const int DIFFERENT_VALUES = 4;
 const int MAX_LENGTH = 20;
+const int SHOW_DELAY = 1000;
+const int BLINK_DELAY = 300;
+const int DEBOUNCE_DELAY = 50;

 int sequence[MAX_LENGTH];
 int currentLength = 0;
@@ -7,7 +10,13 @@
 // Set every pin to specified mode
 void setMode(int mode) {
   for (int i = 0; i < DIFFERENT_VALUES; i++) {
-    pinMode(i, mode);
+    pinMode(i, mode);
+  }
+  // To show current mode
+  if (mode == OUTPUT) {
+    digitalWrite(13, LOW);
+  } else {
+    digitalWrite(13, HIGH);
   }
 }

@@ -18,15 +27,103 @@
   currentLength++;
 }

+void cleanOutput() {
+  // Switch off all outputs
+  for (int i = 0; i < DIFFERENT_VALUES; i++) {
+    digitalWrite(i, LOW);
+  }
+}
+
+// Show the current sequence (up to current length)
+void showSequence() {
+  setMode(OUTPUT);
+  for (int i = 0; i < currentLength; i++) {
+    cleanOutput();
+    delay(SHOW_DELAY);
+    // Switch on current output
+    digitalWrite(sequence[i], HIGH);
+    delay(SHOW_DELAY);
+  }
+  cleanOutput();
+}
+
+void waitForUnpush() {
+  int allInputsAreUnpushed = 0;
+  while (allInputsAreUnpushed == 0) {
+    allInputsAreUnpushed = 1;
+    for (int i = 0; i < DIFFERENT_VALUES; i++) {
+      if (digitalRead(i) ==  HIGH) {
+        // At least one input is not unpushed
+        allInputsAreUnpushed = 0;
+        // Doesn't read other inputs
+        break;
+      }
+    }
+  }
+}
+
+// Returns the smallest input that was pushed (after waiting for it to unpush)
+int readFirstPushed() {
+  int pushedElement = -1;
+  while (pushedElement == -1) {
+    for (int i = 0; i < DIFFERENT_VALUES; i++) {
+      if (digitalRead(i) ==  HIGH) {
+        // Waits some milliseconds to prevent bouncing
+        delay(DEBOUNCE_DELAY);
+
+        waitForUnpush();
+
+        pushedElement = i;
+        // Doesn't read other inputs
+        break;
+      }
+    }
+  }
+  return pushedElement;
+}
+
+void blinkCorrectElement(int element) {
+  setMode(OUTPUT);
+  while (true) {
+    digitalWrite(element, HIGH);
+    delay(BLINK_DELAY);
+    digitalWrite(element, LOW);
+    delay(BLINK_DELAY);
+  }
+}
+
+void readSequence() {
+  setMode(INPUT);
+  for (int i = 0; i < currentLength; i++) {
+    int pushed = readFirstPushed();
+    if (sequence[i] != pushed) {
+      // Wrong element, game over
+      Serial.begin(9600);
+      Serial.println("Game over");
+      Serial.print("Sequence was ");
+      Serial.print(sequence[i]);
+      Serial.print(" but pushed ");
+      Serial.println(pushed);
+      Serial.println("Done\n");
+
+      blinkCorrectElement(sequence[i]);
+    }
+  }
+}
+
 void setup() {
   // if analog input pin 0 is unconnected, random analog
   // noise will cause the call to randomSeed() to generate
   // different seed numbers each time the sketch runs.
   // randomSeed() will then shuffle the random function.
   randomSeed(analogRead(0));
-
-  setMode(INPUT);
+  // Will show input/output state
+  pinMode(13, OUTPUT);
 }

 void loop() {
+  newElement();
+  showSequence();
+  readSequence();
 }
+


ledvo final tweak

ledvo final tweak

--- proj/ledvo_lounge_final/ledvo_lounge_final.ino
+++ proj/ledvo_lounge_final/ledvo_lounge_final.ino
@@ -32,7 +32,7 @@
 #define REVERS_INT 43 // Reversing animations interrupt

 // Variables for the LED strand
-const uint8_t maxBrightness = 175;
+const uint8_t maxBrightness = 85;
 uint8_t gBrightness = maxBrightness; // CHANGE THIS ONCE YOU HAVE ANOTHER POTENTIOMETER

 // Variables for LED strands


alarm stuff

alarm stuff

--- vibrate_alarm_clock_2.ino
+++ vibrate_alarm_clock_2.ino
@@ -55,9 +55,7 @@
 unsigned long timeLastPressedMiddleButton;
 unsigned long timeLastPressedRightButton;

-
-boolean vibrate1 = false;
-boolean vibrate2 = false;
+boolean vibrate = false;

 boolean previousBlinkState;
 unsigned long previousBlinkTime;
@@ -181,62 +179,54 @@
   timeLastPressedLeftButton = currentMillis;

   Serial.println("Left Button Pressed");
-
+
   switch(currentState)
   {
-  case ALARM: stopAlarm();
-  break;
+  case ALARM:
+    stopAlarm();
+    break;
   case NORMAL :
-  {
-    showLCD = !showLCD;
-    turnOffLCD();
-
-  }
-  break;
+    {
+      showLCD = !showLCD;
+      turnOffLCD();
+
+    }
+    break;
   case SETTING_ALARM:
-  {
-   if(settingAlarmProcess == A_HOUR){
-       alarmHour = getNextHourFromCurrentHour(alarmHour, false);
-    } else if(settingAlarmProcess == A_MINUTE){
-       alarmMinute = getNextMinSecFromCurrentMinSec(alarmMinute, false);
-    } else if(settingAlarmProcess == A_TYPE){
-
-       if(!vibrate1 && !vibrate2){
-          vibrate1 = true;
-          vibrate2 = true;
-       } else if(!vibrate1 && vibrate2){
-          vibrate1 = false;
-          vibrate2 = false;
-       } else if(vibrate1 && !vibrate2){
-         vibrate1 = false;
-         vibrate2 = true;
-       } else {
-          vibrate1 = true;
-          vibrate2 = false;
-      }
-   }
-
-  }
-  break;
+    {
+      if(settingAlarmProcess == A_HOUR){
+        alarmHour = getNextHourFromCurrentHour(alarmHour, false);
+      }
+      else if(settingAlarmProcess == A_MINUTE){
+        alarmMinute = getNextMinSecFromCurrentMinSec(alarmMinute, false);
+      }
+      else if(settingAlarmProcess == A_TYPE){
+          vibrate = !vibrate;
+      }
+
+    }
+    break;
   case SETTING_TIME:
-  {
-    DateTime now = RTC.now();
-    DateTime newTime;
-    switch(settingTimeProcess){
+    {
+      DateTime now = RTC.now();
+      DateTime newTime;
+      switch(settingTimeProcess){
       case T_HOUR:
         newTime = DateTime(now.year(), now.month(), now.day(), getNextHourFromCurrentHour(now.hour(), false), now.minute(), now.second());
         break;
       case T_MINUTE:
         newTime = DateTime(now.year(), now.month(), now.day(), now.hour(), getNextMinSecFromCurrentMinSec(now.minute(), false), now.second());
         break;
-      default: break;
-
-    }
-
-    RTC.adjust(newTime);
-  }
-  break;
-  default: break;
+      default:
+        break;
+
+      }
+
+      RTC.adjust(newTime);
+    }
+    break;
+  default:
+    break;
   }

@@ -253,46 +243,52 @@
   timeLastPressedMiddleButton = currentMillis;

   Serial.println("Middle Button Pressed");
-
-    switch(currentState)
+
+  switch(currentState)
   {
-    case ALARM: stopAlarm();
-    break;
-    case NORMAL :
+  case ALARM:
+    stopAlarm();
+    break;
+  case NORMAL :
     {
       if(showLCD){
         currentState = SETTING_ALARM;
         settingAlarmProcess = A_HOUR;
-      } else {
+      }
+      else {
         showLCD = true;
       }

     }
     break;
-    case SETTING_ALARM:
+  case SETTING_ALARM:
     {
       if(settingAlarmProcess == A_HOUR){
-         settingAlarmProcess = A_MINUTE;
-      } else if(settingAlarmProcess == A_MINUTE){
-         settingAlarmProcess = A_TYPE;
-      } else {
+        settingAlarmProcess = A_MINUTE;
+      }
+      else if(settingAlarmProcess == A_MINUTE){
+        settingAlarmProcess = A_TYPE;
+      }
+      else {
         currentState = NORMAL;
       }

     }
     break;
-    case SETTING_TIME:
+  case SETTING_TIME:
     {
       if(settingTimeProcess == T_HOUR){
-         settingTimeProcess = T_MINUTE;
-      } else {
+        settingTimeProcess = T_MINUTE;
+      }
+      else {
         currentState = NORMAL;
       }
-
-    }
-    break;
-    default: break;
-    }
+
+    }
+    break;
+  default:
+    break;
+  }

 }
@@ -312,64 +308,57 @@

   switch(currentState)
   {
-    case ALARM: stopAlarm();
-    break;
-    case NORMAL :
-   {
+  case ALARM:
+    stopAlarm();
+    break;
+  case NORMAL :
+    {
       if(showLCD){
         currentState = SETTING_TIME;
         settingTimeProcess = T_HOUR;
-      } else {
+      }
+      else {
         showLCD = true;
       }
-
-   }
-    break;
-    case SETTING_ALARM:
-    {
-        if(settingAlarmProcess == A_HOUR){
-          alarmHour = getNextHourFromCurrentHour(alarmHour, true);
-        } else if(settingAlarmProcess == A_MINUTE){
-          alarmMinute = getNextMinSecFromCurrentMinSec(alarmMinute, true);
-        } else if(settingAlarmProcess == A_TYPE){
-
-          if(!vibrate1 && !vibrate2){
-                vibrate1 = false;
-                vibrate2 = true;
-              } else if(!vibrate1 && vibrate2){
-                vibrate1 = true;
-                vibrate2 = false;
-              } else if(vibrate1 && !vibrate2){
-                vibrate1 = true;
-                vibrate2 = true;
-              } else {
-                vibrate1 = false;
-                vibrate2 = false;
-              }
-        }
-    }
-    break;
-    case SETTING_TIME:
-      {
-    DateTime now = RTC.now();
-    DateTime newTime;
-    switch(settingTimeProcess){
+
+    }
+    break;
+  case SETTING_ALARM:
+    {
+      if(settingAlarmProcess == A_HOUR){
+        alarmHour = getNextHourFromCurrentHour(alarmHour, true);
+      }
+      else if(settingAlarmProcess == A_MINUTE){
+        alarmMinute = getNextMinSecFromCurrentMinSec(alarmMinute, true);
+      }
+      else if(settingAlarmProcess == A_TYPE){
+          vibrate = !vibrate;
+      }
+    }
+    break;
+  case SETTING_TIME:
+    {
+      DateTime now = RTC.now();
+      DateTime newTime;
+      switch(settingTimeProcess){
       case T_HOUR:
         newTime = DateTime(now.year(), now.month(), now.day(), getNextHourFromCurrentHour(now.hour(), true), now.minute(), now.second());
         break;
       case T_MINUTE:
         newTime = DateTime(now.year(), now.month(), now.day(), now.hour(), getNextMinSecFromCurrentMinSec(now.minute(), true), now.second());
         break;
-      default: break;
-
-    }
-
-    RTC.adjust(newTime);
-  }
-
-
-    break;
-    default: break;
+      default:
+        break;
+
+      }
+
+      RTC.adjust(newTime);
+    }
+
+
+    break;
+  default:
+    break;
   }

 }
@@ -396,19 +385,20 @@
 void writeTimeToDisplayBuffer(DateTime now, boolean blinkOn, boolean secondsBlinkOn){
   uView.setCursor(0,0);
   uView.setFontType(7);
-
-  String timeString = generateTimeString(now.hour(), now.minute(), secondsBlinkOn);
+
+  String timeString = generateTimeString(now.hour(), now.minute(), blinkOn, secondsBlinkOn);
   uView.println(timeString);
 }

-String generateTimeString(int hour, int minute, boolean blinkOn){
+String generateTimeString(int hour, int minute, boolean blinkOn, boolean secondsBlinkOn){
   char buff[3];
-
+
   String hourString;
-
+
   if(currentState == SETTING_TIME && settingTimeProcess == T_HOUR && !blinkOn){
     hourString = "  ";
-  } else {
+  }
+  else {
     sprintf(buff, "%02d", hour);
     hourString = buff;
   }
@@ -416,14 +406,15 @@
   String minuteString;
   if(currentState == SETTING_TIME && settingTimeProcess == T_MINUTE && !blinkOn){
     minuteString = "  ";
-  } else {
+  }
+  else {
     sprintf(buff, "%02d", minute);
     minuteString = buff;
   }
-
+
   String secondString;
-
- if(blinkOn || currentState == SETTING_TIME){
+
+  if(secondsBlinkOn || currentState == SETTING_TIME){
     secondString = ":";
   }
   else {
@@ -439,10 +430,49 @@
 void writeAlarmToDisplayBuffer(boolean blinkOn){
   uView.setFontType(0);
   uView.setCursor(0,24);
-  uView.print(alarmHour);
-  uView.print(":");
-  uView.print(alarmMinute);
-  uView.print(" Vib");
+
+  char buff[3];
+
+  String alarmHourString;
+
+  if(currentState == SETTING_ALARM && settingAlarmProcess == A_HOUR && !blinkOn){
+    //Now setting this, do not show
+    alarmHourString = "  ";
+  }
+  else {
+    sprintf(buff, "%02d", alarmHour);
+    alarmHourString = buff;
+  }
+
+  String alarmMinuteString;
+
+  if(currentState == SETTING_ALARM && settingAlarmProcess == A_MINUTE && !blinkOn){
+    //Now setting this, do not show
+    alarmMinuteString = "  ";
+  }
+  else {
+    sprintf(buff, "%02d", alarmMinute);
+    alarmMinuteString = buff;
+  }
+
+  String alarmTimeString;
+  String alarmSetting;
+
+  if(currentState == SETTING_ALARM && settingAlarmProcess == A_TYPE && !blinkOn){
+    //Now setting this, do not show
+    alarmSetting = "";
+  }
+  else {
+    if(vibrate){
+      alarmSetting = " On";
+    }else {
+      alarmSetting = " Off";
+    }
+  }
+
+  alarmTimeString = alarmHourString + ":" + alarmMinuteString + alarmSetting;
+
+  uView.print(alarmTimeString);

 }

@@ -480,27 +510,30 @@
 void writeButtonStateToDisplayBuffer(boolean blinkOn){
   uView.setFontType(0);
   uView.setCursor(0,41);
-
+
   String buttonFunction;
   switch(currentState)
   {
-    case ALARM:
+  case ALARM:
     {
       if(!blinkOn){
         buttonFunction = "X   X   X";
       }
-
-    }
-    break;
-    case NORMAL : buttonFunction =  "Led Alm Ti";
-    break;
-    case SETTING_ALARM:
+
+    }
+    break;
+  case NORMAL :
+    buttonFunction =  "Led Alm Ti";
+    break;
+  case SETTING_ALARM:
     //Fallthrough
-    case SETTING_TIME: buttonFunction = "-  Next  +";
-    break;
-    default: break;
-  }
-
+  case SETTING_TIME:
+    buttonFunction = "-  Next  +";
+    break;
+  default:
+    break;
+  }
+
   uView.print(buttonFunction);
 }

@@ -548,26 +581,28 @@
   int change;
   if(increment){
     change = 1;
-  } else {
+  }
+  else {
     change = -1;
   }
-
+
   int newValue = current + change;
-
+
   //To produce positive modulo result
   return (newValue % 24 + 24) % 24;
 }

 int getNextMinSecFromCurrentMinSec(int current, boolean increment){
-    int change;
+  int change;
   if(increment){
     change = 1;
-  } else {
+  }
+  else {
     change = -1;
   }
-
+
   int newValue = current + change;
-
+
   //To produce positive modulo result
   return (newValue % 60 + 60) % 60;
 }
@@ -580,3 +615,4 @@

+


remove airclean

remove airclean

--- _04-lcd-dust/a-02-nano-i2c/a-02-nano-i2c.ino
+++ _04-lcd-dust/a-02-nano-i2c/a-02-nano-i2c.ino
@@ -204,8 +204,8 @@
       case 1:
         Serial.println("IR -----> AC Power On");
         lgWhisen.activate();
-        delay(2);
-        lgWhisen.airclean_on();
+        //delay(2);
+        //lgWhisen.airclean_on();
         //delay(5);
         irrecv.enableIRIn();
         break;


Used proper pointers for the WiFi events same as done in the examples.

Signed-off-by: Sacha Telgenhof <2491008b05e873c0de4356ab23a0a79a07dc9d9d@gmail.com>

--- src/_wifi.ino
+++ src/_wifi.ino
@@ -18,7 +18,7 @@
  *
  * @param event WiFiEventStationModeGotIP Event
  */
-void onSTAGotIP(WiFiEventStationModeGotIP event)
+void onSTAGotIP(const WiFiEventStationModeGotIP &event)
 {

 #ifdef DEBUG
@@ -45,7 +45,7 @@
  *
  * @param event WiFiEventSoftAPModeStationConnected Event
  */
-void onAPConnected(WiFiEventSoftAPModeStationConnected event)
+void onAPConnected(const WiFiEventSoftAPModeStationConnected &event)
 {
   DEBUGLOG("[WIFI] SSID        : %s\n", cfg.hostname);
   DEBUGLOG("[WIFI] Password    : %s\n", ADMIN_PASSWORD);
@@ -60,7 +60,7 @@
  *
  * @param event WiFiEventStationModeDisconnected Event
  */
-void onSTADisconnected(WiFiEventStationModeDisconnected event)
+void onSTADisconnected(const WiFiEventStationModeDisconnected &event)
 {
   DEBUGLOG("WiFi connection (%s) dropped.\n", event.ssid.c_str());
   DEBUGLOG("Reason: %d\n", event.reason);
@@ -78,9 +78,9 @@
 {
   static WiFiEventHandler gotIpEventHandler, apConnectedEventHandler,
       disconnectedEventHandler;
-  gotIpEventHandler = WiFi.onStationModeGotIP(onSTAGotIP);
-  apConnectedEventHandler = WiFi.onSoftAPModeStationConnected(onAPConnected);
-  disconnectedEventHandler = WiFi.onStationModeDisconnected(onSTADisconnected);
+  gotIpEventHandler = WiFi.onStationModeGotIP(&onSTAGotIP);
+  apConnectedEventHandler = WiFi.onSoftAPModeStationConnected(&onAPConnected);
+  disconnectedEventHandler = WiFi.onStationModeDisconnected(&onSTADisconnected);

   // Set WiFi hostname
   if (os_strlen(cfg.hostname) == 0)


display contrast and battery percent improvement

--- vibrate_alarm_clock.ino
+++ vibrate_alarm_clock.ino
@@ -12,10 +12,14 @@
 #define MIN_BATTERY_MILLIVOLT 3300 //You may need to calibrate this
 #define MAX_BATTERY_MILLIVOLT 4300 //You may need to calibrate this

+#define DISPLAY_CONTRAST 64
+
 #define INITIAL_TEXT "Happy 24th birthday\n Jason!\n\nBy: Yeo Kheng Meng\n(2014)"
 #define INITIAL_TEXT_DELAY 8000
 #define MIN_TIME_BETWEEN_BUTTON_PRESSES 100  //Debouncing purposes
 #define BLINK_INTERVAL 100
+
+

 #define MIN_TIME_BETWEEN_ALARM_STARTS 60000 //60 seconds
 #define MIN_TIME_TO_CHANGE_MOTOR_DIRECTION 1500
@@ -414,7 +418,7 @@

   display.setTextSize(1);

-  float voltage = (float) batteryMilliVolt / 1000;
+//  float voltage = (float) batteryMilliVolt / 1000;

 //  char buff[5];
 //  String voltageString = dtostrf(voltage, 3, 1, buff);
@@ -424,9 +428,10 @@
 //  display.print("V");

   int batteryRange = MAX_BATTERY_MILLIVOLT - MIN_BATTERY_MILLIVOLT;
-
-  int batteryPercent = 100 * (((float)(batteryMilliVolt - MIN_BATTERY_MILLIVOLT)) / batteryRange);
-
+
+  long numerator =  ((long) ((batteryMilliVolt - MIN_BATTERY_MILLIVOLT))) * 100;
+  int batteryPercent = numerator / batteryRange;
+
   if(batteryPercent < 100){
      display.setCursor(110,40);
   } else {
@@ -759,6 +764,8 @@
   // initialize with the OLED with I2C addr 0x3D (for the 128x64)
   display.begin(SSD1306_SWITCHCAPVCC, 0x3D);

+  display.dim(DISPLAY_CONTRAST);
+
   display.clearDisplay();
   display.setTextColor(WHITE);
   display.setTextSize(1);
@@ -768,6 +775,7 @@

   display.display();

+
   delay(INITIAL_TEXT_DELAY);


doc: Update example

doc: Update example

--- examples/AltPinSerial/AltPinSerial.ino
+++ examples/AltPinSerial/AltPinSerial.ino
@@ -1,34 +1,36 @@
 #include <MIDI.h>

-// Simple tutorial on how to receive and send MIDI messages.
+// Simple tutorial on how to receive and send MIDI messages
+// on a different serial port, using SoftwareSerial.
 // Here, when receiving any message on channel 4, the Arduino
 // will blink a led and play back a note for 1 second.

-#if defined(ARDUINO_SAM_DUE) || defined(SAMD_SERIES)
-   /* example not relevant for this hardware */
+#if defined(ARDUINO_SAM_DUE) || defined(SAMD_SERIES)
+   /* example not relevant for this hardware (SoftwareSerial not supported) */
    MIDI_CREATE_DEFAULT_INSTANCE();
 #else
    #include <SoftwareSerial.h>
+   using Transport = MIDI_NAMESPACE::SerialMIDI<SoftwareSerial>;
    int rxPin = 18;
    int txPin = 19;
    SoftwareSerial mySerial = SoftwareSerial(rxPin, txPin);
-   MIDI_NAMESPACE::SerialMIDI<SoftwareSerial> serialMIDI(mySerial);
-   MIDI_NAMESPACE::MidiInterface<MIDI_NAMESPACE::SerialMIDI<SoftwareSerial>> MIDI((MIDI_NAMESPACE::SerialMIDI<SoftwareSerial>&)serialMIDI);
+   Transport serialMIDI(mySerial);
+   MIDI_NAMESPACE::MidiInterface<Transport> MIDI((Transport&)serialMIDI);
 #endif

 void setup()
 {
   pinMode(LED_BUILTIN, OUTPUT);
-  MIDI.begin(4);                      // Launch MIDI and listen to channel 4
+  MIDI.begin(4);                    // Launch MIDI and listen to channel 4
 }

 void loop()
 {
-  if (MIDI.read())                    // If we have received a message
+  if (MIDI.read())                  // If we have received a message
   {
     digitalWrite(LED_BUILTIN, HIGH);
     MIDI.sendNoteOn(42, 127, 1);    // Send a Note (pitch 42, velo 127 on channel 1)
-    delay(1000);		            // Wait for a second
+    delay(1000);                    // Wait for a second
     MIDI.sendNoteOff(42, 0, 1);     // Stop the note
     digitalWrite(LED_BUILTIN, LOW);
   }


adding comments to code

adding comments to code

--- T0/src/AFE-Firmware-T0.ino
+++ T0/src/AFE-Firmware-T0.ino
@@ -30,12 +30,11 @@
   Serial.begin(115200);
   delay(10);

-  // Comment below if you needed to debug it through Serial
-  // Serial.swap();
+  /* Turn off publishing information to Serial */
+  Serial.swap();

   /* Checking if the device is launched for a first time. If so it sets up
    * the device (EEPROM) */
-  //  Device.setDevice();
   if (Device.isFirstTimeLaunch()) {
     Device.setDevice();
   }
@@ -73,7 +72,6 @@
   if (Device.configuration.isSwitch[0]) {
     Switch.begin(0);
   }
-
   if (Device.configuration.isSwitch[1]) {
     ExternalSwitch.begin(1);
   }
@@ -108,8 +106,6 @@
         if (Device.configuration.httpAPI) {
           if (WebServer.httpAPIlistener()) {
             processHTTPAPIRequest(WebServer.getHTTPCommand());
-
-
           }
         }

@@ -138,6 +134,7 @@
     WebServer.listener();
   }

+  /* Listens for switch events */
   Switch.listener();
   ExternalSwitch.listener();


update for JC_Button library and minor updates

--- toggle_pixels_off_with_button.ino
+++ toggle_pixels_off_with_button.ino
@@ -1,28 +1,27 @@
 //***************************************************************
-// Example to turn some pixels virtually "off" with a button.
-// Pixels are still powered and reciving data, but are simply
-// set to display black when "off".
+// Example to toggles some pixels on or off using a button.
+// The "off" pixels are still powered and reciving data, but
+// are simply set to display black when "off".
 //
-// This example is for a 32 pixel strip.  Pressing the button
-// turns "off" the last 8 pixels.  The pixel number where the
-// cutoff starts is determined in the for loop on line 93.
+// In this example pressing the button toggles pixels 8-15 and 24-31.
 //
 // This is how the button is wired for this example:
-// http://i.imgur.com/hOgQwjX.jpg
+// https://i.imgur.com/qH6cYRp.jpg
 //
 // Instead of a momentary button a switch could be used and
 // the controller could directly read the input pin as high
 // or low.  The button library would not be needed in this case.
 //
 // Marc Miller, Oct 2017
+//   Updated Jan 2020 - for JC_button library updates
 //***************************************************************

 //---------------------------------------------------------------
 // This sketch uses JChristensen's Button Library from:
-//   https://github.com/JChristensen/Button
+//   https://github.com/JChristensen/JC_Button
 //
-#include "Button.h"    // Include the Button library
+#include "JC_Button.h"    // Include Button library

 // Set the digital pin for the pushbutton, and declare the button
 const uint8_t ButtonPin = 4;
@@ -50,6 +49,9 @@
   FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
   FastLED.setBrightness(BRIGHTNESS);
   FastLED.clear();
+
+  OnOff_Button.begin();  // initialize the button object
+  Serial.println("Setup done.\n");
 }

@@ -71,28 +73,45 @@

 //---------------------------------------------------------------
 // Functions
-
 //---------------------------------------------------------------
 //Check the button and set the appropriate flag
 void readbutton() {
   OnOff_Button.read();  // check the state of the button

+
+  //**** Use this bit to toggle on/off each time the button is pressed.
+  //     Comment this bit out and use the below for something different.
   if(OnOff_Button.wasPressed()) {
     OnOff_Status = !OnOff_Status;
     Serial.print("OnOff_Status: "); Serial.println(OnOff_Status);
   }

+
+//  //**** Comment out the above bit and use this to have the button
+//  //     only turn the pixels off while it is pressed (ie. held down).
+//  if(OnOff_Button.isPressed()) {
+//    OnOff_Status = 0;
+//  } else {
+//    OnOff_Status = 1;
+//  }
+
+
 }//end_readbutton

 //---------------------------------------------------------------
-// Turn extra pixels on or off
+// Turn some pixels on or off
 void extraLeds_OnOff(){

   if (OnOff_Status ==0) {
-    for (uint8_t i=24; i < NUM_LEDS; i++) {  //i=24 is the first pixel in the extras to be turned off.
-     leds[i] = CRGB::Black;  // turn "off"
+    for (uint8_t i=8; i < 16; i++) {
+      leds[i] = CRGB::Black;  // turn "off"
     }
+
+    for (uint8_t i=24; i < 32; i++) {
+      leds[i] = CRGB::Black;  // turn "off"
+    }
+
   }

 }//end_extraLeds_OnOff


remove duplicate headers

remove duplicate headers

--- examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
+++ examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
@@ -1,22 +1,3 @@
-//
-// Copyright 2015 Google Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//     http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-
-// FirebaseStream_ESP8266 is a sample that stream bitcoin price from a
-// public Firebase and display it on a i2c OLED screen.
-
 //
 // Copyright 2015 Google Inc.
 //


examples/FirebaseStream: stream data is stringified

--- examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
+++ examples/FirebaseStream_ESP8266/FirebaseStream_ESP8266.ino
@@ -64,7 +64,7 @@
        Serial.print("data: ");
        Serial.println(event.getString("data"));
        String path = event.getString("path");
-       float data = event.getFloat("data");
+       String data = event.getString("data");

        display.clearDisplay();
        display.setTextSize(2);


Added URL for new example

Added URL for new example

--- build/shared/examples/2.Digital/DigitalIputPullup/DigitalIputPullup.ino
+++ build/shared/examples/2.Digital/DigitalIputPullup/DigitalIputPullup.ino
@@ -13,6 +13,8 @@

  created 14 March 2012
  by Scott Fitzgerald
+
+ http://www.arduino.cc/en/Tutorial/InputPullupSerial

  This example code is in the public domain


Fixed cursor naming after refactoring.

Fixed cursor naming after refactoring.

--- examples/Drivers/CosaHCSR04/CosaHCSR04.ino
+++ examples/Drivers/CosaHCSR04/CosaHCSR04.ino
@@ -77,7 +77,7 @@
       tft.set_text_scale(saved);
     }
     else {
-      textbox.set_caret(10, 35);
+      textbox.set_cursor(10, 35);
       cout.printf_P(PSTR("%d"), distance);
     }
   }


Undo comments added to arduino code

Undo comments added to arduino code

--- AndroidTVGateway/edge-agent/edge-agent.ino
+++ AndroidTVGateway/edge-agent/edge-agent.ino
@@ -14,7 +14,7 @@

 DHT dht(DHTPIN, DHTTYPE);
 SoftwareSerial XBee(2, 3); // RX, TX
-uint8_t successRead;
+uint8_t successRead;    // Variable integer to keep if we have Successful Read from Reader
 byte readCard[4];   // Stores scanned ID read from RFID Module
 int lastId = 0;
 char msg[100];
@@ -42,7 +42,7 @@
 }

 void loop() {
-  if (XBee.available()) {
+  if (XBee.available()) {
     String incomingMsg = XBee.readString();
     Serial.println(incomingMsg);
     if (incomingMsg == "LON\r") {


Testing LCD 1604. Updating 10DOF with LCD example sketch.

--- examples/TWI/CosaLCD10DOF/CosaLCD10DOF.ino
+++ examples/TWI/CosaLCD10DOF/CosaLCD10DOF.ino
@@ -41,6 +41,7 @@
  * This file is part of the Arduino Che Cosa project.
  */

+#include "Cosa/Memory.h"
 #include "Cosa/Watchdog.hh"
 #include "Cosa/Trace.hh"
 #include "Cosa/AnalogPin.hh"
@@ -49,6 +50,7 @@
 #include "Cosa/TWI/Driver/BMP085.hh"
 #include "Cosa/TWI/Driver/HMC5883L.hh"
 #include "Cosa/TWI/Driver/L3G4200D.hh"
+#include "Cosa/TWI/Driver/DS1307.hh"

 // LCD and communication port
 // HD44780::Port4b port;
@@ -56,11 +58,17 @@
 // HD44780::SR3WSPI port;
 // HD44780::SR4W port;
 // HD44780::MJKDZ port;
-HD44780::GYIICLCD port;
+HD44780::MJKDZ port(0);
+// HD44780::GYIICLCD port;
 // HD44780::DFRobot port;
 // HD44780::ERM1602_5 port;
-// HD44780 lcd(&port, 20, 4);
-HD44780 lcd(&port);
+
+// Select LCD width and height
+#define WIDTH 16
+// #define WIDTH 20
+// #define HEIGHT 2
+#define HEIGHT 4
+HD44780 lcd(&port, WIDTH, HEIGHT);

 // Digital acceleratometer with alternative address
 ADXL345 acceleratometer(1);
@@ -73,6 +81,9 @@

 // Digital Gyroscope using alternative address
 L3G4200D gyroscope(1);
+
+// Real-time clock
+DS1307 rtc;

 void setup()
 {
@@ -97,21 +108,45 @@

 void loop()
 {
+  // Read the time from the rtc device and print
+  time_t now;
+  rtc.get_time(now);
+  now.to_binary();
+  trace << clear;
+  trace << PSTR("RTC; ") << now;
+
+  // Read battery
+#if (HEIGHT == 2)
+  sleep(2);
+  trace << clear;
+#else
+  trace << endl;
+#endif
+  trace << PSTR("VCC: ") << AnalogPin::bandgap() << PSTR(" mV") << endl;
+
+  // Free memory
+  trace << PSTR("MEM: ") << free_memory() << PSTR(" bytes");
+  sleep(2);
+
   // Read barometer; pressure and temperature
   bmp.sample();
   trace << clear;
-  trace << PSTR("Barometer") << endl;
+  trace << PSTR("Barometer:") << endl;
   trace << bmp.get_pressure() << PSTR(" Pa, ");
   trace << (bmp.get_temperature() + 5) / 10 << PSTR(" C");
+#if (HEIGHT == 2)
   sleep(2);
+  trace << clear;
+#else
+  trace << endl;
+#endif

   // Read compass heading
   compass.read_heading();
   compass.to_milli_gauss();
   HMC5883L::data_t dir;
   compass.get_heading(dir);
-  trace << clear;
-  trace << PSTR("Compass") << endl;
+  trace << PSTR("Compass:") << endl;
   trace << dir.x << PSTR(", ")
 	<< dir.y << PSTR(", ")
 	<< dir.z;
@@ -121,25 +156,23 @@
   trace << clear;
   ADXL345::sample_t acc;
   acceleratometer.sample(acc);
-  trace << PSTR("Accelerometer") << endl;
+  trace << PSTR("Accelerometer:") << endl;
   trace << acc.x << PSTR(", ")
 	<< acc.y << PSTR(", ")
 	<< acc.z;
-  sleep(2);

   // Read gyroscope
+#if (HEIGHT == 2)
+  sleep(2);
   trace << clear;
+#else
+  trace << endl;
+#endif
   L3G4200D::sample_t rate;
   gyroscope.sample(rate);
-  trace << PSTR("Gyroscope") << endl;
+  trace << PSTR("Gyroscope:") << endl;
   trace << rate.x << PSTR(", ")
 	<< rate.y << PSTR(", ")
 	<< rate.z;
   sleep(2);
-
-  // Read battery
-  trace << clear;
-  trace << PSTR("Battery") << endl;
-  trace << AnalogPin::bandgap() << PSTR(" mV");
-  sleep(2);
 }


Fixed some easy mistakes

Fixed some easy mistakes

--- arduino/floppy_control.ino
+++ arduino/floppy_control.ino
@@ -1,18 +1,22 @@
 #include <TimerOne.h>

-// timing loop resolution (microseconds):
-const byte LOOP_RESOLUTION = 50000;
+// timing loop period (microseconds)
+#define LOOP_RESOLUTION 40;

 // head position range
-const byte HEAD_MIN = 0;
-const byte HEAD_MAX = 150;
+#define HEAD_MIN 0;
+#define HEAD_MAX 150;

 // number of drives
-const byte DRIVE_COUNT = 1;
+#define DRIVE_COUNT 1;

 // starting step control pin
-// when looping, we assume step control pins occur every two pins
-const byte STARTING_PIN = 2;
+#define STARTING_PIN 2;
+// we assume step control pins occur on evens and direction pins occur on odds
+// (so for drive 1, step control is pin 4 and direction is pin 5)
+
+// interesting Stack Overflow discussion of #define vs. static const:
+// http://stackoverflow.com/questions/1674032/static-const-vs-define-in-c

 // head directions (by drive):
 byte directions[] = {
@@ -20,7 +24,7 @@
 };

 // active frequencies (by drive):
-byte frequencies[] = {
+int frequencies[] = {
   0
 };

@@ -31,36 +35,33 @@

 // elapsed ticks (by drive):
 // used to know when to step
-byte ticks[] = {
+int ticks[] = {
   0
 };
-
-// first run (used for initial reset):
-boolean first = true;

 void setup() {
   // set all needed pin modes
   pinMode(2, OUTPUT); // 0: step control
   pinMode(3, OUTPUT); // 0: direction

+  // set the drives to starting position if they aren't already
+  resetDrives();
+  delay(2000);
+
   // initialize the timing loop
-  //Timer1.initialize(LOOP_RESOLUTION);
-  //Timer1.attachInterrupt(tick);
+  Timer1.initialize(LOOP_RESOLUTION);
+  Timer1.attachInterrupt(tick);

   // initialize serial interface
   Serial.begin(9600);
 }

 void loop() {
-  if (first) {
-    first = false;
-
-    // move all drives to the minimum position
-    resetDrives();
-    delay(2000);
-  }
+  // everything is done within the tick!
 }

+// @todo this totally doesn't work... the commented stuff is what the final
+// working result should eventually look like
 void tick() {
   step(0);


Added lots of comments

Added lots of comments

Added lots of comments and things to make the code more readable and hopefully easier to edit by others

--- fed-arduino/fed-arduino.ino
+++ fed-arduino/fed-arduino.ino
@@ -1,4 +1,5 @@
-/* Feeder code V3 */
+/* Feeder code V3 */  //code with stars (**) next to it is particularly important or contains variables for tuning values
+//importing libraries
 #include <avr/sleep.h>
 #include <avr/power.h>
 #include <avr/wdt.h>
@@ -12,14 +13,17 @@
 #include <Adafruit_MotorShield.h>
 #include <Stepper.h>

+//defining location of IR interrupter pins (pins 2 and 3)
 #define PHOTO_INTERRUPTER_PIN_1 2
 #define PHOTO_INTERRUPTER_PIN_2 3
 const int PHOTO_INTERRUPTER_PINS[] = { PHOTO_INTERRUPTER_PIN_1, PHOTO_INTERRUPTER_PIN_2 };

+//defining serial display pin (pin 9)
 #define DISPLAY_SERIAL_RX_PIN 255 //255=null
 #define DISPLAY_SERIAL_TX_PIN 9
 SoftwareSerial LEDserial = SoftwareSerial(DISPLAY_SERIAL_RX_PIN, DISPLAY_SERIAL_TX_PIN);

+//reference definitions for time conversions
 const long day2 = 86400000; // 86400000 milliseconds in a day
 const long hour2 = 3600000; // 3600000 milliseconds in an hour
 const long minute2 = 60000; // 60000 milliseconds in a minute
@@ -27,6 +31,8 @@

 RTC_DS1307 RTC; //real time clock (on SD shield)

+//setting up all the variables that will be used for couting pellets**
+//          and storing data on IR photo-interrupter states
 int PIStates[] = { 1, 1 };
 int lastStates[] = { 1, 1 };
 int lastTime[] = { 0, 0 };
@@ -34,17 +40,20 @@
 bool pelletCounted[] = { false, false };
 bool countMe[] = { false, false };

+//setting up variables for dealing with the SD card
 #define FILENAME "PelletData.csv"
 const int CS_pin = 10;
 SdFat SD;
 File dataFile;

-const int MOTOR_STEPS_PER_REVOLUTION = 513;
-const int STEPS_TO_INCREMENT = 48; //24
+//setting up motors and motor variables**
+const int MOTOR_STEPS_PER_REVOLUTION = 513;  //number of "steps" the motor takes in order to make a full revolution.  Typically one more than a power of two
+const int STEPS_TO_INCREMENT = 48; //steps it travels each time it turns
 Adafruit_MotorShield gMotorShield = Adafruit_MotorShield();
 Adafruit_StepperMotor *motor1 = gMotorShield.getStepper(MOTOR_STEPS_PER_REVOLUTION,1);
 Adafruit_StepperMotor *motor2 = gMotorShield.getStepper(MOTOR_STEPS_PER_REVOLUTION,2);

+//initialization, run when the program first starts
 void setup() {
   //power saving stuff
   for (byte i=2; i <= 20; i++)
@@ -70,15 +79,17 @@

   //motor shield stuff
   gMotorShield.begin();
-  motor1->setSpeed(15);
-  motor2->setSpeed(15);
+  motor1->setSpeed(15); //setting speed of motor 1**
+  motor2->setSpeed(15); //setting speed of motor 2**

   //SD card init stuff
   Wire.begin();
   RTC.begin();
   delay(250);

-  //RTC.adjust(DateTime(__DATE__, __TIME__));
+  //RTC.adjust(DateTime(__DATE__, __TIME__));  //<--used for resetting the clock if necessary**
+
+  //checking if clock is running
   if (!RTC.isrunning()) {
     Serial.println(F("RTC is NOT running!"));
     RTC.adjust(DateTime(F(__DATE__), F(__TIME__)));
@@ -89,19 +100,21 @@
     Serial.println(currentTime());
   }

+  //checking if SD card is present
   if (!SD.begin(CS_pin)) {
     Serial.println(F("Card failed, or not present"));
     while (1); //stop
   }
   Serial.println(F("Card initialized."));

+  //checking if SD card file saving works
   dataFile = SD.open(FILENAME, FILE_WRITE);
   if (!dataFile) {
     Serial.println(F("Error opening datalog.txt"));
     while (1);
   }
   else {
-    dataFile.println(F("Time,Pellet #1 Count,Pellet #2 Count"));
+    dataFile.println(F("Time,Pellet #1 Count,Pellet #2 Count")); //header for SD card file
     dataFile.close();
     logData();
   }
@@ -112,6 +125,7 @@
   { PIStates[i] = digitalRead(PHOTO_INTERRUPTER_PINS[i]); lastStates[i] = PIStates[i]; }
 }

+//saving data to SD card:
 void logData() {
   power_twi_enable();
   power_spi_enable();
@@ -121,6 +135,8 @@
   if (dataFile) {
     Serial.println(F("File successfully written..."));
     Serial.println(time);
+
+    //printing to SD card (each comma tells the excel doc to go to the next cell to the right)**
     dataFile.print(time);
     dataFile.print(",");
     dataFile.print(pelletCount[0]);
@@ -133,6 +149,7 @@
   power_spi_disable();
 }

+//main loop - what runs the actual program
 void loop() {
   bool a = updateState(0);
   bool b = updateState(1);
@@ -141,11 +158,12 @@
   delay(100);
 }

+//main function for updating each of the IR sensor values and responding**
 bool updateState(int inputNum)
 {
-  PIStates[inputNum] = digitalRead(PHOTO_INTERRUPTER_PINS[inputNum]);
-
-  if (PIStates[inputNum] == 1  & PIStates[inputNum] != lastStates[inputNum]) {
+  PIStates[inputNum] = digitalRead(PHOTO_INTERRUPTER_PINS[inputNum]); //reading in IR sensors
+
+  if (PIStates[inputNum] == 1  & PIStates[inputNum] != lastStates[inputNum]) { //if currently empty but wasn't empty last time
     //pellet taken
     if (!pelletCounted[inputNum])
     {
@@ -153,9 +171,9 @@
       pelletCounted[inputNum] = true;
     }
   }
-  else if (PIStates[inputNum] == 1) {
+  else if (PIStates[inputNum] == 1) { //if still empty, same as last time
     if (countMe[inputNum] && lastTime[inputNum] >= 8) {
-      pelletCount[inputNum]++;
+      pelletCount[inputNum]++; //counts pellet
       Serial.println(F("Pellet taken"));
       Serial.print(F("Pellets of type #"));
       Serial.print(String(inputNum + 1));
@@ -181,7 +199,7 @@
     { delay(500); lastTime[inputNum] += 1; }
   }

-  else if (PIStates[inputNum] == 0 & PIStates[inputNum] != lastStates[inputNum]) {
+  else if (PIStates[inputNum] == 0 & PIStates[inputNum] != lastStates[inputNum]) { //if currently has pellet but didn't have pellet last time
     //pellet just replaced
     Serial.print(F("Pellet #"));
     Serial.print(String(inputNum + 1));
@@ -189,7 +207,7 @@
     lastTime[inputNum] = 0;
   }

-  else  { //if PIStates == 0
+  else  { //if PIStates == 0 //if still has pellet, same as last time
     //pellet still there, do nothing
     lastStates[inputNum] = PIStates[inputNum];
     lastTime[inputNum] = 0;
@@ -199,6 +217,30 @@
   return true;
 }

+//code for moving motors
+void moveMotor(int motorNum)
+{
+    const int backMotion = 6; //fraction of the motion for which to move backwards (6 -> 1/6th)**
+    power_twi_enable();
+    if (motorNum == 0) //for moving first motor
+    {
+      motor1->step(STEPS_TO_INCREMENT/backMotion,BACKWARD,DOUBLE);
+      motor1->step(STEPS_TO_INCREMENT,FORWARD,DOUBLE);
+      motor1->release();
+    }
+    else if (motorNum == 1) //for moving second motor
+    {
+      motor2->step(STEPS_TO_INCREMENT/backMotion,BACKWARD,DOUBLE);
+      motor2->step(STEPS_TO_INCREMENT,FORWARD,DOUBLE);
+      motor2->release();
+    }
+    power_twi_disable();
+}
+
+
+//-------------------------anything after this probably shouldn't be changed-----------------------
+
+//code for entering sleep mode
 void enterSleep()
 {
   Serial.println(F("Going to sleep.")); delay(50);
@@ -217,7 +259,7 @@
   sleep_disable();
 }

-//run when the interrupt is triggered
+//code for what to do when leaving sleep mode, run when the interrupt is triggered
 void pinInterrupt(void)
 {
   detachInterrupt(digitalPinToInterrupt(PHOTO_INTERRUPTER_PIN_1));
@@ -228,6 +270,7 @@
   delay(300);
 }

+//updating the LCD monitor display
 void updateDisplay()
 {
   clearDisplay();
@@ -240,6 +283,7 @@
   LEDserial.print(String(pelletCount[1]));
 }

+//next few are all methods for editing display
 void clearDisplay()
 { LEDserial.write(0x76); }

@@ -253,6 +297,7 @@
 void setDisplayValues(String value)
 { LEDserial.print(value); }

+//returns time from clock
 String currentTime()
 {
   DateTime datetime = RTC.now();
@@ -265,6 +310,7 @@
   return (month + "/" + day + " " + hour + ":" + minute + ":" + second);
 }

+//formats numbers from clock
 String makeDigit(int i)
 {
   if (i < 10)
@@ -272,21 +318,3 @@
   else
   { return String(i, DEC); }
 }
-
-void moveMotor(int motorNum)
-{
-    power_twi_enable();
-    if (motorNum == 0)
-    {
-      motor1->step(STEPS_TO_INCREMENT/6,BACKWARD,DOUBLE);
-      motor1->step(STEPS_TO_INCREMENT,FORWARD,DOUBLE);
-      motor1->release();
-    }
-    else if (motorNum == 1)
-    {
-      motor2->step(STEPS_TO_INCREMENT/6,BACKWARD,DOUBLE);
-      motor2->step(STEPS_TO_INCREMENT,FORWARD,DOUBLE);
-      motor2->release();
-    }
-    power_twi_disable();
-}


Stop the robot when in idle state

Stop the robot when in idle state

--- Chapter_8/CompetitiveSumoRobot.ino
+++ Chapter_8/CompetitiveSumoRobot.ino
@@ -102,6 +102,8 @@
 			begin_countdown();
 		} else {
 			state = 1;
+			motor.left(0);
+			motor.right(0);
 			Serial.println("Robot entering idle mode.");
 		}
 	}


release I2C properly

release I2C properly

--- d_BacpacCommands.ino
+++ d_BacpacCommands.ino
@@ -271,7 +271,7 @@
 {
   int datalen;
   int i = 1;
-  WIRE.requestFrom(SMARTY, TD_BUFFER_SIZE, I2C_NOSTOP);
+  WIRE.requestFrom(SMARTY, TD_BUFFER_SIZE, I2C_STOP);
   if (WIRE.available()) {
     recv[recve] = WIRE.read();
   } else {


Add baud rate selection menu for 1200/2400/9600 and save to eeprom.  Remove at&w0/&v and recovery to save space.  Still too big for Hayes to compile.

--- MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
+++ MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
@@ -24,7 +24,8 @@

 int BAUD_RATE=2400;
 //#define BAUD_RATE 2400
-#define WiFly_BAUD_RATE 2400
+int WiFly_BAUD_RATE=2400;
+//#define WiFly_BAUD_RATE 2400
 #define MIN_FLOW_CONTROL_RATE 4800  // If BAUD rate is this speed or higher, RTS/CTS flow control is enabled.

 // Wifi
@@ -56,25 +57,14 @@
 // Misc Values
 #define TIMEDOUT  -1
 boolean baudMismatch = (BAUD_RATE != WiFly_BAUD_RATE ? 1 : 0);
-#ifndef HAYES
-boolean Modem_flowControl = false;   // Should this be a menu option for non-Hayes mode?
-#endif
+boolean Modem_flowControl = false;   // for &K setting.  Not currently stored in EEPROM

 // EEPROM Addresses
-#define ADDR_PETSCII            0
-#define ADDR_AUTOSTART          1
-#define ADDR_BAUD               2
-#define ADDR_MODEM_ECHO         10
-#define ADDR_MODEM_FLOW         11
-#define ADDR_MODEM_VERBOSE      12
-#define ADDR_MODEM_QUIET        13
-#define ADDR_MODEM_S0_AUTOANS   14
-#define ADDR_MODEM_S2_ESCAPE    15
-#define ADDR_MODEM_DCD_INVERTED 16
-
-#define ADDR_RECOVERY           254
-#define ADDR_FIRST_TIME_CHECK   255
-
+#define ADDR_PETSCII       0
+#define ADDR_AUTOSTART     1
+#define ADDR_BAUD_LO       2
+#define ADDR_BAUD_HI       3
+//#define ADDR_MODEM_ECHO    10

 // PETSCII state
 boolean petscii_mode = EEPROM.read(ADDR_PETSCII);
@@ -94,32 +84,6 @@

 #endif

-#ifdef HAYES
-// ----------------------------------------------------------
-// Simple Hayes Emulation
-// Portions of this code are adapted from Payton Byrd's Hayesduino - thanks!
-
-boolean Modem_isCommandMode = true;
-boolean Modem_isConnected = false;
-boolean Modem_isRinging = false;
-boolean Modem_Echo = false;
-boolean Modem_flowControl = false;
-boolean Modem_VerboseResponses = true;
-boolean Modem_QuietMode = false;
-boolean Modem_isDcdInverted = false;
-
-boolean Modem_S0_AutoAnswer = false;
-char    Modem_S2_EscapeCharacter = '+';
-
-byte    Modem_Recovery = 0;
-
-#define COMMAND_BUFFER_SIZE  81
-char Modem_LastCommandBuffer[COMMAND_BUFFER_SIZE];
-char Modem_CommandBuffer[COMMAND_BUFFER_SIZE];
-
-int Modem_EscapeCount = 0;
-#endif
-
 byte autostart_mode = EEPROM.read(ADDR_AUTOSTART);    // 0-255 only

 // ----------------------------------------------------------
@@ -127,35 +91,15 @@

 int main(void) {
     init();
-    {
+    {
         uView.begin(); // begin of MicroView
         uView.setFontType(0);
         uView.clear(ALL); // erase hardware memory inside the OLED controller
-
-#ifdef HAYES
-        if (EEPROM.read(ADDR_FIRST_TIME_CHECK) != 222) {
-            // First time - reset to defaults
-            Modem_LoadDefaults();
-            Modem_Save_Settings(0);
-            EEPROM.write(ADDR_FIRST_TIME_CHECK, 222);
-            EEPROM.write(ADDR_RECOVERY, 0);
-        }
-        else
-        {
-            Modem_Load_Settings(0);
-        }
-
-        Modem_Recovery = EEPROM.read(ADDR_RECOVERY);
-        if (Modem_Recovery > 2)   // 2 = 3 times
-        {
-            Modem_LoadDefaults();
-            Modem_Save_Settings(0);
-            delay(1000);
-            EEPROM.write(ADDR_RECOVERY, 0);
-        }
-        Modem_Recovery++;
-        EEPROM.write(ADDR_RECOVERY, Modem_Recovery);
-#endif  // HAYES
+
+        C64Serial.begin(BAUD_RATE);
+        WifiSerial.begin(WiFly_BAUD_RATE);
+
+        C64Serial.setTimeout(1000);

         // Always setup pins for flow control
         pinModeFast(C64_RTS, INPUT);
@@ -167,30 +111,17 @@
         // Force CTS to defaults on both sides to start, so data can get through
         digitalWriteFast(WIFI_CTS, LOW);
         digitalWriteFast(C64_CTS, HIGH);  // C64 is inverted
-
+
+        WifiSerial.begin(WiFly_BAUD_RATE);
+
+        BAUD_RATE = (EEPROM.read(ADDR_BAUD_LO) * 256 + EEPROM.read(ADDR_BAUD_HI));
+        if (BAUD_RATE != 1200 && BAUD_RATE != 2400 && BAUD_RATE != 9600 && BAUD_RATE != 38400)
+            BAUD_RATE = 2400;
+
+        C64Serial.begin(BAUD_RATE);
+
+        delay(1000);
         DisplayBoth(F("Wi-Fi Init..."));
-
-        WifiSerial.begin(WiFly_BAUD_RATE);
-
-#ifndef HAYES
-        BAUD_RATE = EEPROM.read(ADDR_BAUD);
-        switch (BAUD_RATE)
-        {
-          case 0:
-          BAUD_RATE = 2400;
-          break;
-
-          case 1:
-          BAUD_RATE = 9600;
-          break;
-
-          default:
-          BAUD_RATE = 2400;
-        }
-#endif
-
-        C64Serial.begin(BAUD_RATE);
-        C64Serial.setTimeout(1000);

         boolean ok = wifly.begin(&WifiSerial, &C64Serial);

@@ -206,22 +137,23 @@

         // Enable DNS caching, TCP retry, TCP_NODELAY, TCP connection status
             wifly.setIpFlags(16 && 4 && 2 && 1);
-
-#ifndef HAYES
-        if (BAUD_RATE == 9600) {
+
+        if (BAUD_RATE != 2400) {
             delay(1000);
-            setBaudWiFi(9600,0);
-        }
-#endif
-
+            if(BAUD_RATE == 1200)
+                setBaudWiFi(2400);
+            else
+                setBaudWiFi(BAUD_RATE);
+        }
+        baudMismatch = (BAUD_RATE != WiFly_BAUD_RATE ? 1 : 0);
+
         wifly.close();

 #ifdef ENABLE_C64_DCD
         digitalWriteFast(C64_DCD, true);    // true = no carrier
 #endif
-        EEPROM.write(ADDR_RECOVERY, 0);   // We made it to the menu so user is not trying to reset to defaults..
         HandleAutoStart();
-
+
         C64Println();
 #ifdef HAYES
         C64Println(F("Commodore Wi-Fi Modem Hayes"));
@@ -305,7 +237,7 @@
         C64Println(F("1. Display Current Configuration"));
         C64Println(F("2. Change SSID"));
         C64Println(F("3. Autostart Options"));
-        C64Println(F("4. Toggle 2400/9600 baud"));
+        C64Println(F("4. Change baud rate"));
         C64Println(F("5. Direct Terminal Mode (Debug)"));
         C64Println(F("6. Return to Main Menu"));
         C64Println();
@@ -325,10 +257,8 @@
         case '3': ConfigureAutoStart();
             break;

-#ifndef HAYES
         case '4': ConfigureBaud();
             break;
-#endif

         case '5': RawTerminalMode();
             return;
@@ -460,14 +390,6 @@
     uView.display();
 }

-void DisplayInt(int message)
-{
-    uView.clear(PAGE); // erase the memory buffer, when next uView.display() is called, the OLED will be cleared.
-    uView.setCursor(0, 0);
-    uView.println(message);
-    uView.display();
-}
-
 void DisplayBoth(String message)
 {
     C64Println(message);
@@ -499,19 +421,9 @@
     }
 }

-void C64PrintInt(int message)
-{
-    C64Serial.print(message);
-}
 void C64Println(String message)
 {
     C64Print(message);
-    C64Serial.println();
-}
-
-void C64PrintIntln(int message)
-{
-    C64PrintInt(message);
     C64Serial.println();
 }

@@ -837,8 +749,8 @@

     while (wifly.available() != -1) // -1 means closed
     {
-        if (0) {   // Assumes host is slower than WiFly
-        //if (baudMismatch) {   // Assumes host is slower than WiFly
+        //if (1) {   // Assumes host is slower than WiFly
+        if (baudMismatch) {   // Assumes host is slower than WiFly
             while (wifly.available() > 0)
             {
                 digitalWriteFast(WIFI_CTS, HIGH);     // ..stop data from Wi-Fi
@@ -855,14 +767,21 @@
                 // Check that C64 is ready to receive
                 while (digitalReadFast(C64_RTS) == LOW);   // If not...  C64 RTS and CTS are inverted.
                 C64Serial.write(buffer[i]);
+
+                while (wifly.available() > 0)
+                {
+                    DoFlowControl();
+                    C64Serial.write(wifly.read());
+                }
             }

+            /*
             // Only used for displaying max buffer size on Microview for testing
             if (max_buffer_size_reached < buffer_index)
                 max_buffer_size_reached = buffer_index;
             char message[20];
             sprintf_P(message, PSTR("Buf: %d"), max_buffer_size_reached);
-            Display(message);
+            Display(message);*/

             // Show largest buffer size on Microview
             // 4800/9600 = 3
@@ -1220,6 +1139,26 @@
 }

 #ifdef HAYES
+// ----------------------------------------------------------
+// Simple Hayes Emulation
+// Portions of this code are adapted from Payton Byrd's Hayesduino - thanks!
+
+boolean Modem_isCommandMode = true;
+boolean Modem_isConnected = false;
+boolean Modem_isRinging = false;
+//boolean Modem_EchoOn = EEPROM.read(ADDR_MODEM_ECHO);
+boolean Modem_EchoOn = true;
+boolean Modem_VerboseResponses = true;
+boolean Modem_QuietMode = false;
+boolean Modem_isDcdInverted = false;
+boolean Modem_S0_AutoAnswer = false;
+char    Modem_S2_EscapeCharacter = '+';
+
+#define COMMAND_BUFFER_SIZE  81
+char Modem_LastCommandBuffer[COMMAND_BUFFER_SIZE];
+char Modem_CommandBuffer[COMMAND_BUFFER_SIZE];
+
+int Modem_EscapeCount = 0;

 void HayesEmulationMode()
 {
@@ -1235,8 +1174,7 @@

     Modem_EscapeCount = 0;

-    //Modem_LoadDefaults();
-    Modem_Load_Settings(0);
+    Modem_LoadDefaults();
     Modem_ResetCommandBuffer();

     C64Println();
@@ -1279,6 +1217,22 @@
     memset(Modem_CommandBuffer, 0, COMMAND_BUFFER_SIZE);
 }

+
+void Modem_LoadDefaults(void)
+{
+    Modem_isCommandMode = true;
+    Modem_isConnected = false;
+    Modem_isRinging = false;
+    Modem_EchoOn = true;
+    //Modem_SetEcho(true);
+    Modem_VerboseResponses = true;
+    Modem_QuietMode = false;
+    Modem_S0_AutoAnswer = false;
+    Modem_S2_EscapeCharacter = '+';
+    Modem_isDcdInverted = false;
+}
+
+
 int Modem_ToggleCarrier(boolean isHigh)
 {
     int result = 0; //_isDcdInverted ? (isHigh ? LOW : HIGH) : (isHigh ? HIGH : LOW);
@@ -1316,6 +1270,13 @@
     digitalWriteFast(C64_DTR, Modem_ToggleCarrier(false));
 }

+/*void Modem_SetEcho(boolean on)
+{
+    Modem_EchoOn = on;
+//    EEPROM.write(ADDR_MODEM_ECHO, Modem_EchoOn);  // Save
+}*/
+
+
 // Validate and handle AT sequence  (A/ was handled already)
 void Modem_ProcessCommandBuffer()
 {
@@ -1356,8 +1317,7 @@

     if (strcmp(Modem_CommandBuffer, ("ATZ")) == 0)
     {
-        //Modem_LoadDefaults();
-        Modem_Load_Settings(0);
+        Modem_LoadDefaults();
         Modem_PrintOK();
     }
     else if (strcmp(Modem_CommandBuffer, ("ATI")) == 0)
@@ -1414,15 +1374,12 @@
     {
         if (strstr(Modem_CommandBuffer, ("E0")) != NULL)
         {
-            Modem_Echo = false;
-        }
+            Modem_EchoOn = false;
+        }
+
         if (strstr(Modem_CommandBuffer, ("E1")) != NULL)
         {
-            Modem_Echo = true;
-        }
-        if (strstr(Modem_CommandBuffer, ("E?")) != NULL)
-        {
-            C64PrintIntln(Modem_Echo);
+            Modem_EchoOn = true;
         }

         if (strstr(Modem_CommandBuffer, ("Q0")) != NULL)
@@ -1430,28 +1387,22 @@
             Modem_VerboseResponses = false;
             Modem_QuietMode = false;
         }
+
         if (strstr(Modem_CommandBuffer, ("Q1")) != NULL)
         {
             Modem_QuietMode = true;
         }
-        if (strstr(Modem_CommandBuffer, ("Q?")) != NULL)
-        {
-            C64PrintIntln(Modem_QuietMode);
-        }

         if (strstr(Modem_CommandBuffer, ("V0")) != NULL)
         {
             Modem_VerboseResponses = false;
         }
+
         if (strstr(Modem_CommandBuffer, ("V1")) != NULL)
         {
             Modem_VerboseResponses = true;
         }
-        if (strstr(Modem_CommandBuffer, ("V?")) != NULL)
-        {
-            C64PrintIntln(Modem_VerboseResponses);
-        }
-
+
         if (strstr(Modem_CommandBuffer, ("X0")) != NULL)
         {
             // TODO
@@ -1460,35 +1411,14 @@
         {
             // TODO
         }
-        if (strstr(Modem_CommandBuffer, ("X?")) != NULL)
-        {
-            // TODO
-        }
-
         if (strstr(Modem_CommandBuffer, ("&K0")) != NULL)
         {
             Modem_flowControl = false;
-            //EEPROM.write(ADDR_MODEM_FLOW, 0);
         }
         if (strstr(Modem_CommandBuffer, ("&K1")) != NULL)
         {
             Modem_flowControl = true;
-            //EEPROM.write(ADDR_MODEM_FLOW, 1);
-        }
-        if (strstr(Modem_CommandBuffer, ("&K?")) != NULL)
-        {
-            C64PrintIntln(Modem_flowControl);
-        }
-
-        if (strstr(Modem_CommandBuffer, ("&W0")) != NULL)
-        {
-            Modem_Save_Settings(0);
-        }
-
-        if (strstr(Modem_CommandBuffer, ("Y0")) != NULL)
-        {
-            Modem_Load_Settings(0);
-        }
+        }

         if (strstr(Modem_CommandBuffer, ("DL")) != NULL)
         {
@@ -1619,7 +1549,7 @@
             //char inbound = toupper(_serial->read());
             char inbound = C64Serial.read();

-            if (Modem_Echo)
+            if (Modem_EchoOn)
             {
                 if (!Modem_flowControl)
                     delay(100/(BAUD_RATE/2400));         // Slow down command mode to prevent garbage if flow control
@@ -1732,20 +1662,15 @@
         {
             Modem_PrintERROR();
             return;
-        }
-
+        }
+
         if ((index = strstr(host, ":")) != NULL)
         {
             index[0] = '\0';
             hostname = String(host);
             port = atoi(index + 1);
         }
-        else
-        {
-            hostname = String(host);
-        }
-    }
-
+    }
     /*if (hostname == F("5551212"))
     {
         QuantumLinkReloaded();
@@ -1848,56 +1773,7 @@
 Serial.begin(115200);
 */

-#ifdef HAYES
-
-void Modem_LoadDefaults(void)
-{
-    Display(F("Setting defaults"));
-    Modem_isCommandMode = true;
-    Modem_isConnected = false;
-    Modem_isRinging = false;
-    Modem_Echo = true;
-    Modem_flowControl = false;
-    Modem_VerboseResponses = true;
-    Modem_QuietMode = false;
-    Modem_S0_AutoAnswer = false;
-    Modem_S2_EscapeCharacter = '+';
-    Modem_isDcdInverted = false;
-#ifndef HAYES
-    BAUD_RATE = 2400;
-    setBaud(2400,0);
-    delay(2000);
-#endif
-}
-
-// Save settings to profile.  Future:  profile #1 using ADDR_MODEM_ECHO1 etc.
-void Modem_Save_Settings(byte profile_num)
-{
-    EEPROM.write(ADDR_MODEM_ECHO, Modem_Echo);
-    EEPROM.write(ADDR_MODEM_FLOW, Modem_flowControl);
-    EEPROM.write(ADDR_MODEM_VERBOSE, Modem_VerboseResponses);
-    EEPROM.write(ADDR_MODEM_QUIET, Modem_QuietMode);
-    EEPROM.write(ADDR_MODEM_S0_AUTOANS, Modem_S0_AutoAnswer);
-    EEPROM.write(ADDR_MODEM_S2_ESCAPE, Modem_S2_EscapeCharacter);
-    EEPROM.write(ADDR_MODEM_DCD_INVERTED, Modem_isDcdInverted);
-}
-
-void Modem_Load_Settings(byte profile_num)
-// Load settings from profile.  Future:  profile #1 using ADDR_MODEM_ECHO1 etc.
-{
-    Modem_Echo = EEPROM.read(ADDR_MODEM_ECHO);
-    Modem_flowControl = EEPROM.read(ADDR_MODEM_FLOW);
-    Modem_VerboseResponses = EEPROM.read(ADDR_MODEM_VERBOSE);
-    Modem_QuietMode = EEPROM.read(ADDR_MODEM_QUIET);
-    Modem_S0_AutoAnswer = EEPROM.read(ADDR_MODEM_S0_AUTOANS);
-    Modem_S2_EscapeCharacter = EEPROM.read(ADDR_MODEM_S2_ESCAPE);
-    Modem_isDcdInverted = EEPROM.read(ADDR_MODEM_DCD_INVERTED);
-}
-
-
-#endif  // HAYES
-
-#ifndef HAYES
+/*
 void ConfigureBaud()
 {
   if (BAUD_RATE == 2400)
@@ -1908,8 +1784,51 @@
   {
       setBaud(2400,true);
   }
-}
-
+}*/
+
+void ConfigureBaud()
+{
+    while (true)
+    {
+        C64Println();
+        C64Print(F("Baud Rate Menu (Current: "));
+        C64Serial.print(BAUD_RATE);
+        C64Println(F(")"));
+        C64Println();
+        C64Println(F("1. 1200"));
+        C64Println(F("2. 2400"));
+        C64Println(F("3. 9600"));
+        C64Println(F("4. Return to Main Menu"));
+
+        C64Println();
+        C64Print(F("Select: "));
+
+        int option = ReadByte(C64Serial);
+        C64Serial.println((char)option);
+
+        switch (option)
+        {
+        case '1': setBaud(1200, true);
+            break;
+        case '2': setBaud(2400, true);
+            break;
+        case '3': setBaud(9600, true);
+            break;
+        case '4': return;
+
+        case '\n':
+        case '\r':
+        case ' ':
+            continue;
+
+        default: C64Println(F("Unknown option, try again"));
+            continue;
+        }
+
+        EEPROM.write(ADDR_AUTOSTART, autostart_mode);  // Save
+        C64Println(F("Saved"));
+    }
+}

 void setBaud(int newBaudRate, boolean pause) {
   char temp[20];
@@ -1922,33 +1841,34 @@
   C64Serial.begin(BAUD_RATE);
   C64Serial.setTimeout(1000);

+  if(BAUD_RATE == 1200)
+    setBaudWiFi(2400);
+  else
+    setBaudWiFi(BAUD_RATE);
+
+  if (pause)
+    delay(5000);  // Delay 5 seconds so user has time to switch to help prevent junk...
+
+  byte a = newBaudRate/256;
+  byte b = newBaudRate % 256;
+
+  // Let's not waste writes..
+  if (EEPROM.read(ADDR_BAUD_LO) != a)
+      EEPROM.write(ADDR_BAUD_LO, a);
+  if (EEPROM.read(ADDR_BAUD_HI) != b)
+      EEPROM.write(ADDR_BAUD_HI, b);
+}
+
+void setBaudWiFi(int newBaudRate) {
+  baudMismatch = (BAUD_RATE != WiFly_BAUD_RATE ? 1 : 0);
+  WiFly_BAUD_RATE = newBaudRate;
   WifiSerial.flush();
   delay(2);
   wifly.setBaud(newBaudRate);     // Uses set uart instant so no save and reboot needed
   delay(1000);
   WifiSerial.end();
   WifiSerial.begin(newBaudRate);
-
-  if (pause)
-    delay(5000);  // Delay 5 seconds so user has time to switch to help prevent junk...
-  //baudMismatch = (BAUD_RATE != WiFly_BAUD_RATE ? 1 : 0);
-
-  if (BAUD_RATE == 2400)
-    EEPROM.write(ADDR_BAUD, 0);  // Save
-  else
-    EEPROM.write(ADDR_BAUD, 1);  // Save
-}
-
-void setBaudWiFi(int newBaudRate, boolean pause) {
-  WifiSerial.flush();
-  delay(2);
-  wifly.setBaud(newBaudRate);     // Uses set uart instant so no save and reboot needed
-  delay(1000);
-  WifiSerial.end();
-  WifiSerial.begin(newBaudRate);
-}
-
-#endif HAYES
+}

 int freeRam ()
 {


moves once

moves once

--- XBee_rob_function_2.0/xBee_2.0/xBee_2.0.ino
+++ XBee_rob_function_2.0/xBee_2.0/xBee_2.0.ino
@@ -56,7 +56,7 @@
   Dynamixel.setProfileVelocity(0x05, 200);
  }

-int x, y, z, emg1, emg2;
+int x, y, z, emg1, emg2, g;
 int infoPk[24];
 void actualName(){
   if(Serial1.available() >= 24){
@@ -65,28 +65,32 @@
             byte jelly = Serial1.read();
             infoPk[i] = jelly;
           }
-
-
-  if(emg1>100){
+
+  while(emg1==1023 && g==0){
     Dynamixel.performMovement(2148, 2048, 2048, CLOSE);   //"Initial" position
-    delay(1500);
+    delay(1000);
     Dynamixel.performMovement(2148, 1850, 3250, OPEN);     //Ready position
-    delay(2000);
+    delay(1000);
     Dynamixel.performMovement(1600, 2800, 3200, OPEN);      //Move to sponge.
     Dynamixel.gripper(CLOSE);                               //Grab
     Dynamixel.performMovement(2148, 1850, 3250, CLOSE);     //Detour
     Dynamixel.performMovement(2650, 2800, 3200, CLOSE);     //Move to destination
     delay(500);
     Dynamixel.gripper(OPEN);                                //Release
-  delay(500);
+    delay(500);
+    g++;
+    break;
+    }
+  if(emg1!=1023){
+    g=0;
   }
-
   for(int a = 13; a < 24; a++) {
     z = infoPk[13] + (infoPk[12] << 8);
     y = infoPk[15] + (infoPk[14] << 8);
     x = infoPk[17] + (infoPk[16] << 8);
     emg1 = infoPk[19] + (infoPk[18] << 8);
     emg2 = infoPk[21] + (infoPk[20] << 8);
+
    }
     Serial.print(" X = ") && Serial.print(x);
     Serial.print(" Y = ") && Serial.print(y);
@@ -94,11 +98,11 @@
     Serial.print(" EMG Ch.1 = ") && Serial.print(emg1);
     Serial.print(" EMG Ch.2 = ") && Serial.print(emg2);
     Serial.println();
+

+ }
   }
  }
- }
-

 void loop() {
   actualName();


more comments!

more comments!

--- Mod-Sketch/Mod-Sketch.ino
+++ Mod-Sketch/Mod-Sketch.ino
@@ -1,6 +1,7 @@
 /* Mod Sketch v0.2 -- written by Craig Durkin / Comingle. */
 /* This software comes pre-loaded on Comingle Mod sex toys */

+/* Include the library */
 #include <OSSex.h>

 bool clicked = false;
@@ -16,8 +17,8 @@
   // Blip all the motors and flash the LED to show that everything is working and the device is on.
   startupSequence();

-  // Set the patterns that the button will cycle through
-
+  // Set the patterns that the button will cycle through. Toy will do nothing on startup, and clicking the button once will run the 'first' pattern
+  // Clicking again will run 'second', etc.
   Toy.addPattern(first);
   Toy.addPattern(second);
   Toy.addPattern(third);
@@ -35,6 +36,7 @@
   Toy.attachDoubleClick(doubleClick);
   Toy.attachLongPressStart(longPress);

+  // Start the Serial console
   Serial.begin(9600);

 }
@@ -42,43 +44,44 @@

 void loop() {
+  // Serial console. Read a character in to command[1], and a value in to val
   char command[1];
   byte val;
   if (Serial.available() > 0) {
     Serial.readBytes(command,1);
-    if (command[0] == 'l') {
+    if (command[0] == 'l') { // Set LED power
       val = Serial.parseInt();
       Toy.setLED(0,val);
       Serial.println(val);
-    } else if (command[0] == '0' || command[0] == '1' || command[0] == '2') {
+    } else if (command[0] == '0' || command[0] == '1' || command[0] == '2') { // Set power of individual motor
       val = Serial.parseInt();
       Toy.setOutput(command[0], val);
       Serial.println(val);
-    } else if (command[0] == '-') {
+    } else if (command[0] == '-') { // Catch '-1', set power of all motors
       int out = Serial.parseInt();
       out *= -1;
       val = Serial.parseInt();
       Toy.setOutput(out,val);
-    } else if (command[0] == 'p') {
+    } else if (command[0] == 'p') {
       Serial.println(Toy.decreasePower());
-    } else if (command[0] == 'P') {
+    } else if (command[0] == 'P') {
       Serial.println(Toy.increasePower());
-    } else if (command[0] == 't') {
+    } else if (command[0] == 't') { // Decrease pattern time, as in everything goes faster
       Serial.println(Toy.decreaseTime());
     } else if (command[0] == 'T') {
       Serial.println(Toy.increaseTime());
-    } else if (command[0] == 'r') {
+    } else if (command[0] == 'r') { // Run a specific pattern, r,0; r,1; etc.
       val = Serial.parseInt();
       Toy.runPattern(val);
       Serial.println(Toy.getPattern());
-    } else if (command[0] == 'g') {
+    } else if (command[0] == 'g') {  // Get number of currently running pattern
       Serial.println(Toy.getPattern());
     } else if (command[0] == 's') {
       Toy.stop();
     } else if (command[0] == 'c') {
       Toy.cyclePattern();
       Serial.println(Toy.getPattern());
-    } else if (command[0] == 'i') {
+    } else if (command[0] == 'i') { // Read input 0 or 1 and print it to serial port
       int in = Serial.parseInt();
       in %= Toy.device.inCount;
       Serial.println(Toy.getInput(in));
@@ -109,21 +112,25 @@
   }
 }

+// Click handler. Currently moves to next pattern.
 void click() {
   clicked = true;
   Toy.cyclePattern();
 }

+// Double click handler Currently increases power.
 void doubleClick() {
  Toy.increasePower();
 }

+// Click and hold handler. Currently decreases power.
 void longPress() {
   Toy.decreasePower();
 }

 // Begin Pattern functions

+// Step variable for storing next pattern step. Must be global.
 int step[3];

 // Turn on all outputs slightly offset from each other. Continues to generate steps even after outputs are on so that the power can be adjusted.
@@ -213,6 +220,7 @@
   return step;
 }

+// First motor only
 int* first(int seq) {
   step[0] = 0;
   step[1] = 100;
@@ -220,6 +228,7 @@
   return step;
 }

+// Second motor only
 int* second(int seq) {
   step[0] = 1;
   step[1] = 100;
@@ -227,6 +236,7 @@
   return step;
 }

+// Third motor only
 int* third(int seq) {
   step[0] = 2;
   step[1] = 100;
@@ -255,6 +265,7 @@
   return step;
 }

+// This pattern is described as boring! Use at your own risk.
 int* fadeSequence(int seq) {
   step[2] = 30;


Fixed Test File

Fixed Test File

--- firmware/examples/mark-iv-flip-dot-display-sign-14x28-controller-test.ino
+++ firmware/examples/mark-iv-flip-dot-display-sign-14x28-controller-test.ino
@@ -1,5 +1,5 @@

-#include "mark-iv-flip-dot-display-sign-14x28-controller.h"
+#include "mark-iv-flip-dot-display-sign-14x28-controller/mark-iv-flip-dot-display-sign-14x28-controller.h"
 //#include <avr/pgmspace.h>


Update WizFi250 example

Update WizFi250 example

--- examples/Boards_WiFi/WizFi250/WizFi250.ino
+++ examples/Boards_WiFi/WizFi250/WizFi250.ino
@@ -29,6 +29,9 @@
 /* Comment this out to disable prints and save space */
 #define BLYNK_PRINT Serial

+/* Fill-in your Template ID (only if using Blynk.Cloud) */
+//#define BLYNK_TEMPLATE_ID   "YourTemplateID"
+

 #include <WizFi250.h>
 #include <BlynkSimpleWizFi250.h>


Update MDriver_no_PWM.ino

Update MDriver_no_PWM.ino

--- examples/MDriver_no_PWM/MDriver_no_PWM.ino
+++ examples/MDriver_no_PWM/MDriver_no_PWM.ino
@@ -27,9 +27,11 @@
  * stop(); - остановка двигателя
  */

-//Подключение двигателей без регулировки скорости,
-//подразумевается что пин EN на плате драйвера подтянут к +5V.
-//Конструктор принимает следующие аргументы MDrive(IN1, IN2)
+/*
+ * Подключение моторов без регулировки скорости,
+ * подразумевается что пин EN на плате драйвера двигателей подтянут к +5V.
+ * Конструктор принимает следующие аргументы MDrive(IN1, IN2)
+ */
 MDriver m1(IN1, IN2);
 MDriver m2(IN3, IN4);


Turn on/off diode on receiving any command from BT

--- Arduino/bluetooth_scatch/bluetooth_scatch.ino
+++ Arduino/bluetooth_scatch/bluetooth_scatch.ino
@@ -2,6 +2,7 @@
 #define RxD 2
 #define TxD 3

+#define Handler 13

 SoftwareSerial blueToothSerial(RxD,TxD);//the software serial port

@@ -9,9 +10,11 @@

 void setup()
 {
-    // user PIN 9 for AT mode
+    // use PIN 9 for AT mode
     pinMode(9, OUTPUT);
     digitalWrite(9, HIGH);
+
+    pinMode(Handler, OUTPUT);

     Serial.begin(9600);   //Serial port for debugging
     pinMode(RxD, INPUT);    //UART pin for Bluetooth
@@ -31,8 +34,10 @@
         Serial.print("From BT: ");
         Serial.println((char *)recv_str);

-        blueToothSerial.print("Return: ");
+        blueToothSerial.print("Arduino: ");
         blueToothSerial.println((char *)recv_str);
+
+        handleCommand();
     }

 }
@@ -49,6 +54,20 @@
     }

     return i;
+}
+
+// handles the command received from BT
+void handleCommand()
+{
+    int state = digitalRead(Handler);
+    if(state == HIGH)
+    {
+        digitalWrite(Handler, LOW);
+    }
+    else
+    {
+        digitalWrite(Handler, HIGH);
+    }
 }

 //configure the Bluetooth through AT commands


[FW] Some improvements

[FW] Some improvements

- Faster ROM loading
- Leading zeroes for ROM number

--- firmware/MultiRomVC4000/MultiRomVC4000.ino
+++ firmware/MultiRomVC4000/MultiRomVC4000.ino
@@ -30,7 +30,7 @@
 unsigned blinkTimeHigh = 500;
 unsigned blinkTimeLow  = 500;
 TM1637Display display(DISPLAY_CLK, DISPLAY_DIO);
-byte displayInitData[] = {0, 0, 0, 0};
+byte displayInitData[] = { 0, 0, 0, 0 };

 void setup() {
   pinMode(SD_CS, OUTPUT);
@@ -56,18 +56,19 @@
       ++romNumber;
     else if (key == DOWNKEY && lastkey != DOWNKEY && romNumber > 1)
       --romNumber;
-    display.showNumberDec(romNumber, false, 2, 2);
+    display.showNumberDec(romNumber, true, 2, 2);
     lastkey = key;
     key = getKey(A7);
   } while (key != SELECTKEY);

   // Construct ROM file name
-  itoa(romNumber, romName, 10);
-  byte len = strlen(romName);
-  romName[len]   = '.';
-  romName[len+1] = 'b';
-  romName[len+2] = 'i';
-  romName[len+3] = 'n';
+  if (romNumber < 10) {
+    romName[0] = '0';
+    itoa(romNumber, romName+1, 10);
+  } else {
+    itoa(romNumber, romName, 10);
+  }
+  strcpy(romName+2, ".bin");

   // Initialize SD card and open ROM file
   if (SD.begin(SD_CS)) {
@@ -140,7 +141,6 @@
   shiftOut(DATA, CLOCK, MSBFIRST, highbyte);
   shiftOut(DATA, CLOCK, MSBFIRST, lowbyte);
   digitalWrite(LATCH, HIGH);
-  delay(1);
   digitalWrite(LATCH, LOW);
 }


Formatting

Formatting

--- Valokepakko.ino
+++ Valokepakko.ino
@@ -1,13 +1,12 @@
-
-
 #include <avr/pgmspace.h>
 #include <math.h>

+#include <Adafruit_NeoPixel.h>
+
 #include "image.h"

-#include <Adafruit_NeoPixel.h>
 #ifdef __AVR__
-  #include <avr/power.h>
+#include <avr/power.h>
 #endif

 /****************************************************/
@@ -52,9 +51,9 @@

 void setup() {
   // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
-  #if defined (__AVR_ATtiny85__)
-    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
-  #endif
+#if defined (__AVR_ATtiny85__)
+  if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
+#endif
   // End of trinket special code

   strip.begin();
@@ -71,7 +70,7 @@
 // Same as the built in map function but for floats
 float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
 {
- return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
+  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
 }

 // Returns the color from the palette. Return black if pixelindex is -1.
@@ -93,33 +92,33 @@

 // Lookup the pixel's color for the tilt based interface.
 uint32_t tiltColorLookup(int led, float angle) {
-    const float originX = IMAGE_WIDTH / 2;
-    const float originY = IMAGE_HEIGHT - 1;
+  const float originX = IMAGE_WIDTH / 2;
+  const float originY = IMAGE_HEIGHT - 1;

-    const float hypotenuse = sqrt(originX*originX +
-                                  originY*originY);
+  const float hypotenuse = sqrt(originX*originX +
+                                originY*originY);

-    int h = mapfloat(led, 0.0, float(LEDS), 0, hypotenuse);
+  int h = mapfloat(led, 0.0, float(LEDS), 0, hypotenuse);

-    int deltaX = cos(angle) * h;
-    int deltaY = sin(angle) * h;
+  int deltaX = cos(angle) * h;
+  int deltaY = sin(angle) * h;

-    int x = int(originX + deltaX);
-    int y = int(originY + deltaY);
-    int pixelIndex = x + y * IMAGE_WIDTH;
-    // If we are out of bounds set color to black
-    if (x < 0 || x > IMAGE_WIDTH - 1 || y < 0 || y > IMAGE_HEIGHT - 1) {
-      pixelIndex = -1;
-    }
-    return lookupColor(pixelIndex);
+  int x = int(originX + deltaX);
+  int y = int(originY + deltaY);
+  int pixelIndex = x + y * IMAGE_WIDTH;
+  // If we are out of bounds set color to black
+  if (x < 0 || x > IMAGE_WIDTH - 1 || y < 0 || y > IMAGE_HEIGHT - 1) {
+    pixelIndex = -1;
+  }
+  return lookupColor(pixelIndex);
 }

 // Lookup the pixel's color for the wheel based interface.
 uint32_t wheelColorLookup(int led, float angle) {
-    int x = int(mapfloat(angle, -PI, PI, 0.0, float(IMAGE_WIDTH-1)));
+  int x = int(mapfloat(angle, -PI, PI, 0.0, float(IMAGE_WIDTH-1)));

-    int pixelIndex = x + led * IMAGE_WIDTH;
-    return lookupColor(pixelIndex);
+  int pixelIndex = x + led * IMAGE_WIDTH;
+  return lookupColor(pixelIndex);
 }

 // Last tick for the timer based interface.