ServoController now has an altitude controlled servo and a serial interface to communicate with the Rasperry Pi 3.

--- software/Arduino/ServoController/ServoController.ino
+++ software/Arduino/ServoController/ServoController.ino
@@ -1,10 +1,11 @@
 /**********************************************************************
  * Arduino Uno Program - Controls Servo and Reads IMU                 *
  * Project: Eclipse Tracking (2017)                                   *
- * Version: 1.0 (3/18/2017)                                           *
+ * Version: 1.0 (3/27/2017)                                           *
  * Max Bowman / Jeremy Seeman / George Moe                            *
  **********************************************************************/
 #include <Stepper.h>
+#include <Servo.h>
 #include <Wire.h>
 #include <MsTimer2.h>
 #include <SparkFunLSM9DS1.h>
@@ -15,48 +16,62 @@
 int stepperPins[] = {9, 10, 11, 12};
 int stepperSteps = 200;
 Stepper motor(stepperSteps, stepperPins[0], stepperPins[1], stepperPins[2], stepperPins[3]);
+Servo altitude;

 int n = 10; // gyro sample
 int k = 200; // servo sample
 int j = 0; // keep track of what to sample
-float runningSum = 0;
+float runningSumXY = 0;
+float runningSumZ = 0;
+
+float currentServoVal = 90;

 bool int_flag = false; // interrupt flag for executing gyro read every 100 ms
 const int LED = 13; // indicator LED
-
-char ch[4]; // for receiving commands from Raspberry Pi 3

 void setup() {
   Serial.begin(115200);
   pinMode(LED, OUTPUT);
   setupIMU(); // set up hardware
   motor.setSpeed(10);
+  altitude.attach(3);

   blinkLED(20, 10); // Let the use know everything initialized

   MsTimer2::set(n, a); // accepts ms argument
-  MsTimer2::start(); // set up and start a timer interrupt
-
+  MsTimer2::start(); // set up and start a timer interrupt
 }

 void loop() {
-  if (Serial.available() == 4) {
-    int correctionFactor = 0;
-    int neg = 0;
-    if (Serial.read() == '1') neg = 1;
-    correctionFactor += (Serial.read() - '0') * 100;
-    correctionFactor += (Serial.read() - '0') * 10;
-    correctionFactor += (Serial.read() - '0');
-    if (neg) correctionFactor -= 2 * correctionFactor;
-    rotateStepperBy(correctionFactor);
+  if (Serial.available() == 8) {
+    int correctionFactorXY = 0;
+    int correctionFactorZ = 0;
+    byte negXY = 0;
+    byte negZ = 0;
+    if (Serial.read() == '1') negXY = 1;
+    correctionFactorXY += (Serial.read() - '0') * 100;
+    correctionFactorXY += (Serial.read() - '0') * 10;
+    correctionFactorXY += (Serial.read() - '0');
+    if (negXY) correctionFactorXY = -correctionFactorXY;
+    rotateStepperBy(correctionFactorXY);
+    if (Serial.read() == '1') negZ = 1;
+    correctionFactorZ += (Serial.read() - '0') * 100;
+    correctionFactorZ += (Serial.read() - '0') * 10;
+    correctionFactorZ += (Serial.read() - '0');
+    if (negZ) correctionFactorZ = -correctionFactorZ;
+    altitude.write(currentServoVal + correctionFactorZ);
   }
   if (int_flag) {
     j++;
     j %= k / n + 1;
-    runningSum += n * readGyro() / 1000;
+    runningSumXY += n * readGyroZ() / 1000;
+    runningSumZ += n * readGyroY() / 1000;
     if (j == 0) {
-      rotateStepperBy(-runningSum); // runningSum is the total theta change
-      runningSum = 0;
+      rotateStepperBy(-runningSumXY); // runningSumXY is the total theta change on the Z axis of rotation
+      runningSumXY = 0;
+      altitude.write(currentServoVal + runningSumZ); // runningSumZ is the total theta change on the Y axis of rotation
+      currentServoVal += runningSumZ;
+      runningSumZ = 0;
     }
   }
 }
@@ -80,11 +95,18 @@
   motor.step(steps);
 }

-float readGyro() {
+float readGyroZ() {
   if (imu.gyroAvailable()) {
     imu.readGyro();
   }
   return imu.calcGyro(imu.gz);
+}
+
+float readGyroY() {
+  if (imu.gyroAvailable()) {
+    imu.readGyro();
+  }
+  return imu.calcGyro(imu.gy);
 }

 void blinkLED(int del, int n) {


fix wrong index searched by the example

fix wrong index searched by the example

--- examples/ESP_AsyncFSBrowser/ESP_AsyncFSBrowser.ino
+++ examples/ESP_AsyncFSBrowser/ESP_AsyncFSBrowser.ino
@@ -505,7 +505,7 @@
   server.addHandler(&events);

   server.addHandler(new SPIFFSEditor(http_username,http_password));
-  server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.html");
+  server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm");

   server.on("/heap", HTTP_GET, [](AsyncWebServerRequest *request){
     request->send(200, "text/plain", String(ESP.getFreeHeap()));


Adds correction table for next update.

Adds correction table for next update.

--- examples/T3_ILI9341_display/T3_ILI9341_display.ino
+++ examples/T3_ILI9341_display/T3_ILI9341_display.ino
@@ -53,7 +53,7 @@
 OBD9141 obd;

 // Use random values to display.
-#define DEBUG 1
+// #define DEBUG 1

 // typedefs for the OBD entries.
 typedef struct{
@@ -137,6 +137,26 @@

 }

+
+/*
+  Velocity correction table measurements, for future improvement.
+
+  Dash  OBD     GPS
+  -----------------
+  120   107     113
+  120   108     113
+  80    71      74-75
+  80    71      74
+  70    62      64
+  100   90-91   94
+  100   90-91   93-96
+  100   90-91   93-94
+  70    62      64
+  130   117-118 122
+  130   118     122
+*/
+
+
 void loop(){
   tft.fillScreen(ILI9341_BLACK);
   tft.setCursor(0, 100);
@@ -158,7 +178,7 @@
     #ifndef DEBUG
     return;
     #endif
-    delay(3000);
+    delay(5000);
   }
   #ifdef DEBUG
     got_success = true;


Update to use flash string helper

Update to use flash string helper

--- examples/httpclient_progmem/httpclient_progmem.ino
+++ examples/httpclient_progmem/httpclient_progmem.ino
@@ -32,73 +32,71 @@
 const char site[] = "hunt.net.nz";

 void terminal();
-void print_P(const prog_char *str);
-void println_P(const prog_char *str);

 void setup()
 {
     char buf[32];

     Serial.begin(115200);
-    println_P(PSTR("Starting"));
-    print_P(PSTR("Free memory: "));
+    Serial.println(F("Starting"));
+    Serial.print(F("Free memory: "));
     Serial.println(wifly.getFreeMemory(),DEC);

     wifiSerial.begin(9600);
     if (!wifly.begin(&wifiSerial, &Serial)) {
-        println_P(PSTR("Failed to start wifly"));
+        Serial.println(F("Failed to start wifly"));
 	terminal();
     }

     /* Join wifi network if not already associated */
     if (!wifly.isAssociated()) {
 	/* Setup the WiFly to connect to a wifi network */
-	println_P(PSTR("Joining network"));
+	Serial.println(F("Joining network"));
 	wifly.setSSID(mySSID);
 	wifly.setPassphrase(myPassword);
 	wifly.enableDHCP();

 	if (wifly.join()) {
-	    println_P(PSTR("Joined wifi network"));
+	    Serial.println(F("Joined wifi network"));
 	} else {
-	    println_P(PSTR("Failed to join wifi network"));
+	    Serial.println(F("Failed to join wifi network"));
 	    terminal();
 	}
     } else {
-        println_P(PSTR("Already joined network"));
+        Serial.println(F("Already joined network"));
     }

     //terminal();

-    print_P(PSTR("MAC: "));
+    Serial.print(F("MAC: "));
     Serial.println(wifly.getMAC(buf, sizeof(buf)));
-    print_P(PSTR("IP: "));
+    Serial.print(F("IP: "));
     Serial.println(wifly.getIP(buf, sizeof(buf)));
-    print_P(PSTR("Netmask: "));
+    Serial.print(F("Netmask: "));
     Serial.println(wifly.getNetmask(buf, sizeof(buf)));
-    print_P(PSTR("Gateway: "));
+    Serial.print(F("Gateway: "));
     Serial.println(wifly.getGateway(buf, sizeof(buf)));
-    print_P(PSTR("SSID: "));
+    Serial.print(F("SSID: "));
     Serial.println(wifly.getSSID(buf, sizeof(buf)));

     wifly.setDeviceID("Wifly-WebClient");
-    print_P(PSTR("DeviceID: "));
+    Serial.print(F("DeviceID: "));
     Serial.println(wifly.getDeviceID(buf, sizeof(buf)));

     if (wifly.isConnected()) {
-        println_P(PSTR("Old connection active. Closing"));
+        Serial.println(F("Old connection active. Closing"));
 	wifly.close();
     }

     if (wifly.open(site, 80)) {
-        print_P(PSTR("Connected to "));
+        Serial.print(F("Connected to "));
 	Serial.println(site);

 	/* Send the request */
 	wifly.println("GET / HTTP/1.0");
 	wifly.println();
     } else {
-        println_P(PSTR("Failed to connect"));
+        Serial.println(F("Failed to connect"));
     }
 }

@@ -132,18 +130,3 @@
 	}
     }
 }
-
-/* Print a string from program memory */
-void print_P(const prog_char *str)
-{
-    char ch;
-    while ((ch=pgm_read_byte(str++)) != 0) {
-	Serial.write(ch);
-    }
-}
-
-void println_P(const prog_char *str)
-{
-    print_P(str);
-    Serial.println();
-}


Fixed the reading of frames and color stops

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -28,31 +28,29 @@
     #define SERIAL_BUFFER_SIZE 64
 #endif

-struct Frame {
-  uint16_t transitionTime;
-  uint16_t pauseTime;
-  uint8_t colorStopCount;
-
-};
-
 struct ColorStop {
   uint16_t ledIndex;
   uint8_t r;
   uint8_t g;
   uint8_t b;
-
+
 };

-Adafruit_NeoPixel* strip       = NULL;
-struct Frame* currentFrame     = NULL;
-struct ColorStop** colorStops = NULL;
+struct Frame {
+  uint16_t transitionTime;
+  uint16_t pauseTime;
+  uint8_t colorStopCount;
+
+};
+
+Adafruit_NeoPixel* strip = NULL;
 uint8_t currentFrameIndex = 0;
-uint8_t* startR;
-uint8_t* startG;
-uint8_t* startB;
-uint8_t* stepR;
-uint8_t* stepG;
-uint8_t* stepB;
+uint8_t* startR = NULL;
+uint8_t* startG = NULL;
+uint8_t* startB = NULL;
+uint8_t* stepR = NULL;
+uint8_t* stepG = NULL;
+uint8_t* stepB = NULL;
 uint16_t stepsUntilNextFrame = 0;

 void setup() {
@@ -98,14 +96,6 @@
   //show the gradient
   strip->setBrightness(64);
   strip->show();
-
-  //Create arrays
-  startR = (uint8_t*) malloc(ledCount);
-  startG = (uint8_t*) malloc(ledCount);
-  startB = (uint8_t*) malloc(ledCount);
-  stepR = (uint8_t*) malloc(ledCount);
-  stepG = (uint8_t*) malloc(ledCount);
-  stepB = (uint8_t*) malloc(ledCount);

   //Load current profile
   applyProfile();
@@ -121,27 +111,71 @@

 void applyProfile() {
   currentFrameIndex = 0;
-  loadFrame(currentFrameIndex);
-
-}
-
-void loadFrame(uint8_t index) {
+  loadNextAnimationStep();
+
+}
+
+void loadNextAnimationStep() {
+  //increase frame
+  currentFrameIndex++;
+
+  //Free arrays to gain RAM
+  if(stepR != NULL) {
+    free(stepR);
+    free(stepG);
+    free(stepB);
+
+  }
+
+  //Load current Frame;
+  struct Frame* frame = NULL;
+  struct ColorStop** colorStops = NULL;
+  loadFrame(0, &frame, &colorStops);
+
+  /*
+  Serial.println("-------------------");
+  Serial.print("colorStopCount: ");
+  Serial.println(frame->colorStopCount);
+  Serial.print("transitionTime: ");
+  Serial.println(frame->transitionTime);
+  Serial.print("pauseTime: ");
+  Serial.println(frame->pauseTime);
+  Serial.print("colorStops[0]->ledIndex: ");
+  Serial.println(colorStops[0]->ledIndex);
+  Serial.print("firstColorStop->r: ");
+  Serial.println(colorStops[0]->r);
+  Serial.print("firstColorStop->g: ");
+  Serial.println(colorStops[0]->g);
+  Serial.print("firstColorStop->b: ");
+  Serial.println(colorStops[0]->b);
+  Serial.print("colorStops[1]->ledIndex: ");
+  Serial.println(colorStops[1]->ledIndex);
+  Serial.print("firstColorStop->r: ");
+  Serial.println(colorStops[1]->r);
+  Serial.print("firstColorStop->g: ");
+  Serial.println(colorStops[1]->g);
+  Serial.print("firstColorStop->b: ");
+  Serial.println(colorStops[1]->b);
+  */
+
+}
+
+void loadFrame(uint8_t index, struct Frame** framePointer, struct ColorStop*** colorStopsPointer) {
   uint8_t i;
-
-  //Create a Frame struct if not allocated
-  if(currentFrame == NULL) {
-    currentFrame = (struct Frame*) malloc(sizeof(struct Frame));
-    currentFrame->transitionTime = 0;
-    currentFrame->pauseTime =      0;
-    currentFrame->colorStopCount = 0;
-
-  }
-
-  uint8_t availableColorStops = currentFrame->colorStopCount;
-
+
+  //If there is no frame at the pointed address, override create a new one and save it to the pointer
+  if(*framePointer == NULL) {
+    *framePointer = (struct Frame*) malloc(sizeof(struct Frame));
+    (*framePointer)->colorStopCount = 0;
+
+  }
+
+  //Save simple pointer to frame
+  struct Frame* frame = *framePointer;
+
   //Init Frame address with the porfile start
   uint16_t frameAddress = EEPROM_CURRENT_PROFILE_START;
-
+
   //Iterate over all Frames until the desired one
   for(i=0; i<index; i++) {
     //Read how many ColorStops the Frame contains and multiply it by the size of one ColorStop, add it to Address
@@ -154,50 +188,23 @@

   //frameAddress is now the address of the desired Frame
   //Read the values
-  currentFrame->transitionTime = EEPROM.readInt(frameAddress);
-  currentFrame->pauseTime =      EEPROM.readInt(frameAddress+2);
-  currentFrame->colorStopCount = EEPROM.read(frameAddress+4);
-
-  /*
-  Serial.print("colorStopCount: ");
-  Serial.println(currentFrame->colorStopCount);
-  Serial.print("transitionTime: ");
-  Serial.println(currentFrame->transitionTime);
-  Serial.print("pauseTime: ");
-  Serial.println(currentFrame->pauseTime);
-  Serial.print("availableColorStops: ");
-  Serial.println(availableColorStops);
-  */
-
-  //free all ColorStops
-  for(i=0; i<availableColorStops; i++) {
-    free(colorStops[i]);
-
-  }
-
-  //free colorStops and allocate new
-  free(colorStops);
-  colorStops = (ColorStop**) malloc(sizeof(struct ColorStop*) * currentFrame->colorStopCount);
-
-  //Serial.println("ColorStops: ");
-
+  frame->transitionTime = EEPROM.readInt(frameAddress);
+  frame->pauseTime =      EEPROM.readInt(frameAddress+2);
+  frame->colorStopCount = EEPROM.read(frameAddress+4);
+
+  if(*colorStopsPointer == NULL) {
+    struct ColorStop** array =  (struct ColorStop**) malloc(sizeof(struct ColorStop) * frame->colorStopCount);
+    *colorStopsPointer = array;
+
+  }
+
+  struct ColorStop** colorStops = *colorStopsPointer;
+
   //Load ColorStops
-  for(i=0; i<currentFrame->colorStopCount; i++) {
+  for(i=0; i<frame->colorStopCount; i++) {
     colorStops[i] = (ColorStop*) malloc(sizeof(struct ColorStop));
-    loadColorStop(i, frameAddress, colorStops[i]);
-
-    /*
-    Serial.println(i);
-    Serial.print("  ledIndex: ");
-    Serial.println(colorStops[i]->ledIndex);
-    Serial.print("  r: ");
-    Serial.println(colorStops[i]->r);
-    Serial.print("  g: ");
-    Serial.println(colorStops[i]->g);
-    Serial.print("  b: ");
-    Serial.println(colorStops[i]->b);
-    */
-
+    loadColorStop(i, frameAddress,  colorStops[i]);
+
   }
 }

@@ -280,8 +287,8 @@
   uint16_t receivedCount = 9;
   transmissionLength -= receivedCount;

-  uint64_t checksum = 0;
-  uint8_t buffer;
+  int64_t checksum = 0;
+  int8_t buffer;

   while(!EEPROM.isReady());


refactor code

refactor code

--- sanro/sanro.ino
+++ sanro/sanro.ino
@@ -21,6 +21,11 @@

 #include <Keyboard.h>
 #include "cache.h"
+#include "limits.h"
+
+#if MODE_JIRO
+#define HEAVY_THRES LONG_MAX
+#endif

 int channelSample [CHANNELS];
 int lastChannelSample [CHANNELS];
@@ -31,9 +36,9 @@

 bool triggered [CHANNELS];

-#if MODE_DEBUG
-long int lastTime;
-#endif
+int pins[] = { A0, A1, A2, A3 };  // L don, R don, L kat, R kat
+char lightKeys[] = { 'g', 'h', 'f', 'j' };
+char heavyKeys[] = { 't', 'y', 'r', 'u' };

 void setup() {
   Serial.begin (9600);
@@ -44,25 +49,27 @@
     lastChannelSample [i] = 0;
     triggered [i] = false;
   }
-#if MODE_DEBUG
-lastTime = 0;
-#endif
 }

 void loop() {

-  channelSample[0] = analogRead (A0);  // L don
-  channelSample[1] = analogRead (A1);  // R don
-  channelSample[2] = analogRead (A2);  // L kat
-  channelSample[3] = analogRead (A3);  // R kat
-
 #if MODE_DEBUG
-  Serial.print (micros () - lastTime);
-  lastTime = micros ();
-  Serial.print ("\t");
+  long int sampleLastTime = 0;
+  long int calcLastTime = 0;
 #endif

   for (short int i = 0; i < CHANNELS; i++) {
+
+#if MODE_DEBUG
+    long int lastTime = micros();
+#endif
+
+    channelSample[i] = analogRead (pins[i]);
+
+#if MODE_DEBUG
+    sampleLastTime += micros () - lastTime;
+    lastTime = micros();
+#endif

     sampleCache [i].put (channelSample [i] - lastChannelSample [i]);

@@ -79,47 +86,29 @@
     powerCache [i].put (power [i]);
     lastChannelSample [i] = channelSample [i];

+    if (powerCache [i].get (1) == 0) {
+      triggered [i] = false;
+    }
+
+    bool isDescending = true;
     for (short int j = 0; j < POWER_CACHE_LENGTH - 1; j++){
-
-      if (powerCache [i].get (j) == 0) {
-        triggered [i] = false;
+      if (!triggered [i] && (powerCache [i].get (j - 1) > powerCache [i].get (j))) {
+        isDescending = false;
+        break;
       }
-
-      if (!triggered [i]) {
-        if (powerCache [i].get (j + 1) >= powerCache [i].get (j) || j != POWER_CACHE_LENGTH - 2) {
-          break;
-        } else {
-#if MODE_JIRO
-          if (power [i] >= LIGHT_THRES) {
-            triggered [i] = true;
-            switch (i) {
-              case 0: Keyboard.print ('g'); break;
-              case 1: Keyboard.print ('h'); break;
-              case 2: Keyboard.print ('f'); break;
-              case 3: Keyboard.print ('j'); break;
-            }
-          }
-#else
-          if (power [i] >= HEAVY_THRES) {
-            triggered [i] = true;
-            switch (i) {
-              case 0: Keyboard.print ('t'); break;
-              case 1: Keyboard.print ('y'); break;
-              case 2: Keyboard.print ('r'); break;
-              case 3: Keyboard.print ('u'); break;
-            }
-          } else if (power [i] >= LIGHT_THRES) {
-            triggered [i] = true;
-            switch (i) {
-              case 0: Keyboard.print ('g'); break;
-              case 1: Keyboard.print ('h'); break;
-              case 2: Keyboard.print ('f'); break;
-              case 3: Keyboard.print ('j'); break;
-            }
-          }
+    }
+    if (isDescending) {
+      if (power [i] >= HEAVY_THRES) {
+        triggered [i] = true;
+        Keyboard.print (heavyKeys [i]);
+      } else if (power [i] >= LIGHT_THRES) {
+        triggered [i] = true;
+        Keyboard.print (lightKeys [i]);
+      }
+
+#if MODE_DEBUG
+    calcLastTime += micros () - lastTime;
 #endif
-        }
-      }
     }

 #if MODE_DEBUG
@@ -131,8 +120,9 @@
   }

 #if MODE_DEBUG
-  Serial.print (micros () - lastTime);
-  lastTime = micros ();
+  Serial.print(sampleLastTime);
+  Serial.print('\t');
+  Serial.print(calcLastTime);
   Serial.println ("");
 #endif


altered window size and pid refresh

altered window size and pid refresh

--- rice-cooker-sous-vide/rice-cooker-sous-vide.ino
+++ rice-cooker-sous-vide/rice-cooker-sous-vide.ino
@@ -57,7 +57,7 @@
 PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

 // 10 second Time Proportional Output window
-int WindowSize = 10000;
+int WindowSize = 5000;
 unsigned long windowStartTime;

 // ************************************************
@@ -107,7 +107,7 @@
    Serial.print("Kd: ");
    Serial.println(Kd);

-   myPID.SetSampleTime(1000);
+   myPID.SetSampleTime(WindowSize/2);
    myPID.SetOutputLimits(0, WindowSize);

   // Run timer2 interrupt every 15 ms so the pulse timing will be accurate
@@ -195,6 +195,7 @@
   }
   else // Execute control algorithm
   {
+    Serial.println("");
     Serial.println("computing PID");
      myPID.Compute();
   }


シリアル通信で[p]が来たらツボを押すだけのArduinoプログラム

シリアル通信で[p]が来たらツボを押すだけのArduinoプログラム

saga/16:32

--- edison/servo_controll/servo_controll.ino
+++ edison/servo_controll/servo_controll.ino
@@ -1,9 +1,80 @@
-void setup() {
-  // put your setup code here, to run once:
+#include <Servo.h>

+#define PUSH_MIN -180           // もっとも緩んでいる状態のサーボ角度(deg)
+#define PUSH_MAX 180            // もっとも締めている状態のサーボ角度(deg)
+#define STEP_DEG 10             // 1回に変化させる角度(deg)
+#define STEP_INTERVAL 10        // 変化させる時間の頻度(ms)
+#define PUSH_TIME_LENGTH 3000   // 押している時間(ms)
+
+#define MAX_CHAR_LENGTH 100
+
+Servo myservo;  // サーボ
+
+int pos;        // サーボの角度
+char input_string[MAX_CHAR_LENGTH];   // 入力文字列のための配列
+int char_length;                      // 入力文字列の長さ
+int push_now;   // 今押してる最中なら1, でなければ0
+int i;
+
+
+// 押し始め
+void start_push(){
+  for(pos = PUSH_MIN; pos <= PUSH_MAX; pos += STEP_DEG) // PUSH_MIN度からPUSH_MAX度まで, STEP_DEG度ずつ押す
+  {
+    push_now = 1;
+    myservo.write(pos);
+    delay(STEP_INTERVAL);                               // 1STEP_DEG度の移動につきSTEP_INTERVAL msだけかける
+  }
 }

-void loop() {
-  // put your main code here, to run repeatedly:
+// 押し終わり
+void end_push(){
+  for(pos = PUSH_MAX; pos>=PUSH_MIN; pos-= STEP_DEG)    // PUSH_MAX度からPUSH_MIN度まで, STEP_DEG度ずつ緩める
+  {
+    push_now = 0;
+    myservo.write(pos);
+    delay(STEP_INTERVAL);                               // 1STEP_DEG度の移動につきSTEP_INTERVAL msだけかける
+  }
+}

+
+void setup()
+{
+  myservo.attach(9);  // pin 9 をサーボ用に設定
+  Serial.begin(115200);
+  push_now = 0;
 }
+
+void loop()
+{
+  // 届いている文字列を最大許容数まで格納
+  char_length = 0;
+  while( Serial.available() ){
+    input_string[char_length] = Serial.read();
+    char_length++;
+    if( char_length == MAX_CHAR_LENGTH ){
+      break;
+    }
+  }
+
+  // 何も来てなければpush終了
+  if( char_length == 0 && push_now ){
+    end_push();
+  }
+
+  // 文字列を処理
+  for( i = 0 ; i < char_length ; i++ ){
+    if( input_string[i] == 'p' ){   // 一つでもpが来たらpush!
+      if( !push_now ){              // 今押してる最中ならそのままでおk
+        start_push();
+      }
+      delay(PUSH_TIME_LENGTH);
+      break;
+    }else if( i == char_length-1 ){ // 最後までpが来なかったらpush終了
+      end_push();
+    }
+  }
+
+  delay(10);
+}
+


Fixed include of Board.hh to allow ATtiny to ignore print/IOStream/trace.

--- examples/OWI/CosaDS18B20/CosaDS18B20.ino
+++ examples/OWI/CosaDS18B20/CosaDS18B20.ino
@@ -28,6 +28,7 @@
  * This file is part of the Arduino Che Cosa project.
  */

+#include "Cosa/Board.hh"
 #include "Cosa/OWI/Driver/DS18B20.hh"
 #include "Cosa/Trace.hh"
 #include "Cosa/IOStream/Driver/UART.hh"


sysver & discon. evt

sysver & discon. evt

Aggiunta variabile sysver per la versione del fw da mostrare sullo
schermo; modificata schermata Evt Disconnected

--- Beta_v02/Beta_v02.ino
+++ Beta_v02/Beta_v02.ino
@@ -11,7 +11,7 @@
 #include "icons.h" //include bitmap file
 //Put the nRF8001 setup in the RAM of the nRF8001.
 #include "services.h"
-
+byte sysver[2] = {0, 2};
 /**
 Include the services_lock.h to put the setup in the OTP memory of the nRF8001.
 This would mean that the setup cannot be changed once put in.
@@ -108,7 +108,10 @@
   display.setCursor(14, 0);
   display.println("CodeATLAS");
   display.setCursor(14, 8);
-  display.println("WerCA 0.2");
+  display.print("WerCA ");
+  display.print(sysver[0], DEC);
+  display.print(".");
+  display.print(sysver[1], DEC);
   //Serial.println("Display scritto");
   //delay(200);
   display.drawBitmap(24, 20, logo32, 32, 32, BLACK);
@@ -366,9 +369,21 @@
         //Serial.println(F("Evt Disconnected/Advertising timed out"));
         lib_aci_connect(0/* in seconds  : 0 means forever */, 0x0050 /* advertising interval 50ms*/);

-        display.clearDisplay();
-        display.setCursor(0,8);
-        display.println(F("DISCONNESSO\nRiconnettere\nil telefono"));
+  display.clearDisplay();
+  display.setContrast(32);
+  display.setTextSize(1);
+  display.setTextColor(BLACK);
+  display.setCursor(14, 0);
+  display.println("CodeATLAS");
+  display.setCursor(14, 8);
+  display.print("WerCA ");
+  display.print(sysver[0], DEC);
+  display.print(".");
+  display.print(sysver[1], DEC);
+    //Serial.println("Display scritto");
+  //delay(200);
+  display.drawBitmap(24, 20, logo32, 32, 32, BLACK);
+  display.display();
         //Serial.println(F("Advertising started. Tap Connect on the nRF UART app"));
         break;


completed load of hbumtf_v001

completed load of hbumtf_v001


Update arduino/arduino.ino

Update arduino/arduino.ino

Updated sponsors

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -1,243 +1,245 @@
-/*
-* Author: Gunther Cox
-* CC: Salvius Robot Project
-* Website: http://salviusrobot.blogspot.com
-*
-*/
-
-// FOR ETHERNET
-#include <Ethernet.h>
-#include <SPI.h>
-
-#include <Client.h>
-#include <Server.h>
-#include <Udp.h>
-
-// VARIABLES FOR MANUAL SETUP
-byte mac[] = {
-  0x90, 0xA2, 0xDA, 0x0D, 0x00, 0x8F }; // physical mac address
-byte ip[] = {
-  192, 168, 1, 177 };          // ip in lan
-byte gateway[] = {
-  192, 168, 0, 1 };       // internet access via router
-byte subnet[] = {
-  255, 255, 255, 0 };      //subnet mask
-EthernetServer server(80);
-
-//int pirPin = 3;    // PIR SENSOR
-int relayPin1 = 4; // relay connected to digital pin 4 (D3 on relay shield - on switch)
-int relayPin2 = 7; // relay connected to digital pin 5 (D2 on relay shield) - Inferred LEDs
-int relayPin3 = 6; // relay connected to digital pin 6 (D1 on relay shield) - Ultraviolte LEDs
-int relayPin4 = 5; // relay connected to digital pin 7 (D0 on relay shield) (not used)
-//pin 10 - RESERVED FOR ETHERNET SHIELD
-//pin 11 - RESERVED FOR ETHERNET SHIELD
-//pin 12 - RESERVED FOR ETHERNET SHIELD
-//pin 13 - RESERVED FOR ETHERNET SHIELD
-
-// STORES URL DATA
-String readString = String(30);
-
-// STATUS FLAGS
-boolean FORWARD = false;
-boolean BACKWARD = false;
-boolean LEFT = false;
-boolean RIGHT = false;
-boolean LEDON = false;
-boolean LED2ON = false;
-
-void setup(){
-  // Start Ethernet
-  Ethernet.begin(mac, ip, gateway, subnet);
-  pinMode(relayPin3, OUTPUT);  //Set pin 7 to output
-  pinMode(relayPin4, OUTPUT);
-
-  //  pinMode(pirPin, INPUT);        // declare sensor as input
-  pinMode(relayPin1, OUTPUT);    // declare relay1 as output
-  pinMode(relayPin2, OUTPUT);    // declare relay2 as output
-  pinMode(relayPin3, OUTPUT);    // declare relay3 as output
-  pinMode(relayPin4, OUTPUT);    // declare relay4 as output
-
-  /*digitalWrite(relayPin1, LOW);
-   digitalWrite(pirPin, LOW);
-   pirState = digitalRead(pirPin); // read the initial state
-   delay(60000);                   // pause before calibrating
-   */
-}
-
-void loop(){
-  // Create a client connection
-  EthernetClient client = server.available();
-  if (client) {
-    while (client.connected()) {
-      if (client.available()) {
-        char c = client.read();
-        //read char by char HTTP request
-        if (readString.length() < 100) {
-          readString += c; //store characters to string
-        }
-
-        if (c == '\n') {  //if HTTP request has ended
-
-          //dirty skip of "GET /favicon.ico HTTP/1.1"
-          if (readString.indexOf("?") <0) { /*skip everything*/
-          }
-
-          else
-
-            // BEGIN DRIVE CONTROL
-          if(readString.indexOf("N1=Forward") >0) {
-
-            // ITEM HAS TO BE TURNED ON
-            digitalWrite(relayPin1, HIGH);    // set the item on
-            FORWARD = true;
-          }
-
-          else {
-
-            // ITEM HAS TO BE TURNED OFF
-            digitalWrite(relayPin1, LOW);    // set the item off
-            FORWARD = false;
-          }
-
-          if (readString.indexOf("N2=BACKWARD") > 0) {
-            //item has to be turned ON
-            digitalWrite(relayPin2, HIGH);    // set the item on
-            BACKWARD = true;
-          }
-          else {
-            //item has to be turned OFF
-            digitalWrite(relayPin2, LOW);    // set the item off
-            BACKWARD = false;
-          }
-
-          if (readString.indexOf("N3=LEFT") > 0) {
-            //item has to be turned ON
-            digitalWrite(relayPin3, HIGH);    // set the item on
-            LEFT = true;
-          }
-          else {
-            //item has to be turned OFF
-            digitalWrite(relayPin3, LOW);    // set the item off
-            LEFT = false;
-          }
-
-          if (readString.indexOf("N4=RIGHT") > 0) {
-            //item has to be turned ON
-            digitalWrite(relayPin4, HIGH);    // set the item on
-            RIGHT = true;
-          }
-          else {
-            //item has to be turned OFF
-            digitalWrite(relayPin4, LOW);    // set the item off
-            RIGHT = false;
-          }
-          // end drive control
-
-          //lets check if LED should be lighted
-          if (readString.indexOf("L=ON") >0) {
-            //led has to be turned ON
-            digitalWrite(relayPin3, HIGH);    // set the LED on
-            LEDON = true;
-          }
-          else if (readString.indexOf("L2=ON") >0) {
-            //led has to be turned ON
-            digitalWrite(relayPin4, HIGH);    // set the LED on
-            LED2ON = true;
-          }
-          //led has to be turned OFF
-          else {
-            //led has to be turned OFF
-            digitalWrite(relayPin4, LOW);    // set the LED OFF
-            LED2ON = false;
-            digitalWrite(relayPin3, LOW);    // set the LED OFF
-            LEDON = false;
-          }
-
-          // now output HTML data starting with standart header
-          client.println("HTTP/1.1 200 OK");
-          client.println("Content-Type: text/html");
-          client.println();
-          client.println("<link href='http://192.168.1.2/bootstrap/css/bootstrap.css' rel='stylesheet'>");
-
-          client.println("<form method=get name=NAV>");
-          client.println("<input type=submit name=N1 value=FORWARD>");
-          client.println("<input type=submit name=N3 value=LEFT><input type=submit value=STOP><input type=submit name=N4 value=RIGHT>");
-          client.println("<input type=submit name=N2 value=BACKWARD>");
-
-          //controlling leds via buttons (address will look like http://192.168.1.177/?L=ON when submited)
-          if (LEDON)
-            client.println("<form method=get name=LED><input type=submit value=OFF></form>");
-          else
-            client.println("<form method=get name=LED><input type=submit name=L value=ON></form>");
-
-          if (LED2ON)  // begin second LED
-            client.println("<form method=get name=LED2><input type=submit value=OFF></form>
");
-          else
-            client.println("<form method=get name=LED2><input type=submit name=L2 value=ON></form>");
-          client.println("</form>");
-
-          // Begin print drive status
-          if (FORWARD)
-            client.println("DRIVING FORWARD");
-
-          else if (BACKWARD)
-            client.println("DRIVING BACKWARD");
-
-          else if (LEFT)
-            client.println("TURNING LEFT");
-
-          else if (RIGHT)
-            client.println("TURNING RIGHT");
-
-          else
-            client.println("PROBABLY NOT DRIVING");
-          // End print drive status
-
-          //printing LED status
-          client.print("LED status: ");
-          if (LEDON)
-            client.println("ULTRAVIOLET ON");
-
-          else if (LED2ON)
-            client.println("INFERRED ON");
-
-          else
-            client.println("OFF");
-          // end second LED
-
-          client.println("");
-          //clearing string for next read
-          readString="";
-          //stopping client
-          client.stop();
-        }
-      }
-    }
-  }
-}
-
-// auto-activation function
-void autoActivat() {
-  // Begin variables for motion sensor (these were at the top)
-  int pirState = LOW; // we start, assuming no motion detected
-  int val;            // variable for reading the pin status
-  int pirMode = 0;    // determines if the relay closed already (0 = not closed yet)
-  // End variabled for motion sensor
-
-  /*val = digitalRead(pirPin);  // read input value and store it in val
-  if(digitalRead(pirPin) == HIGH) {
-    if (pirMode == 0) {
-      if (val != pirState) {            //look for 2 inconsistant readings
-        // turn main computer on
-        digitalWrite(relayPin1, HIGH);  // sets relay1 on
-        delay(1000);                    // waits for 1 second
-        digitalWrite(relayPin1, LOW);   // sets relay1 off
-        pirMode = pirMode + 1;   // relay has been on
-        //delay(50);
-      }
-    }
-  }
-  */
-}
-
-
+/*
+* Author: Gunther Cox
+* CC: Salvius Robot Project
+* Website: http://salviusrobot.blogspot.com
+*
+* This project has been made possible with funding from the following individuals:
+* Jennifer Cox, Adam Iredale, Janet Wise
+*/
+
+// FOR ETHERNET
+#include <Ethernet.h>
+#include <SPI.h>
+
+#include <Client.h>
+#include <Server.h>
+#include <Udp.h>
+
+// VARIABLES FOR MANUAL SETUP
+byte mac[] = {
+  0x90, 0xA2, 0xDA, 0x0D, 0x00, 0x8F }; // physical mac address
+byte ip[] = {
+  192, 168, 1, 177 };          // ip in lan
+byte gateway[] = {
+  192, 168, 0, 1 };       // internet access via router
+byte subnet[] = {
+  255, 255, 255, 0 };      //subnet mask
+EthernetServer server(80);
+
+//int pirPin = 3;    // PIR SENSOR
+int relayPin1 = 4; // relay connected to digital pin 4 (D3 on relay shield - on switch)
+int relayPin2 = 7; // relay connected to digital pin 5 (D2 on relay shield) - Inferred LEDs
+int relayPin3 = 6; // relay connected to digital pin 6 (D1 on relay shield) - Ultraviolte LEDs
+int relayPin4 = 5; // relay connected to digital pin 7 (D0 on relay shield) (not used)
+//pin 10 - RESERVED FOR ETHERNET SHIELD
+//pin 11 - RESERVED FOR ETHERNET SHIELD
+//pin 12 - RESERVED FOR ETHERNET SHIELD
+//pin 13 - RESERVED FOR ETHERNET SHIELD
+
+// STORES URL DATA
+String readString = String(30);
+
+// STATUS FLAGS
+boolean FORWARD = false;
+boolean BACKWARD = false;
+boolean LEFT = false;
+boolean RIGHT = false;
+boolean LEDON = false;
+boolean LED2ON = false;
+
+void setup(){
+  // Start Ethernet
+  Ethernet.begin(mac, ip, gateway, subnet);
+  pinMode(relayPin3, OUTPUT);  //Set pin 7 to output
+  pinMode(relayPin4, OUTPUT);
+
+  //  pinMode(pirPin, INPUT);        // declare sensor as input
+  pinMode(relayPin1, OUTPUT);    // declare relay1 as output
+  pinMode(relayPin2, OUTPUT);    // declare relay2 as output
+  pinMode(relayPin3, OUTPUT);    // declare relay3 as output
+  pinMode(relayPin4, OUTPUT);    // declare relay4 as output
+
+  /*digitalWrite(relayPin1, LOW);
+   digitalWrite(pirPin, LOW);
+   pirState = digitalRead(pirPin); // read the initial state
+   delay(60000);                   // pause before calibrating
+   */
+}
+
+void loop(){
+  // Create a client connection
+  EthernetClient client = server.available();
+  if (client) {
+    while (client.connected()) {
+      if (client.available()) {
+        char c = client.read();
+        //read char by char HTTP request
+        if (readString.length() < 100) {
+          readString += c; //store characters to string
+        }
+
+        if (c == '\n') {  //if HTTP request has ended
+
+          //dirty skip of "GET /favicon.ico HTTP/1.1"
+          if (readString.indexOf("?") <0) { /*skip everything*/
+          }
+
+          else
+
+            // BEGIN DRIVE CONTROL
+          if(readString.indexOf("N1=Forward") >0) {
+
+            // ITEM HAS TO BE TURNED ON
+            digitalWrite(relayPin1, HIGH);    // set the item on
+            FORWARD = true;
+          }
+
+          else {
+
+            // ITEM HAS TO BE TURNED OFF
+            digitalWrite(relayPin1, LOW);    // set the item off
+            FORWARD = false;
+          }
+
+          if (readString.indexOf("N2=BACKWARD") > 0) {
+            //item has to be turned ON
+            digitalWrite(relayPin2, HIGH);    // set the item on
+            BACKWARD = true;
+          }
+          else {
+            //item has to be turned OFF
+            digitalWrite(relayPin2, LOW);    // set the item off
+            BACKWARD = false;
+          }
+
+          if (readString.indexOf("N3=LEFT") > 0) {
+            //item has to be turned ON
+            digitalWrite(relayPin3, HIGH);    // set the item on
+            LEFT = true;
+          }
+          else {
+            //item has to be turned OFF
+            digitalWrite(relayPin3, LOW);    // set the item off
+            LEFT = false;
+          }
+
+          if (readString.indexOf("N4=RIGHT") > 0) {
+            //item has to be turned ON
+            digitalWrite(relayPin4, HIGH);    // set the item on
+            RIGHT = true;
+          }
+          else {
+            //item has to be turned OFF
+            digitalWrite(relayPin4, LOW);    // set the item off
+            RIGHT = false;
+          }
+          // end drive control
+
+          //lets check if LED should be lighted
+          if (readString.indexOf("L=ON") >0) {
+            //led has to be turned ON
+            digitalWrite(relayPin3, HIGH);    // set the LED on
+            LEDON = true;
+          }
+          else if (readString.indexOf("L2=ON") >0) {
+            //led has to be turned ON
+            digitalWrite(relayPin4, HIGH);    // set the LED on
+            LED2ON = true;
+          }
+          //led has to be turned OFF
+          else {
+            //led has to be turned OFF
+            digitalWrite(relayPin4, LOW);    // set the LED OFF
+            LED2ON = false;
+            digitalWrite(relayPin3, LOW);    // set the LED OFF
+            LEDON = false;
+          }
+
+          // now output HTML data starting with standart header
+          client.println("HTTP/1.1 200 OK");
+          client.println("Content-Type: text/html");
+          client.println();
+          client.println("<link href='http://192.168.1.2/bootstrap/css/bootstrap.css' rel='stylesheet'>");
+
+          client.println("<form method=get name=NAV>");
+          client.println("<input type=submit name=N1 value=FORWARD>");
+          client.println("<input type=submit name=N3 value=LEFT><input type=submit value=STOP><input type=submit name=N4 value=RIGHT>");
+          client.println("<input type=submit name=N2 value=BACKWARD>");
+
+          //controlling leds via buttons (address will look like http://192.168.1.177/?L=ON when submited)
+          if (LEDON)
+            client.println("<form method=get name=LED><input type=submit value=OFF></form>");
+          else
+            client.println("<form method=get name=LED><input type=submit name=L value=ON></form>");
+
+          if (LED2ON)  // begin second LED
+            client.println("<form method=get name=LED2><input type=submit value=OFF></form>
");
+          else
+            client.println("<form method=get name=LED2><input type=submit name=L2 value=ON></form>");
+          client.println("</form>");
+
+          // Begin print drive status
+          if (FORWARD)
+            client.println("DRIVING FORWARD");
+
+          else if (BACKWARD)
+            client.println("DRIVING BACKWARD");
+
+          else if (LEFT)
+            client.println("TURNING LEFT");
+
+          else if (RIGHT)
+            client.println("TURNING RIGHT");
+
+          else
+            client.println("PROBABLY NOT DRIVING");
+          // End print drive status
+
+          //printing LED status
+          client.print("LED status: ");
+          if (LEDON)
+            client.println("ULTRAVIOLET ON");
+
+          else if (LED2ON)
+            client.println("INFERRED ON");
+
+          else
+            client.println("OFF");
+          // end second LED
+
+          client.println("");
+          //clearing string for next read
+          readString="";
+          //stopping client
+          client.stop();
+        }
+      }
+    }
+  }
+}
+
+// auto-activation function
+void autoActivat() {
+  // Begin variables for motion sensor (these were at the top)
+  int pirState = LOW; // we start, assuming no motion detected
+  int val;            // variable for reading the pin status
+  int pirMode = 0;    // determines if the relay closed already (0 = not closed yet)
+  // End variabled for motion sensor
+
+  /*val = digitalRead(pirPin);  // read input value and store it in val
+  if(digitalRead(pirPin) == HIGH) {
+    if (pirMode == 0) {
+      if (val != pirState) {            //look for 2 inconsistant readings
+        // turn main computer on
+        digitalWrite(relayPin1, HIGH);  // sets relay1 on
+        delay(1000);                    // waits for 1 second
+        digitalWrite(relayPin1, LOW);   // sets relay1 off
+        pirMode = pirMode + 1;   // relay has been on
+        //delay(50);
+      }
+    }
+  }
+  */
+}
+
+


Switching to 6byte API key - still 2^48 possibilities :)

--- arduino/arduino.ino
+++ arduino/arduino.ino
@@ -21,7 +21,7 @@
 #define USE_STROMBEWUSST_SERVER
 #define STROMBEWUSST_IP (188, 40, 78, 147)
 #define STROMBEWUSST_PORT 8888
-#define STROMBEWUSST_KEY {49,50,51,52,53,54,55,56,57,48,49,50,51,52,53,54};
+#define STROMBEWUSST_KEY {0xAA,0xBB,0xCC,0xDD,0xEE,0xFF};

 // TriggerPin - the PIN that gets HIGH when 1.25W/h were used on the line
 #define TRIGGER_PIN 8
@@ -33,6 +33,8 @@
 #define STORAGE_HOURS 1

 #define SERVER_PORT 80
+//#define LOCAL
+
 // *************************************

 #ifdef LOCAL
@@ -93,7 +95,7 @@

 #ifdef USE_STROMBEWUSST_SERVER
   // UDP Format: <16xkey><1xtimeframe><1xticks>
-  byte udpBuffer[18] = STROMBEWUSST_KEY;
+  byte udpBuffer[8] = STROMBEWUSST_KEY;
   IPAddress strombewusstIP STROMBEWUSST_IP;
 #endif

@@ -146,7 +148,7 @@

   #ifdef USE_STROMBEWUSST_SERVER
     // UDP Format: <32xkey><1xtimeframe><1xticks>
-    udpBuffer[16] = (byte)TIMEFRAME;
+    udpBuffer[6] = (byte)TIMEFRAME;
     udp.begin(STROMBEWUSST_PORT);
   #endif
 }
@@ -412,9 +414,9 @@
   Serial.println("[strombewusst] push!");

   // Set the last byte to the latest storage field
-  udpBuffer[17] = (byte)storageSum(1);
+  udpBuffer[7] = (byte)storageSum(1);
   udp.beginPacket(strombewusstIP, STROMBEWUSST_PORT);
-  udp.write(udpBuffer, 18);
+  udp.write(udpBuffer, 8);
   udp.endPacket();
 }
 #endif


-Show correct light status.

-Show correct light status.

--- tfttask.ino
+++ tfttask.ino
@@ -111,24 +111,32 @@

 void showMenu()
 {
+  static lightStatus_t lastStatus;
+
   if ( tftClearScreen )
   {
-    ledcWrite( TFT_BACKLIGHT_CHANNEL, 0 );
     tft.fillScreen( ILI9341_BLACK );
     drawMenuButtons();
     drawBacklightSlider();
     ledcWrite( TFT_BACKLIGHT_CHANNEL, map( tftBrightness, 0, 100, 0, backlightMaxvalue ) );
     tftClearScreen = false;
+    lastStatus = lightStatus;
   }

   /* check if tftBrightness has changed */
   if ( map( tftBrightness, 0, 100, 0, backlightMaxvalue ) != ledcRead( TFT_BACKLIGHT_CHANNEL ) )
-  {
-    //set new backlight value
+  { /* set new backlight value */
     ledcWrite( TFT_BACKLIGHT_CHANNEL, map( tftBrightness, 0, 100, 0, backlightMaxvalue ) );
     drawBacklightSlider();
   }

+  /* check if light status has changed */
+  if ( lastStatus != lightStatus )
+  {
+    drawMenuButtons();
+    lastStatus = lightStatus;
+  }
+
   if ( touch.touched() )
   {
     TS_Point p = touch.getPoint();
@@ -136,17 +144,14 @@
     if ( buttonPressed( LIGHTSON_BUTTON , p ) )
     {
       lightsOn();
-      drawMenuButtons();
     }
     else if ( buttonPressed( LIGHTSOFF_BUTTON , p ) )
     {
       lightsOff();
-      drawMenuButtons();
     }
     else if ( buttonPressed( LIGHTSAUTO_BUTTON , p ) )
     {
       lightsAuto();
-      drawMenuButtons();
     }
     else if ( buttonPressed( sliderArea , p ) )
     {
@@ -154,7 +159,6 @@

       touchedLocation = mapToTft( p.x, p.y );
       tftBrightness = map( touchedLocation.y , SLIDER_YPOS, SLIDER_HEIGHT + SLIDER_YPOS, 100, 0 );
-      drawBacklightSlider();
     }
     else if ( buttonPressed( EXIT_BUTTON , p ) )
     {


add delay back

add delay back

--- examples/piface/piface.ino
+++ examples/piface/piface.ino
@@ -34,7 +34,9 @@
     }
   }
   digitalWrite(mcp23s17.pin(2), HIGH);
+  delay(500);

   digitalWrite(mcp23s17.pin(2), LOW);
+  delay(500);

 }


Test use of mavlink for feedback (not working so far)

--- Arduino/GroundUnit/GroundUnit.ino
+++ Arduino/GroundUnit/GroundUnit.ino
@@ -14,6 +14,7 @@
 #include <PID_v1.h>       // From https://github.com/br3ttb/Arduino-PID-Library/tree/master/PID_v1
 #include <RH_ASK.h>
 #include <SPI.h> // Not actualy used but needed to compile
+#include <MavlinkForArduino.h>

 // Port definition
 #define      TX_PIN 8 // Plug to Sabertooth RX
@@ -54,6 +55,7 @@
 uint8_t buflen = sizeof(buf);
 uint8_t data[4];  // 2 element array of unsigned 8-bit type, holding Joystick readings
 RH_ASK driver(4800, RF_DATA_PIN, 6);
+boolean isRFUpdated = false;
 // RECEPTEUR : DATA D11

 // PID for robust control
@@ -156,7 +158,7 @@
 	{
           data[i] = buf[i];
         }
-
+        isRFUpdated = true;
     }
 }

@@ -192,6 +194,7 @@
         }
         if (feedback_request.isUpdated())
         {
+          // $ORFBR,0*57
           isFeedbackRequested = true;
           digitalWrite(LED_PIN, HIGH);
         }
@@ -235,9 +238,40 @@

 void sendFeedback()
 {
+  mavlink_message_t msg;
+  uint8_t bufout[MAVLINK_MAX_PACKET_LEN];
+  uint16_t len;
+  uint64_t time_us = micros();
+  int group_mlx = 0;
+  uint8_t system_id = 100;
+  uint8_t target_system = system_id;
+  uint8_t component_id = 1;
+  uint8_t target_component = 2;// Sabertooth
+
   // All the feedback values are normalized in the range 0-1023 (10 bits resolution)
   if (isFeedbackRequested)
   {
+
+    if (isRFUpdated)
+    {
+      float fdbk[8];//fdbk
+      fdbk[0] = float(Input1);
+      fdbk[1] = float(Input2);
+      fdbk[2] = float(Input3);
+
+      isRFUpdated = false;
+
+      //mavlink_msg_actuator_control_target_pack(system_id, component_id, &msg, time_us, group_mlx, fdbk);
+      //len = mavlink_msg_to_send_buffer(bufout, &msg);
+      //Serial.write(bufout, len);
+    }
+    float orders[8];
+    orders[0] = float(power1/127.);
+    orders[1] = float(power2/127.);
+    //mavlink_msg_set_actuator_control_target_pack(system_id, component_id, &msg, time_us, group_mlx, target_system, target_component, orders);
+    //len = mavlink_msg_to_send_buffer(bufout, &msg);
+    //Serial.write(bufout, len);
+
     Serial.print((power1+127)*4);
     Serial.print(", ");
     Serial.print((power2+127)*4);


DHT sparkline example

DHT sparkline example

[#20]


Implement 'Averaging of N-X ADC samples'

--- battery-monitor.ino
+++ battery-monitor.ino
@@ -5,6 +5,7 @@
 #define CONNECT_WAIT_MILLIS 10000
 #define LOW_THRESHOLD 12000 // milliVolts
 #define ADC_SAMPLES 20
+#define ADC_DISPERSED 2
 #define SLEEP_SECS 3600 // 1 hour
 //#define SLEEP_SECS 15

@@ -71,7 +72,7 @@

 void publishVoltageEvent() {
     char eventData[5];
-    uint16_t milliVolts = getAvgBatteryMilliVolts();
+    uint16_t milliVolts = getCentralAvgBatteryMilliVolts();
     sprintf(eventData, "%.1f", milliVolts / 1000.0);
     if (milliVolts < LOW_THRESHOLD) {
         Particle.publish(LOW_EVENT, eventData, 60, PRIVATE);
@@ -106,8 +107,28 @@
     flashing = true;
 }

+// Averaging of N-X ADC samples as per ST Application Note AN4073
+uint16_t getCentralAvgBatteryMilliVolts() {
+    uint32_t mV = 0;
+    uint16_t readings[ADC_SAMPLES];
+
+    for (int i = 0; i < ADC_SAMPLES; i++) {
+        readings[i] = readMilliVolts(BATTERY_PIN);
+        delay(3);
+    }
+
+    qsort(readings, ADC_SAMPLES, sizeof(uint16_t), uint16Compare);
+
+    for (int i = ADC_DISPERSED; i < ADC_SAMPLES - ADC_DISPERSED; i++) {
+        mV += readings[i];
+    }
+
+    return round(mV * DIV_RATIO / (float) ADC_SAMPLES - (2 * ADC_DISPERSED));
+}
+
+// Averaging of N ADC samples as per ST Application Note AN4073
 uint16_t getAvgBatteryMilliVolts() {
-    uint16_t mV = 0;
+    uint32_t mV = 0;
     for (int i = 0; i < ADC_SAMPLES; i++) {
         mV += readMilliVolts(BATTERY_PIN);
         delay(3);
@@ -123,3 +144,16 @@
 uint16_t readMilliVolts(int pin) {
 	return map(analogRead(pin), 0, 4095, 0, VCC);
 }
+
+int uint16Compare (const void *pa, const void *pb) {
+    uint16_t a = *(const uint16_t *) pa;
+    uint16_t b = *(const uint16_t *) pb;
+
+    if (a < b) {
+        return -1;
+    } else if (a > b) {
+        return 1;
+    } else {
+        return 0;
+    }
+}


working basic implementation without SD i/o

--- src/main/arduino/templogger/templogger.ino
+++ src/main/arduino/templogger/templogger.ino
@@ -1,17 +1,19 @@
+#include <Wire.h>
+#include <OneWire.h>
+#include <RTC_DS3231.h>

-#include <Wire.h>
-//#include <SPI.h>
-#include <RTC_DS3231.h>  // rtc
+#define LOOP_DELAY 1000 //ms delay time in loop
+//#define LOOP_DELAY 59000 //ms delay time in loop
+#define TEMP_PIN 38 // signal pin for DS18S20

 RTC_DS3231 RTC;
+OneWire ds(TEMP_PIN);

 void setup() {
-
+  Serial.begin(57600);
   Wire.begin(); // I2C init as master

   setupRTC();
-
-
 }

 void setupRTC() {
@@ -27,18 +29,100 @@
   // this may result in a few-second offset between "real" time and
   // RTC time, but this is negligible as temperature will not change
   // drastically in a matter of a few seconds
-  DateTime now = RTC.now();
-  DateTime compiled = DateTime(__DATE__, __TIME__);
-  if (now.unixtime() < compiled.unixtime()) {
-    RTC.adjust(DateTime(__DATE__, __TIME__));
-  }
+  //DateTime now = RTC.now();
+  //DateTime compiled = DateTime(__DATE__, __TIME__);
+  //if (now.unixtime() < compiled.unixtime()) {
+  //  RTC.adjust(DateTime(__DATE__, __TIME__));
+  //}
 }

 void loop() {

+  /*
+  Toggle Count over 5000ms with PWM_COUNT of 1020:  0
+  2014/12/23 17:26:27
+   since midnight 1/1/1970 = 1419355587s = 16427d
+   now + 7d + 30s: 2014/12/30 17:26:57
+  Temp as float: 25.2500000000
+  Temp as word: 25.25
+  */

+  DateTime now = RTC.now();
+  printTime(now);

+  float temperature = getTemp();
+  printTemp(temperature);

+  // calculate the remaining time
+
+  // sleep for the remaining time
+
+  delay(LOOP_DELAY); // DEBUG
 }

+void printTime(DateTime now) {
+  Serial.print(now.year(), DEC);
+  Serial.print('/');
+  Serial.print(now.month(), DEC);
+  Serial.print('/');
+  Serial.print(now.day(), DEC);
+  Serial.print(' ');
+  Serial.print(now.hour(), DEC);
+  Serial.print(':');
+  Serial.print(now.minute(), DEC);
+  Serial.print(':');
+  Serial.print(now.second(), DEC);
+  Serial.println();
+}

+void printTemp(float temperature) {
+  Serial.println(temperature);
+}
+
+float getTemp() {
+//  http://bildr.org/2011/07/ds18b20-arduino/
+ //returns the temperature from one DS18S20 in DEG Celsius
+
+   byte data[12];
+   byte addr[8];
+
+   if ( !ds.search(addr)) {
+     //no more sensors on chain, reset search
+     ds.reset_search();
+     return -1000;
+   }
+
+   if ( OneWire::crc8( addr, 7) != addr[7]) {
+     Serial.println("CRC is not valid!");
+     return -1000;
+   }
+
+   if ( addr[0] != 0x10 && addr[0] != 0x28) {
+     Serial.print("Device is not recognized");
+     return -1000;
+   }
+
+   ds.reset();
+   ds.select(addr);
+   ds.write(0x44,1); // start conversion, with parasite power on at the end
+
+   byte present = ds.reset();
+   ds.select(addr);
+   ds.write(0xBE); // Read Scratchpad
+
+
+   for (int i = 0; i < 9; i++) { // we need 9 bytes
+    data[i] = ds.read();
+   }
+
+   ds.reset_search();
+
+   byte MSB = data[1];
+   byte LSB = data[0];
+
+   float tempRead = ((MSB << 8) | LSB); //using two's compliment
+   float TemperatureSum = tempRead / 16;
+
+   return TemperatureSum;
+
+}


fixed JS developer C++ compile issue

fixed JS developer C++ compile issue

--- grill.ino
+++ grill.ino
@@ -21,8 +21,6 @@
 TargetKnob targetKnob(A1);

 void setup() {
-  // turn the PID on
-  // pid.SetMode(AUTOMATIC);
 }

 void loop() {
@@ -36,14 +34,13 @@
       pid.SetMode(MANUAL);
     }
     fan.powerTo(0);
-    return;
   } else {
     if (pid.GetMode() != AUTOMATIC) {
       pid.SetMode(AUTOMATIC);
     }
-    if ((output == 0 || output == 100) && pid.GetKi() !== 0) {
+    if ((output == 0 || output == 255) && pid.GetKi() != 0) {
       pid.SetTunings(P, 0, D);
-    } else if (pid.GetKi() !== I) {
+    } else if (pid.GetKi() != I) {
       pid.SetTunings(P, I, D);
     }
     pid.Compute();


[Arduino] Don't lower watchdog after setup.

Signed-off-by: Juri Berlanda <738ab29df2b6849f3ca85cffd121042aabdbdda0@hotmail.com>

--- Arduino/vj-flight-controller/vj-flight-controller.ino
+++ Arduino/vj-flight-controller/vj-flight-controller.ino
@@ -221,10 +221,6 @@
   pinMode(LED_PIN, OUTPUT);

   while (Serial.available() && Serial.read()); // empty buffer
-
-  // Lower Watchdog to 60msec
-  wdt_disable();
-  wdt_enable(WDTO_60MS);
 }

 // ================================================================


Add files via upload

Add files via upload

Merged MoveActuator.ino with Jeremy's version; added outputToSerial function to base.

--- MoveActuator/MoveActuator.ino
+++ MoveActuator/MoveActuator.ino
@@ -22,9 +22,9 @@
 #include <Settings.h>

 // Define the tests to do.
-//#define BRAKE_RAMP
+#define BRAKE_RAMP
 #define STEER_RAMP
-//#define MOTOR_RAMP
+#define MOTOR_RAMP
 // If operating with the MegaShieldDB, we can use the Digital Analog Converter to move the vehicle
 #define DAC

@@ -214,7 +214,7 @@
 void setup()
 {
     //Set up pin modes and interrupts, call serial.begin and call initialize.
-    Serial.begin(19200);
+    Serial.begin(9600);

     // SPI: set the slaveSelectPin as an output:
     pinMode (SelectAB, OUTPUT);
@@ -274,12 +274,9 @@
  // apply steering
 #ifdef STEER_RAMP
     SteerPosition += SteerIncrement;
-//    moveSteer(Straight);   // TCF
     if (SteerPosition > HardLeft || SteerPosition < HardRight)
-    {
         SteerIncrement = -SteerIncrement;
-        moveSteer(SteerPosition);
-    }
+    moveSteer(SteerPosition);
 #endif  // Steer_RAMP
   outputToSerial();
 }
@@ -401,4 +398,3 @@
 }
 /*---------------------------------------------------------------------------------------*/

-


Исправлена GraphMode

Исправлена GraphMode

Переписана с использованием простого счетчика и функции millis()

--- general_code14.ino
+++ general_code14.ino
@@ -410,98 +410,106 @@

 void GraphMode(MyDataOutput data)
 {
-
-  //Выводим иконки
-  display.drawBitmap(0, 0, temp, 64, 49, WHITE);
-  display.setTextSize(1);
-  display.setCursor(100,10);
-  display.print("0");
-  display.setTextSize(3);
-  display.setCursor(105,15);
-  display.println("C");
-  display.setTextSize(5);
-  display.setCursor(35,65);
-  display.print(data.avtemp,0);
-
-  if (data.avtemp > 30)
-{
-   display.fillRect(0, 125, 128, 5, RED);
-  }
-else
-{
-   display.fillRect(0, 125, 128, 5, GREEN);
-  }
-
-  delay(5000);
-  display.clearScreen();
-
-  display.drawBitmap(0, 0, hum, 33, 45, WHITE);
-  display.setTextSize(3);
-  display.setCursor(105,15);
-  display.println("%");
-  display.setTextSize(5);
-  display.setCursor(35,65);
-  display.print(data.hum,0);
+
+if (millis() - previousMillis > interval)
+{
+  previousMillis = millis();
+  switch (slide)
+  {
+    case 0:
+    display.clearScreen();
+    display.drawBitmap(0, 0, temp, 64, 49, WHITE);
+    display.setTextSize(1);
+    display.setCursor(100,10);
+    display.print("0");
+    display.setTextSize(3);
+    display.setCursor(105,15);
+    display.println("C");
+    display.setTextSize(5);
+    display.setCursor(35,65);
+    display.print(data.avtemp,0);
+
+    if (data.avtemp > 30)
+  {
+     display.fillRect(0, 125, 128, 5, RED);
+    }
+  else
+  {
+         display.fillRect(0, 125, 128, 5, GREEN);
+    }
+        break;
+    case 1:
+     display.clearScreen();
+     display.drawBitmap(0, 0, hum, 33, 45, WHITE);
+     display.setTextSize(3);
+     display.setCursor(105,15);
+     display.println("%");
+     display.setTextSize(5);
+     display.setCursor(35,65);
+     display.print(data.hum,0);

-  if (data.hum > 70 || data.hum < 30 )
-{
-   display.fillRect(0, 125, 128, 5, RED);
-  }
-else
-{
-   display.fillRect(0, 125, 128, 5, GREEN);
-  }
-
-  delay(5000);
-  display.clearScreen();
-
-  display.drawBitmap(0, 0, CO2, 64, 50, WHITE);
-  display.setTextSize(2);
-  display.setCursor(85,15);
-  display.println("ppm");
-  display.setTextSize(5);
-
-  if(data.co2 < 999)
-  {
-    display.setCursor(23,65);
-    }
-  else
-  {
-    display.setCursor(5,65);
-    }
-  display.print(data.co2,0);
-
-  if (data.co2 > 750)
-{
-   display.fillRect(0, 125, 128, 5, RED);
-  }
-else
-{
-   display.fillRect(0, 125, 128, 5, GREEN);
-  }
-
-  delay(5000);
-  display.clearScreen();
-
-  display.drawBitmap(0, 0, airpress, 40, 49, WHITE);
-  display.setTextSize(3);
-  display.setCursor(85,15);
-  display.print(utf8rus("мм"));
-  display.setTextSize(5);
-  display.setCursor(23,65);
-  display.print(data.ap,0);
-
-  if (data.ap > 750)
-{
-   display.fillRect(0, 125, 128, 5, RED);
-  }
-else
-{
-   display.fillRect(0, 125, 128, 5, GREEN);
-  }
-
-  delay(5000);
-  display.clearScreen();
+     if (data.hum > 70 || data.hum < 30 )
+   {
+      display.fillRect(0, 125, 128, 5, RED);
+     }
+   else
+   {
+    display.fillRect(0, 125, 128, 5, GREEN);
+   }
+         break;
+    case 2:
+     display.clearScreen();
+     display.drawBitmap(0, 0, CO2, 64, 50, WHITE);
+     display.setTextSize(2);
+     display.setCursor(85,15);
+     display.println("ppm");
+     display.setTextSize(5);
+
+     if(data.co2 < 999)
+     {
+        display.setCursor(23,65);
+       }
+     else
+     {
+        display.setCursor(5,65);
+       }
+      display.print(data.co2,0);
+
+     if (data.co2 > 750)
+   {
+      display.fillRect(0, 125, 128, 5, RED);
+     }
+   else
+   {
+      display.fillRect(0, 125, 128, 5, GREEN);
+     }
+         break;
+    case 3:
+     display.clearScreen();
+     display.drawBitmap(0, 0, airpress, 40, 49, WHITE);
+     display.setTextSize(3);
+     display.setCursor(85,15);
+     display.print(utf8rus("мм"));
+     display.setTextSize(5);
+     display.setCursor(23,65);
+     display.print(data.ap,0);
+
+   if (data.ap > 750)
+   {
+      display.fillRect(0, 125, 128, 5, RED);
+     }
+   else
+   {
+      display.fillRect(0, 125, 128, 5, GREEN);
+     }
+         break;
+  }
+  slide++;
+  if (slide > 3)
+  {
+    slide = 0;
+  }
+ }

 }


Fix typo: SPI_CLOCK_DIV128

Fix typo: SPI_CLOCK_DIV128

--- build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
+++ build/shared/examples/11.ArduinoISP/ArduinoISP/ArduinoISP.ino
@@ -54,14 +54,9 @@
 #define LED_PMODE 7
 #define PROG_FLICKER true

-#if defined(ARDUINO_ARCH_SAM) or defined(ARDUINO_ARCH_SAMD)
-
-#define SPI_CLOCK_DIV_MAX	255
-
-#else
+#if !defined(ARDUINO_ARCH_SAM) and !defined(ARDUINO_ARCH_SAMD)

 #define USE_HARDWARE_SPI
-#define SPI_CLOCK_DIV_MAX	SPI_CLOCK_DIV_128

 #endif

@@ -101,7 +96,10 @@

 #ifdef USE_HARDWARE_SPI
 #include "SPI.h"
+#define SPI_CLOCK_DIV_MAX	SPI_CLOCK_DIV128
 #else
+
+#define SPI_CLOCK_DIV_MAX	255

 class BitBangedSPI {
   public:


Update rgbled.ino

Update rgbled.ino

--- 3/rgbled/rgbled.ino
+++ 3/rgbled/rgbled.ino
@@ -8,23 +8,15 @@
     pinMode(BLUE, OUTPUT);
 }

-
-/** Dims an LED on the pin up to max brightness, then back down to off.
- */
-void dimLED(int pin) {
-    for(int i = 0; i <= 255; i++) {
-        analogWrite(pin, i);
-        delay(1);
-    }
-
-    for(int i = 255; i > 0; i--) {
-        analogWrite(pin, i);
-        delay(1);
-    }
+void flashColor(int red, int green, int blue) {
+    analogWrite(RED, red);
+    analogWrite(GREEN, green);
+    analogWrite(BLUE, blue);
+    delay(50);
 }

 void loop() {
-    dimLED(BLUE);
-    dimLED(RED);
-    dimLED(GREEN);
+    flashColor(100, 150, 255);
+    flashColor(200, 25, 100);
+    flashColor(187, 201, 17);
 }


remove out-of-date TacanPanel example

remove out-of-date TacanPanel example

--- examples/TacanPanel/TacanPanel.ino
+++ examples/TacanPanel/TacanPanel.ino
@@ -1,65 +0,0 @@
-#include <DcsBios.h>
-#include <Servo.h>
-#include <Wire.h>
-#include <LedControl.h>
-
-DcsBios::ProtocolParser parser;
-
-DcsBios::Switch2Pos tacanTestButton("TACAN_TEST_BTN", A6);
-DcsBios::ActionButton xyToggleButton("TACAN", "XY", 9);
-byte modeSelectorPins[] = {2,3,4,5,6};
-DcsBios::SwitchMultiPos modeSelector("TACAN_MODE", modeSelectorPins, 5);
-DcsBios::Potentiometer volumeKnob("TACAN_VOL", A0);
-DcsBios::RotaryEncoder khzKnob("TACAN", "-1", "+1", A1, A2);
-DcsBios::RotaryEncoder mhzKnob("TACAN", "-10", "+10", 7, 8);
-DcsBios::LED tacanTestLED("TACAN_TEST", A3);
-
-
-LedControl lc=LedControl(11,12,10,1);
-
-void setup() {
-  Serial.begin(500000);
-  Wire.begin(9);
-
-  lc.shutdown(0,false);
-  lc.setIntensity(0,8);
-  lc.clearDisplay(0);
-
-  lc.setDigit(0,0,8,false);
-  lc.setDigit(0,1,5,false);
-  lc.setDigit(0,2,5,false);
-  lc.setDigit(0,3,4,false);
-}
-
-void loop() {
-  while(Serial.available()) {
-    parser.processChar(Serial.read());
-  }
-
-  DcsBios::PollingInput::pollInputs();
-}
-
-void onDcsBiosMessage(const char* msg, const char* arg) {
-  if (strcmp(msg, "TACAN_CHANNEL") == 0) {
-    lc.setChar(0, 0, arg[0], false);
-    lc.setChar(0, 1, arg[1], false);
-    lc.setChar(0, 2, arg[2], false);
-    if (arg[3] == 'X') {
-      lc.setDigit(0, 3, 4, false);
-    } else {
-      lc.setChar(0, 3, ' ', false);
-      lc.setLed(0, 3, 1, true);
-      lc.setLed(0, 3, 2, true);
-      lc.setLed(0, 3, 6, true);
-    }
-  }
-}
-
-void sendDcsBiosMessage(const char* msg, const char* arg) {
-  Wire.beginTransmission(8);
-  Wire.write(msg);
-  Wire.write(' ');
-  Wire.write(arg);
-  Wire.write('\n');
-  Wire.endTransmission();
-}


Removes usart1 enable/disable mcu_dis/enable_usart1


see http://bbs.aprbrother.com/t/cactus-micro-r2-temperature-logger/356/7

--- examples/thingspeak/thingspeak.ino
+++ examples/thingspeak/thingspeak.ino
@@ -15,7 +15,7 @@

 dht DHT;

-ESP esp(&Serial1, &Serial, 4);
+ESP esp(&Serial1, &Serial, PIN_ENABLE_ESP);

 REST rest(&esp);


Delete JsonParserExample.ino

Delete JsonParserExample.ino

--- src/third-party/arduino-json-5.1.1/examples/JsonParserExample/JsonParserExample.ino
+++ src/third-party/arduino-json-5.1.1/examples/JsonParserExample/JsonParserExample.ino
@@ -1,67 +0,0 @@
-// Copyright Benoit Blanchon 2014-2016
-// MIT License
-//
-// Arduino JSON library
-// https://github.com/bblanchon/ArduinoJson
-// If you like this project, please add a star!
-
-#include <ArduinoJson.h>
-
-void setup() {
-  Serial.begin(9600);
-  while (!Serial) {
-    // wait serial port initialization
-  }
-
-  // Memory pool for JSON object tree.
-  //
-  // Inside the brackets, 200 is the size of the pool in bytes,
-  // If the JSON object is more complex, you need to increase that value.
-  StaticJsonBuffer<200> jsonBuffer;
-
-  // StaticJsonBuffer allocates memory on the stack, it can be
-  // replaced by DynamicJsonBuffer which allocates in the heap.
-  // It's simpler but less efficient.
-  //
-  // DynamicJsonBuffer  jsonBuffer;
-
-  // JSON input string.
-  //
-  // It's better to use a char[] as shown here.
-  // If you use a const char* or a String, ArduinoJson will
-  // have to make a copy of the input in the JsonBuffer.
-  char json[] =
-      "{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";
-
-  // Root of the object tree.
-  //
-  // It's a reference to the JsonObject, the actual bytes are inside the
-  // JsonBuffer with all the other nodes of the object tree.
-  // Memory is freed when jsonBuffer goes out of scope.
-  JsonObject& root = jsonBuffer.parseObject(json);
-
-  // Test if parsing succeeds.
-  if (!root.success()) {
-    Serial.println("parseObject() failed");
-    return;
-  }
-
-  // Fetch values.
-  //
-  // Most of the time, you can rely on the implicit casts.
-  // In other case, you can do root["time"].as<long>();
-  const char* sensor = root["sensor"];
-  long time = root["time"];
-  double latitude = root["data"][0];
-  double longitude = root["data"][1];
-
-  // Print values.
-  Serial.println(sensor);
-  Serial.println(time);
-  Serial.println(latitude, 6);
-  Serial.println(longitude, 6);
-}
-
-void loop() {
-  // not used in this example
-}


Update ac.io to turn on/off ac

Update ac.io to turn on/off ac


Add slewrate and tune PID to avoid loss of control Format serial output to use serial plotter

--- Arduino/AK60-6/AK60-6.ino
+++ Arduino/AK60-6/AK60-6.ino
@@ -18,24 +18,29 @@
 float Kd_MAX = 5;
 float Test_Pos = 0.0;

- float pos = 0;
+int dt_ms = 20;
+
+ float order = 0;
+ float setpoint = 0;
+ float slew_rate = 20;
 ServoInputPin<6> servo;
 void setup() {
   Serial.begin(9600);
   //while (!Serial);
   delay(3000);

-  Serial.println("CAN Sender");
+  //Serial.println("CAN Sender");

   // start the CAN bus at 500 kbps
   if (!CAN.begin(1000E3)) {
-    Serial.println("Starting CAN failed!");
+    //Serial.println("Starting CAN failed!");
     while (1);
   }
-
+  setZero(0x01);
   setMotormode(0x01);
-  setZero(0x01);
+
   //exitMotormode(0x01);
+
 }

 float mapfloat(float x, float in_min, float in_max, float out_min, float out_max)
@@ -47,11 +52,14 @@
   float angle = servo.getAngle();  // get angle of servo (0 - 180)

-  pos = mapfloat(angle, 0, 180, P_MIN, P_MAX);
-  Serial.println(pos);
-  setCommand(0x01, pos, 0.0, 3, 1, 0*pos);
+  order = mapfloat(angle, 0, 180, P_MIN, P_MAX);
+  Serial.print("order:"); Serial.print(order); Serial.print(", ");
+  setpoint = setpoint + constrain(order-setpoint, -slew_rate * dt_ms/1000., slew_rate * dt_ms/1000.);
+  Serial.print("setpoint:"); Serial.print(setpoint); Serial.print(", ");
+  setCommand(0x01, setpoint, 0.0, 25, 5, 0*setpoint);
   readCAN();
-  delay(100);
+  Serial.println("");
+  delay(dt_ms);
   //
 }

@@ -184,12 +192,9 @@

    float speed = v;
    float torque = i;
-   Serial.print(position);
-   Serial.print("rad ");
-   Serial.print(speed);
-   Serial.print("rad/s ");
-   Serial.print(torque);
-   Serial.println("A");
+   Serial.print("position:"); Serial.print(position); Serial.print(", ");
+   Serial.print("speed:"); Serial.print(speed); Serial.print(", ");
+   Serial.print("intensity:"); Serial.print(torque); Serial.print(", ");
    }
  }


Tweaking comments

Tweaking comments

--- Arduino/Ziffer/Ziffer.ino
+++ Arduino/Ziffer/Ziffer.ino
@@ -30,7 +30,7 @@
   byte outbyte = 0;
   byte currentByte = 0;

-  //For loop for building a byte from bits
+  //Loop for building a byte from bits
   for(int j=0; j < 8; j++){
     //Pins are read using registers because its much faster than digitalRead()
     pinInput1 = (PINB >> 3) & B00000001;
@@ -45,6 +45,8 @@

   //Mix the current byte with the previous one
   outbyte = currentByte ^ previousByte;
+
+  //Send it to your computer
   Serial.write(outbyte);

   previousByte = currentByte;


cancel flow

cancel flow

--- gameboy.ino
+++ gameboy.ino
@@ -162,17 +162,24 @@
         trade_centre_state = TRADE_PENDING;
       }
     } else if(trade_centre_state == TRADE_PENDING && (in & 0x60) == 0x60) {
-      send = 0x60; // first pokemon
-      trade_pokemon = in - 0x60;
+      if (in == 0x6f) {
+        trade_centre_state = READY_TO_GO;
+        send = 0x6f;
+      } else {
+        send = 0x60; // first pokemon
+        trade_pokemon = in - 0x60;
+      }
     } else if(trade_centre_state == TRADE_PENDING && in == 0x00) {
       send = 0;
       trade_centre_state = TRADE_CONFIRMATION;
     } else if(trade_centre_state == TRADE_CONFIRMATION && (in & 0x60) == 0x60) {
+      send = in;
       if (in  == 0x61) {
         trade_pokemon = -1;
+        trade_centre_state = TRADE_PENDING;
+      } else {
+        trade_centre_state = DONE;
       }
-      send = in;
-      trade_centre_state = DONE;
     } else if(trade_centre_state == DONE && in == 0x00) {
       send = 0;
       trade_centre_state = INIT;


Updated control functions

Updated control functions

--- FumeHoodMonitor/HotPlatePowerRelay.ino
+++ FumeHoodMonitor/HotPlatePowerRelay.ino
@@ -1,15 +1,32 @@
 #define relayPin 18
+
+bool onFire = false;
+bool airHigh = false;
+bool oilHigh = false;

 void initializePowerRelay(){
   writeLCD("Starting PWR Relay..");
+  Serial.println("Starting Hot Plate Power Relay");
   pinMode(relayPin, OUTPUT);
+  digitalWrite(relayPin, HIGH);
+}
+
+void powerUpHotPlate(){
   digitalWrite(relayPin, LOW);
 }

-void powerUpHotPlate(){
+void powerDownHotPlate(){
   digitalWrite(relayPin, HIGH);
 }

-void powerDownHotPlate(){
-  digitalWrite(relayPin, LOW);
+void controlHotPlatePowerRelay(float airTemp, float oilTemp){
+  if (isFlamePresent() || isAirTempOnFire(airTemp) || isOilTempOnFire(oilTemp)) onFire = true;
+  else {
+    if (isOilTempHigh(oilTemp)) oilHigh = true;
+    else if (isOilTempLow(oilTemp)) oilHigh = false;
+    if (isAirTempHigh(airTemp)) airHigh = true;
+    else if (isAirTempLow(airTemp)) airHigh = false;
+  }
+  if(onFire || oilHigh || airHigh) powerDownHotPlate();
+  else powerUpHotPlate();
 }


Update Stabilisator.ino

Update Stabilisator.ino


[Minor] Formatting fix

[Minor] Formatting fix

--- arduino/agg_node/agg_node.ino
+++ arduino/agg_node/agg_node.ino
@@ -969,7 +969,7 @@
     Serial.print(" 'Source Node Id' : "); Serial.print((uint16_t)pPayload->uNodeId);Serial.print(",");
     Serial.print(" 'Dest Node Id' : "); Serial.print((uint16_t)pPayload->uRelayId);Serial.print(",");
     Serial.print(" 'pH' : "); Serial.print((uint16_t)pPayload->uPH);Serial.print(",");
-    Serial.print(" 'Conductivity' : "); Serial.println((uint16_t)pPayload->uConductivity);Serial.print(",");
+    Serial.print(" 'Conductivity' : "); Serial.print((uint16_t)pPayload->uConductivity);Serial.print(",");
     Serial.print(" 'Light' : "); Serial.print((uint16_t)pPayload->uLight);Serial.print(",");
     Serial.print(" 'Temp (Air)' : "); Serial.print((uint16_t)pPayload->uTempAir);Serial.print(",");
     Serial.print(" 'Humidity' : "); Serial.print((uint16_t)pPayload->uHumidity);Serial.print(",");
@@ -1009,3 +1009,4 @@

+


Remove dead code, fix formatting.

Remove dead code, fix formatting.

--- MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
+++ MicroView/WiFiModem-Menu/WiFiModem-Menu.ino
@@ -7,8 +7,6 @@
 /* TODO
  *  set ip tcp-mode 0x10 to disable remote configuration
  *  Confirm CheckTelnet() for inbound is working
- *  ATH1 handling
- *  +++ guard time for inbound
  *
  *
  *
@@ -20,7 +18,7 @@

 // Defining HAYES enables Hayes commands and disables the 1) and 2) menu options for telnet and incoming connections.
 // This is required to ensure the compiled code is <= 30,720 bytes
-#define HAYES
+//#define HAYES

 #ifdef MICROVIEW
 #include <MicroView.h>
@@ -108,11 +106,11 @@
 boolean Modem_QuietMode = false;
 boolean Modem_S0_AutoAnswer = false;
 char    Modem_S2_EscapeCharacter = '+';
-#endif    // HAYES

 #define COMMAND_BUFFER_SIZE  81
 char Modem_LastCommandBuffer[COMMAND_BUFFER_SIZE];
 char Modem_CommandBuffer[COMMAND_BUFFER_SIZE];
+#endif    // HAYES

 // Misc Values
 #define TIMEDOUT  -1
@@ -132,10 +130,6 @@
 #define AUTO_QLINK    3
 #define AUTO_CUSTOM   100   // TODO

-//#ifndef HAYES
-//byte autostart_mode = EEPROM.read(ADDR_AUTOSTART);    // 0-255 only
-//#endif
-
 // ----------------------------------------------------------
 // Arduino Setup Function

@@ -147,7 +141,7 @@
     uView.setFontType(0);
     uView.clear(ALL); // erase hardware memory inside the OLED controller
 #else // MICROVIEW
-    delay(3000);
+    delay(3000);   // Five WiFly time to boot
 #endif // MICROVIEW
     pinModeFast(C64_DCD, OUTPUT);
     Modem_DCDFollowsRemoteCarrier = EEPROM.read(ADDR_MODEM_DCD);
@@ -195,8 +189,6 @@
         updateEEPROMByte(ADDR_BAUD_HI,b);
     }

-    //setBaud(BAUD_RATE, false, true);
-
     //
     // Baud rate detection end
     //
@@ -220,16 +212,6 @@
     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);

     C64Serial.println();
     DisplayBoth(F("Wi-Fi Init..."));
@@ -252,13 +234,13 @@

     configureWiFly();

-        if (BAUD_RATE != 2400) {
-        delay(1000);
-        if(BAUD_RATE == 1200)
-            setBaudWiFi(2400);
-        else
-            setBaudWiFi(BAUD_RATE);
-        }
+    if (BAUD_RATE != 2400) {
+    delay(1000);
+    if(BAUD_RATE == 1200)
+        setBaudWiFi(2400);
+    else
+        setBaudWiFi(BAUD_RATE);
+    }
     baudMismatch = (BAUD_RATE != WiFly_BAUD_RATE ? 1 : 0);

     wifly.close();
@@ -281,59 +263,57 @@
     C64Println();
     ShowInfo(true);

-while (1)
-{
-    Display(F("READY."));
-
-    ShowPETSCIIMode();
-    C64Print(F("1. Telnet to host or BBS\r\n"
-                 "2. Phone Book\r\n"
-                 "3. Wait for incoming connection\r\n"
-                 "4. Configuration\r\n"
-                 "\r\n"
-                 "Select: "));
-
-    int option = ReadByte(C64Serial);
-    C64Serial.println((char)option);
-
-    switch (option)
-    {
-    case '1':
-        DoTelnet();
-        break;
-
-    case '2':
-        PhoneBook();
-        break;
-
-    case '3':
-        Incoming();
-        break;
+    while (1)
+    {
+        Display(F("READY."));
+
+        ShowPETSCIIMode();
+        C64Print(F("1. Telnet to host or BBS\r\n"
+                     "2. Phone Book\r\n"
+                     "3. Wait for incoming connection\r\n"
+                     "4. Configuration\r\n"
+                     "\r\n"
+                     "Select: "));
+
+        int option = ReadByte(C64Serial);
+        C64Serial.println((char)option);
+
+        switch (option)
+        {
+        case '1':
+            DoTelnet();
+            break;
+
+        case '2':
+            PhoneBook();
+            break;
+
+        case '3':
+            Incoming();
+            break;

-    case '4':
-            Configuration();
-        break;
+        case '4':
+                Configuration();
+            break;

-    case '\n':
-    case '\r':
-    case ' ':
-        break;
-
-    case 8:
-        SetPETSCIIMode(false);
-        break;
-
-    case 20:
-        SetPETSCIIMode(true);
-        break;
-
-    default:
-        C64Println(F("Unknown option, try again"));
-        break;
-    }
-}
-
-
+        case '\n':
+        case '\r':
+        case ' ':
+            break;
+
+        case 8:
+            SetPETSCIIMode(false);
+            break;
+
+        case 20:
+            SetPETSCIIMode(true);
+            break;
+
+        default:
+            C64Println(F("Unknown option, try again"));
+            break;
+        }
+    }
 #endif // HAYES
 }

@@ -386,9 +366,6 @@
             updateEEPROMByte(ADDR_MODEM_DCD,Modem_DCDFollowsRemoteCarrier);
             break;

-/*      case '4': ConfigureBaud();
-            break;*/
-
         case '5': RawTerminalMode();
             return;

@@ -507,7 +484,6 @@

         C64Println();
         DisplayPhoneBook();
-        //C64Print(F("\r\nSelect: #, m to modify, a to set\r\n""auto-start, 0 to go back: "));
         C64Print(F("\r\nSelect: #, m to modify, c to clear all\r\na to set auto-start, 0 to go back: "));

         char addressChar = ReadByte(C64Serial);
@@ -569,13 +545,6 @@
             {
                 C64Serial.print(phoneBookNumber);
                 updateEEPROMByte(ADDR_HOST_AUTO, phoneBookNumber);
-                /*switch (phoneBookNumber) {
-                    case 0:
-                    break;
-
-                    default:
-                    updateEEPROMByte(ADDR_HOST_AUTO, phoneBookNumber);
-                }*/
             }

         }
@@ -866,7 +835,6 @@
 {
     int localport = WiFlyLocalPort;

-    //C64Println();
     C64Print(F("\r\nIncoming port ("));
     C64Serial.print(localport);
     C64Print(F("): "));
@@ -905,10 +873,9 @@
     CheckTelnet();
     TerminalMode();
 }
+
 // ----------------------------------------------------------
 // Telnet Handling
-
-
 void DoTelnet()
 {
     int port = lastPort;
@@ -960,8 +927,6 @@
         return(lastPort);
     }
 }
-
-
 #endif // HAYES

 void Connect(String host, int port, boolean raw)
@@ -1048,7 +1013,6 @@
     int buffer_bytes = 0;
     int max_buffer_size_reached = 0;

-
     while (wifly.available() != -1) // -1 means closed
     {
         if (baudMismatch) {   // If host is slower than WiFly we need to buffer.  Only used for 1200 baud.
@@ -1288,15 +1252,6 @@

 int PeekByte(Stream& in, unsigned int timeout)
 {
-    /*unsigned long timer;
-    timer = millis();
-
-    while (in.available() == 0)
-    {
-      if (millis() - timeout < timer)
-          return TIMEDOUT;
-    }*/
-
     elapsedMillis timeElapsed = 0;

     while (in.available() == 0)
@@ -1336,8 +1291,6 @@
         }

         Modem_Dialout(address);
-        //Connect(F("www.commodoreserver.com"), 1541, true);
-        //delay(1000);
     }
 }
 #endif  // HAYES
@@ -1875,7 +1828,7 @@
                     }
                     break;

-                    /*case '2':
+                    case '2':
                     switch(Modem_CommandBuffer[i++])
                     {
                         case '=':
@@ -1898,7 +1851,7 @@
                         i=j;
                         break;
                     }
-                    break;*/
+                    break;
                 }
                 break;

@@ -2505,96 +2458,6 @@

 #endif // HAYES

-/*
-void ConfigureBaud()
-{
-  if (BAUD_RATE == 2400)
-  {
-      setBaud(9600,true);
-  }
-  else
-  {
-      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, boolean setup) {
-    char temp[20];
-    BAUD_RATE = newBaudRate;
-    if (!setup) {
-        sprintf(temp, "New baud: %d", BAUD_RATE);
-    C64Println(temp);
-    C64Serial.flush();
-    delay(2);
-    C64Serial.end();
-    }
-    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(unsigned int newBaudRate) {
   WiFly_BAUD_RATE = newBaudRate;
   WifiSerial.flush();
@@ -2667,7 +2530,6 @@
         EEPROM.write(address, value);
 }

-//void updateEEPROMPhoneBook(byte address, String host, int port)
 void updateEEPROMPhoneBook(int address, String host)
 {
     int i=0;
@@ -2675,12 +2537,6 @@
     {
         EEPROM.write(address + i, host.c_str()[i]);
     }
-
-    /*byte a = BAUD_RATE / 256;
-    byte b = BAUD_RATE % 256;
-
-    updateEEPROMByte(address+i++,a);
-    updateEEPROMByte(address+i,b);*/
 }

 String readEEPROMPhoneBook(int address)
@@ -2692,10 +2548,6 @@
         host[i] = EEPROM.read(address + i);
     }
     return host;
-
-    //lastHost = host;
-
-    //lastPort = (EEPROM.read(address+i++) * 256 + EEPROM.read(address+i));
 }

@@ -2734,7 +2586,6 @@

     DoFlowControlC64ToModem();
     wifly.write(C64input);
-    //wifly.write(C64Serial.read());
 }

 void removeSpaces(char *temp)
@@ -2758,8 +2609,6 @@
         wifly.setPort(localport);
         wifly.save();
         WiFlyLocalPort = localport;
-        //wifly.reboot();
-        //delay(5000);

         if (WiFly_BAUD_RATE != 2400) {
             C64Println(F("\n\rReboot MicroView & WiFi to set new port."));


bugfixes, afstanden worden nu in cm getoond

--- DRIVING/src/client/client.ino
+++ DRIVING/src/client/client.ino
@@ -83,7 +83,7 @@
   if(*instruction == 'M'){
     ++instruction;
     if(containsChar("SP", *instruction)){
-      int value = atoi(instruction);
+      int value = atoi(instruction + 1);
       if(*instruction == 'S'){
 	return value < 255 && value > -255;
       }
@@ -142,9 +142,9 @@

 void printDistanceInfo(Distance_Info info){
   Serial.print("Afstand emmer: ");
-  Serial.print(info.emmerDistance);
+  Serial.print(info.emmerDistance / 59.0);
   Serial.print(", afstand pomp: ");
-  Serial.println(info.pompDistance);
+  Serial.println(info.pompDistance / 59.0);
 }

 void printStateInfo(State_Info info){
@@ -206,12 +206,6 @@
   Serial.println(" )");
 }

-bool isValidSymbol(char character){
-  static char symbols[] = "RPSMDTAM-";
-
-  return !containsChar(symbols, character);
-}
-
 bool containsChar(char *string, char character){
   if(!(*string)){ //if string is empty
     return false;


Compatibel met dht11

Compatibel met dht11

--- Sources/Shrimp/Shrimp.ino
+++ Sources/Shrimp/Shrimp.ino
@@ -1,26 +1,39 @@
+#include <dht11.h>
+
 // Pins
 const int ledPin = 13;
-const int buttonPin = 2;
-const int thermometerPin = A0;
+const int dhc11Pin = 8;
+

 // Variables
+dht11 DHT11;
 int travelTime = 0; // Total travel time in s
 int logInterval = 0; // Hoe vaak willen we loggen?
-int temperature = 0;

 void setup() {
   // Initialize pins
   pinMode(ledPin, OUTPUT);

+  DHT11.attach(dhc11Pin);
   Serial.begin(9600);
-  digitalWrite(ledPin, LOW);
 }

 void loop() {
   // put your main code here, to run repeatedly:
-  temperature = analogRead(thermometerPin);
-  Serial.println(temperature, DEC);
-  delay(1);
+  int chk = DHT11.read();
+  switch (chk)
+  {
+    case 0: Serial.println("OK"); break;
+    case -1: Serial.println("Checksum error"); break;
+    case -2: Serial.println("Time out error"); break;
+    default: Serial.println("Unknown error"); break;
+  }

+  Serial.print("Humidity (%): ");
+  Serial.println((int)DHT11.humidity, DEC);

+  Serial.print("Temperature (°C): ");
+  Serial.println((float)DHT11.temperature, DEC);
+
+  delay(2000);
 }


this commit fixes #64

this commit fixes #64

--- examples/ESP8266-OTA/ESP8266-OTA.ino
+++ examples/ESP8266-OTA/ESP8266-OTA.ino
@@ -44,7 +44,6 @@

   Serial.setDebugOutput(true);
   if (ESP.updateSketch(*pub.payload_stream(), size, true, false)) {
-    pub.payload_stream()->stop();
     Serial.println("Clearing retained message.");
     client.publish(MQTT::Publish(pub.topic(), "")
                    .set_retain());


added watchdog and time display

added watchdog and time display

--- examples/KitchenSink/KitchenSink.ino
+++ examples/KitchenSink/KitchenSink.ino
@@ -7,11 +7,12 @@
 #include <KMqtt.h>
 #include <KButton.h>
 #include <KDisplay.h>
+#include <KWatchdog.h>

 #define BUTTON_A    9
 #define BUTTON_B    6
 #define BUTTON_C    5
-#define LEDPIN      13
+#define LEDPIN      LED_BUILTIN

 #define WIFI_SSID   "ssid"
 #define WIFI_PASS   "pass"
@@ -21,6 +22,7 @@
 #define MQTT_PASS   "aio-key"
 #define MDNS_NAME   "feather"

+KWatchdog watchdog;
 KDisplay display;
 KWiFi wifi(WIFI_SSID, WIFI_PASS);
 Adafruit_WINC1500Client client;
@@ -146,3 +148,31 @@
 void loop() {
     KTask::loop();
 }
+
+char * timeToString(unsigned long t)
+{
+    static char str[12];
+    long h = t / 3600;
+    t = t % 3600;
+    int m = t / 60;
+    int s = t % 60;
+    sprintf(str, "%04ld:%02d:%02d", h, m, s);
+    return str;
+}
+
+void displayTime() {
+    display.display.fillRect(11*6, 3*8, 10*6, 1*8, 0);
+    display.display.setCursor(11*6, 3*8);
+    display.display.print(timeToString(millis()/1000));
+    display.display.display();
+}
+KTask displayTimer(1000, displayTime);
+
+const char RUNTIME_FEED[] = MQTT_USER "/feeds/runtime";
+KMqttPublish runtimePub = KMqttPublish(&mqtt, RUNTIME_FEED);
+
+void publishTime() {
+    if (mqtt.connected()) runtimePub.publish(timeToString(millis()/1000));
+}
+KTask publishTimer(15000, publishTime);
+


Update to use Nanoshield_LCD library

Update to use Nanoshield_LCD library

--- examples/SimpleClock/SimpleClock.ino
+++ examples/SimpleClock/SimpleClock.ino
@@ -8,10 +8,10 @@
 #include <Wire.h>
 #include <stdio.h>
 #include "Nanoshield_RTC.h"
-#include "Deuligne.h"
+#include "Nanoshield_LCD.h"

 Nanoshield_RTC rtc;
-Deuligne lcd;
+Nanoshield_LCD lcd;

 #define BUFFER_SIZE 50
 char buf[BUFFER_SIZE];
@@ -27,7 +27,7 @@
   Serial.println("");

   // Initialize LCD
-  lcd.init();
+  lcd.begin();
   lcd.clear();
   lcd.print("Initializing...");


Reset Controller Data before Inputting

Reset Controller Data before Inputting

	You can now choose to automatically reset the controller datar or not before executing an input
	You just have to send Preamble and Postamble 0x12, and the value to disable or enable the reset on the 8th byte (Zero indexed array)
	0 means Resetting before inputting is enabled, any value different than 0 is disabled

--- ps2_controller/ps2_controller.ino
+++ ps2_controller/ps2_controller.ino
@@ -107,6 +107,7 @@

 unsigned long readMotorsStatus = 0; // 0 = Read Both Low to High and High to Low changes, 1 = Disabled, 2 = Read Low to High changes, 3 = Read High to Low Changes. 0 Means it's enabled by default.
 unsigned long autoResetControllerDataStatus = 0; // 0 = Automatic reset is enabled, 1 = Automatic reset is disabled
+unsigned long resetBeforeInputStatus = 0; // 0 = Resetting before inputting is enabled, 1 = Resetting before inputting is disabled

 unsigned long resetCalled = 0;
 unsigned long resetDone = 0;
@@ -131,6 +132,7 @@
 byte serial_rx_buffer_reset_controller[12];
 byte serial_rx_buffer_change_motors_status[12];
 byte serial_rx_buffer_change_autoreset_controller_status[12];
+byte serial_rx_buffer_toggle_before_input_reset[12];
 unsigned long serial_rx_buffer_counter = 0;
 unsigned long controller = 0;

@@ -142,7 +144,7 @@
   inputDelay = 0;
   isInputtingDelayed = false;
   isInputting = false;
-
+
   currentMillis = millis();
   Serial.begin(baudRate);
   isConnected = false;
@@ -317,6 +319,7 @@
   getAttention();
   readMotors();
   manualResetControllerData();
+  toggleBeforeInputReset();

   serial_rx_buffer_change_motors_status[0] = 0x0F;
   serial_rx_buffer_change_motors_status[1] = 0x00;
@@ -344,6 +347,19 @@
   serial_rx_buffer_change_autoreset_controller_status[10] = 0x00;
   serial_rx_buffer_change_autoreset_controller_status[11] = 0x11;

+  serial_rx_buffer_toggle_before_input_reset[0] = 0x13;
+  serial_rx_buffer_toggle_before_input_reset[1] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[2] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[3] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[4] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[5] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[6] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[7] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[8] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[9] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[10] = 0x00;
+  serial_rx_buffer_toggle_before_input_reset[11] = 0x13;
+
   inputDelay = 0;
   isInputtingDelayed = false;
   isInputting = false;
@@ -425,6 +441,9 @@
     //  1 == 0x01
     if ((serial_rx_buffer[0] == 0x01) && (serial_rx_buffer[11] == 0x01)) {

+      if (resetBeforeInputStatus == 0) {
+        manualResetControllerData();
+      }
       //  Count bytes and parse ASCII values to their respective commands, such as buttons and axis
       for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer); serial_rx_buffer_counter++) {
         Serial.write(serial_rx_buffer[serial_rx_buffer_counter]); //  This line writes the serial data back to the computer as a way to check if the Arduino isn't interpreting wrong values
@@ -511,8 +530,18 @@
       Serial.flush();
       changeAutoResetControllerData();
     }
+    else if ((serial_rx_buffer[0] == 0x12) && (serial_rx_buffer[11] == 0x12)) {
+      // Choose to enable or disable Automatic Reset Controller Data
+      for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_toggle_before_input_reset); serial_rx_buffer_counter++) {
+        //  Pass Serial Buffer to toggleBeforeInout Buffer
+        serial_rx_buffer_toggle_before_input_reset[serial_rx_buffer_counter] = serial_rx_buffer[serial_rx_buffer_counter];
+        Serial.write(serial_rx_buffer_toggle_before_input_reset[serial_rx_buffer_counter]);
+      }
+      Serial.flush();
+      toggleBeforeInputReset();
+    }
     //  Get Invalid Command
-    else if ((((serial_rx_buffer[0] < 0x01) || (serial_rx_buffer[0] > 0x11)) && ((serial_rx_buffer[11] < 0x01) || (serial_rx_buffer[11] > 0x11))) && (((serial_rx_buffer[0] != 0xA0) && (serial_rx_buffer[0] != 0xA1)) && ((serial_rx_buffer[11] != 0xA0) && (serial_rx_buffer[11] != 0xA1)))) {
+    else if ((((serial_rx_buffer[0] < 0x01) || (serial_rx_buffer[0] > 0x13)) && ((serial_rx_buffer[11] < 0x01) || (serial_rx_buffer[11] > 0x13))) && (((serial_rx_buffer[0] != 0xA0) && (serial_rx_buffer[0] != 0xA1)) && ((serial_rx_buffer[11] != 0xA0) && (serial_rx_buffer[11] != 0xA1)))) {
       for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_invalid_command); serial_rx_buffer_counter++) {
         //  Pass Serial Buffer to Reset Controller Data Buffer
         serial_rx_buffer_invalid_command[serial_rx_buffer_counter] = serial_rx_buffer[serial_rx_buffer_counter];
@@ -539,6 +568,36 @@
   getAttention();
   autoResetControllerData();
 } // Close Loop Function
+
+void toggleBeforeInputReset() {
+  //  This is where we choose whether or not the Arduino resets the controller data before executing an input
+  //inputDelay = 0;
+  //isInputtingDelayed = false;
+  //isInputting = false;
+  autoResetControllerData();
+  manualResetControllerData();
+  //Serial.println("");
+  //Serial.print("Changing from ");
+  //Serial.print(resetBeforeInputStatus);
+  //Serial.print(" to");
+  resetBeforeInputStatus = serial_rx_buffer_toggle_before_input_reset[8];
+  serial_rx_buffer_toggle_before_input_reset[0] = 0x13;
+  serial_rx_buffer_toggle_before_input_reset[11] = 0x13;
+
+  for (serial_rx_buffer_counter = 0; serial_rx_buffer_counter < sizeof(serial_rx_buffer_toggle_before_input_reset); serial_rx_buffer_counter++) {
+    //  Write back data as a way to tell the Status changed correctly
+    Serial.write(serial_rx_buffer_toggle_before_input_reset[serial_rx_buffer_counter]);
+  }
+  //Serial.flush();
+  //Serial.print(resetBeforeInputStatus);
+  //Serial.println(" .");
+  //Serial.flush();
+  autoResetControllerData();
+  manualResetControllerData();
+  //inputDelay = 0;
+  //isInputtingDelayed = false;
+  //isInputting = false;
+}

 void changeAutoResetControllerData() {
   inputDelay = 0;


Update RovMain.ino

Update RovMain.ino

--- Software/OpenCM9.04/RovMain/RovMain.ino
+++ Software/OpenCM9.04/RovMain/RovMain.ino
@@ -13,53 +13,38 @@
 //----------------------------------------------------------------------------
 #include <Servo.h>
 #include "RSP.h"
+#include "Define.h"
+#include "IMU.h"
+#include "LED.h"

 RSP     RovSerial;
-
-#define USB_TEST_AVAILABLE 1  // control Motor & LED by using USB serial
-
-#define RC_MOTOR_L    0
-#define RC_MOTOR_C    1
-#define RC_MOTOR_R    2
-
-#define RC_MOTOR_PIN_L  2
-#define RC_MOTOR_PIN_C  3
-#define RC_MOTOR_PIN_R  5
-
-#define LED_PIN_L  8
-#define LED_PIN_R  9
-
-#define MOTOR_NEUTRAL 1500
-
-bool IsConnected;
+Servo   RovServo[3];
+cIMU    IMU;
+cLED    LED;
+
+bool       IsConnected;
+uint8_t    err_code;

 void rc_usb_test();
-void led_setup();
+void Motor_init();
 void process_recv_cmd( void );

 void send_cmd_info( void );
 void recv_cmd_control( RSP_CMD_OBJ *pCmd );
-
-Servo   RovServo[3];
+void sout_IMU_info();
+void cal_IMU_acc();

 void setup()
 {
   Serial.begin(115200);

   RovSerial.begin(115200);
-  RovServo[RC_MOTOR_L].attach(RC_MOTOR_PIN_L, 1000, 2000, 0, 255 );
-  RovServo[RC_MOTOR_C].attach(RC_MOTOR_PIN_C, 1000, 2000, 0, 255 );
-  RovServo[RC_MOTOR_R].attach(RC_MOTOR_PIN_R, 1000, 2000, 0, 255 );
-
-  RovServo[RC_MOTOR_L].writeMicroseconds(1500);
-  RovServo[RC_MOTOR_C].writeMicroseconds(1500);
-  RovServo[RC_MOTOR_R].writeMicroseconds(0);
-
-  pinMode(LED_PIN_L, PWM);
-  pinMode(LED_PIN_R, PWM);
-
-  analogWrite(LED_PIN_L, 0);
-  analogWrite(LED_PIN_R, 0);
+
+  Motor_init();
+
+  LED.Led_init();
+
+  err_code = IMU.begin();

   IsConnected = false;
 }
@@ -67,29 +52,34 @@

 void loop()
 {
-  static uint32_t tTime[8];
-
+  static uint32_t tTime[3];
+
+  if( (millis()-tTime[0]) >= 500 )
+  {
+    tTime[0] = millis();
+    LED.toggle();
+  }
+
+  IMU.update();
   //-- 명령어 수신 처리
   //
   process_recv_cmd();

+  //-- 100ms마다 ROV정보 전달
+  //
+  if( (millis()-tTime[1]) >= 100 )
+  {
+    tTime[1] = millis();
+
+   sout_IMU_info();
+   send_cmd_info();
+  }
+  cal_IMU_acc();
+
+
   if(USB_TEST_AVAILABLE)
   rc_usb_test();
-
-  //-- 100ms마다 ROV정보 전달
-  //
-  if( (tTime[0] - millis()) >= 100 )
-  {
-    tTime[0] = millis();
-
-    send_cmd_info();
-
-    if( IsConnected == true )
-    {
-      //Serial.println("Connected");
-    }
-  }
-
+
   //-- 연결이 끊어진 상태
   //
 /*
@@ -101,7 +91,6 @@
   }
   */
 }
-

 void process_recv_cmd( void )
 {
@@ -116,21 +105,7 @@
   {
         pCmd  = RovSerial.Get_CmdPtr();

-    /*
-    Serial.print("Cmd : ");
-    Serial.print( pCmd->Cmd, HEX);
-    Serial.print(" Size : ");
-    Serial.print( pCmd->Length, DEC);
-    Serial.print(" ");
-    for( i=0; i<pCmd->Length; i++ )
-    {
-      Serial.print(pCmd->Data[i]);
-      Serial.print(" ");
-    }
-    Serial.println(" ");
-    */
-
-    switch( pCmd->Cmd )
+      switch( pCmd->Cmd )
     {
       case 0x01:
         IsConnected = true;
@@ -198,7 +173,7 @@
   //Led_Left
   if(pCmd->Data[0] == 1)
   {
-    Led[0] = (0xFFFF - (pCmd->Data[2]<<8) | (pCmd->Data[1]));
+    Led[0] = (LED_OFF - (pCmd->Data[2]<<8) | (pCmd->Data[1]));
     Serial.print("Led_L : ");
     Serial.println(Led[0]);
     analogWrite(LED_PIN_L, Led[0]);
@@ -206,7 +181,7 @@
   //Led_Right
   if(pCmd->Data[3] == 1)
   {
-    Led[1] = (0xFFFF - (pCmd->Data[5]<<8) | (pCmd->Data[4]));
+    Led[1] = (LED_OFF - (pCmd->Data[5]<<8) | (pCmd->Data[4]));
     Serial.print("Led_R : ");
     Serial.println(Led[1]);
     analogWrite(LED_PIN_R, Led[1]);
@@ -214,6 +189,51 @@
 }

+void Motor_init()
+{
+  RovServo[RC_MOTOR_L].attach(RC_MOTOR_PIN_L, 1000, 2000, 0, 255 );
+  RovServo[RC_MOTOR_C].attach(RC_MOTOR_PIN_C, 1000, 2000, 0, 255 );
+  RovServo[RC_MOTOR_R].attach(RC_MOTOR_PIN_R, 1000, 2000, 0, 255 );
+
+  RovServo[RC_MOTOR_L].writeMicroseconds(1500);
+  RovServo[RC_MOTOR_C].writeMicroseconds(1500);
+  RovServo[RC_MOTOR_R].writeMicroseconds(0);
+}
+
+void sout_IMU_info()
+{
+    Serial.print(err_code);
+    Serial.print(" ");
+    Serial.print(IMU.angle[0]/10);
+    Serial.print(" ");
+    Serial.print(IMU.angle[1]/10);
+    Serial.print(" ");
+    Serial.println(IMU.angle[2]);
+}
+
+void cal_IMU_acc()
+{
+ if( Serial.available() )
+  {
+    char Ch = Serial.read();
+
+    if( Ch == '1' )
+    {
+      Serial.println("ACC Cali Start");
+
+      IMU.SEN.acc_cali_start();
+      while( IMU.SEN.acc_cali_get_done() == false )
+      {
+        IMU.update();
+        //Serial.println( IMU.SEN.calibratingA );
+      }
+
+      Serial.print("ACC Cali End ");
+    }
+  }
+}
+
+
 //---------RCtest(control Motor & LED by using USB serial)---------

 void rc_usb_test()
@@ -229,7 +249,7 @@
     {
       rc_pwm = MOTOR_NEUTRAL;
       RovServo[RC_MOTOR_C].writeMicroseconds(rc_pwm);
-      Serial.println("Pwm = 0");
+      Serial.println("Stop");
     }

     if( ch == 'w' )


Added velocity and load functions.

Added velocity and load functions.

--- jaws2_serial/firmware/firmware.ino
+++ jaws2_serial/firmware/firmware.ino
@@ -3,6 +3,9 @@

 #include "ax12.h"
 #include <Servo.h>
+
+#define GetSpeed(id) (ax12GetRegister(id, AX_PRESENT_SPEED_L, 2))
+#define GetLoad(id) (ax12GetRegister(id, AX_PRESENT_LOAD_L, 2))

 ros::NodeHandle nh;
 std_msgs::Float64 state;
@@ -10,7 +13,9 @@

 int port_servo_cmd = 150;
 int stbd_servo_cmd = 150;
-int state[] = {150, 150};
+int port_servo_pos = 150;
+int stbd_servo_pos = 150;
+int state[] = {150, 150, 0, 0, 0, 0};

 void callback(const std_msgs::Float64 cmd);
 {
@@ -76,6 +81,10 @@
   }
   state[0] = port_servo_pos;
   state[1] = stbd_servo_pos;
+  state[2] = GetSpeed(PORT_SERVO);
+  state[2] = GetSpeed(STBD_SERVO);
+  state[4] = GetLoad(PORT_SERVO);
+  state[5] = GetLoad(STBD_SERVO);
   state_pub.publish(&state);
   delay(33);
 }


event用のレスポンスに変更

event用のレスポンスに変更

--- arduino/GeneralIoSerial/GeneralIoSerial.ino
+++ arduino/GeneralIoSerial/GeneralIoSerial.ino
@@ -308,7 +308,7 @@
     if(ai_stream_info[i].interval_ms){
       if(ai_stream_info[i].counter > ai_stream_info[i].interval_ms){
         ai_stream_info[i].counter = 0;
-        Serial.println(aiRead(i));
+        Serial.println(wrapEventJson("ai", aiRead(i)));
       }
     }
   }
@@ -317,12 +317,13 @@
     if(di_stream_info[i].interval_ms){
       if(di_stream_info[i].counter > di_stream_info[i].interval_ms){
         di_stream_info[i].counter = 0;
-        Serial.println(diRead(i));
+        Serial.println(wrapEventJson("di", diRead(i)));
       }
     }
   }

 }
+

 String task(String msg){
   // 関数テーブルからタスクを決定する.
@@ -741,6 +742,19 @@
 }

+/*
+
+   {"event":"[type]", "data":{"msg":"OK", , , , }}
+
+   的なjsonを作る.
+ */
+String wrapEventJson(String type, String dataJson){
+  String body = stringJson("event", type)
+          + wrapDq("data") + ":" + dataJson;
+  return wrapBrace(body);
+}
+
+
 String switchTypeReturnJson(String msg, String refType){
   String body = stringJson("msg", msg) + ","
     + stringJson("type", refType);


Add version number (2.0)

Add version number (2.0)


Use of ShiftrConnector as receiver

Use of ShiftrConnector as receiver

--- counter/counter.ino
+++ counter/counter.ino
@@ -2,8 +2,16 @@

 #include "logger.h"

+/////////////////////////////////////////////
+// Include of Iot Platform's connectors
 #include "thingspeakReceiver.h"
 ThingspeakReceiver thingspeakReceiver;
+int thingsSpeakCounter = 0;
+
+#include "shiftrConnector.h"
+ShiftrConnector shiftrConnector;
+int shiftrCounter = 0;
+/////////////////////////////////////////////

 #include <Adafruit_LEDBackpack.h>
 #include <Adafruit_GFX.h>
@@ -28,6 +36,7 @@
   //setup the IoT platforms
   logger->log("Start setup connection with IoT platforms...\n");
   thingspeakReceiver.init();
+  shiftrConnector.init();

   //Everything seems to be ok, let's start !
   logger->log("\nBottle Opener up, Let's start to play :) !!!\n");
@@ -40,11 +49,16 @@
    Arduino Loop
 */
 void loop() {
-  int counter = thingspeakReceiver.receiveCounter();
+  //need to refresh shiftr API in order to send and receive new messages
+  shiftrConnector.loop();

-  displayCounter(counter);
+  thingsSpeakCounter = thingspeakReceiver.receiveCounter();
+  shiftrCounter = shiftrConnector.receiveMessage();

-  delay(500);
+  //display whatever counter, they should be the same, independently of the platform
+  displayCounter(shiftrCounter);
+
+  delay(10);
 }

 /**