Juste un nettoyage du main

Juste un nettoyage du main

--- calibrateur.ino
+++ calibrateur.ino
@@ -12,57 +12,72 @@
 //afaire : faire un réinit propre car si on fait 2 étalonnage à la suite ca marche pas
 //a Faire : lire l'autre voie de la roue codeuse pour detectr les rebond du servo

-//a faire tester repetabilité avec tempo à 100 et à 200. Avec 100 on a des comportement louche lors des cycles de fin (le servo bouge apeine sur certains des cycle a la palce d'un grand débatement)
+//a faire tester repetabilité avec tempo à 100 et à 200.
+Avec 100 on a des comportement louche lors des cycles de fin
+(le servo bouge apeine sur certains des cycle a la palce d'un grand débatement)
 // a faire : comprendre pourquoi les vitesses sont pas les memes selon les modes.

 #*******************************************************************************
  J.Soranzo
-	16/12/2015 gestion sous git + github
-	https://github.com/gilles293/calibrateurServo.git
-	nettoyage du code, j'ai craqué
+    16/12/2015 gestion sous git + github
+    https://github.com/gilles293/calibrateurServo.git
+    nettoyage du code, j'ai craqué
 */
-
-//pour la suite faire moyenne pour mesure PWMIN et PWMMAX et virer le calcul de la moyenne mesureimpulsion pour le remplacer par la méthode
+//------------------------------------------------------------------------------
+//pour la suite faire moyenne pour mesure PWMIN et PWMMAX et virer
+//le calcul de la moyenne mesureimpulsion pour le remplacer par la méthode

 #include <EEPROM.h>
 #include <SCoop.h>
 #include <Wire.h>
+#include <Adafruit_PWMServoDriver.h>
+#include <Servo.h>
+
+//------------------------------------------------------------------------------
+//Lib projet
 #include "bouton.h"
 #include "afficheur.h"
 #include "servoTest.h"
 #include "potar.h"
-#include <Adafruit_PWMServoDriver.h>
-#include <Servo.h>
+
+//------------------------------------------------------------------------------
 #define DELTA 150
-#define TEMPOSLEEP 800 //en ms le temps pour le servo de bouger d'un increment quand on fait les mesure à la roue codeuse
+#define TEMPOSLEEP 800
+//en ms le temps pour le servo de bouger d'un increment
+//quand on fait les mesure à la roue codeuse
+
 #define ERREURCOMPTAGE 15 //la tolérance de comptage avant que l'on estime que le servo est arrivé au bout
 #define NBRCYCLE_AR 10 //nbre de cycle d'aller et retour pour la fin des mesure de caractérisation et nbr de cycle pour la mesure des PWMIN et PWMMAX
-#define TEMPO_STAT 100 // tempo pour laisser le servo avancr lors des mesures statistique à la fin de la calibration
+#define TEMPO_STAT 100 // tempo pour laisser le servo avancr lors des mesures
+                       // statistique à la fin de la calibration
 #define ADRESSE_EEPROM 42//position de leeprom ou la valeur de reglage de vitesse est stocké
 #define VITESSEMAXSERVO 3500 // vitesse max d'un servo en microsecond de PWM par seconde
 #define PINSERVO 5 // pin arduino ou est branché le servo

-//
+//------------------------------------------------------------------------------
+// Etats de la machine d'état
 enum {
-		POTAR = 3,
-		MILIEU = 4,
-		USB = 1,
-		ETALORSWEEP = 10,
-		REGPOTENCINVIT = 11,
-		REGLPOTENC = 12,
-		MESREFPULSE = 13,
-		FINDMINMAX = 14,
-		WAITCLIC = 15,
-		DISPRESULT = 16,
-		WAITCLIC2 = 17,
-    LECTURE_OU_ECRITURE_EEEPROM=18,
-		SWEEPTOMIN = 2,
-		SWEEPTOMAX = 20,
-    VITESSE=22,
-
+        POTAR = 3,
+        MILIEU = 4,
+        USB = 1,
+        ETALORSWEEP = 10,
+        //REGPOTENCINVIT = 11,
+        REGLPOTENC = 12,
+        MESREFPULSE = 13,
+        FINDMINMAX = 14,
+        WAITCLIC = 15,
+        DISPRESULT = 16,
+        WAITCLIC2 = 17,
+        //LECTURE_OU_ECRITURE_EEEPROM=18,
+        SWEEPTOMIN = 2,
+        SWEEPTOMAX = 20,
+        VITESSE=22,
 };
+
+//------------------------------------------------------------------------------
+//Variables globales
 bouton boutonP(4);
 afficheur affichage(0x20);
 //int bonnePositionPotence;
@@ -74,7 +89,10 @@
 //servoTest potence(11);
 unsigned long dateChangeServo;
 bool changeTypeServo(false);
-int compteur(0);
+
+int compteur(0); //variable compteur d'impulsions
+                //mise à jour par interruptions
+
 int compteurRef(0);
 int resultatImpulsionMax[NBRCYCLE_AR];
 long resultatTempsMax[NBRCYCLE_AR];
@@ -87,46 +105,38 @@
 int vitesseTemp;

-int objTest (0); // varaible temporaire pour ...peut sans doute etre supprimé en faisant apelle aux bnnes méthode pour connaitre etat courrant du servo
-
-
-
+int objTest (0); // varaible temporaire pour ...peut sans doute etre supprimé
+// en faisant apelle aux bnnes méthode pour connaitre etat courrant du servo
+
+//------------------------------------------------------------------------------
+//fonctions de calculs
 long ecartType (int tailleTab, int tab [])
-
 {
-  long moy(moyenne(tailleTab,tab));
-  long ecType(0);
-  int j(0);
-
-  for (j=0;j<tailleTab;j++)
-         {
-            ecType=ecType+pow(tab[j]-moy,2);
-
-          }
-  ecType=sqrt(ecType);
-  return ecType;
-
+    long moy(moyenne(tailleTab,tab));
+    long ecType(0);
+    int j(0);
+    for (j=0;j<tailleTab;j++)
+    {
+        ecType=ecType+pow(tab[j]-moy,2);
+    }
+    ecType=sqrt(ecType);
+    return ecType;
 }

 long ecartType (int tailleTab, long tab [])
-
 {
-  long moy(moyenne(tailleTab,tab));
-  long ecType(0);
-  int j(0);
-
-  for (j=0;j<tailleTab;j++)
-         {
-            ecType=ecType+pow(tab[j]-moy,2);
-
-          }
-  ecType=sqrt(ecType);
-  return ecType;
-
+    long moy(moyenne(tailleTab,tab));
+    long ecType(0);
+    int j(0);
+    for (j=0;j<tailleTab;j++)
+    {
+        ecType=ecType+pow(tab[j]-moy,2);
+    }
+    ecType=sqrt(ecType);
+    return ecType;
 }

 long moyenne (int tailleTab, long tab [])
-
 {
   byte j;
   long moyenne (0);
@@ -136,45 +146,45 @@
           }
    moyenne=moyenne/(tailleTab);
    return moyenne;
-
 }

 long moyenne (int tailleTab, int tab [])
-
 {
   byte j;
   long moyenne (0);
   for (j=0;j<tailleTab;j++)
-         {
-              moyenne=moyenne+tab[j];
-          }
+    {
+        moyenne=moyenne+tab[j];
+    }
    moyenne=moyenne/(tailleTab);
-   return moyenne;
-
-}
-
+   return moyenne;
+}
+
+//------------------------------------------------------------------------------
+//Scoop Timers
 defineTimerRun(rafraichirAffichage,800)
  //ne pas mettre ce timer a une valeur trop faible pour éviter le rebond
  //lors de l'apuui bouton (ne pas compter des apuis multiple pour un seul appuie voulu)
 {
-	 //Serial.println("affichagePP");
-	  affichage.refreshAfficheur();
+     //Serial.println("affichagePP");
+      affichage.refreshAfficheur();
 }

 defineTimerRun(surveilleBouton,40)
 //ne pas mettre ce timer a une valeur trop faible pour éviter le rebond lors de
 //l'apuui bouton (ne pas compter des apuis multiple pour un seul appuie voulu)
 {
-	//Serial.println("bouton");
-	boutonP.refreshBouton();
-}
-
-defineTimerRun(surveilleServo,100) //conserver 100 ou modifier le "*0.1" dans méthode appliqueobjectif du Servo
+    //Serial.println("bouton");
+    boutonP.refreshBouton();
+}
+
+defineTimerRun(surveilleServo,100) //conserver 100 ou modifier le "*0.1"
+//dans méthode appliqueobjectif du Servo
 {
-	 //Serial.println("Servo");
-	 //Serial.println("potence.
-	 leServo.appliqueObjectif();
-	 //potence.appliqueObjectif();
+     //Serial.println("Servo");
+     //Serial.println("potence.
+     leServo.appliqueObjectif();
+     //potence.appliqueObjectif();
 }

 defineTimerRun(surveillePotar,80)
@@ -183,481 +193,394 @@
     lePotar.refresh();
 }

+
+//------------------------------------------------------------------------------
+//La tache Scoop
 defineTask(reflechi)
-    void reflechi::setup()
-	{
-
-	}
-
+    void reflechi::setup(){ }
     void reflechi::loop()
     //defineTimerRun(reflechi,40)
-	{
-    //Serial.println("proute");
-    //Serial.println("reflechi");
+/*
+  AFFICHERIEN,
+  AFFICHEUSB,
+  AFFICHESWEEP,
+  AFFICHEPOTAR,
+  AFFICHEMILIEU,
+  AFFICHEADAFRUIT,
+  AFFICHECLASSIQUE
+  */
+    {
     byte i;
-		if (boutonP.hasBeenLongClicked())
-			{
-				dateChangeServo=(millis());
-				changeTypeServo=true;
-				if (leServo.getType())
-					{
-						leServo.setType(false);
-						affichage.affiche(5);
-						Serial.println(F("servo de type Adafruit"));
-					}
-				else
-					{
-						leServo.setType(true);
-						affichage.affiche(6);
-						Serial.println(F("servo de type Classique"));
-					}
-				//sleep( 3000);
-				boutonP.acquit();
-			}
-		if (millis()>dateChangeServo+3000 && changeTypeServo)
-			{
-				affichage.affiche(etatCalibrateur);
-				changeTypeServo=false;
-			}
-
-
-		switch (etatCalibrateur)
-			{
-				case USB :
-
-
-          Serial.println(F("Double Clic pour procéder à mesure via USB, sinon simple clic change de mode"));
-					etatCalibrateur=ETALORSWEEP;
-					break;
-
-				case ETALORSWEEP :
-
-					if (boutonP.hasBeenClicked())
-						{
-							boutonP.acquit();
-							etatCalibrateur=SWEEPTOMIN;
-							affichage.affiche(SWEEPTOMIN);
-							leServo.setObjectif(leServo.getMin());
-              lePotar.acquit();
-						}
-
-					if (boutonP.hasBeenDoubleClicked())
-					{
-						boutonP.acquit();
-            leServo.setVitesse(VITESSEMAXSERVO);
-            leServo.setObjectif(leServo.getMilieu());
-         // pour etre certain qu'on aprt du milieu et que le servo
+        if (boutonP.hasBeenLongClicked())
+            {
+                dateChangeServo=(millis());
+                changeTypeServo=true;
+                if (leServo.getType())
+                    {
+                        leServo.setType(false);
+                        affichage.affiche(AFFICHEADAFRUIT);
+                        Serial.println(F("servo de type Adafruit"));
+                    }
+                else
+                    {
+                        leServo.setType(true);
+                        affichage.affiche(AFFICHECLASSIQUE);
+                        Serial.println(F("servo de type Classique"));
+                    }
+                //sleep( 3000);
+                boutonP.acquit();
+            }
+        if (millis()>dateChangeServo+3000 && changeTypeServo)
+            {
+                affichage.affiche(etatCalibrateur);
+                changeTypeServo=false;
+            }
+
+
+        switch (etatCalibrateur)
+            {
+                case USB :
+                    Serial.println(F(\
+          "Double Clic pour procéder à mesure via USB, sinon simple clic change de mode"));
+                    etatCalibrateur=ETALORSWEEP;
+                    break;
+
+                case ETALORSWEEP :
+                    if (boutonP.hasBeenClicked())
+                        {
+                            boutonP.acquit();
+                            etatCalibrateur=SWEEPTOMIN;
+                            affichage.affiche(SWEEPTOMIN);
+                            leServo.setObjectif(leServo.getMin());
+                            lePotar.acquit();
+                        }
+
+                    if (boutonP.hasBeenDoubleClicked())
+                    {
+                        boutonP.acquit();
+                        leServo.setVitesse(VITESSEMAXSERVO);
+                        leServo.setObjectif(leServo.getMilieu());
+         // pour etre certain qu'on part du milieu et que le servo
           //n'est pas n'importe ou suite à des manip de type sweep
           //ou potar par ex
-
-						//Serial.println(F("si lecture EEPROM pour potence Simple clic, si reglage potence double clic"));
-						etatCalibrateur=LECTURE_OU_ECRITURE_EEEPROM;
-            etatCalibrateur=MESREFPULSE;
-					}
-					break;
-
-//				case LECTURE_OU_ECRITURE_EEEPROM :
-//					if (boutonP.hasBeenClicked())
-//						{
-//							boutonP.acquit();
-//							EEPROM.get(ADRESSE_EEPROM, bonnePositionPotence); //lire la prom
-//
-//              Serial.println(F("j'ai lu"));
-//              Serial.println(bonnePositionPotence);
-//              potence.setObjectif(bonnePositionPotence);
-//              sleep( TEMPOSLEEP );
-//              etatCalibrateur=MESREFPULSE;
-//
-//						}
-//
-//					if (boutonP.hasBeenDoubleClicked())
-//					{
-//						boutonP.acquit();
-//
-//						Serial.println(F("tourner potar à fond à gauche"));
-//						etatCalibrateur=REGPOTENCINVIT;
-//					}
-//					break;
-//
-//
-//          case REGPOTENCINVIT :
-//
-//					if (lePotar.getValue()>1000)
-//					{
-//						etatCalibrateur=REGLPOTENC;
-//						Serial.println(F("quand potence reglé (sur le disque optique) faire 1 clic"));
-//					}
-//					break;
-//
-//				case REGLPOTENC :
-//					// Serial.print("obj potence=");
-//					// Serial.print(potence.getObjectif());
-//					// Serial.print("   Encours potence=");
-//					// Serial.print(potence.getEnCours());
-//					// Serial.print("   obj Pot=");
-//					// Serial.println(map(lePotar.getValue(),0,1023,potence.getMin(),potence.getMax()));
-//					// Serial.println("_____");
-//					potence.setObjectif(map(lePotar.getValue(),0,1023,potence.getMin(),potence.getMax()));
-//					if (boutonP.hasBeenClicked())
-//						{
-//							bonnePositionPotence=map(lePotar.getValue(),0,1023,potence.getMin(),potence.getMax());
-//							boutonP.acquit();
-//              EEPROM.put(ADRESSE_EEPROM, bonnePositionPotence);//enregistre en eeprom
-//              Serial.print(F("sauver en prom = ")); Serial.println( bonnePositionPotence );
-//
-//							etatCalibrateur=MESREFPULSE;
-//						}
-//					break;
-
-				case MESREFPULSE: //mesure des impulsion de reference sur une rotation de delta faite X fois pour plus de certitude
-
-          compteurRef=0;
-          compteur=0;
-          for (i=0;i<NBRCYCLE_AR;i=i+1)
-          {
-    					Serial.print(F("iteration de mesure de ref="));
-
-
-    					leServo.setObjectif(leServo.getMilieu()+DELTA);
-    					sleep(TEMPOSLEEP);
-              mesureRef[i]=compteur;
-              leServo.setObjectif(leServo.getMilieu());
-              sleep(TEMPOSLEEP);
-              compteur=0;
-              Serial.println(mesureRef[i]);
-          }
-
-
-
-
-					etatCalibrateur=FINDMINMAX;
-					compteurRef=moyenne(NBRCYCLE_AR,mesureRef);
-          Serial.print(F(" SUPERcmpteurRefMoyenne="));
-          Serial.print(compteurRef);
-          Serial.print(F(" (ecart type : "));
-          Serial.println(ecartType(NBRCYCLE_AR,mesureRef));
-
-					if (compteurRef==0)
-						{
-							Serial.println(F("PB : compteur Ref=0 aucune impulsion fourche optique détecté"));
-							Serial.println(F("retour au début de procédure"));
-							etatCalibrateur=USB;
-						}
-
-          if (ERREURCOMPTAGE*3>compteurRef)
-             {
-              Serial.println(F("ce serait bien que la marge d'erreur soit de l'ordre de 30% de la mesure de reference"));
-							Serial.println(F("je vais faire autre chose.... Programme a recompiler"));
-              Serial.println(F("modifier macro ERREURCOMPTAGE et DELTA"));
-
-
-							etatCalibrateur=POTAR;
-              affichage.affiche(POTAR);
-              }
-					break;
-				case FINDMINMAX:
-					//Serial.println("lalalal");
-					//sequence pour aller au max puis au min et de déterminer les pwm Min et Max du servo
-					compteur=compteurRef;
-					while (compteur>compteurRef-ERREURCOMPTAGE && compteur<compteurRef+ERREURCOMPTAGE)
-						{
-							Serial.print("M+.....");
-//            Serial.print(" ObjTest=");
-//            Serial.println(objTest);
-
-							compteur=0;
-							//objTest=objTest+DELTA;
-							leServo.setObjectif(leServo.getObjectif()+DELTA);
-							sleep(TEMPOSLEEP);
-//            Serial.print(" Objectif =");
-//            Serial.println(leServo.getObjectif());
-
-              Serial.print(" cmptr=");
-              Serial.println(compteur);
-
-
-						}
-					leServo.setMax(leServo.getObjectif()-DELTA);
-					leServo.setObjectif(leServo.getMilieu());
-          Serial.print("MAX=");
-          Serial.println(leServo.getMax());
-          Serial.println("retourneMilieu");
-					sleep(TEMPOSLEEP);
-					compteur=compteurRef;
-					while (compteur>compteurRef-ERREURCOMPTAGE && compteur<compteurRef+ERREURCOMPTAGE  )
-						{
-							Serial.print(F("M-......"));
-							compteur=0;
-							//objTest=objTest-DELTA;
-							leServo.setObjectif(leServo.getObjectif()-DELTA);
-							sleep(TEMPOSLEEP);
-              //Serial.print(" Objectif =");
-              //Serial.print(leServo.getObjectif());
-
-              Serial.print(" cmpteur=");
-              Serial.println(compteur);
-						}
-					leServo.setMin(leServo.getObjectif()+DELTA);
-					leServo.setObjectif(leServo.getObjectif()+DELTA);
-          Serial.print("MIN=");
-          Serial.println(leServo.getMin());
-					sleep(TEMPOSLEEP);
-					Serial.println("la le servo est au min et va faire grande course");
-          leServo.setObjectif(leServo.getMin());
-					//séquence pour mesurer une vitesse et amplitude moyenne
-					//(10 cycle d'aller et retour et enregistrement systématique des mesures)
-
-					for (i=0;i<NBRCYCLE_AR;i=i+1)
-						{
-							compteur=0;
-							compteurRef=0;//compteur ref utilisé différement dans la suite par rapport à ce qui était fait jusque là. Compteur ref est utilisé pour voir si le servo continue de bouger
-							tempsMesureVitesse=millis();
-              Serial.print("tempsMesureVitesse=");
-              Serial.println(tempsMesureVitesse);
-							leServo.setObjectif(leServo.getMax());
-							sleep(TEMPO_STAT);
-              Serial.print("cmpt=");
-              Serial.println(compteur);
-								while (compteur>compteurRef+20)
-								{
-
-									compteurRef=compteur;
-
-                  Serial.print("yop");
-                  Serial.print(" cmpt=");
-                  Serial.println(compteur);
-                  sleep(TEMPO_STAT);
-								}
-							resultatImpulsionMax[i]=compteur;
-							resultatTempsMax[i]=millis()-tempsMesureVitesse-TEMPO_STAT;
-              Serial.print(F("Cycle "));
-              Serial.print(i);
-              Serial.print(F(" imp= "));
-              Serial.print(resultatImpulsionMax[i]);
-              Serial.print(F(" temps= "));
-              Serial.println(resultatTempsMax[i]);
-
-							compteur=0;
-							compteurRef=0;
-							tempsMesureVitesse=millis();
-							leServo.setObjectif(leServo.getMin());
-							sleep(TEMPO_STAT);
-								while (compteur>compteurRef+20)
-									{
-									compteurRef=compteur;
-
-                  Serial.print("yup ");
-                  Serial.print("cmpt=");
-                  Serial.println(compteur);
-                  sleep(TEMPO_STAT);
-									}
-							resultatImpulsionMin[i]=compteur;
-							resultatTempsMin[i]=millis()-tempsMesureVitesse-TEMPO_STAT;
-              Serial.print(F("Cycle "));
-              Serial.print(i+1);
-              Serial.print(F(" imp= "));
-              Serial.print(resultatImpulsionMin[i]);
-              Serial.print(F(" temps= "));
-              Serial.println(resultatTempsMin[i]);
-
-						}
+                        //etatCalibrateur=LECTURE_OU_ECRITURE_EEEPROM;
+                        etatCalibrateur=MESREFPULSE;
+                    }
+                    break;
+
+                case MESREFPULSE:
+                //mesure des impulsion de reference sur une rotation
+                //de delta faite X fois pour plus de certitude
+                    compteurRef=0;
+                    compteur=0;
+                    for (i=0;i<NBRCYCLE_AR;i=i+1)
+                    {
+                        Serial.print(F("iteration de mesure de ref="));
+                        leServo.setObjectif(leServo.getMilieu()+DELTA);
+                        sleep(TEMPOSLEEP);
+                        mesureRef[i]=compteur;
+                        leServo.setObjectif(leServo.getMilieu());
+                        sleep(TEMPOSLEEP);
+                        compteur=0;
+                        Serial.println(mesureRef[i]);
+                    }
+                    etatCalibrateur=FINDMINMAX;
+                    compteurRef=moyenne(NBRCYCLE_AR,mesureRef);
+                    Serial.print(F(" SUPERcmpteurRefMoyenne="));
+                    Serial.print(compteurRef);
+                    Serial.print(F(" (ecart type : "));
+                    Serial.println(ecartType(NBRCYCLE_AR,mesureRef));
+                    if (compteurRef==0)
+                        {
+                            Serial.println(F("PB : compteur Ref=0 aucune impulsion fourche optique détecté"));
+                            Serial.println(F("retour au début de procédure"));
+                            etatCalibrateur=USB;
+                        }
+                    if (ERREURCOMPTAGE*3>compteurRef)
+                    {
+                        Serial.println(F("ce serait bien que la marge d'erreur soit de l'ordre de 30% de la mesure de reference"));
+                        Serial.println(F("je vais faire autre chose.... Programme a recompiler"));
+                        Serial.println(F("modifier macro ERREURCOMPTAGE et DELTA"));
+                        etatCalibrateur=POTAR;
+                        affichage.affiche(POTAR);
+                    }
+                    break;
+                case FINDMINMAX:
+                    //Serial.println("lalalal");
+                    //sequence pour aller au max puis au min et de déterminer
+                    //les pwm Min et Max du servo
+                    //----------------------------------------------------------
+                    //find max
+                    compteur=compteurRef;
+                    while (compteur>compteurRef-ERREURCOMPTAGE\
+                            && compteur<compteurRef+ERREURCOMPTAGE)
+                        {
+                            Serial.print("M+.....");
+                            compteur=0;
+                            //objTest=objTest+DELTA;
+                            leServo.setObjectif(leServo.getObjectif()+DELTA);
+                            sleep(TEMPOSLEEP);
+                            Serial.print(" cmptr="); Serial.println(compteur);
+                        }
+                    leServo.setMax(leServo.getObjectif()-DELTA);
+                    leServo.setObjectif(leServo.getMilieu());
+                    Serial.print("MAX="); Serial.println(leServo.getMax());
+                    Serial.println("retourneMilieu");
+                    sleep(TEMPOSLEEP);
+                    //----------------------------------------------------------
+                    //find mmin
+                    compteur=compteurRef;
+                    while (compteur>compteurRef-ERREURCOMPTAGE\
+                            && compteur<compteurRef+ERREURCOMPTAGE  )
+                        {
+                            Serial.print(F("M-......"));
+                            compteur=0;
+                            //objTest=objTest-DELTA;
+                            leServo.setObjectif(leServo.getObjectif()-DELTA);
+                            sleep(TEMPOSLEEP);
+                            Serial.print(" cmpteur="); Serial.println(compteur);
+                        }
+                    leServo.setMin(leServo.getObjectif()+DELTA);
+                    leServo.setObjectif(leServo.getObjectif()+DELTA);
+                    Serial.print("MIN="); Serial.println(leServo.getMin());
+                    sleep(TEMPOSLEEP);
+                    Serial.println("la le servo est au min et va faire grande course");
+                    leServo.setObjectif(leServo.getMin());
+                    //----------------------------------------------------------
+                    //séquence pour mesurer une vitesse et amplitude moyenne
+                    //(10 cycles d'aller et retour de min à max
+                    //et enregistrement systématique des mesures)
+                    for (i=0;i<NBRCYCLE_AR;i=i+1)
+                        {
+                            compteur=0;
+                            compteurRef=0;
+                            //compteur ref utilisé différement dans la suite
+                            //par rapport à ce qui était fait jusque là. Compteur
+                            //ref est utilisé pour voir si le servo continue
+                            //de bouger
+                            tempsMesureVitesse=millis();
+                            Serial.print("tempsMesureVitesse=");
+                            Serial.println(tempsMesureVitesse);
+                            // Mesure de min vers max
+                            leServo.setObjectif(leServo.getMax());
+                            sleep(TEMPO_STAT);
+                            Serial.print("cmpt="); Serial.println(compteur);
+                            while (compteur>compteurRef+20)
+                                {
+                                    compteurRef=compteur;
+                                    Serial.print("yop");
+                                    Serial.print(" cmpt=");
+                                    Serial.println(compteur);
+                                    sleep(TEMPO_STAT);
+                                }
+                            resultatImpulsionMax[i]=compteur;
+                            resultatTempsMax[i]=millis()-tempsMesureVitesse-\
+                                                    TEMPO_STAT;
+                            Serial.print(F("Cycle "));
+                            Serial.print(i);
+                            Serial.print(F(" imp= "));
+                            Serial.print(resultatImpulsionMax[i]);
+                            Serial.print(F(" temps= "));
+                            Serial.println(resultatTempsMax[i]);
+
+                            compteur=0;
+                            compteurRef=0;
+                            tempsMesureVitesse=millis();
+                            // Mesure de max vers min
+                            leServo.setObjectif(leServo.getMin());
+                            sleep(TEMPO_STAT);
+                            while (compteur>compteurRef+20)
+                                {
+                                    compteurRef=compteur;
+                                    Serial.print("yup ");
+                                    Serial.print("cmpt=");
+                                    Serial.println(compteur);
+                                    sleep(TEMPO_STAT);
+                                }
+                            resultatImpulsionMin[i]=compteur;
+                            resultatTempsMin[i]=millis()-tempsMesureVitesse-TEMPO_STAT;
+                            Serial.print(F("Cycle "));
+                            Serial.print(i+1);
+                            Serial.print(F(" imp= "));
+                            Serial.print(resultatImpulsionMin[i]);
+                            Serial.print(F(" temps= "));
+                            Serial.println(resultatTempsMin[i]);
+                        } //fin for NBCYCLES

-					Serial.println(F("ATTENTION regarder  et noter le sens de rotation du premier mouvement "));
-					Serial.println(F("si pret faire un clic "));
-					etatCalibrateur=WAITCLIC;
-
-
-				case WAITCLIC:
-					if (boutonP.hasBeenClicked())
-						{
-							boutonP.acquit();
-							etatCalibrateur=DISPRESULT;
-							leServo.setObjectif(leServo.getMax());
-						}
-					break;
-
-				case DISPRESULT:
-
-
-
-                                       Serial.println();
-                                       Serial.println();
-
-                                       Serial.println(F("Alors quelle sens de rotation ?") );
-                                       Serial.println();
-                                       Serial.println();
-				                               Serial.print(F(" Dans le sens croissant pwm, moyenne : "));
-                                       Serial.print(moyenne(NBRCYCLE_AR,resultatImpulsionMax));
-                                       Serial.print(F(" impulsions (Ecart type : "));
-                                       Serial.print(ecartType(NBRCYCLE_AR,resultatImpulsionMax));
-                                       Serial.print(F(") atteintes en un temps moyen de : "));
-                                       Serial.print(moyenne(NBRCYCLE_AR,resultatTempsMax));
-                                       Serial.print(F(" ms (ecart type : "));
-                                       Serial.print(ecartType(NBRCYCLE_AR,resultatTempsMax));
-                                       Serial.println(F(" ms)"));
-
-                                       Serial.print(F(" Dans le sens decroissant pwm, moyenne  : "));
-                                       Serial.print(moyenne(NBRCYCLE_AR,resultatImpulsionMin));
-                                       Serial.print(F("impulsions (Ecart type : "));
-                                       Serial.print(ecartType(NBRCYCLE_AR,resultatImpulsionMin));
-                                       Serial.print(F(") atteintes en un temps moyen de : "));
-                                       Serial.print(moyenne(NBRCYCLE_AR,resultatTempsMin));
-                                       Serial.print(F(" ms (ecart type : "));
-                                       Serial.print(ecartType(NBRCYCLE_AR,resultatTempsMin));
-                                       Serial.println(F(" ms)"));
-
-
-
-                            					//potence.setObjectif(potence.getMax());
-                            					Serial.println(F("si nouveau servo : doubleClic, si changement mode clic"));
-                            					etatCalibrateur=WAITCLIC2;
-                            					break;
-
-				case WAITCLIC2:
-					if (boutonP.hasBeenClicked())
-						{
-							boutonP.acquit();
-							etatCalibrateur=SWEEPTOMIN;
-							affichage.affiche(SWEEPTOMIN);
-							leServo.setObjectif(leServo.getMin());
+                    Serial.println(F("ATTENTION regarder  et noter le sens de rotation du premier mouvement "));
+                    Serial.println(F("si pret faire un clic "));
+                    etatCalibrateur=WAITCLIC;
+
+
+                case WAITCLIC:
+                    if (boutonP.hasBeenClicked())
+                        {
+                            boutonP.acquit();
+                            etatCalibrateur=DISPRESULT;
+                            leServo.setObjectif(leServo.getMax());
+                        }
+                    break;
+
+                case DISPRESULT:
+                    Serial.println();
+                    Serial.println();
+                    Serial.println(F("Alors quelle sens de rotation ?") );
+                    Serial.println();
+                    Serial.println();
+                    Serial.print(F(" Dans le sens croissant pwm, moyenne : "));
+                    Serial.print(moyenne(NBRCYCLE_AR,resultatImpulsionMax));
+                    Serial.print(F(" impulsions (Ecart type : "));
+                    Serial.print(ecartType(NBRCYCLE_AR,resultatImpulsionMax));
+                    Serial.print(F(") atteintes en un temps moyen de : "));
+                    Serial.print(moyenne(NBRCYCLE_AR,resultatTempsMax));
+                    Serial.print(F(" ms (ecart type : "));
+                    Serial.print(ecartType(NBRCYCLE_AR,resultatTempsMax));
+                    Serial.println(F(" ms)"));
+                    Serial.print(F(" Dans le sens decroissant pwm, moyenne  : "));
+                    Serial.print(moyenne(NBRCYCLE_AR,resultatImpulsionMin));
+                    Serial.print(F("impulsions (Ecart type : "));
+                    Serial.print(ecartType(NBRCYCLE_AR,resultatImpulsionMin));
+                    Serial.print(F(") atteintes en un temps moyen de : "));
+                    Serial.print(moyenne(NBRCYCLE_AR,resultatTempsMin));
+                    Serial.print(F(" ms (ecart type : "));
+                    Serial.print(ecartType(NBRCYCLE_AR,resultatTempsMin));
+                    Serial.println(F(" ms)"));
+                    //potence.setObjectif(potence.getMax());
+                    Serial.println(F("si nouveau servo : doubleClic, si changement mode clic"));
+                    etatCalibrateur=WAITCLIC2;
+                    break;
+
+                case WAITCLIC2:
+                    if (boutonP.hasBeenClicked())
+                        {
+                            boutonP.acquit();
+                            etatCalibrateur=SWEEPTOMIN;
+                            affichage.affiche(SWEEPTOMIN);
+                            leServo.setObjectif(leServo.getMin());
               Serial.print(F("bouger le potar modifie la vitesse, double click la sauve en prom "));
-						}
-					if (boutonP.hasBeenDoubleClicked())
-						{
-							boutonP.acquit();
-							etatCalibrateur=MESREFPULSE;
-              leServo=servoTest(PINSERVO);
-							leServo.setObjectif(leServo.getMilieu());
-							//potence.setObjectif(bonnePositionPotence);
-							sleep(TEMPOSLEEP*3);
-						}
-					break ;
-
-				case SWEEPTOMIN:
-					if (leServo.isMin())
-						{
-							etatCalibrateur=SWEEPTOMAX;
-							leServo.setObjectif(leServo.getMax());
-						}
-
-					if (boutonP.hasBeenClicked())
-						{
-							boutonP.acquit();
-             lePotar.acquit();
-							etatCalibrateur=POTAR;
-							affichage.affiche(POTAR);
-						}
-
+                        }
+                    if (boutonP.hasBeenDoubleClicked())
+                        {
+                            boutonP.acquit();
+                            etatCalibrateur=MESREFPULSE;
+                            leServo=servoTest(PINSERVO);
+                            leServo.setObjectif(leServo.getMilieu());
+                            //potence.setObjectif(bonnePositionPotence);
+                            sleep(TEMPOSLEEP*3);
+                        }
+                    break ;
+
+                case SWEEPTOMIN:
+                    if (leServo.isMin())
+                        {
+                            etatCalibrateur=SWEEPTOMAX;
+                            leServo.setObjectif(leServo.getMax());
+                        }
+                    if (boutonP.hasBeenClicked())
+                        {
+                            boutonP.acquit();
+                            lePotar.acquit();
+                            etatCalibrateur=POTAR;
+                            affichage.affiche(POTAR);
+                        }
+                    if (lePotar.hasBeenMovedALot())
+                        {
+                         //Serial.println("plip");
+                          leServo.setVitesse(map(lePotar.getValue()\
+                                                ,0,1023,0,VITESSEMAXSERVO));
+                        }
+                    if (boutonP.hasBeenDoubleClicked())
+                        {
+                            boutonP.acquit();
+                            lePotar.getValue();
+                            //enregistre en eeprom
+                            EEPROM.put(ADRESSE_EEPROM, lePotar.getValue());
+                            Serial.print(F("sauver en prom vitesse = "));
+                            Serial.print( lePotar.getValue());
+                            Serial.print(F("microsec de PWM par seconde"));
+                        }

-           if (lePotar.hasBeenMovedALot())
-           {
-             //Serial.println("plip");
-              leServo.setVitesse(map(lePotar.getValue(),0,1023,0,VITESSEMAXSERVO));
-
+                    break;
+
+                case SWEEPTOMAX:
+                    if (leServo.isMax())
+                        {
+                            etatCalibrateur=SWEEPTOMIN;
+                            leServo.setObjectif(leServo.getMin());
+                        }
+                    if (boutonP.hasBeenClicked())
+                        {
+                            boutonP.acquit();
+                            lePotar.acquit();
+                            etatCalibrateur=POTAR;
+                            affichage.affiche(POTAR);
+                        }
+                    if (lePotar.hasBeenMovedALot())
+                        {
+                            //Serial.println("plup");
+                            leServo.setVitesse(map(lePotar.getValue(),\
+                                                    0,1023,0,VITESSEMAXSERVO));
+                        }
+                    if (boutonP.hasBeenDoubleClicked())
+                        {
+                            boutonP.acquit();
+                            lePotar.getValue();
+                            //enregistre en eeprom
+                            EEPROM.put(ADRESSE_EEPROM,\
+                                        map(lePotar.getValue(),0,1023,0,\
+                                        VITESSEMAXSERVO));
+                            Serial.print(F("sauver en prom vitesse = "));
+                            Serial.print( map(lePotar.getValue(),\
+                                                0,1023,0,VITESSEMAXSERVO));
+                            Serial.print(F("microsec de PWM par seconde"));
+                        }
+                    break;
+
+                case POTAR:
+                    int temp;
+                    int potarVal;
+                    potarVal=lePotar.getValue();
+                    temp=map(potarVal,0,1023,leServo.getMin(),leServo.getMax());
+                    leServo.setObjectif(temp);
+                    if (boutonP.hasBeenClicked())
+                        {
+                            boutonP.acquit();
+                            etatCalibrateur=4;
+                            affichage.affiche(4);
+                            //leServo.setObjectif(leServo.getMilieu());
+                        }
+                    break;
+
+                case MILIEU:
+                    leServo.setObjectif(leServo.getMilieu());
+                    if (boutonP.hasBeenClicked())
+                        {
+                            boutonP.acquit();
+                            etatCalibrateur=1;
+                            affichage.affiche(1);
+                        }
+                    break;
+
+                case 8:
+                    break;
             }
-
-
-            if (boutonP.hasBeenDoubleClicked())
-           {
-              boutonP.acquit();
-              lePotar.getValue();
-              EEPROM.put(ADRESSE_EEPROM, lePotar.getValue());//enregistre en eeprom
-              Serial.print(F("sauver en prom vitesse = ")); Serial.print( lePotar.getValue());Serial.print(F("microsec de PWM par seconde"));
-            }
-
-					break;
-
-				case SWEEPTOMAX:
-					if (leServo.isMax())
-						{
-							etatCalibrateur=SWEEPTOMIN;
-							leServo.setObjectif(leServo.getMin());
-						}
-
-					if (boutonP.hasBeenClicked())
-						{
-							boutonP.acquit();
-              lePotar.acquit();
-							etatCalibrateur=POTAR;
-							affichage.affiche(POTAR);
-						}
-
-             if (lePotar.hasBeenMovedALot())
-           {
-
-              //Serial.println("plup");
-               leServo.setVitesse(map(lePotar.getValue(),0,1023,0,VITESSEMAXSERVO));
-
-            }
-
-
-          if (boutonP.hasBeenDoubleClicked())
-           {
-              boutonP.acquit();
-              lePotar.getValue();
-              EEPROM.put(ADRESSE_EEPROM, map(lePotar.getValue(),0,1023,0,VITESSEMAXSERVO));//enregistre en eeprom
-              Serial.print(F("sauver en prom vitesse = ")); Serial.print( map(lePotar.getValue(),0,1023,0,VITESSEMAXSERVO));Serial.print(F("microsec de PWM par seconde"));
-            }
-					break;
-
-				case POTAR:
-					int temp;
-					int potarVal;
-					potarVal=lePotar.getValue();
-					//Serial.print("lepotar : ");
-					//Serial.println(potarVal);
-					temp=map(potarVal,0,1023,leServo.getMin(),leServo.getMax());
-					// if (leServo.getType())
-					// {
-					// temp=map(potarVal,0,1023,300,3000);
-					// }
-					// else
-					// {
-					// temp=map(potarVal,0,1023,100,1000);
-					// }
-					//Serial.print ("OBJECTIF=  ");
-					//Serial.println(temp);
-					leServo.setObjectif(temp);
-					//potence.setObjectif(temp);
-					if (boutonP.hasBeenClicked())
-						{
-							boutonP.acquit();
-							etatCalibrateur=4;
-							affichage.affiche(4);
-							//leServo.setObjectif(leServo.getMilieu());
-						}
-					break;
-
-				case MILIEU:
-					leServo.setObjectif(leServo.getMilieu());
-					if (boutonP.hasBeenClicked())
-						{
-							boutonP.acquit();
-							etatCalibrateur=1;
-							affichage.affiche(1);
-						}
-					break;
-
-				case 8:
-					break;
-			}

-	}
+    }

 void setup()
 {
   int vitesseDinit;
-	Serial.begin(57600);
-	//potence.setPotence();
+    Serial.begin(57600);
+    //potence.setPotence();
   lePotar.init();
-	leServo.setType(true);
+    leServo.setType(true);
   EEPROM.get(ADRESSE_EEPROM, vitesseDinit);
  // Serial.print("vitesse lu=");Serial.println(vitesseDinit);
   if (vitesseDinit<=VITESSEMAXSERVO && vitesseDinit>=0)
@@ -670,18 +593,18 @@
     leServo.setVitesse(300);
    }

-	Wire.begin();
-
-	Serial.println("hello");
-	mySCoop.start();
-	temp=millis();
-	//etatCalibrateur=3; fait dans l'init de la variable
-	affichage.affiche(POTAR);
-	attachInterrupt(0, updatePulseCompteur, CHANGE ); // Int0= la pin N°2 sur un UNO
+    Wire.begin();
+
+    Serial.println("hello");
+    mySCoop.start();
+    temp=millis();
+    //etatCalibrateur=3; fait dans l'init de la variable
+    affichage.affiche(POTAR);
+    attachInterrupt(0, updatePulseCompteur, CHANGE ); // Int0= la pin N°2 sur un UNO
 }
  void updatePulseCompteur()
 {
-	compteur++;
+    compteur++;
 }

@@ -689,11 +612,11 @@

 void loop ()
 {
-	mySCoop.sleep(1);
-	if (millis()>2000+temp)
-		{
-			temp=millis();
-		}
-
-}
-
+    mySCoop.sleep(1);
+    if (millis()>2000+temp)
+        {
+            temp=millis();
+        }
+
+}
+


done : initialise_pwr_src_select

done : initialise_pwr_src_select

--- _09_ir_tx_rx/_09_ir_tx_rx.ino
+++ _09_ir_tx_rx/_09_ir_tx_rx.ino
@@ -228,15 +228,16 @@

 boolean initialise_pwr_src_select()
 {
+  decode_results results;
   irrecv.resume();
   while(irrecv.decode(&results) != 1 ) { }

   switch (results.value) {
     case 0xFF02FD:
-        return True;
+        return 1;
         break;
     case 0xFF9867:
-        return False;
+        return 0;
         break;
     default:
         initialise_pwr_src_select();
@@ -259,7 +260,7 @@

   lcd.clear();
   lcd.setCursor(0, 0);
-  lcd.print('Select pwr src :');
+  lcd.print("Select pwr src :");
   lcd.setCursor(0, 1);
   lcd.print("ON: TV OFF: USB");


removed duplicate file. Need the arduino code to be in a sketch folder

--- ArduinoSerialInterface/ArduinoPythonInterfacer.ino
+++ ArduinoSerialInterface/ArduinoPythonInterfacer.ino
@@ -1,60 +0,0 @@
-volatile int count = 0; //number of encoder counts (using a quadrature encoder)
-
-//encoder pins: pins 2,3 are hardware interrupts
-const int encoderA = 2;
-const int encoderB = 3;
-
-//actuator pins: pins 3,5,6,9,10,11 are capable of hardware pwm
-const int motorPWM = 5;
-const int servoPWM = 6;
-
-//end flag and delimiter used to parse incoming serial message of setpoints, etc.
-//Your message should be of the form: "XXX,YYY,ZZZ,etc.f". Note that there are no spaces.
-char flag = 'f';
-char delim[2] = ",";
-
-volatile unsigned long curr_time;
-volatile unsigned long temp;
-char *parser;
-char readIn[16];
-
-void setup() {
-  // put your setup code here, to run once:
-  pinMode(encoderA, INPUT);
-  pinMode(encoderB, INPUT);
-  pinMode(motorPWM, OUTPUT);
-  attachInterrupt(digitalPinToInterrupt(encoderA), inc, CHANGE);
-  attachInterrupt(digitalPinToInterrupt(encoderB), inc, CHANGE);
-  curr_time = millis();
-  Serial.begin(250000);
-  Serial.println("Running");
-
-}
-
-void loop() {
-  // put your main code here, to run repeatedly:
-  temp = millis()-curr_time;
-  if (temp > 2) {
-    Serial.println(count/temp * 1000); //prints velocity out to the serial port
-    count = 0;
-    curr_time = millis();
-  }
-
-
-  //parses any available incoming data. Use atoi() to convert the characters to bytes (for math manipulation)
-  temp = Serial.available();
-  if (temp > 0) {
-    Serial.readBytesUntil(flag, readIn, 8);
-    parser = strtok(readIn, delim);
-    while (parser != NULL) {
-      //Serial.println(atoi(parser) + 2);
-      parser = strtok(NULL, delim);
-    }
-  }
-
-  delay(1);
-}
-
-void inc() {
-  count++;
-}


removed redundant code

removed redundant code

--- module/module.ino
+++ module/module.ino
@@ -45,13 +45,11 @@
 	}

 	// RFID tag detected, read block that contains time data
-	if(responseFlag == true) {
-		digitalWrite(ledPin, HIGH);
-		MF_READ(0x01, 0x05);
-		delay(200);
-		responseFlag = getResponse();
-		if(responseFlag == false) Serial.println("Unexpected result");
-	}
+	digitalWrite(ledPin, HIGH);
+	MF_READ(0x01, 0x05);
+	delay(200);
+	responseFlag = getResponse();
+	if(responseFlag == false) Serial.println("Unexpected result");

 	// Get ready to accumulate time
 	elapsedTime = accumulator();
@@ -85,13 +83,12 @@
 }

 /*
-	Checksum: Function that calculates the checksum of a packet to ensure
-			  data integrity.
+	Calculates the checksum of a packet to ensure data integrity.

 	Param: A[] 		- array containing all bytes in a packet
 		   numBytes - number of bytes in the array

-	Post: Returns checksum.
+	Returns: checksum

 */
 unsigned char checksum(unsigned char A[], int numBytes) {
@@ -106,7 +103,7 @@
 }

 /*
-	MiFare Classic SNR: Function that gets the serial number of an RFID tag.
+	Gets the serial number of an RFID tag.

 	Post: Response packet contains OK status and serial number of the tag selected

@@ -119,7 +116,7 @@
 }

 /*
-	MiFare Classic Write: Function that writes to the selected RFID tag.
+	Writes to the selected RFID tag.

 	Param: numBlocks 	- number of 16 byte blocks to be written to (max 3)
 		   startAddress - address of the first block (0 - 63)
@@ -159,7 +156,7 @@
 }

 /*
-	MiFare Classic Read: Function that reads the selected RFID tag.
+	Reads the selected RFID tag.

 	Param: numBlocks	- number of 16 byte blocks to be read (max 3)
 		   startAddress - address of first block to read (0 - 63)
@@ -182,10 +179,10 @@

 }
 /*
-	Accumulator: Function that waits for a control signal to go high and counts
-				 time that control signal is high for.
+	Function that waits for a control signal to go high and counts time
+	that control signal is high for.

-	Post: Returns time accumulated.
+	Return: time accumulated

 */
 unsigned long accumulator(void) {


Fixed timer.

Fixed timer.

--- BackEnd/BackEnd.ino
+++ BackEnd/BackEnd.ino
@@ -942,22 +942,13 @@
   { // Overwrite fPinValSum based on timer

    // Check for a positive edge is detected
-    if( g_aPins[_iOutPinNum].prev_value < DIGITAL_VOLTAGE_THRESHOLD && g_aPins[_iOutPinNum].value >= DIGITAL_VOLTAGE_THRESHOLD )
+    if( !g_aPins[_iOutPinNum].timer_running && g_aPins[_iOutPinNum].prev_value < DIGITAL_VOLTAGE_THRESHOLD && g_aPins[_iOutPinNum].value >= DIGITAL_VOLTAGE_THRESHOLD )
     {
       g_aPins[_iOutPinNum].timer_running = true;
       g_aPins[_iOutPinNum].timer_start_time = millis();
       Serial.println("timer_running = true");
     }

-    // IF timer_is_on && Timer_Running
-      // IF timer expired
-        // Set timer_is_on == false
-        //
-     // ELSE
-       // Set pin to HIGH (Over write the output)
-   // ELSE
-     // Set pin to VALUE
-
     // Set pin value to zero if timer expired
     if( g_aPins[_iOutPinNum].timer_running )
     {
@@ -976,14 +967,6 @@
        fPinValSum = 0.0;
     }
   }
-
-  // KEEP value LOW until we hit the back to normal condition
-
-// BACK to normal?
-//      g_aPins[_iOutPinNum].value = fPinValSum;
-// ELSE
-//       g_aPins[_iOutPinNum].value = 0.0; // Keep the output value off
-

   // Updating values
   g_aPins[_iOutPinNum].prev_value = g_aPins[_iOutPinNum].value;


ignore "B" command when oneshot

ignore "B" command when oneshot

--- ptw-wheel.ino
+++ ptw-wheel.ino
@@ -165,12 +165,15 @@
     // set instrument_brightness_target value
     // "b:[0.0-1.0];"
     else if(command=="B") {
-      // TODO argument check
-      // argument is float
-      instrument_brightness_target = argument.toFloat();
-      // Serial.print("set instrument_brightness min value: ");
-      // Serial.println(instrument_brightness_target);
-      updateLED();
+      if(i_type==INSTRUMENT_TYPE_LONGSHOT){
+        // TODO argument check
+        // argument is float
+        instrument_brightness = argument.toFloat();
+        // instrument_brightness_target = argument.toFloat();
+        // Serial.print("set instrument_brightness min value: ");
+        // Serial.println(instrument_brightness_target);
+        updateLED();
+      }
     }
     else {
       Serial.print("Command not found: ");
@@ -184,23 +187,6 @@
     if(i_type==INSTRUMENT_TYPE_ONESHOT){
       if(instrument_brightness_min+0.01 <= instrument_brightness) {
         instrument_brightness -= 0.01;
-        updateLED();
-      }
-    }
-    else if(i_type==INSTRUMENT_TYPE_LONGSHOT){
-      // fade effect brightness to instrument_brightness_target value
-      float diff = abs(instrument_brightness_target-instrument_brightness);
-      if(0.01<diff){
-        if(instrument_brightness_target < instrument_brightness) {
-          instrument_brightness -= 0.01;
-        }
-        else {
-          instrument_brightness += 0.01;
-        }
-        updateLED();
-      }
-      else if(diff != 0.0){
-        effect_brightness = effect_brightness_target;
         updateLED();
       }
     }


Fixes on BLE_Notify

Fixes on BLE_Notify

--- cpp_utils/tests/BLETests/Arduino/BLE_notify/BLE_notify.ino
+++ cpp_utils/tests/BLETests/Arduino/BLE_notify/BLE_notify.ino
@@ -23,7 +23,8 @@
 #include <BLEUtils.h>
 #include <BLE2902.h>

-BLEServer *pServer = NULL;
+BLEServer* pServer = NULL;
+BLECharacteristic* pCharacteristic = NULL;
 bool deviceConnected = false;
 bool oldDeviceConnected = false;
 uint8_t value = 0;
@@ -61,7 +62,7 @@
   BLEService *pService = pServer->createService(SERVICE_UUID);

   // Create a BLE Characteristic
-  BLECharacteristic * pCharacteristic = pService->createCharacteristic(
+  pCharacteristic = pService->createCharacteristic(
                       CHARACTERISTIC_UUID,
                       BLECharacteristic::PROPERTY_READ   |
                       BLECharacteristic::PROPERTY_WRITE  |


Delete 01_Particle.ino

Delete 01_Particle.ino

--- 01_Particle.ino
+++ 01_Particle.ino
@@ -1,89 +0,0 @@
-/**************************************************************
- * Blynk is a platform with iOS and Android apps to control
- * Arduino, Raspberry Pi and the likes over the Internet.
- * You can easily build graphic interfaces for all your
- * projects by simply dragging and dropping widgets.
- *
- *   Downloads, docs, tutorials: http://www.blynk.cc
- *   Blynk community:            http://community.blynk.cc
- *   Social groups:              http://www.fb.com/blynkapp
- *                               http://twitter.com/blynk_app
- *
- * Blynk library is licensed under MIT license
- * This example code is in public domain.
- *
- * WARNING: It is recommended to use SparkCorePolledTimer library
- *          to make periodic actions (similar to SimpleTimer on Arduino).
- *
- **************************************************************/
-//#define BLYNK_DEBUG // Uncomment this to see debug prints
-#define BLYNK_PRINT Serial
-#include "blynk/blynk.h"
-
-// You should get Auth Token in the Blynk App.
-// Go to the Project Settings (nut icon).
-char auth[] = "YourAuthToken";
-
-// Attach a Button widget (mode: Switch) to the Digital pin 7 - and control the built-in blue led.
-// Attach a Graph widget to Analog pin 1
-// Attach a Gauge widget to Analog pin 2
-
-// No coding required for direct pin operations!
-
-void setup()
-{
-    Serial.begin(9600);
-    delay(5000); // Allow board to settle
-    Blynk.begin(auth);
-}
-
-// Attach a Button widget (mode: Push) to the Virtual pin 1 - and send sweet tweets!
-BLYNK_WRITE(V1) {
-    if (param.asInt() == 1) { // On button down...
-        // Tweeting!
-        // Note:
-        //   We allow 1 tweet per minute for now.
-        //   Twitter doesn't allow identical subsequent messages.
-        Blynk.tweet("My Particle project is tweeting using @blynk_app and it’s awesome!\n @Particle #IoT #blynk");
-
-        // Pushing notification to the app!
-        // Note:
-        //   We allow 1 notification per minute for now.
-        Blynk.notify("You pressed the button and I know it ;)");
-    }
-}
-
-// Attach a ZeRGBa widget (mode: Merge) to the Virtual pin 2 - and control the built-in RGB led!
-BLYNK_WRITE(V2) {
-    int r = param[0].asInt();
-    int g = param[1].asInt();
-    int b = param[2].asInt();
-    if (r > 0 || g > 0 || b > 0) {
-        RGB.control(true);
-        RGB.color(r, g, b);
-    } else {
-        RGB.control(false);
-    }
-}
-
-void loop()
-{
-    Blynk.run();
-
-    if (ModeBtnPressed()) {
-        Blynk.notify("Mode button was pressed");
-    }
-}
-
-// *** Utility functions
-
-bool ModeBtnPressed() {
-    if(millis() > 5000) {
-        if(BUTTON_GetDebouncedTime(BUTTON1) >= 50) {
-            BUTTON_ResetDebouncedState(BUTTON1);
-            return 1;
-        }
-    }
-    return 0;
-}
-


The DebugVersion_06 was removed to put in a more general name, so the version number will in the file, rather than in the name.

--- DebugVersion_06.ino
+++ DebugVersion_06.ino
@@ -1,213 +0,0 @@
-/*
- Manchester Encoding reading by delay rather than interrupt
- Rob Ward July 2014
- This example code is in the public domain.
- */
-
-//Interface Definitions
-int RxPin           = 8;   //The number of signal from the Rx
-int ledPin          = 13;  //The number of the onboard LED pin
-
-// Variables for Manchester Receiver Logic:
-word    sDelay     = 245;  //Small Delay about 1/4 of bit duration  begin with 320
-word    lDelay     = 490;  //Long Delay about 1/2 of bit duration  begin with 640, 1/4 + 1/2 = 3/4
-byte    polarity   = 1;    //0 for lo->hi==1 or 1 for hi->lo==1 for Polarity, sets tempBit at start
-byte    tempBit    = 1;    //Reflects the required transition polarity
-boolean firstZero  = false;//flags when the first '0' is found.
-boolean noErrors   = true; //flags if signal does not follow Manchester conventions
-//variables for Header detection
-byte    headerBits = 10;   //The number of ones expected to make a valid header
-byte    headerHits = 0;    //Counts the number of "1"s to determine a header
-//Variables for Byte storage
-boolean sync0In=true;      //Expecting sync0 to be inside byte boundaries, set to false for sync0 outside bytes
-byte    dataByte   = 0;    //Accumulates the bit information
-byte    nosBits    = 0;    //Counts to 8 bits within a dataByte
-byte    maxBytes   = 5;    //Set the bytes collected after each header. NB if set too high, any end noise will cause an error
-byte    nosBytes   = 0;    //Counter stays within 0 -> maxBytes
-//Variables for multiple packets
-byte    bank       = 0;    //Points to the array of 0 to 3 banks of results from up to 4 last data downloads
-byte    nosRepeats = 0;    //Number of times the header/data is fetched at least once or up to 4 times
-//Banks for multiple packets if required (at least one will be needed)
-byte  manchester[4][20];   //Stores 4 banks of manchester pattern decoded on the fly
-
-/* Sample Printout, Binary for every packet, but only combined readings after three of the different packets have been received
- This is an example where the Sync '0' is inside the byte alignment
-
- Using a delay of 1/4 bitWaveform 245 uSecs 1/2 bitWaveform 490 uSecs
- Positive Polarity
- 10 bits required for a valid header
- Sync Zero inside Packet
- D 00 00001111 01 22223333 02 44445555 03 66667777 04 88889999 05 AAAABBBB 06 CCCCDDDD 07 EEEEFFFF 08 00001111 90 22223333
- D 5F 01011111 14 00010100 28 00101000 C5 11000101 01 00000001 //Oregon Scientific Temperature
- D 54 01010100 98 10011000 20 00100000 A0 10100000 00 00000000 //Oregon Scientific Rainfall
- D 58 01011000 91 10010001 20 00100000 52 01010010 13 00010011 //Oregon Scientific Anemometer/Wind direction
-These are just raw test dumps. The data has to be processed and require 10-11 bytes for all the packet to be seen
-Oregon Scientific works on nibbles and these need to reversed ie ABCD become DCBA in each nibble
-Also the OS protocol has a simple checksum to assist with validation as the packets are only sent once a cycle
- */
-
-void setup() {
-  Serial.begin(115200);//make it fast so it dumps quick!
-  pinMode(RxPin, INPUT);
-  pinMode(ledPin, OUTPUT);
-  Serial.println();
-  lDelay=2*sDelay;//just to make sure the 1:2 ratio is established. They can have some other ratio if required
-  Serial.print("Using a delay of 1/4 bitWaveform ");// +-15% and they still seem to work ok, pretty tolerant!
-  Serial.print(sDelay,DEC);
-  Serial.print(" uSecs 1/2 bitWaveform ");//these may not be exactly 1:2 ratio as processing also contributes to these delays.
-  Serial.print(lDelay,DEC);
-  Serial.println(" uSecs ");
-  if (polarity){
-    Serial.println("Negative Polarity hi->lo=1");
-  }
-  else{
-    Serial.println("Positive Polarity lo->hi=1");
-  }
-  Serial.print(headerBits,DEC);
-  Serial.println(" bits expected for a valid header");
-  if (sync0In){
-    Serial.println("Sync Zero inside Packet");
-  }
-  else{
-    Serial.println("Sync Zero outside Packet");
-  }
-  Serial.println("D 00 00001111 01 22223333 02 44445555 03 66667777 04 88889999 05 AAAABBBB 06 CCCCDDDD 07 EEEEFFFF 08 00001111 90 22223333");
-  //if packet is repeated then best to have non matching numbers in the array slots to begin with
-  //clear the array to different nos cause if all zeroes it might think that is a valid 3 packets ie all equal
-  eraseManchester();  //clear the array to different nos cause if all zeroes it might think that is a valid 3 packets ie all equal
-}//end of setup
-
-// Main routines, find header, then sync in with it, get a packet, and decode data in it, plus report any errors.
-void loop(){
-  tempBit=polarity; //these begin the same for a packet
-  noErrors=true;
-  firstZero=false;
-  headerHits=0;
-  nosBits=0;
-  nosBytes=0;
-  while (noErrors && (nosBytes<maxBytes)){
-    while(digitalRead(RxPin)!=tempBit){
-      //pause here until a transition is found
-    }//at Data transition, half way through bit pattern, this should be where RxPin==tempBit
-    delayMicroseconds(sDelay);//skip ahead to 3/4 of the bit pattern
-    // 3/4 the way through, if RxPin has changed it is definitely an error
-    digitalWrite(ledPin,0); //Flag LED off!
-    if (digitalRead(RxPin)!=tempBit){
-      noErrors=false;//something has gone wrong, polarity has changed too early, ie always an error
-    }//exit and retry
-    else{
-      delayMicroseconds(lDelay);
-      //now 1 quarter into the next bit pattern,
-      if(digitalRead(RxPin)==tempBit){ //if RxPin has not swapped, then bitWaveform is swapping
-        //If the header is done, then it means data change is occuring ie 1->0, or 0->1
-        //data transition detection must swap, so it loops for the opposite transitions
-        tempBit = tempBit^1;
-      }//end of detecting no transition at end of bit waveform, ie end of previous bit waveform same as start of next bitwaveform
-
-      //Now process the tempBit state and make data definite 0 or 1's, allow possibility of Pos or Neg Polarity
-      byte bitState = tempBit ^ polarity;//if polarity=1, invert the tempBit or if polarity=0, leave it alone.
-      if(bitState==1){ //1 data could be header or packet
-        if(!firstZero){
-          headerHits++;
-          if (headerHits==headerBits){
-            digitalWrite(ledPin,1); //valid header accepted, minimum required found
-            //Serial.print("H");
-          }
-        }
-        else{
-          add(bitState);//already seen first zero so add bit in
-        }
-      }//end of dealing with ones
-      else{  //bitState==0 could first error, first zero or packet
-        // if it is header there must be no "zeroes" or errors
-        if(headerHits<headerBits){
-          //Still in header checking phase, more header hits required
-          noErrors=false;//landing here means header is corrupted, so it is probably an error
-        }//end of detecting a "zero" inside a header
-        else{
-          //we have our header, chewed up any excess and here is a zero
-          if (!firstZero){ //if first zero, it has not been found previously
-            firstZero=true;
-            if(sync0In){
-              add(bitState);//Add zero to bytes
-            }
-            //Serial.print("!");
-          }//end of finding first zero
-          else{
-            add(bitState);
-          }//end of adding a zero bit
-        }//end of dealing with a first zero
-      }//end of dealing with zero's (in header, first or later zeroes)
-    }//end of first error check
-  }//end of while noErrors=true and getting packet of bytes
-  digitalWrite(ledPin,0); //data processing exited, look for another header
-}//end of mainloop
-
-//Read the binary data from the bank and apply conversions where necessary to scale and format data
-void analyseData(){
-}
-
-void add(byte bitData){
-  dataByte=(dataByte<<1)|bitData;
-  nosBits++;
-  if (nosBits==8){
-    nosBits=0;
-    manchester[bank][nosBytes]=dataByte;
-    nosBytes++;
-    //Serial.print("B");
-  }
-  if(nosBytes==maxBytes){
-    hexBinDump();//for debug purposes dump out in hex and bainary
-    //analyseData();//later on develop your own analysis routines
-  }
-}
-
-void hexBinDump(){
-  //Print the fully aligned binary data in manchester[bank] array
-  Serial.print("D ");
-  for( int i=0; i < maxBytes; i++){
-    byte mask = B10000000;
-    if (manchester[bank][i]<16){
-      Serial.print("0"); //Pad single digit hex
-    }
-    Serial.print(manchester[bank][i],HEX);
-    Serial.print(" ");
-    for (int k=0; k<8; k++){
-      if (manchester[bank][i] & mask){
-        Serial.print("1");
-      }
-      else{
-        Serial.print("0");
-      }
-      mask = mask >> 1;
-    }
-    Serial.print(" ");
-  }
-  Serial.println();
-}
-
-void eraseManchester(){
-  //Clear the memory to non matching numbers across the banks
-  //If there is only one packet, with no repeats this is not necessary.
-  for( int j=0; j < 4; j++){
-    for( int i=0; i < 20; i++){
-      manchester[j][i]=j+i;
-    }
-  }
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-


Refactored photoResistorTest

Refactored photoResistorTest

--- Arduino/photoresistorTest/photoresistorTest.ino
+++ Arduino/photoresistorTest/photoresistorTest.ino
@@ -19,11 +19,12 @@
 // Interrupt is called once a millisecond (Timer0 frequency)
 SIGNAL(TIMER0_COMPA_vect)
 {
-  int val = readValue();
+  readSample();
   //we're interested in events that happen roughly within 15-20 ms
   if (m_counter++ >= 4) {
-      Serial.println(val);
-      m_counter = 0;
+    int val = readBuffer();
+    Serial.println(val);
+    m_counter = 0;
   }
 }

@@ -36,8 +37,7 @@
   return value;
 }

-int readValue() {
-  int value = readSample();
+int readBuffer() {
   //TODO: test if median is better than avg
   int sum = 0;
   for (int n = 0; n < BUFFER_SIZE; ++n) {


Wire up chat client to matrix

Wire up chat client to matrix

--- nano/nano.ino
+++ nano/nano.ino
@@ -1,6 +1,32 @@
 #include "mduino.h"
+#include <BLE_API.h>

-#define PIN 3
+#define DEVICE_NAME                       "BLE Serial"
+#define TXRX_BUF_LEN                      20
+
+BLE                                       ble;
+Timeout                                   timeout;
+
+static uint8_t rx_buf[TXRX_BUF_LEN];
+static uint8_t rx_buf_num;
+static uint8_t rx_state=0;
+
+// The uuid of service and characteristics
+static const uint8_t service1_uuid[]        = {0x71, 0x3D, 0, 0, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
+static const uint8_t service1_tx_uuid[]     = {0x71, 0x3D, 0, 3, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
+static const uint8_t service1_rx_uuid[]     = {0x71, 0x3D, 0, 2, 0x50, 0x3E, 0x4C, 0x75, 0xBA, 0x94, 0x31, 0x48, 0xF1, 0x8D, 0x94, 0x1E};
+static const uint8_t uart_base_uuid_rev[]   = {0x1E, 0x94, 0x8D, 0xF1, 0x48, 0x31, 0x94, 0xBA, 0x75, 0x4C, 0x3E, 0x50, 0, 0, 0x3D, 0x71};
+
+uint8_t tx_value[TXRX_BUF_LEN] = {0,};
+uint8_t rx_value[TXRX_BUF_LEN] = {0,};
+
+// Create characteristic and service
+GattCharacteristic  characteristic1(service1_tx_uuid, tx_value, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE );
+GattCharacteristic  characteristic2(service1_rx_uuid, rx_value, 1, TXRX_BUF_LEN, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY);
+GattCharacteristic *uartChars[] = {&characteristic1, &characteristic2};
+GattService         uartService(service1_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));
+
+
 uint8_t outDataBuffer[5];
 OutgoingMessage om = OutgoingMessage();
 mduino m = mduino();
@@ -11,10 +37,78 @@
   om.setData(outDataBuffer);
   om.setDataLength(sizeof(outDataBuffer));
   om.setMsgId(0);
+
+  Serial.attach(uart_handle);
+
+  ble.init();
+  ble.onDisconnection(disconnectionCallBack);
+  ble.onDataWritten(gattServerWriteCallBack);
+
+  // setup adv_data and srp_data
+  ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
+  ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
+                                   (const uint8_t *)"TXRX", sizeof("TXRX") - 1);
+  ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,
+                                   (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid_rev));
+  // set adv_type
+  ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
+  // add service
+  ble.addService(uartService);
+  // set device name
+  ble.setDeviceName((const uint8_t *)DEVICE_NAME);
+  // set tx power,valid values are -40, -20, -16, -12, -8, -4, 0, 4
+  ble.setTxPower(4);
+  // set adv_interval, 100ms in multiples of 0.625ms.
+  ble.setAdvertisingInterval(160);
+  // set adv_timeout, in seconds
+  ble.setAdvertisingTimeout(0);
+  // start advertising
+  ble.startAdvertising();
+}
+
+void disconnectionCallBack(const Gap::DisconnectionCallbackParams_t *params) {
+  ble.startAdvertising();
+}
+
+void gattServerWriteCallBack(const GattWriteCallbackParams *Handler) {
+  uint8_t buf[TXRX_BUF_LEN];
+  uint16_t bytesRead, index;
+
+  if (Handler->handle == characteristic1.getValueAttribute().getHandle()) {
+    ble.readCharacteristicValue(characteristic1.getValueAttribute().getHandle(), buf, &bytesRead);
+    om.setData(buf);
+    om.setDataLength(bytesRead);
+    m.send(om);
+  }
+}
+
+void m_uart_rx_handle() {
+  //update characteristic data
+  ble.updateCharacteristicValue(characteristic2.getValueAttribute().getHandle(), rx_buf, rx_buf_num);
+  memset(rx_buf, 0x00,20);
+  rx_state = 0;
+}
+
+void uart_handle(uint32_t id, SerialIrq event) {
+  // Serial rx IRQ
+  if(event == RxIrq) {
+    if (rx_state == 0) {
+      rx_state = 1;
+      timeout.attach_us(m_uart_rx_handle, 100000);
+      rx_buf_num=0;
+    }
+    while(Serial.available()) {
+      if(rx_buf_num < 20) {
+        rx_buf[rx_buf_num] = Serial.read();
+        rx_buf_num++;
+      }
+      else
+        Serial.read();
+    }
+  }
 }

 void loop() {
-  m.send(om);
-  outDataBuffer[0]++;
-  // delay(300);
-}+  // put your main code here, to run repeatedly:
+  ble.waitForEvent();
+}


Fixed SAFE_LIMIT error in stepper driver test

--- arduino/timer_isr_test/timer_isr_test.ino
+++ arduino/timer_isr_test/timer_isr_test.ino
@@ -1,11 +1,12 @@

-// Robot parameters
+// Robot parameters.
+// Note this driver issues one physical step every two position increments.

 #define CYCLOID_RATIO 21
 #define MICROSTEPS 4
 #define STEPS_PER_REV 200

-#define SAFE_LIMIT ((MICROSTEPS * STEPS_PER_REV * CYCLOID_RATIO) / 3)
+#define SAFE_LIMIT ((2 * MICROSTEPS * STEPS_PER_REV * CYCLOID_RATIO) / 4)

 // Maximum step rate is half of this number
 #define INTERRUPT_FREQUENCY 8000


bywhat

bywhat

--- _09_ir_tx_rx/_09_ir_tx_rx.ino
+++ _09_ir_tx_rx/_09_ir_tx_rx.ino
@@ -195,7 +195,7 @@
   lcd.backlight();
   lcd.clear();

-  delay(5000);
+  delay(1000);

   // Timer start
   temp_Mills = millis();
@@ -216,7 +216,7 @@
   pinMode(BZ_OU_PIN, OUTPUT);
   digitalWrite(BZ_OU_PIN, HIGH);

-  delay(300);
+  delay(3000);

   // PIR
   attachInterrupt(0, PIRCHECKING, CHANGE);
@@ -409,7 +409,7 @@

 void doTvOffTimer()
 {
-  irSendTv(0);
+  irSendTv(0, 0);
   tvOffTimer();
   lcd.setCursor(15, 0);
   lcd.write(6);
@@ -417,7 +417,7 @@

 void doTvOnTimer()
 {
-  irSendTv(1);
+  irSendTv(1, 0);
   tvOnTimer();
   lcd.setCursor(15, 0);
   lcd.print(" ");
@@ -431,18 +431,18 @@
     case 1:
       lcd.setCursor(15, 0);
       lcd.print(" ");
-      irSendTv(1);
+      irSendTv(1, 1);
       break;
     case 0:
       lcd.setCursor(15, 0);
       lcd.write(6);
-      irSendTv(0);
+      irSendTv(0, 1);
       break;
   }
   r = !r;
 }

-void irSendTv(int onoff)
+void irSendTv(int onoff, int bywhat)
 {
   if ( o_wrkMode == 1 && o_startMode == 1 )
   {
@@ -453,8 +453,12 @@
           if ( tvPowerStatus == 0 )
           {
             irsend.sendNEC(tv_onoff, 32);
-            tvPowerStatus = 1;
-            temp_Mills = millis();
+
+            if ( bywhat == 0 ) {
+              tvPowerStatus = 1;
+              temp_Mills = millis();
+            }
+
             delay(300);
             irrecv.enableIRIn();
           }
@@ -463,8 +467,12 @@
           if ( tvPowerStatus == 1 )
           {
             irsend.sendNEC(tv_onoff, 32);
-            tvPowerStatus = 0;
-            temp_Mills = millis();
+
+            if ( bywhat == 0 ) {
+              tvPowerStatus = 0;
+              temp_Mills = millis();
+            }
+
             delay(300);
             irrecv.enableIRIn();
           }
@@ -472,6 +480,7 @@
         default:
           return;
           break;
+
       }
     } else {
       switch (onoff) {
@@ -480,12 +489,18 @@
           {
             irsend.sendNEC(tv_input, 32);
             delay(3000);
+
             for ( int i = 0 ; i < o_channelGap ; i++ ) {
               irsend.sendNEC(tv_left, 32);
               delay(300);
             }
+
             irsend.sendNEC(tv_enter, 32);
-            tvPowerStatus = 1;
+
+            if ( bywhat == 0 ) {
+              tvPowerStatus = 1;
+            }
+
             delay(300);
             irrecv.enableIRIn();
           }
@@ -495,12 +510,18 @@
           {
             irsend.sendNEC(tv_input, 32);
             delay(3000);
+
             for ( int i = 0 ; i < o_channelGap ; i++ ) {
               irsend.sendNEC(tv_right, 32);
               delay(300);
             }
+
             irsend.sendNEC(tv_enter, 32);
-            tvPowerStatus = 0;
+
+            if ( bywhat == 0 ) {
+              tvPowerStatus = 0;
+            }
+
             delay(300);
             irrecv.enableIRIn();
           }
@@ -508,6 +529,7 @@
         default:
           return;
           break;
+
       }
     }
   } else {


updated master module

updated master module

--- arduinoMasterAndSlave/I2C_FORCEPAD_V3_MASTER/I2C_FORCEPAD_V3_MASTER.ino
+++ arduinoMasterAndSlave/I2C_FORCEPAD_V3_MASTER/I2C_FORCEPAD_V3_MASTER.ino
@@ -3,7 +3,7 @@
 unsigned long initial;
 unsigned long final;

-int count = 0;
+int count=0;
 int c;

 void setup()
@@ -11,81 +11,81 @@
   Wire.begin();        // join i2c bus (address optional for master)
   Serial.begin(115200);  // start serial for output

+//
   Wire.beginTransmission(0x10); // transmit to device #4
-  Wire.write(100);              // sends one byte
+  Wire.write(100);              // sends one byte
   Wire.endTransmission();    // stop transmitting
-
-  //  Wire.beginTransmission(0x20); // transmit to device #4
-  //  Wire.write(100);              // sends one byte
-  //  Wire.endTransmission();    // stop transmitting
-  //
-  //
+
+//  Wire.beginTransmission(0x20); // transmit to device #4
+//  Wire.write(100);              // sends one byte
+//  Wire.endTransmission();    // stop transmitting
+//
+//
   delay(2000); //give the master a second to boot up
-
-
+
+
 }

 void loop()
 {

-  //get data from each of the 4 mats.  Comment out each block as needed.
-  Serial.print("one ");
-  request(0x10);
-  delay(50);
-  //
-  //Serial.print("two ");
-  //request(0x20);
-  //delay(50);
+//get data from each of the 4 mats.  Comment out each block as needed.
+Serial.print("one ");
+request(0x10);
+delay(50);
+//
+//Serial.print("two ");
+//request(0x20);
+//delay(50);

-  //Serial.print("three ");
-  //request(0x30);
-  //delay(50);
-  //
-  //Serial.print("four ");
-  //request(0x40);
-  //delay(50);
+//Serial.print("three ");
+//request(0x30);
+//delay(50);
+//
+//Serial.print("four ");
+//request(0x40);
+//delay(50);

 }

 //********ANALOG MODE***Read in analog values from the slave boards
-void request(int ID) {
+void request(int ID){

   //initial = millis();
+
+  Wire.requestFrom(ID, 2);    // request 1 byte from slave device given in the ID
+  if( Wire.available() == 2){        // if the two bytes are available
+   byte low = Wire.read();            // read a byte of the buffer
+   byte high = Wire.read();           // read the next byte of the buffer.
+   c = word (high, low);     // generate a two byte number
+   //Serial.println(c);
+
+}

-  Wire.requestFrom(ID, 2);    // request 1 byte from slave device given in the ID
-  if ( Wire.available() == 2) {      // if the two bytes are available
-    byte low = Wire.read();            // read a byte of the buffer
-    byte high = Wire.read();           // read the next byte of the buffer.
-    c = word (high, low);     // generate a two byte number
-    //Serial.println(c);
-
+if(c==1023){  //if a 1023 is recieved
+  for(int i=0;i<512;i++){       //repeat 512 times for each sensor value
+    Wire.requestFrom(ID, 2);    //request a two byte number (0-1022) from the slave
+
+   if( Wire.available() == 2){        // if the two bytes are available
+   byte low = Wire.read();            // read a byte of the buffer
+   byte high = Wire.read();           // read the next byte of the buffer.
+   int result = word (high, low);     // generate a two byte number
+   Serial.print(String(result));      // print the result as a string
+   Serial.print(" ");
+   count+=1;}                // print a space
+
+    else {
+    Serial.println("Didn't get two bytes");
+    }
   }
-
-  if (c == 1023) { //if a 1023 is recieved
-    for (int i = 0; i < 512; i++) { //repeat 512 times for each sensor value
-      Wire.requestFrom(ID, 2);    //request a two byte number (0-1022) from the slave
-
-      if ( Wire.available() == 2) {      // if the two bytes are available
-        byte low = Wire.read();            // read a byte of the buffer
-        byte high = Wire.read();           // read the next byte of the buffer.
-        int result = word (high, low);     // generate a two byte number
-        Serial.print(String(result));      // print the result as a string
-        Serial.print(" ");
-        count += 1;
-      }                // print a space
-
-      else {
-        Serial.println("Didn't get two bytes");
-      }
-    }
     Serial.println("");   // print a new line
     //Serial.println(count);
     //count=0;
-  }
+ }

-  //Serial.println(millis()-initial);
+//Serial.println(millis()-initial);

 }

@@ -94,7 +94,7 @@
 //void request(int ID){
 //
 //  initial = millis();
-//
+//
 //  Wire.requestFrom(ID, 1);    // request 6 bytes from slave device #2
 //  while(Wire.available()){
 //  c = Wire.read(); //look for the first 255
@@ -103,7 +103,7 @@
 //if(c==255){
 //  for(int i=0;i<512;i++){
 //    Wire.requestFrom(ID, 1);    // request 6 bytes from slave device #2
-//
+//
 //    while(Wire.available()){
 //
 //    int c = Wire.read();
@@ -121,7 +121,7 @@
 //void request(int ID){
 //
 //  initial = millis();
-//
+//
 //  Wire.requestFrom(ID, 1);    // request 6 bytes from slave device #2
 //  while(Wire.available()){
 //  c = Wire.read(); //look for the first 255
@@ -130,7 +130,7 @@
 //if(c==255){
 //  for(int i=0;i<16;i++){
 //    Wire.requestFrom(ID, 32);    // request 6 bytes from slave device #2
-//
+//
 //    while(Wire.available()){
 //
 //    int c = Wire.read();
@@ -142,5 +142,5 @@
 //
 //Serial.println(millis()-initial);
 //
-//
+//
 //}


- make test example a counter

- make test example a counter

--- examples/test/test.ino
+++ examples/test/test.ino
@@ -12,22 +12,18 @@
 #define BLE_RDY 2
 #define BLE_RST 9

-BLEPeripheral blePeripheral = BLEPeripheral(BLE_REQ, BLE_RDY, BLE_RST);
+BLEPeripheral     blePeripheral        = BLEPeripheral(BLE_REQ, BLE_RDY, BLE_RST);

-BLEService test1Service = BLEService("fff0");
-BLECharacteristic test1Characteristic1 = BLECharacteristic("fff1", BLE_PROPERTY_READ | BLE_PROPERTY_WRITE, 2);
-BLECharacteristic test1Characteristic2 = BLECharacteristic("fff2", BLE_PROPERTY_READ | BLE_PROPERTY_WRITE, 2);
-BLEDescriptor test1Descriptor = BLEDescriptor("2901", 4);
-
-BLEService test2Service = BLEService("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFF0");
-BLECharacteristic test2Characteristic = BLECharacteristic("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFF1", BLE_PROPERTY_READ | BLE_PROPERTY_WRITE, 5);
+BLEService        test1Service         = BLEService("fff0");
+BLECharacteristic test1Characteristic1 = BLECharacteristic("fff1", BLE_PROPERTY_READ | BLE_PROPERTY_WRITE | BLE_PROPERTY_WRITE_WITHOUT_RESPONSE | BLE_PROPERTY_NOTIFY | BLE_PROPERTY_INDICATE, 2);
+BLEDescriptor     test1Descriptor      = BLEDescriptor("2901", 7);

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

   blePeripheral.setLocalName("test");
 #if 1
-  blePeripheral.setAdvertisedServiceUuid("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFF0");
+  blePeripheral.setAdvertisedServiceUuid("fff0");
 #else
   const char manufacturerData[4] = {0x12, 0x34, 0x56, 0x78};
   blePeripheral.setManufacturerData(manufacturerData, sizeof(manufacturerData));
@@ -39,15 +35,9 @@
   blePeripheral.addAttribute(test1Service);
   blePeripheral.addAttribute(test1Characteristic1);
   blePeripheral.addAttribute(test1Descriptor);
-  blePeripheral.addAttribute(test1Characteristic2);
-
-  blePeripheral.addAttribute(test2Service);
-  blePeripheral.addAttribute(test2Characteristic);

   test1Characteristic1.setValue("yo", 2);
-  test1Characteristic2.setValue("hi", 2);
-  test1Descriptor.setValue("desc", 4);
-  test2Characteristic.setValue("there", 5);
+  test1Descriptor.setValue("counter", 7);

   blePeripheral.begin();

@@ -62,14 +52,26 @@
 void loop() {
   blePeripheral.poll();

+  static unsigned short s = 0;
+  static unsigned long last_sent = 0;
+
   if (blePeripheral.isConnected()) {
     if (test1Characteristic1.valueUpdated()) {
-       Serial.print(F("value updated = "));
-       Serial.print(test1Characteristic1.value()[0]);
-       Serial.print(test1Characteristic1.value()[1]);
-       Serial.println();
+      Serial.println(F("counter written, reset"));

-      test1Characteristic1.setValue("oy", 2);
+      last_sent = 0;
+      s = 0;
+    }
+
+    if ((millis() - 1000) > last_sent) {
+      last_sent = millis();
+
+      s++;
+
+      Serial.print(F("counter = "));
+      Serial.println(s, DEC);
+
+      test1Characteristic1.setValue((char *)&s, 2);
     }
   }
 }


Corrected wrap around of micros()

Corrected wrap around of micros()

--- neopixel_with_pushbutton_selector/neopixel_with_pushbutton_selector.ino
+++ neopixel_with_pushbutton_selector/neopixel_with_pushbutton_selector.ino
@@ -17,6 +17,9 @@
 // How many NeoPixels are attached to the Arduino?
 #define LED_COUNT 8

+/* do we want Serial output? */
+//#define DEBUG
+
 // Declare our NeoPixel strip object:
 Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
 // Argument 1 = Number of pixels in NeoPixel strip
@@ -33,9 +36,9 @@
 const byte interruptPin = 2;
 volatile byte state = HIGH;
 long debounce_time = 250;
-volatile unsigned long last_micros;
+volatile unsigned long last_micros = 0;
 int r, g, b;
-int lastState;
+unsigned long lastState;

 void setup() {
   // put your setup code here, to run once:
@@ -56,9 +59,9 @@
   last_micros = micros();

   randomSeed(analogRead(0));
-
+#ifdef DEBUG
   Serial.begin(9600);
-
+#endif
   r = random(0, 255);
   g = random(0, 255);
   b = random(0, 255);
@@ -70,7 +73,10 @@

 void loop() {
   // put your main code here, to run repeatedly:
-
+#ifdef DEBUG
+  Serial.print("micros(): ");
+  Serial.println((unsigned long)micros());
+#endif
   /* Did the state change (did the button get pressed)? */
   if(lastState != state) {
     lastState = state;
@@ -86,9 +92,18 @@
    *  a long time, so micros() could have looped back around to zero.  This
    *  happens abut every 70 minutes.
    */
-  if(((long)(micros() - last_micros) >= debounce_time * 1000) || (micros() < last_micros)){
+
+  unsigned long curr_micros = (long)micros();
+#ifdef DEBUG
+  Serial.print("curr_micros: ");
+  Serial.println(curr_micros);
+  Serial.print("last_miros: ");
+  Serial.println(last_micros);
+  Serial.println();
+#endif
+  if(((unsigned long)(curr_micros - last_micros) >= debounce_time * 1000) || (unsigned long)(curr_micros < last_micros)){
     state = !state;
-    last_micros = micros();
+    last_micros = curr_micros;
     changeColor();
   }
 }


fix: Update scoring and boss spawning

fix: Update scoring and boss spawning

- Add score for surviving
- Add score for hitting enemies and boss
- Spawn boss by passing score thresholds

--- arduboy-game/arduboy-game.ino
+++ arduboy-game/arduboy-game.ino
@@ -410,14 +410,20 @@
   livesRemaining = MAX_LIVES;
   spaceShip.reset();
   stopMusic();
+  boolean spawnedBossOne = false;
+  boolean spawnedBossTwo = false;

   while (livesRemaining > 0) {
     arduboy.clear();
     inGameFrame++;

-    // Cool off the gun
-    if (inGameFrame % 20 == 0 && spaceShip.gunTemp > 0) {
-      spaceShip.gunTemp--;
+    if (inGameFrame % 20 == 0) {
+      score++;
+
+      if (spaceShip.gunTemp > 0) {
+        // Cool off the gun
+        spaceShip.gunTemp--;
+      }
     }

     drawGunTemp();
@@ -425,19 +431,21 @@
     drawScore();

     drawPlayerShip();
+
+    if (!isBossAlive) {
+      if ((score >= 5000) && (!spawnedBossOne)) {
+        drawBoss(69, 6, 1);
+        spawnedBossOne = true;
+      } else if ((score >= 12000) && (!spawnedBossTwo)) {
+        drawBoss(96, 24, 2);
+        spawnedBossTwo = true;
+      }
+    }

-    if(!isBossAlive) {
-      updateEnemies();
-    }
-
-    if(score > 0) {
-      if(score % 3000 == 0) {
-        drawBoss(69, 6, 1);
-      } else if(score % 5000 == 0) {
-        drawBoss(96, 24, 2);
-      } else if(isBossAlive) {
-        drawBoss(boss.x, boss.y, boss.type);
-      }
+    if (isBossAlive) {
+      drawBoss(boss.x, boss.y, boss.type);
+    } else {
+      updateEnemies();
     }

     if(inGameAButtonLastPress > 80 || inGameBButtonLastPress > 60) {
@@ -627,6 +635,7 @@
           // Hit Boss
           playerBullets[i].hide();
           boss.health -= playerBullets[i].damage;
+          score += playerBullets[i].damage;

           if (boss.health <= 0) {
             // Killed Boss
@@ -639,6 +648,7 @@
           if ((enemies[j].health > 0) && (playerBullets[i].isHittingObject(enemies[j].x, enemies[j].y, enemies[j].width, enemies[j].height))) {
             // Hit Enemy
             playerBullets[i].hide();
+            score += playerBullets[i].damage;

             if (playerBullets[i].damage > enemies[j].health) {
               enemies[j].health = 0;


Added custom server example

Added custom server example

--- examples/Transports/Ethernet/Ethernet.ino
+++ examples/Transports/Ethernet/Ethernet.ino
@@ -13,7 +13,7 @@
  * This example code is in public domain.
  *
  **************************************************************
- *
+ *
  * This example shows how to use Arduino Ethernet shield (W5100)
  * to connect your project to Blynk.
  * Feel free to apply it to any other example. It's simple!
@@ -33,6 +33,10 @@
 {
   Serial.begin(9600);
   Blynk.begin(auth);
+  // You can also specify server.
+  // For more options, see Transports/Advanced/CustomEthernet example
+  //Blynk.begin(auth, "server.org", 8442);
+  //Blynk.begin(auth, IPAddress(192,168,1,100), 8888);
 }

 void loop()


fix: brightness_min

fix: brightness_min

--- ptw-wheel.ino
+++ ptw-wheel.ino
@@ -150,7 +150,7 @@
     }
   }
   else {
-    if(brightness_min < brightness) {
+    if(brightness_min+0.01 <= brightness) {
       brightness -= 0.01;
       updateLED();
     }


optimized esp init

optimized esp init

--- FirmwareManager/src/FirmwareManager.ino
+++ FirmwareManager/src/FirmwareManager.ino
@@ -959,7 +959,7 @@
             DEBUG("ArduinoOTA >> End Failed\n");
         }
     });
-    ArduinoOTA.begin(false);
+    ArduinoOTA.begin();
 }

 void waitForController() {


Changes to getInfo message sent by stage to PC.

--- OpenStage/openStage_SerialFunctions.ino
+++ OpenStage/openStage_SerialFunctions.ino
@@ -236,16 +236,24 @@
 // Reports a bunch of useful information to the serial port as text
 void reportInfo(){
   byte ii;
-
-  SerialComms->print("Gear Ratios: ");
+
+  SerialComms->println("OpenStage Settings Information");
+
+  SerialComms->print("Number of axes: ");
+  SerialComms->print(numAxes);
+  SerialComms->print('\n');
+
+
+
+  SerialComms->print("Gear Ratios at each axis: ");
   for (ii=0; ii<numAxes; ii++){
     SerialComms->print(gearRatio[ii]);
     if (ii<numAxes-1)
        SerialComms->print(",");
     }
-    SerialComms->print('\n');
-
-  SerialComms->print("Full Steps Per Rev: ");
+    SerialComms->println(" microns/rev");
+
+  SerialComms->print("Motor Full Steps Per Rev at each axis: ");
   for (ii=0; ii<numAxes; ii++){
     SerialComms->print(int(1/(fullStep[ii]/360.0)));
     if (ii<numAxes-1)
@@ -253,7 +261,7 @@
    }
     SerialComms->print('\n');

-  SerialComms->print("Hat Stick max speeds: ");
+  SerialComms->print("Hat Stick max speeds (speed modes 1 to 4) : ");
   for (ii=0; ii<4; ii++){
     SerialComms->print(maxSpeed[ii]);
     if (ii<3)
@@ -262,7 +270,7 @@
   SerialComms->print('\n');
   SerialComms->print('\n');

-  SerialComms->print("moveTo() speeds:");
+  SerialComms->print("Serial move specs at each axis:");
   SerialComms->print('\n');
   for (ii=0; ii<numAxes; ii++){
     SerialComms->print(ii+1);


refactored the use of abs() at handleInput() which was producing unexpected results

--- examples/androidCar/androidCar.ino
+++ examples/androidCar/androidCar.ino
@@ -147,7 +147,8 @@
     unsigned short throttleFreq = pulseIn(OVERRIDE_THROTTLE_PIN, HIGH, MAX_STEERING_WAVELENGTH);
     //handle override servo
     if (servoFreq) { //if you get 0, ignore it as it is between the pulses
-      if (abs(servoFreq - NEUTRAL_FREQUENCY) < OVERRIDE_FREQ_TOLERANCE) {
+      short diff = servoFreq - NEUTRAL_FREQUENCY;
+      if (abs(diff) < OVERRIDE_FREQ_TOLERANCE) {
         car.setSteeringWheel(0);
       } else {
         if (servoFreq > NEUTRAL_FREQUENCY) {
@@ -159,13 +160,16 @@
     }
     //handle override throttle
     if (throttleFreq) {
-      if (abs(throttleFreq - NEUTRAL_FREQUENCY) < OVERRIDE_FREQ_TOLERANCE) {
+      short diff = throttleFreq - NEUTRAL_FREQUENCY;
+      if (abs(diff) < OVERRIDE_FREQ_TOLERANCE) {
         car.setSpeed(0);
       } else {
         if (throttleFreq > NEUTRAL_FREQUENCY) {
           car.setSpeed(OVERRIDE_FORWARD_SPEED);
+
         } else {
           car.setSpeed(OVERRIDE_BACKWARD_SPEED);
+          int i = abs(throttleFreq - NEUTRAL_FREQUENCY);
         }
       }
     }


improved sleep pattern

improved sleep pattern

--- avoccado-aino-mpu6050/avoccado-aino-mpu6050.ino
+++ avoccado-aino-mpu6050/avoccado-aino-mpu6050.ino
@@ -188,7 +188,7 @@
   delay(64);
   vibr(0); // stop vibrating
   // initialize devices
-  Serial.println(F("avoccado aino 0.201406191627"));
+  Serial.println(F("avoccado aino 0.201411141705"));
 #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
   Serial.println(F("I2C setup"));
   Wire.begin(); // join I2C bus (I2Cdev library doesn't do this automatically)
@@ -297,6 +297,7 @@
       mpu.setStandbyXGyroEnabled(1);
       mpu.setStandbyYGyroEnabled(1);
       mpu.setStandbyZGyroEnabled(1);
+      Serial.print(F("Sleeping."));
       vibr(1);
       delay(64);
       vibr(0);
@@ -307,9 +308,11 @@
       setup_watchdog(wdt_250ms); // set touch check interval
       while ( ((ay < (-10000)) || ay > (10000)) ) { // if the Avoccado device is resting in this position
         do_sleep(); // keep on sleeping
-        powerMode(1); // power up MEMS, wake up every watchdog timer interval
+        Serial.print(F("."));
+        mpu.setSleepEnabled(0); // power up MEMS, wake up every watchdog timer interval
         //        mpucheck();
         mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); // get the new acceleration values TODO: implement for ADXL345
+        //mpu.setSleepEnabled(1);
       }
       for (int _i = 0; _i < 2; _i++) { // vibrate briefly when waking up from hibernation mode
         vibr(1);
@@ -317,6 +320,7 @@
         vibr(0);
         delay(56);
       }
+      Serial.println();
       powerMode(1); // power up MEMS
       mpu.setStandbyXGyroEnabled(0);
       mpu.setStandbyYGyroEnabled(0);


Bump version

Bump version

--- src/homie-sonoff-touch.ino
+++ src/homie-sonoff-touch.ino
@@ -2,7 +2,7 @@
 #include <Homie.h>

 #define FW_NAME "homie-sonoff-touch"
-#define FW_VERSION "1.0.0"
+#define FW_VERSION "1.0.1"

 /* Magic sequence for Autodetectable Binary Upload */
 const char *__FLAGGED_FW_NAME = "\xbf\x84\xe4\x13\x54" FW_NAME "\x93\x44\x6b\xa7\x75";


feat(power): Go into deep sleep mode for 60 seconds

Temporarily commented out because it's a pain to come back from...

--- kiln.ino
+++ kiln.ino
@@ -5,6 +5,12 @@
 const int TMP36_DATA_PIN = A0;

 const String KILN_EVENT = "kiln";
+
+const int MEASUREMENT_INTERVAL = 60;
+const int FAILURE_INTERVAL = 2000;
+
+const int WAKEUP_DELAY = 2000;
+const int PRE_SLEEP_DELAY = 500;

 RHT03 rht03;
 TMP36 tmp36;
@@ -14,6 +20,8 @@

 	tmp36.begin(TMP36_DATA_PIN);
 	rht03.begin(RHT03_DATA_PIN);
+
+	delay(WAKEUP_DELAY);
 }

 void loop() {
@@ -32,13 +40,17 @@

 		if(!publishEvent()) {
 			Serial.println("Unable to publish temp event!");
+		} else {
+			// if we were successful, go to sleep for a while to save battery life.
+			// this will reset the entire program so we start up from the beginning
+			delay(PRE_SLEEP_DELAY);
+			//System.sleep(SLEEP_MODE_DEEP, MEASUREMENT_INTERVAL);
 		}
-	} else {
-		// if we fail, wait a little while for things to reset before we try again
-		delay(RHT_READ_INTERVAL_MS);
 	}

-	delay(2000);
+	// we'll only get here if something went wrong.  wait a little while before
+	// we try again
+	delay(FAILURE_INTERVAL);
 }

 bool publishEvent() {