Update Treadmill.ino

Update Treadmill.ino

--- Treadmill/Treadmill.ino
+++ Treadmill/Treadmill.ino
@@ -1,11 +1,29 @@
-int set_speed = 0, set_speed_old = 0;
+/*
+Program to control the AD5220 digipot via UART. The pot is initialized at max
+resistance then controlled with the '+' and '-' characters.
+*/
+
+//control pins on AD5220
+int CLK = 8, UD = 9, CS = 10;
+//serial byte
+char set_speed;
+//parameter for counting time
+unsigned long previousMillis = 0;
+//to measure wiper voltage
+float v_wiper;

 void setup(){
-  Serial.begin(115200);
+  //pro mini bootloader communicates at 57600 baud
+  Serial.begin(57600);

   pinMode(CS, OUTPUT);
   pinMode(UD, OUTPUT);
   pinMode(CLK, OUTPUT);
+
+  //change pot wiper from middle to max resistance
+  for (int i=0; i<20; i++){
+    decrease_speed();
+  }

   //hold current pot resistance
   digitalWrite(CS, HIGH);
@@ -13,31 +31,81 @@
 }

 void loop(){
-  if (Serial.available() > 0){
-    char c = Serial.read();
-    //convert char to int
-    set_speed = c - '0';
+  //get current time
+  unsigned long currentMillis = millis();
+
+  int wiper = analogRead(A0);
+  v_wiper = wiper * (3.3 / 1023);
+
+  //if 2000 msecs have passed
+  if (currentMillis - previousMillis >= 2000){
+    previousMillis = currentMillis;
+
+    Serial.println(v_wiper);
   }

-  if (set_speed > set_speed_old){
-    digitalWrite(CS, LOW);
-    digitalWrite(UD, LOW);
-    digitalWrite(CLK, LOW);
-    digitalWrite(CLK, HIGH);
-
-    set_speed_old = set_speed;
+  //read serial data when it arrives
+  if (Serial.available() > 0){
+    set_speed = Serial.read();
   }

-  else if(set_speed < set_speed_old){
+  //decrease speed
+  if (set_speed == '-'){
+    decrease_speed();
+  }
+
+  //increase speed
+  else if (set_speed == '+'){
+    increase_speed();
+  }
+
+  //get belt moving
+  else if (set_speed == 's'){
+    start();
+  }
+
+  //stop the belt
+  else if (set_speed == 'e'){
+    stop();
+  }
+
+  //hold pot resistance
+  else {
+    digitalWrite(CS, HIGH);
+  }
+}
+
+void decrease_speed(){
+  digitalWrite(CS, LOW);
+  digitalWrite(UD, LOW);
+  digitalWrite(CLK, LOW);
+  digitalWrite(CLK, HIGH);
+
+  set_speed = '\0';
+}
+
+void increase_speed(){
+  digitalWrite(CS, LOW);
+  digitalWrite(UD, HIGH);
+  digitalWrite(CLK, LOW);
+  digitalWrite(CLK, HIGH);
+
+  set_speed = '\0';
+}
+
+//increase wiper voltage to ~0.75V, when belt starts moving
+void start(){
+  for (int i = 0; i < 30; i++){
     digitalWrite(CS, LOW);
     digitalWrite(UD, HIGH);
     digitalWrite(CLK, LOW);
     digitalWrite(CLK, HIGH);
-
-    set_speed_old = set_speed;
   }
-
-  else {
-    digitalWrite(CS, HIGH);
+  set_speed = '\0';
+}
+
+void stop(){
+  while (v_wiper > 0.5){
+    decrease_speed();
   }
 }


Fixing issue where light can't be turned off by json state command. (#17)

--- Arilux_AL-LC0X.ino
+++ Arilux_AL-LC0X.ino
@@ -378,6 +378,8 @@
       }

       if (root.containsKey("color")) {
+        startFade = true;
+        inFade = false; // Kill the current fade
         int red_color = root["color"]["r"];
         int green_color = root["color"]["g"];
         int blue_color = root["color"]["b"];
@@ -391,10 +393,10 @@
         realBlue = arilux.getBlueValue();
       }

-      startFade = true;
-      inFade = false; // Kill the current fade

       if (root.containsKey("flash")) {
+        startFade = true;
+        inFade = false; // Kill the current fade
         flashLength = (int)root["flash"] * 1000;

         if (root.containsKey("brightness")) {
@@ -425,6 +427,9 @@
           if (strcmp(root["state"], "ON") == 0) {
             arilux.turnOn();
           } else if (strcmp(root["state"], "OFF") == 0) {
+            startFade = false;
+            startFlash = false;
+            inFade = false; // Kill the current fade
             arilux.turnOff();
           }
         }


Remove old ino file

Remove old ino file

--- CRAPnode_Setup.ino
+++ CRAPnode_Setup.ino
@@ -1,116 +0,0 @@
-//
-// CRAPnode setup tool
-//
-//
-//
-//
-// Instructions:
-//  1. Enter your WiFi SSID and password below.
-//  2. Upload the sketch to the CRAPnode.
-//  3. Ground GPIO0 on the ESP8266 module (short bare pads under the ISP connector)
-//  4. Update the ESP8266 module using this guide (files are in this folder): http://www.xess.com/blog/esp8266-reflash/
-//     Note that you must swap the RX and TX lines of the serial module.
-//  5. Unground GPIO0. Uncomment the line below this one.
-#define TESTMODE
-//  6. Upload to the CRAPnode again and wait for green (pass) LED.
-//     If the LED is red, the test has failed.
-//     Check your router to see if the CRAPnode has connected.
-//     The test is likely to fail if there is no battery.
-//
-
-
-#define SSID "xxx"
-#define PASS "12345678"
-
-
-
-
-
-
-#include <Wire.h>
-#include "RTClib.h"
-#include <SoftwareSerial.h>
-
-RTC_DS1307 rtc;
-
-boolean passFailState = 0; // 0 is pass, 1 is fail
-
-#if defined(TESTMODE)
-
-void setup () {
-  Serial.begin(115200);
-  pinMode(A3, OUTPUT);
-  digitalWrite(A3, HIGH);
-  ledTest();
-  //if (rtcTest()) if (!passFailState) passFailState = 1;
-  if (wifiTest()) if (!passFailState) passFailState = 1;
-  delay(100);
-  if (passFailState) digitalWrite(2, HIGH);
-  else digitalWrite(8, HIGH);
-}
-
-void loop() {
-}
-
-void ledTest() {
-  pinMode(2, OUTPUT);
-  pinMode(8, OUTPUT);
-  for (byte i = 0; i < 20; i++) {
-    digitalWrite(2, HIGH);
-    digitalWrite(8, LOW);
-    delay(50);
-    digitalWrite(2, LOW);
-    digitalWrite(8, HIGH);
-    delay(50);
-    digitalWrite(8, LOW);
-  }
-}
-
-byte rtcTest() {
-  Wire.begin();
-  rtc.begin();
-  rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
-  delay(5000);
-  DateTime now = rtc.now();
-  if (now.second() == 5) return 0;
-  else return 1;
-}
-
-byte wifiTest() {
-  serialFlush();
-  Serial.println("AT+RST");
-  delay(1000);
-  if (Serial.find("ready")) {
-    String cmd = "AT+CWJAP=\"";
-    cmd += SSID;
-    cmd += "\",\"";
-    cmd += PASS;
-    cmd += "\"";
-    Serial.println(cmd);
-    return 0;
-  }
-  else return 1;
-}
-
-void serialFlush() {
-  while (Serial.available() > 0) {
-    char t = Serial.read();
-  }
-}
-
-#else
-
-// Sets the serial port pins to high impedance and enable the ESP module.
-
-void setup () {
-  pinMode(A3, OUTPUT);
-  pinMode(0, INPUT);
-  pinMode(1, INPUT);
-  digitalWrite(A3, HIGH);
-}
-
-void loop() {
-}
-
-#endif
-


Fixed portc pin count bug

Fixed portc pin count bug

PortC Pins 7 and 8 on most arduinos are not accessible.

--- ArduinoServoExample/ArduinoServoExample.ino
+++ ArduinoServoExample/ArduinoServoExample.ino
@@ -11,7 +11,7 @@

 // Servos
 int active_servos = 1;
-int const NUM_SERVOS = 20;
+int const NUM_SERVOS = 18;
 Servo* servo[NUM_SERVOS];
 int pattern = 1;

@@ -22,7 +22,7 @@

   DDRD = B11111100;
   DDRB = B00111111;
-  DDRC = B11111111;
+  DDRC = B00111111;

  // Servo s = new Servo();

@@ -38,7 +38,7 @@
     {
       attach(servo[i], &PORTB, 1<<(i-6));
     }
-    else if(i < 20)
+    else if(i < 18)
     {
       attach(servo[i], &PORTC, 1<<(i-12));
     }


Delete Stabilisator.ino

Delete Stabilisator.ino

--- Firmware/Ball/Stabilisator/Stabilisator.ino
+++ Firmware/Ball/Stabilisator/Stabilisator.ino
@@ -1,616 +0,0 @@
-String version = "0.1.3";
-/*
-
- >      FIRMWARE ONLY FOR AN ARDUINO NANO !!    <
- > IF YOU USE ANOTHER ARDUINO, ADAPT THE PINOUT <
-
- ###################################################
-  ______  ______     _     _ ______  _____ _______
- (____  \(____  \   | |   | |  ___ \(_____|_______)
-  ____)  )____)  )__| |   | | |   | | | | | |
- |  __  (|  __  (___) |   | | |   | | | | | |
- | |__)  ) |__)  )  | |___| | |   | |_| |_| |_____
- |______/|______/    \______|_|   |_(_____)\______)
-    A open source project for create you own BB-8!
- ###################################################
-
- https://github.com/Gruniek/BB-UNIT
- Made by Daniel M/Gruniek/MOUS
-
- Compatible only with an Arduino Nano and the specific PCB.
- PCB Link : https://github.com/Gruniek/BB-UNIT/tree/master/Head/Stabiliser/PCB
-
- --------------
- - Change log -
- --------------
-
- 11/2016
- =========
- - FIX alls bug foe stabilisation
- - ADD BOOT, STAT, ROTATE command
- - ADD Z motor configuration and production
- - ADD BOOT mode, for initilize or reinizialize the Droid position
-
- 10/2016
- ==========
- - Add PID for X and Y
-
-
- To do list
- ==========
- - Add Z rotation controller
- - Add Rx/Tx from the motherboard for change de coordinate of the head,
-  rotate the head and report to the remote the status off all sensors/positiom.
-
-
-  Big thanks for http://r2builders.fr/ !
-  Initial project : http://r2builders.fr/forum/viewtopic.php?f=26&t=3928&hilit=BB8+par+MOUS
-
-  ===============
-  EXEMPLE COMMAND
-  ===============
-  < SET >
-  'SET x87 y75 h3 \n'        // SET a new setpoint for x and y with 3degree of Hysteressis
-  'SET x90 y90 i1 j0 k1 \n'  // SET an inversion of the sensor X Y and invert the direction of X
-
-  	x = SETPOINT for X
-	y = SETPOINT for Y
-	m = MULTIPLIER FOR THE SPEED OF THE MOTOR X and Y
-	i = INVERT the angle sensor ( X = Y and Y = X )
-	j = INVERT the direction of X
-	k = INVERT the direction of Y
-	h = SET a new HYSTERESSIS
-
-
-
-  < BOOT >
-  'BOOT \n'  // LAUNCH TEST for X, Y and Z -> Return X and Y to initial SETPOINT (x90 y90 ) and Z to ZERO
-
-
-
-  < RUN >
-  'RUN \n'   // RUN the code in production mode (Recieved all data, X and Y runing for the SETPOINT poistion and Z folow the remote controll
-
-  < STOP >
-  'STOP \n'  // STOP the production mode. All motors are stopped.
-
-
-  < ROTATE >
-  'ROTATE d1 s100 \n'   // ROTATE Z motor on the RIGHT DIRECTION (d0 LEFT, d1 RIGHT) WITH the SPEED at 1000/100 = 10 step/sec = 18dec/sec
-
-
-  < STAT >
-  // It is all data SENDED to the MASTER-BOARD
-
-*/
-
-#include "Wire.h"
-#include "MPU6050.h"
-
-
-
-// MOTOR CONFIGURATION // YOU CAN TOUCH THIS
-
-#define pinEnable        4      // Activation off all stepper
-
-#define pinStepX         3      // PIN STEP FOR X
-#define pinDirX          2      // PIN DIRECTION FOR X
-
-#define pinStepY         6      // PIN STEP FOR Y
-#define pinDirY          5      // PIN DIRECTION FOR Y
-
-#define pinStepZ         8      // PIN STEP FOR Y
-#define pinDirZ          7      // PIN DIRECTION FOR Y
-
-#define Z_POSITION       9      // PIN FOR THE DIGITAL INPUT FOR THE HEAD POSITION
-
-bool    invertX        = false; // INVERT THE X MOTOR DIRECTION
-bool    invertY        = true;  // INVERT THE Y MOTOR DIRECTION
-bool    invertXY       = false; // INVERT X Y AXIAL
-
-int     minX           = 45;    // SET THE MIN INCLINAISON FOR X
-int     maxX           = 135;   // SET THE MAX INCLINAISON FOR X
-int     minY           = 45;    // SET THE MIN INCLINAISON FOR Y
-int     maxY           = 135;   // SET THE MAX INCLINAISON FOR Y
-
-int     etalonX        = 0;     // AJUSTEMENT FOR X
-int     etalonY        = -6;    // AJUSTEMENT FOR Y
-
-int     hysteresis     = 1;     // HYSTERESSIS FOR THE ANGLE CALCULATION
-
-
-//=====================//
-// NOW YOU CAN'T TOUCH //
-//=====================//
-
-// MPU6050
-MPU6050 accelgyro;
-
-int16_t ax, ay, az;
-int16_t gx, gy, gz;
-
-// I2C
-int adress         = 2;
-int PING           = 13; // PIN
-int PING_MASTER    = 12;
-// VARIABLE
-int x              = 0;
-int y              = 0;
-int vx             = 0;
-int vy             = 0;
-
-int speedX         = 0;
-int speedY         = 0;
-int speedZ         = 0;
-int setpointX      = 90;
-int setpointY      = 90;
-
-int Zangle         = 0;
-
-
-int multiplier     = 15;
-int emergencyStop  = 11; // PIN
-int eStop          = 12; // PIN
-bool emgStop       = false;
-
-bool runX          = false;
-bool runY          = false;
-bool runZ          = false;
-bool directX       = false; // false = Gauche / true = droite
-bool directY       = false; // false = Gauche / true = droite
-bool directZ       = false; // false = Gauche / true = droite
-
-bool xok           = false;
-bool yok           = false;
-bool zok           = false;
-
-// PID
-unsigned long previousMillisX = 0;
-unsigned long previousMillisY = 0;
-unsigned long previousMillisZ = 0;
-
-long                    intX  = 0;
-long                    intY  = 0;
-
-
-unsigned long trigGyro = 100;
-unsigned long trigSec  = 1000;
-unsigned long trigG    = 0;
-unsigned long trigS    = 0;
-
-
-bool production = false;
-bool LED_PING   = false;
-bool BOOT = false;
-
-bool ifPing    = false;
-int tmpPing    = 0;
-int tmpPing2   = 0;
-int pingMaster = 0;
-
-//=============================================================================//
-//   SETUP
-//=============================================================================//
-void setup()
-{
-    pinMode( pinEnable   , OUTPUT );
-    pinMode( pinDirX     , OUTPUT );
-    pinMode( pinStepX    , OUTPUT );
-    pinMode( pinDirY     , OUTPUT );
-    pinMode( pinStepY    , OUTPUT );
-    pinMode( PING        , OUTPUT );
-    pinMode( PING_MASTER , INPUT  );
-    pinMode( Z_POSITION  , INPUT  );
-
-
-    Serial.begin(9600);
-
-    Serial.println(" ");
-    Serial.println("#######################################");
-    Serial.println("#         Astromech Industrie         #");
-    Serial.println("#                BB-UNIT              #");
-    Serial.println("# https://github.com/Gruniek/BB-UNIT/ #");
-    Serial.println("#######################################");
-    Serial.println(" ");
-    Serial.print("  BB-8 Version ");
-    Serial.println(version);
-    Serial.println("===================");
-    Serial.println(" ");
-
-    Serial.print("Initializing I2C devices...  I2C ADRESS :");
-    Serial.print(adress);
-    Wire.begin(adress);
-
-    accelgyro.initialize();
-    Serial.print("Connect to the MPU6050 : ");
-
-    Serial.println(accelgyro.testConnection() ? "Connection successful" : "Connection failed");
-
-    Serial.println("Booting successful !");
-    Serial.println("====================");
-
-
-}
-
-//=============================================================================//
-//   LOOP
-//=============================================================================//
-void loop()
-{
-    // GET MOTION
-    //-------------------------------------------------------------------------//
-    unsigned long currentG = millis(); // millis();
-
-    if (currentG - trigG  >= trigGyro)
-    {
-    	trigG = currentG;
-
-
-    	accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
-		if(invertXY)
-		{
-			y = (((ax/180)+etalonX)+90);
-  			x = (((ay/180)+etalonY)+90);
-		}
-		else
-		{
-			x = (((ax/180)+etalonX)+90);
-  			y = (((ay/180)+etalonY)+90);
-		}
-    }
-
-    // GET SERIAL DATA
-    //-------------------------------------------------------------------------//
-
-    char msg[30];
-    if (Serial.available() > 0)
-    {
-    	Serial.readBytesUntil('\n', msg, sizeof msg);
-
-    	if (strcmp(strtok(msg, " "), "SET") == 0)
-    	{
-        	Serial.println("UPDATE SETPOINT");
-      		// trouvé le message
-      		char *p;
-      		while ((p = strtok(NULL, " ")) != NULL)
-      		{
-        		int val = atoi(p + 1);
-        		switch (*p)
-        		{
-          			case 'x': setpointX  = val; break;
-          			case 'y': setpointY  = val; break;
-      	  			case 'm': multiplier = val; break;
-      				case 'i': invertXY   = val; break;
-      				case 'j': invertX    = val; break;
-      				case 'k': invertX    = val; break;
-      				case 'h': hysteresis = val; break;
-        		}
-      		}
-    	}
-
-    	if (strcmp(strtok(msg, " "), "RUN") == 0)
-    	{
-        	Serial.println("ROll BB-8 ROLL !");
-      	    production = true;
-      	    emgStop = false;
-    	}
-
-    	if (strcmp(strtok(msg, " "), "STOP") == 0)
-    	{
-    		Serial.println("STOP");
-    	    production = false;
-    	}
-
-    	if (strcmp(strtok(msg, " "), "RESET") == 0)
-    	{
-    		Serial.println("RESET");
-    	    production = false;
-    	}
-
-    	if (strcmp(strtok(msg, " "), "BOOT") == 0)
-    	{
-
-    	    BOOT = true;
-    	    Serial.println("BOOTING UP...");
-    	    delay(2000);
-    	}
-
-    	if (strcmp(strtok(msg, " "), "ROTATE") == 0) // ROTATE d1 s100  <-- Rotate Z right, 18c/sec
-    	{
-      		// trouvé le message
-      		char *p;
-      		while ((p = strtok(NULL, " ")) != NULL)
-      		{
-        		int val = atoi(p + 1);
-        		switch (*p)
-        		{
-          			case 'd': directZ  = val; break;
-          			case 's': speedZ   = val; break;
-        		}
-      		}
-    	}
-
-
-  }
-
-   if(BOOT)
-   {
-   	    // SET X IN POSITION
-   		if(x < 90) directX = false;
-  		else directX = true;
-
-  		if(invertX)
-  		{
-    		if(directX) directX = false;
-    		else directX = true;
-  		}
-  		digitalWrite(pinDirX, directX); // dirX
-
-  		if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis ))
-  		{
-  	        digitalWrite(pinStepX, 1);
-        	delayMicroseconds( 500 );
-    	    digitalWrite(pinStepX, 0);
-    	    delayMicroseconds( 500 );
-  		}
-  		else
-  		{
-  			if(!xok)
-  			{
-  				Serial.println("BOOT x1 ");
-  				xok = true;
-  				delay(2000);
-  			}
-  		}
-
-
-  		// SET Y IN POSITION
-   		if(y < 90) directY = false;
-  		else directY = true;
-
-  		if(invertY)
-  		{
-    		if(directY) directY = false;
-    		else directY = true;
-  		}
-  		digitalWrite(pinDirY, directY); // dirX
-
-  		if(x > (setpointY + hysteresis) || (y < setpointY - hysteresis ))
-  		{
-  	        digitalWrite(pinStepY, 1);
-        	delayMicroseconds( 500 );
-    	    digitalWrite(pinStepY, 0);
-    	    delayMicroseconds( 500 );
-  		}
-  		else
-  		{
-  			if(!yok)
-  			{
-  				Serial.println("BOOT y1 ");
-  				yok = true;
-  				delay(2000);
-  			}
-  		}
-
-  		// SET Z IN POSITION
-
-  		if(!Z_POSITION)
-  		{
-  		  	digitalWrite(pinStepZ, 1);
-        	delayMicroseconds( 500 );
-    	    digitalWrite(pinStepZ, 0);
-    	    delayMicroseconds( 500 );
-  		}
-  		else
-  		{
-  		  	if(!zok)
-  			{
-  				Serial.println("BOOT z1 ");
-  				zok = true;
-  				Zangle = 0;
-  				delay(2000);
-  			}
-  		}
-
-  		if( xok && yok && zok)
-  		{
-			Serial.println("STAT b1 ");
-  			Serial.println("Booting UP OK!");
-  			Serial.println("SEND 'RUN \n' for start the production");
-  			BOOT = false;
-  		}
-
-
-   }
-
-	// PRODUCTION CODE
-    //-------------------------------------------------------------------------//
-    if(production && !emgStop)  //-
-    {
-
-  		// X //
-
-		// Direction
-  		if(x < 90) directX = false;
-  		else directX = true;
-
-  		if(invertX)
-  		{
-    		if(directX) directX = false;
-    		else directX = true;
-  		}
-  		digitalWrite(pinDirX, directX); // dirX
-
-  		// Si ont doit demarer le moteur
-  		if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis ))
-  		{
-    		if(x > minX && x < maxX) runX = true;
-    		else runX = false;
-  		}
-  		else runX = false;
-
-  		// Calcul du PID X
-  		if(x < 90) vx = (90 - x);
-  		if(x == 0) vx = 0;
-  		if(x > 90) vx = (x - 90);
-
-  		speedX = 1000 / (vx);
-  		speedX = speedX * multiplier; // DEL
-  		if(speedX < 15) speedX = 15;
-
-		// Mise en route du moteur
-  		unsigned long currentX = millis();
-
-    	if (currentX - previousMillisX >= speedX)
-    	{
-      		previousMillisX = currentX;
-
-      		if(runX)
-      		{
-        		digitalWrite(pinStepX, 1);
-        		delayMicroseconds( 500 );
-        		digitalWrite(pinStepX, 0);
-    	 		delayMicroseconds( 500 );
-      		}
-  		}
-
-  		// Y //
-  		// Direction
-  		if(y < 90) directY = false;
-  		else directY = true;
-  		if(invertY)
-  		{
-    		if(directY) directY = false;
-    		else directY = true;
-  		}
-  		digitalWrite(pinDirY, directY);
-
-		// Si ont doit demarer le moteur
-  		if(y > (setpointY + hysteresis) || (y < setpointY - hysteresis ))
-  		{
-    		if(y > minY && y < maxY) runY = true;
-    		else runY = false;
-  		}
-  		else runY = false;
-
-  		// Calcul du PID Y
-  		if(y < 90) vy = (90 - y);
-  		if(y == 0) vy = 0;
-  		if(y > 90) vy = (y - 90);
-
-  		speedY = 1000 / (vy);
-  		speedY = speedY * multiplier; // DEL
-  		if(speedY < 15) speedY = 15;
-
-  		// Mise en route du moteur
-  		unsigned long currentY = millis(); // millis();
-
-    	if (currentY - previousMillisY >= speedY)
-    	{
-      		previousMillisY = currentY;
-
-      		if(runY)
-      		{
-        		digitalWrite(pinStepY, 1);
-        		delayMicroseconds( 500 );
-        		digitalWrite(pinStepY, 0);
-        		delayMicroseconds( 500 );
-      		}
-  		}
-
-  		//--- Z
-  		if(speedZ != 0)
-  		{
-  			unsigned long currentZ = millis();
-  			if (currentZ - previousMillisZ >= speedZ)
-    		{
-      			previousMillisZ = currentZ;
-
-    	 		digitalWrite(pinStepY, 1);
-    	    	delayMicroseconds( 500 );
-    	    	digitalWrite(pinStepY, 0);
-    	    	delayMicroseconds( 500 );
-    	    	if(directZ) Zangle++;
-    	    	else Zangle--;
-  			}
-  		}
-  		if(Zangle == 201) Zangle = 0;
-  		if(Zangle == -1)  Zangle = 0;
-
-
-  } //-
-
-  // Check if the Master-Board are ALIVE
-
-  if(digitalRead(PING_MASTER) && !ifPing)
-  {
-  	ifPing = true;
-  	pingMaster++;
-  }
-
-  if(digitalRead(PING_MASTER) && ifPing) ifPing = false;
-
-
-  	// SEND SERIAL DATA
-    //-------------------------------------------------------------------------//
-    unsigned long currentS = millis(); // millis();
-
-    if (currentS - trigS  >= trigSec)
-    {
-    	trigS = currentS;
-
-
-
-    	// PING
-    	if(LED_PING) LED_PING = false;
-    	else LED_PING = true;
-    	digitalWrite(PING, LED_PING);
-
-
-    	tmpPing2++;
-
-    	if(pingMaster > tmpPing)
-    	{
-    		tmpPing = pingMaster;
-    		tmpPing2 = 0;
-    	}
-    	if(tmpPing2 > 3) emgStop = true;
-
-
-
-    	if(!accelgyro.testConnection());
-    	{
-    		production = false;
-    		emgStop = true;
-    		accelgyro.initialize();
-    		if(accelgyro.testConnection())
-    		{
-    			production = true;
-    		}
-    	}
-
-
-
-    	/*
-
-    	// SEND STATUT
-    	Serial.print("STAT x");
-    	Serial.print(x);
-    	Serial.print(" y");
-    	Serial.print(y);
-    	Serial.print(" i");
-    	Serial.print(invertXY);
-    	Serial.print(" j");
-    	Serial.print(invertX);
-    	Serial.print(" k");
-    	Serial.print(invertY);
-    	Serial.print(" m");
-    	Serial.print(multiplier);
-    	Serial.print(" z");
-    	Serial.print(Zangle);
-
-    	Serial.println(" ");
-
-    	*/
-    }
-}


#1 #8 can now interrupt pano with IR remote.

Also moved the startup delay *after* the pano status was displayed, so
it does not look like the button press had no effect.

--- pano-controller.ino
+++ pano-controller.ino
@@ -307,18 +307,20 @@

     button_clicked = false;
-    joystick.clear(4000);
-    remote.clear(4000);
-    delay(2000); // don't start moving while button is being pressed
+    joystick.clear(4000), remote.clear(4000);
     pano.start();
     attachInterrupt(digitalPinToInterrupt(JOYSTICK_SW), button_click, FALLING);

     while (running){
         displayPanoStatus();
+        if (!pano.position){
+            delay(2000);
+        }
         pano.shutter();
         running = pano.next();

-        if (button_clicked){
+        if (button_clicked || remote.read()){
+            joystick.clear(1000), remote.clear(1000);
             // button was clicked mid-pano, go in manual mode
             int event;
             displayPanoStatus();


changed the way we are printing out float data. Embedded C lang doesnt support sprintf(%f)

--- Calibration/liveCode/overclockAccel/overclockAccel.ino
+++ Calibration/liveCode/overclockAccel/overclockAccel.ino
@@ -20,6 +20,7 @@
 sensors_vec_t   orientation;
 //data buffer for the accel and orientation readings
 char dataArray[80];
+
 void initAccel()
 {
   if(!accel.begin())
@@ -38,7 +39,7 @@
 {
   //this is needed for the duemilanove and uno without ethernet shield
   const int sdCardPin = 10;
-  delay(1000);
+  delay(2000);
   pinMode(10,OUTPUT);
   if (!SD.begin(sdCardPin)) {
     // don't do anything more:
@@ -65,8 +66,12 @@
   accel.getEvent(&accel_event);
   if (dof.accelGetOrientation(&accel_event, &orientation))
   {
-    sprintf(dataArray, "%f, %f, %f, %f, %f, %f", accel_event.acceleration.x, accel_event.acceleration.y, accel_event.acceleration.z, orientation.roll, orientation.pitch, orientation.heading);
-    sdWrite(dataArray);
+    sdWrite((String)accel_event.acceleration.x);
+    sdWrite((String)accel_event.acceleration.y);
+    sdWrite((String)accel_event.acceleration.z);
+    sdWrite((String)accel_event.orientation.roll);
+    sdWrite((String)accel_event.orientation.pitch);
+    sdWrite((String) accel_event.orientation.heading);
     sdWriteNewline();
   }
 }
@@ -89,6 +94,7 @@
   // if the file is available, write to it:
   if (dataFile) {
     dataFile.print(data);
+    dataFile.print(", ");i
     dataFile.close();
     // print to the serial port too:
   }


Add beginnings of pong. Completely untested.

--- BlinkenScreen.ino
+++ BlinkenScreen.ino
@@ -25,6 +25,7 @@
   RAW_WIPE,
   WIPE,
   BUMP,
+  PONG,
   MODE_SENTINAL_H
 };

@@ -119,6 +120,38 @@
   return val;
 }

+
+void animation_pong(char button) {
+  static uint16_t ball = 0x00F0;
+  static unsigned char dir = 0;
+
+  // Reset ball with button #5
+  if (button == B5)
+    ball = 0x00F0;
+
+  // Move ball
+  if (dir)
+    ball >>= 1;
+  else
+    ball <<= 1;
+
+
+  // Draw paddles or blank the feild
+  s.b[0] = s.b[1] = s.b[2] = button == B3 ? 0xF0 : 0x00;
+  s.b[3] = s.b[4] = s.b[5] = button == B4 ? 0x01 : 0x00;
+
+  // Test ball collision with paddle, volley if good
+  if (s.b[0] == ball || s.b[5] == ball)
+    dir ^= 1;
+
+  // Draw the ball
+  s.b[1] |= ball >> 8; // Left
+  s.b[4] |= ball;      // Right
+
+  s.i = massage(s.i);
+}
+
+
 void animation_wipe() {
   animation_raw_wipe();

@@ -185,8 +218,6 @@
       break;
   }

-  Serial.println((int)mode);
-
   switch (mode) {
     case RAW_WIPE:
       animation_raw_wipe();
@@ -200,6 +231,10 @@
       animation_bump();
       break;

+    case PONG:
+      animation_pong(button);
+      break;
+
     // Outside range, correct it
     case MODE_SENTINAL_H:
       mode = MODE_SENTINAL_L + 1;


Removing old debug code.

Removing old debug code.

--- smc/debug/debug.ino
+++ smc/debug/debug.ino
@@ -1,78 +0,0 @@
-#include <Wire.h>
-#include <I2Cdev.h>
-// #include <MPU6050.h>
-#include <MPU6050_9Axis_MotionApps41.h>
-
-// Status LEDs.
-#define GREEN_LED 7
-#define RED_LED 8
-
-bool toggle = true;
-
-MPU6050 imu;
-
-uint16_t imuPacketSize;
-uint16_t imuFIFOCount;
-uint8_t  imuFIFOBuffer[64];
-
-Quaternion quaternion;  // [w, x, y, z]
-
-volatile bool imuInt;
-void imuIntFunc() {
-  imuInt = true;
-}
-
-void readData() {
-  imuInt = false;
-
-  while (imuFIFOCount < imuPacketSize) imuFIFOCount = imu.getFIFOCount();
-  imu.getFIFOBytes(imuFIFOBuffer, imuPacketSize);
-  imuFIFOCount -= imuPacketSize;
-}
-
-void statusLight(bool state) {
-  digitalWrite(GREEN_LED, state ? HIGH : LOW);
-  digitalWrite(RED_LED, state ? LOW : HIGH);
-}
-
-void setup() {
-  // Setup status LEDs.
-  pinMode(GREEN_LED, OUTPUT);
-  pinMode(RED_LED, OUTPUT);
-  statusLight(0);
-
-  Wire.begin();
-
-  Serial.begin(38400);
-
-  imu.initialize();
-  imu.dmpInitialize();
-  imu.setDMPEnabled(true);
-  attachInterrupt(0, imuIntFunc, RISING);
-  imuPacketSize = imu.dmpGetFIFOPacketSize();
-
-  statusLight(1);
-}
-
-void loop() {
-  if (imuInt) {
-
-    if (toggle = !toggle) {
-      digitalWrite(GREEN_LED, HIGH);
-    } else {
-      digitalWrite(GREEN_LED, LOW);
-    }
-
-    if (imu.getIntStatus() & 0x02) {
-      readData();
-      imu.dmpGetQuaternion(&quaternion, imuFIFOBuffer);
-      Serial.print(quaternion.w);
-      Serial.print("\t");
-      Serial.print(quaternion.x);
-      Serial.print("\t");
-      Serial.print(quaternion.y);
-      Serial.print("\t");
-      Serial.println(quaternion.z);
-    }
-  }
-}


Added simple HTTP server to DNSServer example

--- libraries/DNSServer/examples/DNSServer/DNSServer.ino
+++ libraries/DNSServer/examples/DNSServer/DNSServer.ino
@@ -1,9 +1,11 @@
 #include <ESP8266WiFi.h>
 #include <DNSServer.h>
+#include <ESP8266WebServer.h>

 const byte DNS_PORT = 53;
 IPAddress apIP(192, 168, 1, 1);
 DNSServer dnsServer;
+ESP8266WebServer webServer(80);

 void setup() {
   WiFi.mode(WIFI_AP);
@@ -21,8 +23,19 @@

   //start DNS server for a specific domain name
   dnsServer.start(DNS_PORT, "www.example.com", apIP);
+
+  //simple HTTP server to see that DNS server is working
+  webServer.onNotFound([]() {
+    String message = "Hello World!\n\n";
+    message += "URI: ";
+    message += webServer.uri();
+
+    webServer.send(200, "text/plain", message);
+  });
+  webServer.begin();
 }

 void loop() {
   dnsServer.processNextRequest();
+  webServer.handleClient();
 }


Updated LEDTest example.

Updated LEDTest example.

Now uses newer µSpeech 4.0 API.

--- examples/LEDTest/LEDTest.ino
+++ examples/LEDTest/LEDTest.ino
@@ -7,6 +7,13 @@
 boolean newline=false;
 int sum = 0;
 void setup(){
+  voice.f_enabled = true;
+  voice.minVolume = 1500;
+  voice.fconstant = 400;
+  voice.econstant = 1;
+  voice.aconstant = 2;
+  voice.vconstant = 3;
+  voice.shconstant = 4;
   voice.calibrate();
   Serial.begin(9600);
   pinMode(led, OUTPUT);


new flashy pattern

new flashy pattern

--- src/blinky.ino
+++ src/blinky.ino
@@ -11,7 +11,7 @@
 #define PIXEL_PIN 6
 #define PIXEL_TYPE NSFastLED::NEOPIXEL
 #define HUE_STEP 10 // 1..255, each loop increments hue by this value
-#define LOOP_DELAY 100 //ms
+#define LOOP_DELAY 50 //ms
 #define HSV_BRIGHTNESS 255
 #define HSV_SATURATION 255
 /* set this to match the number of patterns you flip
@@ -78,7 +78,7 @@
   }
 }

-// pattern 1
+// disorient themed flickering.
 void pattern_disorient_1(){
   // illumination probability
   // -> random sparkle probability (white)
@@ -122,6 +122,21 @@
   base_hue += HUE_STEP;
 }

+// rainbow pulsing with varied breathing cycles
+void pattern_phase_rainbow_pulse() {
+  uint8_t bpm = NSFastLED::beatsin8(6, 6, 160); // on a period of 10s, cycle bpm between 6-200
+  uint8_t cBrightness = NSFastLED::beatsin8(bpm, 0, 255);
+  NSFastLED::CHSV hsv = NSFastLED::CHSV(base_hue, HSV_SATURATION, cBrightness);
+  NSFastLED::CRGB rgb;
+  NSFastLED::hsv2rgb_rainbow(hsv, rgb);
+  for (int i = 0 ; i < PIXEL_COUNT ; ++i){
+    leds[i] = rgb;
+  }
+  // set the center pixel to mirror what pixel 0 is
+  RGB.color(rgb.r, rgb.g, rgb.b);
+  base_hue += 2;
+}
+
 // pattern 3
 void pattern_hsv_circle_loop(){
   NSFastLED::CHSV hsv = NSFastLED::CHSV(base_hue, HSV_SATURATION, HSV_BRIGHTNESS);
@@ -184,11 +199,11 @@
   } else if (pattern == 1) {
     pattern_hsv_offset_circle_loop();
   } else if (pattern == 2) {
-    pattern_disorient_1();
+    pattern_hsv_circle_loop();
   } else if (pattern == 3) {
-    pattern_hsv_circle_loop();
+    pattern_disorient_2();
   } else if (pattern == 4) {
-    pattern_disorient_2();
+    pattern_phase_rainbow_pulse();
   }

   gLED->setBrightness(gBrightness);


Updates motor control constants for competition platform.

--- sandbox/arduino/MotorShield/MotorShield.ino
+++ sandbox/arduino/MotorShield/MotorShield.ino
@@ -12,8 +12,8 @@
 volatile int tickDataRight = 0;
 volatile int tickDataLeft = 0;

-const float ticksPerRev = 7000.0;
-const float wheelCir = 1.11715; // Meters
+const float ticksPerRev = 6000.0;
+const float wheelCir = 1.092; // Meters
 const float metersPerTick = wheelCir / ticksPerRev;
 const float DEADBAND = 10;


display of ip address corrected

display of ip address corrected

--- esp8266_NeoPixelLightStick.ino
+++ esp8266_NeoPixelLightStick.ino
@@ -123,8 +123,10 @@
   for (int i = 0; i < 4; i++) {
     byte octet = WiFi.localIP()[i];
     Serial.println(octet);
-    if (octet / 100 > 0) {
+    if (octet / 100 > 1) {
       NeoPixelLightStick.setColor(i * 9, 255, 0, 0);
+    } else if (octet / 100 > 0) {
+      NeoPixelLightStick.setColor(i * 9, 255 / 6, 0, 0);
     } else {
       NeoPixelLightStick.setColor(i * 9, 255 / 127, 0, 0);
     }


Delete measure_Pressure.ino

Delete measure_Pressure.ino

--- measure_Pressure.ino
+++ measure_Pressure.ino
@@ -1,18 +0,0 @@
-//*******************************************************************************
-// Measure, average, calibrate and display boiler pressure
-//********************************************************************************
-
-float measurePressure()
-{
-#ifdef CALIBRATE_PRESSURE
-	float pressure = analogRead(PRESSURE_SENSOR_INPUT); // Just show the integer reading
-#else
-	float pressure = (float)(map((int)analogRead(PRESSURE_SENSOR_INPUT), LOW_CALIBRATION_PRESSURE_READING, HIGH_CALIBRATION_PRESSURE_READING, LOW_CALIBRATION_PRESSURE, HIGH_CALIBRATION_PRESSURE)) / 10.0 ; // Every loop we measure and average pressure in boiler
-#endif
-
-
-	g_averageP.push(pressure); // add the measurement to the rolling average
-	return pressure; //we return pressure for the PID PP loop
-
-}
-


fingerprint更新

fingerprint更新

--- examples/rss_disp/rss_disp.ino
+++ examples/rss_disp/rss_disp.ino
@@ -44,7 +44,7 @@
   const char *figerprint;
 } site_t;

-const char *yahoo_fingerprint = "2c4cc1be32d3a6021bbce7f918290af709972130";
+const char *yahoo_fingerprint = "1E8BB7F438189245FCC779DD4DA9912BBC2F70CF";

 const site_t site[] = {
     {"Yahoo News", 20, "https://news.yahoo.co.jp/pickup/rss.xml",
@@ -235,6 +235,7 @@
     LedMat.alignPrintf(x + w / 2, y, TA_CENTER, TA_TOP, "%02d:%02d:%02d",
                        tm->tm_hour, tm->tm_min, tm->tm_sec);
     t0 = t;
+    LedMat.display();
   }
 }


Changes towards commercial mute

Changes towards commercial mute

--- source/monkeyDAB/monkeyDAB.ino
+++ source/monkeyDAB/monkeyDAB.ino
@@ -185,7 +185,15 @@

 radio_state_t    Radio;
 radio_config_t   Conf;
+
 RTC_time_t       RTC_time;
+/*
+typedef struct {
+  byte            second, minute, hour, day, month, year;
+  bool            isOk;
+} RTC_time_t;
+*/
+
 char             ch;
 int              res, nProg, iProg, iPrevProg, dirProg;
 unsigned long    tLastUpdate;
@@ -199,6 +207,7 @@
 bool             isControlChanged;
 bool             isDisplayOn;
 bool             lastBusy;
+bool             isMutedByUser;
 bool             isProgDialLocked, isFirstUpdateFSM;

 control_t        Controls[CONTROL_COUNT] = {
@@ -215,6 +224,10 @@
   {PIN_DIAL_TON, 0,         CONTROL_DIAL_R, "TON",
    LOW, LOW,  LOW,  LOW, LOW,  0,0,-1, false, 0.0, 0L}};

+//--------------------------------------------------------------------------------
+// Constants and variables related to arranging DAB programs across the
+// (capacitance) range of the station dial
+//
 const int        dBordMin  = 1;
 const int        nBordDef  = 15;
 const int        nTrials   = 50;
@@ -266,6 +279,7 @@
   lastBusy             = true;
   isProgDialLocked     = false;
   isFirstUpdateFSM     = true;
+  isMutedByUser        = false;

   BBE_EQ.BBEOn         = 2;
   BBE_EQ.EQMode        = EQ_MODE_JAZZ;
@@ -400,6 +414,26 @@
     Radio.isProgChanged = false;
   }

+  // If muted by user, check if full or half hour is coming up to unmute
+  //
+  if(isMutedByUser) {
+    if(!RTC_time.isOk) {
+      // Unmute now as the time seems not to be available
+      //
+      // ...
+    }
+    else {
+      // Check time ...
+      //
+      /*
+      typedef struct {
+        byte            second, minute, hour, day, month, year;
+        bool            isOk;
+      } RTC_time_t;
+      */
+    }
+  }
+
   // Update radio info at a defined interval
   //
   if(millis() > (tLastUpdate +RADIO_UPDATE_MS)) {


Change up the twinkle timing a bit.

Change up the twinkle timing a bit.

--- arduino/rainbow_cloud/rainbow_cloud/rainbow_cloud.ino
+++ arduino/rainbow_cloud/rainbow_cloud/rainbow_cloud.ino
@@ -67,7 +67,7 @@
 void updateTwinkleLocation(){
   uint8_t i;
   for(i=0; i < NUM_TWINKLES; i++){
-    if( random(0,50) == 0){
+    if( random(0,10) == 0){
       twinkles[i][0] = random(0, NUM_PIXELS-3);
     }
   }
@@ -103,7 +103,7 @@
    for(uint8_t i=0; i < NUM_TWINKLES; i++){
     twinkles[i][0] = random(0,NUM_PIXELS - 3);
     twinkles[i][2] = random(0,255);
-    twinkles[i][3] = 1;
+    twinkles[i][3] = random(1,5);
    }
 }


fix led timeout that caused ir received didn't make led blink

--- client/client.ino
+++ client/client.ino
@@ -74,7 +74,7 @@
 void loop()
 {
   //led control
-  if(mills() - start_time > pendingThreshold) {
+  if(millis() - start_time > pendingThreshold) {
     //stop blinking after a period of time
     digitalWrite(ledStatePin, LOW);
     statePending = false;
@@ -99,6 +99,7 @@

     //client starts blinking
     statePending = true;
+    start_time = millis();
     ledStateInterval = 600;

   }


IO Expanders working for Ops

IO Expanders working for Ops

Integrated the I/O exapnder to control Action Groups 1 - 10, Stage, Gear, Lights, RCS, Brakes, Abort!  Very convenient they call fits.

--- KSPboard.ino
+++ KSPboard.ino
@@ -39,19 +39,20 @@
 #define PIN_ROT_DATA A2
 #define PIN_ROT_SW // no pin yet

-// ops pins
-#define PIN_OP_LAUNCH 0
-#define PIN_OP_STAGE 0
-#define PIN_OP_ACG3 0
-#define PIN_OP_ACG5 0
+// i2c addresses / stuff
+#define I2C_SUCCESS 0
+#define IO_ADDR_BASE 0x20
+#define IO_DATA_LENGTH 2
+
+#define IO_DEV_OPS 0

 // delays
-#define DELAY_LOOP 10
+#define DELAY_LOOP 1000
 #define DELAY_START 30
 #define DELAY_OP 100

 // misc
-#define OPS (sizeof(opPin) / sizeof(uint8_t))
+#define OPS 16

 // helm
 #define RAMP_MAX 50
@@ -59,6 +60,7 @@
 #define DIR_MAX 2000
 #define DIR_MIN -DIR_MAX

+// helper stuff for helm / shorthand
 #define PITCH_STICK digitalRead(PIN_PITCH_S)
 #define ROLL_STICK digitalRead(PIN_ROLL_S)
 #define YAW_STICK digitalRead(PIN_YAW_S)
@@ -74,50 +76,48 @@

 // op control variables
 // state == 0 to DELAY_OP-1 -> off / debounce, state == DELAY_OP -> on
-uint8_t opState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
-// operation pins set to zero are skipped
-uint8_t opPin[] = // this will hold bitmasks for i/o expander
-{
-  0,             // null
-  0,             // action group 1
-  0,             // '' 2
-  PIN_OP_ACG3,   // '' 3
-  0,             // '' 4
-  PIN_OP_ACG5,   // '' 5
-  0,             // '' 6
-  0,             // '' 7
-  0,             // '' 8
-  0,             // '' 9
-  0,             // '' 10
-  PIN_OP_LAUNCH, //
-  PIN_OP_STAGE   //
-};
+uint8_t opState[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

 // this controls whether the python script closes or not, 1 == run
 boolean state = 1;

-// specialized control functions
-
-

 //// helper functions
 //

+// i/o expander helpers
+uint8_t requestDevice(uint8_t address) // ping the device / send start command
+{
+  Wire.beginTransmission(IO_ADDR_BASE | address);
+  return (Wire.endTransmission());
+}
+
+boolean requestData(uint8_t address) // returns success fail
+{
+  return (Wire.requestFrom(IO_ADDR_BASE | address, IO_DATA_LENGTH) == IO_DATA_LENGTH);
+}
+
+uint16_t readData() // get the data and stuff it into a 16-bit unsigned value
+{
+  return (~(Wire.read() | (Wire.read() << 8)));
+}
+
+// direction helpers
 int16_t getAdjustment(uint8_t pinH, uint8_t pinL, int8_t adj) // get control input
 {
   switch (digitalRead(pinH) ? HIGH : (digitalRead(pinL) ? LOW : NEUTRAL))
   {
-    case HIGH:
+    case HIGH: // pitch up / roll right / yaw right
       if (adj++ > RAMP_MAX)
         adj = RAMP_MAX;
       break;

-    case LOW:
+    case LOW: // pitch down / roll left / yaw left
       if (adj-- < RAMP_MIN)
         adj = RAMP_MIN;
       break;

-    case NEUTRAL:
+    case NEUTRAL: // stuck in the middle with you
     default:
       adj = 0;
   }
@@ -134,13 +134,12 @@
   }
   else
   {
-    current += adj;
-
-    if (current > DIR_MAX)
+    current += adj; // adjust current direction
+
+    if (current > DIR_MAX) // keep the current direction in bounds
       current = DIR_MAX;
-    else
-      if (current < DIR_MIN)
-        current = DIR_MIN;
+    else if (current < DIR_MIN)
+      current = DIR_MIN;
   }

   return (current);
@@ -189,11 +188,8 @@
 }

 void setupOps()
-{ // disabled while building the joystick control
-  /*pinMode(PIN_OP_LAUNCH, INPUT_PULLUP);
-    pinMode(PIN_OP_STAGE, INPUT_PULLUP);
-    pinMode(PIN_OP_ACG3, INPUT_PULLUP);
-    pinMode(PIN_OP_ACG5, INPUT_PULLUP);*/
+{
+  // put check here for i/o expander??
 }

@@ -231,20 +227,24 @@
   uint8_t ops = 0;
   uint8_t index = 0;

-
-  for (index = 0; index < OPS; index++)
-  {
-    if (!opPin[index]) // if the pin is zero, skip
-      continue;
-
-    if (opState[index] > 0) // check for debounce on current pin
+  if (requestDevice(IO_DEV_OPS) == I2C_SUCCESS) // send start, skip if failure
+  {
+    if (requestData(IO_DEV_OPS)) // ask for data, skip if failure
     {
-      opState[index]--; // decrement debounce counter for current state
-    }
-    else // if not we can check to see if it's triggered
-    {
-      opState[index] = digitalRead(opPin[index]) ? DELAY_OP : 0;
-      ops++;
+      uint16_t data = readData(); // finally get the 2 byte data packet
+
+      for (index = 0; index < OPS; index++) // scan through ops 1-16 (everything but sas)
+      {
+        if (opState[index] > 0) // check for debounce on current pin
+        {
+          opState[index]--; // decrement debounce counter for current state
+        }
+        else // if not we can check to see if it's triggered
+        {
+          opState[index] =  ((1 << index) & data) ? DELAY_OP : 0;
+          ops++;
+        }
+      }
     }
   }

@@ -284,7 +284,7 @@
   if (state)
   {
     updateHelm();
-    //updateOps();
+    updateOps();
   }

   delay(DELAY_LOOP);


Fix bug tracking latching state

Fix bug tracking latching state

Since the latching state was determined from the last value sent, we
couldn't figure out the state if both the "on" and "off" values were
either >= or < 128.  Instead, track it explicitly in a new LatchState
array.

Also fix an embarassing typo with note events.

--- MidiController.ino
+++ MidiController.ino
@@ -30,9 +30,10 @@
 int    PinState[PIN_COUNT];  // Previous value, indexed by pin
 int    NewState[PIN_COUNT];  // Current value, indexed by pin

-EventMap *EventList; // List of events to handle
-unsigned NumEvents;  // Number of entries in EventList
-uint8_t  *LastValue; // Last value calculated for controller
+EventMap *EventList;  // List of events to handle
+unsigned NumEvents;   // Number of entries in EventList
+uint8_t  *LastValue;  // Last value calculated for controller
+uint8_t  *LatchState; // Last state recorded for pin

 // Generate an output event, based on an input pin state and
@@ -59,8 +60,8 @@
 #ifdef LOG_EVENTS
       Serial.println(String("Off ") + noteEvt->Channel + "/" + noteEvt->Note + ": " + noteEvt->OffVelocity);
 #endif
-      usbMIDI.sendNoteOn(noteEvt->Note, noteEvt->OffVelocity, noteEvt->Channel);
-      MIDI.sendNoteOn(noteEvt->Note, noteEvt->OffVelocity, noteEvt->Channel);
+      usbMIDI.sendNoteOff(noteEvt->Note, noteEvt->OffVelocity, noteEvt->Channel);
+      MIDI.sendNoteOff(noteEvt->Note, noteEvt->OffVelocity, noteEvt->Channel);
     }
     value = state / 8; // Scale to 0-127 range
     break;
@@ -194,13 +195,16 @@
     }
   }

-  // Initialize EventList, NumEvents, LastValue
+  // Initialize EventList, NumEvents, LastValue, LatchState
   NumEvents = count;
   EventList = (EventMap *)realloc (EventList, NumEvents * sizeof (*EventList));
   memcpy(EventList, &DefaultEventList[i], NumEvents * sizeof (*EventList));

   LastValue = (uint8_t *)realloc (LastValue, NumEvents * sizeof (*LastValue));
   memset(LastValue, 0, NumEvents * sizeof (*LastValue));
+
+  LatchState = (uint8_t *)realloc (LatchState, NumEvents * sizeof (*LatchState));
+  memset(LatchState, 0, NumEvents * sizeof (*LatchState));

   // Send any initialization events, and initialize LastValue[]

@@ -215,10 +219,12 @@
     else if (m->Handling == LatchingOn) {
       // Default the value to "on"
       LastValue[i] = 0x7f;
+      LatchState[i] = 1;
     }
     else {
       // Default the value to "off"
       LastValue[i] = 0;
+      LatchState[i] = 0;
     }
   }
 }
@@ -374,22 +380,15 @@

     case LatchingOff:
     case LatchingOn:
-      // Fetch current latch state based on last value sent
-      if (LastValue[i] < 64) {
-        state = 0;
-      }
-      else {
-        state = 1023;
-      }
-
       // Toggle state on button press
       if (PinState[pinNum] < 512 && NewState[pinNum] >= 512) {
-        state = 1023 - state;
+        LatchState[i] ^= 1;
         changed = 1;
       }
       else {
         changed = 0;
       }
+      state = (LatchState[i] == 0) ? 0 : 1023;
       break;

     default:


Console2TFT.inoのフォントをgenfontに変更

Console2TFT.inoのフォントをgenfontに変更

landscapeで30行表示したくなったので。

--- examples/Console2TFT/Console2TFT.ino
+++ examples/Console2TFT/Console2TFT.ino
@@ -12,9 +12,15 @@
 #include "SWTFT.h" // Hardware-specific library
 #include "TFTKanji.h"

+#if 0
 // 小伝馬町16
 #define kanji_file "GONZN16X.TLF"
 #define ank_file   "GONHN16X.TLF"
+#else
+// genfont(16x8)
+#define kanji_file "GENZN08X.FNT"
+#define ank_file   "GENHN08X.FNT"
+#endif

 // Pin numbers in templates must be constants.
 const uint8_t SOFT_MISO_PIN = 12;


remake

remake

--- examples/serial_menu/serial_menu.ino
+++ examples/serial_menu/serial_menu.ino
@@ -1,3 +1,32 @@
+/*
+ * LiquidMenu library - serial_menu.ino
+ *
+ * This example uses the serial communication to execute commands.
+ *
+ * The available commands will be printed on the serial monitor.
+ *
+ * The circuit:
+ * https://github.com/VasilKalchev/LiquidMenu/blob/master/examples/serial_menu/serial_menu.png
+ * - LCD RS pin to Arduino pin 12
+ * - LCD E pin to Arduino pin 11
+ * - LCD D4 pin to Arduino pin 5
+ * - LCD D5 pin to Arduino pin 4
+ * - LCD D6 pin to Arduino pin 3
+ * - LCD D7 pin to Arduino pin 2
+ * - LCD R/W pin to ground
+ * - LCD VSS pin to ground
+ * - LCD VCC pin to  5V
+ * - 10k ohm potentiometer: ends to 5V and ground, wiper to LCD V0
+ * - 150 ohm resistor from 5V to LCD Anode
+ * - LCD Cathode to ground
+ *
+ * Created July 24, 2016
+ * by Vasil Kalchev
+ *
+ * https://github.com/VasilKalchev/LiquidMenu
+ *
+ */
+
 #include <LiquidCrystal.h>
 #include <LiquidMenu.h>

@@ -18,51 +47,70 @@
 LiquidScreen welcome_screen(welcome_line1, welcome_line2);

 LiquidLine line21(4, 0, "Screen 2");
-LiquidLine line22(1, 1, "next, previous");
-LiquidScreen screen2(line21, line22);
+LiquidLine type_line(4, 1, "type...");
+LiquidScreen screen2(line21, type_line);

 LiquidLine line31(4, 0, "Screen 3");
-LiquidLine line32(1, 1, "focus, position");
-LiquidScreen screen3(line31, line32);
+LiquidScreen screen3(line31, type_line);

 LiquidLine line41(4, 0, "Screen 4");
-LiquidLine line42(1, 1, "update");
-LiquidScreen screen4(line41, line42);
+LiquidScreen screen4(line41, type_line);

 LiquidMenu menu(lcd, welcome_screen, screen2, screen3, screen4);

+void callback_function() {
+  Serial.println("You called the callback function.");
+}
+
 void setup() {
-	Serial.begin(250000);
-	lcd.begin(16, 2);
+  Serial.begin(250000);
+  lcd.begin(16, 2);

-	menu.update();
+  line21.attach_function(1, callback_function);
+  line31.attach_function(1, callback_function);
+  line41.attach_function(1, callback_function);
+  type_line.attach_function(1, callback_function);
+
+  menu.update();
+
+  Serial.print("LiquidMenu "); Serial.print(VERSION); Serial.println(" - Serial example:");
+  Serial.println("To navigate the menu type 'menu.next_screen()' or 'menu.previous_screen()'.");
+  Serial.println("To switch focus type 'menu.switch_focus()'.");
+  Serial.println("To call the callback function type 'menu.call_function(1)'.");
+  Serial.println("To adjust the focus position type 'menu.set_focusPosition(Position::LEFT)'");
+  Serial.println("  or 'menu.set_focusPosition(Position::RIGHT)'.");
+  Serial.println("To update the display type 'menu.update()'."); Serial.println();
 }

 void loop() {
-	while (Serial.available() > 0) {
-		String command = Serial.readStringUntil('\0');
-		if (command == "next") {
-			Serial.println(command);
-			menu.next_screen();
-		} else if (command == "previous") {
-			Serial.println(command);
-			menu.previous_screen();
-		} else if (command == "focus") {
-			Serial.println(command);
-			menu.switch_focus(); // switches focus to the next line
-			// focus is used with functions (see 'functions_menu' example)
-		} else if (command == "focus position = left") {
-			Serial.println(command);
-			// this function sets the focus position
-			menu.set_focusPosition(Position::LEFT);
-		} else if (command == "focus position = right") {
-			Serial.println(command);
-			menu.set_focusPosition(Position::RIGHT);
-		} else if (command == "update") {
-			Serial.println(command);
-		} else {
-			Serial.print(command); Serial.println(" - unknown command");
-		}
-		menu.update();
-	}
+  while (Serial.available() > 0) {
+    String command = Serial.readStringUntil('\0');
+    if (command == "menu.next_screen()") {
+      Serial.println(command);
+      menu.next_screen();
+    } else if (command == "menu.previous_screen()") {
+      Serial.println(command);
+      menu.previous_screen();
+    } else if (command == "menu.switch_focus()") {
+      Serial.println(command);
+      menu.switch_focus(); // switches focus to the next line
+      // focus is used with functions (see 'functions_menu' example)
+    } else if (command == "menu.call_function(1)") {
+      Serial.println(command);
+      menu.call_function(1);
+    } else if (command == "menu.set_focusPosition(Position::LEFT)") {
+      Serial.println(command);
+      // this function sets the focus position
+      menu.set_focusPosition(Position::LEFT);
+    } else if (command == "menu.set_focusPosition(Position::RIGHT)") {
+      Serial.println(command);
+      menu.set_focusPosition(Position::RIGHT);
+    } else if (command == "menu.update()") {
+      Serial.println(command);
+      menu.update();
+    } else {
+      Serial.print(command); Serial.println(" - unknown command");
+    }
+    menu.update();
+  }
 }


Move globals to const loop locals.

Move globals to const loop locals.

--- examples/seq/seq.ino
+++ examples/seq/seq.ino
@@ -257,8 +257,8 @@
   virtual void loop()
   {
     // cache stage, step, and clock gate (so that each loop is "atomic")
-    cached_stage = stage;
-    cached_step = step;
+    const uint8_t cached_stage = stage;
+    const uint8_t cached_step = step;
     cached_clock_gate = Clock.state();
     cached_retrigger = Clock.retrigger();

@@ -341,7 +341,7 @@
     // display gate
     if(gate != last_gate || stage != last_stage)
     {
-      uint8_t last_stage_cached = last_stage;
+      const uint8_t last_stage_cached = last_stage;
       last_gate = gate;
       last_stage = stage;

@@ -741,7 +741,6 @@
   DUINO_MultiDisplayWidget<8> * widgets_gate_;
   DUINO_MultiDisplayWidget<8> * widgets_slew_;

-  uint8_t cached_stage, cached_step;
   bool cached_clock_gate, cached_retrigger;
   unsigned long clock_time;


Handle encoder spin for (most) parameter value changes.

--- examples/seq/seq.ino
+++ examples/seq/seq.ino
@@ -122,6 +122,10 @@
     // verify settings and export to function parameters
     for(uint8_t i = 0; i < 8; ++i)
     {
+      if(stage_pitch[i] < 0)
+      {
+        stage_pitch[i] = 0;
+      }
       if(stage_pitch[i] > 119)
       {
         stage_pitch[i] = 119;
@@ -140,11 +144,16 @@

     for(uint8_t i = 0; i < 8; ++i)
     {
-      if(stage_gate[i] > 5)
-      {
-        stage_gate[i] = 5;
+      if(stage_gate[i] < 0 || stage_gate[i] > 5)
+      {
+        stage_gate[i] = 2;
       }
       seq_values.stage_gate[i] = (GateMode)stage_gate[i];
+    }
+
+    for(uint8_t i = 0; i < 8; ++i)
+    {
+      seq_values.stage_slew[i] = (bool)((stage_slew >> i) & 1);
     }

     if(stage_count < 1 || stage_count > 8)
@@ -157,9 +166,9 @@
     seq_values.slew_rate = (float)slew_rate / 255.0;
     seq_values.gate_time = (float)gate_time / 255.0;

-    if(clock_bpm > 30)
-    {
-      clock_bpm = 30;
+    if(clock_bpm < 0 || clock_bpm > 30)
+    {
+      clock_bpm = 0;
     }
     seq_values.clock_period = bpm_to_ms(clock_bpm);
     seq_values.clock_ext = !(bool)clock_bpm;
@@ -213,6 +222,7 @@
     }
     else if(b == DUINO_Encoder::Clicked)
     {
+      // switch local selection
       invert_current_selection();
       switch(main_selected)
       {
@@ -240,6 +250,135 @@
       display_changed = true;
     }

+    // handle encoder spin
+    int16_t v = encoder->get_value();
+    if(v)
+    {
+      switch(main_selected)
+      {
+        case 0: // save
+          break;
+        case 1: // top
+          switch(top_selected)
+          {
+            case 0: // count
+              stage_count += v;
+              if(stage_count < 1)
+              {
+                stage_count = 1;
+              }
+              else if(stage_count > 8)
+              {
+                stage_count = 8;
+              }
+              seq_values.stage_count = stage_count;
+              display->fill_rect(37, 1, 7, 9, DUINO_SSD1306::White);
+              display->draw_char(38, 2, '0' + stage_count, DUINO_SSD1306::Black);
+              break;
+            case 1: // dir/add
+              if(v < 0)
+              {
+                diradd_mode = 0;
+              }
+              else if(v > 0)
+              {
+                diradd_mode = 1;
+              }
+              seq_values.diradd_mode = (bool)diradd_mode;
+              display->fill_rect(46, 1, 7, 9, DUINO_SSD1306::White);
+              display->draw_char(47, 2, diradd_mode ? 'A' : 'D', DUINO_SSD1306::Black);
+              break;
+            case 2: // slew
+              // TODO: slew
+              display->fill_rect(55, 1, 20, 9, DUINO_SSD1306::White);
+              break;
+            case 3: // gate
+              // TODO: gate
+              display->fill_rect(77, 1, 20, 9, DUINO_SSD1306::White);
+              break;
+            case 4: // clock
+              clock_bpm += v;
+              if(clock_bpm < 0)
+              {
+                clock_bpm = 0;
+              }
+              else if(clock_bpm > 30)
+              {
+                clock_bpm = 30;
+              }
+              seq_values.clock_period = bpm_to_ms(clock_bpm);
+              seq_values.clock_ext = !(bool)clock_bpm;
+              display->fill_rect(99, 1, 19, 9, DUINO_SSD1306::White);
+              display_clock(100, 2, clock_bpm, DUINO_SSD1306::Black);
+              break;
+          }
+          break;
+        case 2: // pitch
+          stage_pitch[stage_selected] += v;
+          if(stage_pitch[stage_selected] < 0)
+          {
+            stage_pitch[stage_selected] = 0;
+          }
+          else if(stage_pitch[stage_selected] > 119)
+          {
+            stage_pitch[stage_selected] = 119;
+          }
+          seq_values.stage_cv[stage_selected] = note_to_cv(stage_pitch[stage_selected]);
+          display->fill_rect(16 * stage_selected, 10, 16, 15, DUINO_SSD1306::White);
+          display_note(16 * stage_selected, 9, stage_pitch[stage_selected], DUINO_SSD1306::Black);
+          break;
+        case 3: // steps
+          stage_steps[stage_selected] += v;
+          if(stage_steps[stage_selected] < 1)
+          {
+            stage_steps[stage_selected] = 1;
+          }
+          else if(stage_steps[stage_selected] > 8)
+          {
+            stage_steps[stage_selected] = 8;
+          }
+          seq_values.stage_steps[stage_selected] = stage_steps[stage_selected];
+          display->fill_rect(16 * stage_selected, 25, 16, 17, DUINO_SSD1306::White);
+          for(uint8_t j = 0; j < stage_steps[stage_selected]; ++j)
+          {
+            display->draw_hline(16 * stage_selected + 2, 40 - j * 2, 5, DUINO_SSD1306::Black);
+            display->draw_hline(16 * stage_selected + 9, 40 - j * 2, 5, DUINO_SSD1306::Black);
+          }
+          break;
+        case 4: // gate
+          stage_gate[stage_selected] += v;
+          if(stage_gate[stage_selected] < 0)
+          {
+            stage_gate[stage_selected] = 0;
+          }
+          else if(stage_gate[stage_selected] > 5)
+          {
+            stage_gate[stage_selected] = 5;
+          }
+          seq_values.stage_gate[stage_selected] = (GateMode)stage_gate[stage_selected];
+          display->fill_rect(16 * stage_selected, 42, 16, 16, DUINO_SSD1306::White);
+          display->draw_icon_16(16 * stage_selected, 43, gate_mode_icons, (GateMode)stage_gate[stage_selected],
+              DUINO_SSD1306::Black);
+          break;
+        case 5: // slew
+          if(v < 0)
+          {
+            stage_slew |= (1 << stage_selected);
+          }
+          else if(v > 0)
+          {
+            stage_slew &= ~(1 << stage_selected);
+          }
+          seq_values.stage_slew[stage_selected] = (bool)((stage_slew >> stage_selected) & 1);
+          display->fill_rect(16 * stage_selected + 1, 59, 14, 4, DUINO_SSD1306::Black);
+          display->fill_rect(16 * stage_selected + 2 + 6 * ((stage_slew >> stage_selected) & 1), 60, 6, 2,
+              DUINO_SSD1306::White);
+          break;
+      }
+
+      display_changed = (bool)main_selected;
+    }
+
     if(display_changed)
     {
       display->display();
@@ -248,7 +387,7 @@
   }

  private:
-  float note_to_cv(uint8_t note)
+  float note_to_cv(int8_t note)
   {
     return ((float)note - 36.0) / 12.0;
   }
@@ -262,17 +401,17 @@
   {
     if(bpm == 0)
     {
-      display->draw_text(x, y, "EXT", DUINO_SSD1306::White);
+      display->draw_text(x, y, "EXT", color);
     }
     else
     {
-      display->draw_char(x, y, '0' + bpm / 10, DUINO_SSD1306::White);
-      display->draw_char(x + 6, y, '0' + bpm % 10, DUINO_SSD1306::White);
-      display->draw_char(x + 12, y, '0', DUINO_SSD1306::White);
-    }
-  }
-
-  void display_note(int16_t x, int16_t y, uint8_t note, DUINO_SSD1306::SSD1306Color color)
+      display->draw_char(x, y, '0' + bpm / 10, color);
+      display->draw_char(x + 6, y, '0' + bpm % 10, color);
+      display->draw_char(x + 12, y, '0', color);
+    }
+  }
+
+  void display_note(int16_t x, int16_t y, int8_t note, DUINO_SSD1306::SSD1306Color color)
   {
     // draw octave
     display->draw_char(x + 9, y + 8, '0' + note / 12, color);
@@ -346,15 +485,15 @@

   bool display_changed;

-  uint8_t stage_pitch[8];
-  uint8_t stage_steps[8];
-  uint8_t stage_gate[8];
+  int8_t stage_pitch[8];
+  int8_t stage_steps[8];
+  int8_t stage_gate[8];
   uint8_t stage_slew;
-  uint8_t stage_count;
+  int8_t stage_count;
   uint8_t diradd_mode;
   uint8_t slew_rate;
   uint8_t gate_time;
-  uint8_t clock_bpm;
+  int8_t clock_bpm;
 };

 DU_SEQ_Function * function;


Removed old functions

Removed old functions

--- src/code.ino
+++ src/code.ino
@@ -16,7 +16,7 @@
 static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
 const char website[] PROGMEM = "adb.dokku.d.h";

-static void my_callback (byte status, word off, word len)
+static void my_callback(byte status, word off, word len)
 {
     Serial.println(">>>");
     Ethernet::buffer[off+300] = 0;


changed orbit tsopStrength tunings

changed orbit tsopStrength tunings

--- master/master.ino
+++ master/master.ino
@@ -833,13 +833,13 @@

 		orbit_k = 1;

-		if (tsopStrength > 156){
+		if (tsopStrength > 148){
 			orbit_k = 1.0;
 		}
-		else if (tsopStrength > 150){
+		else if (tsopStrength > 140){
 			orbit_k = 0.9;
 		}
-		else if (tsopStrength > 140){
+		else if (tsopStrength > 135){
 			orbit_k = 0.8;
 		}
 		else if (tsopStrength > 130){


Frame counter inside of debug draw

Frame counter inside of debug draw

Next thing to do is work on the jumping mechanic

--- src/draw.ino
+++ src/draw.ino
@@ -5,13 +5,13 @@

 //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 void draw( Level& level ) {
-    const bool debug = false;
+    const bool debug = true;
     const short floorStart = 42;
     const short floorWidth = 4;
-    g_gb.display.print(F("Frame:"));
-    g_gb.display.print(level.frameProgress);
     // Level Debug
     if ( debug ) {
+        g_gb.display.print(F("Frame:"));
+        g_gb.display.print(level.frameProgress);
         for ( short i = 0; i < level.numObjects; ++i ) {
             LevelObject& obj = level.levelObjects[ i ];
             {


v2.0 Improve main sleep processing

v2.0 Improve main sleep processing

--- WeatherDisplay.ino
+++ WeatherDisplay.ino
@@ -5,9 +5,9 @@
 //     Based on the following:                                       //
 // http://educ8s.tv/art-deco-weather-forecast-display/               //
 //                                                                   //
-//     See the following for a description on JSON                   //
-//     decoding:                                                     //
+//     See the following for a description on JSON decoding:         //                                                    //
 // https://www.arduino.cc/en/Tutorial.WiFi101WeatherAudioNotifier    //
+//                                                                   //
 ///////////////////////////////////////////////////////////////////////

 #include "WeatherDisplay.h"
@@ -20,18 +20,17 @@
 char servername[] = "api.openweathermap.org"; // remote server we will connect to
 String result;
 boolean night = false;
+Adafruit_ST7735 tft(TFT_CS, TFT_DC, TFT_RST);

 extern unsigned char cloud[];
 extern unsigned char thunder[];
 extern unsigned char wind[];
-// Fill in these four variables within NetworkConnection.c
-// with your ssid, password, APIKey and cityID
+/* Fill in these four variables within NetworkConnection.c
+   with your ssid, password, APIKey and cityID */
 extern const char* ssid; // SSID of local network
 extern const char* password; // Password on network
 extern const char* APIKey; // openweathermap.org API key
 extern const char* cityID; // openweathermap.org city
-
-Adafruit_ST7735 tft(TFT_CS, TFT_DC, TFT_RST);

 void setup() {
 #ifdef DEBUG
@@ -108,7 +107,7 @@
     analogWrite(ALIVE_LED, flasher * ALIVEBRIGHTNESS);
     // Seed random number generator
     randomSeed(counter + flasher);
-    delay(5000);
+    delay(1000);
 #ifdef DEBUG
     Serial.print("counter = ");
     Serial.println(counter);
@@ -210,6 +209,12 @@
   Serial.println(latitude + " Deg");
   Serial.print("Longitude ");
   Serial.println(longitude + " Deg");
+  Serial.print("Sunrise ");
+  Serial.print(riseI);
+  Serial.println("am");
+  Serial.print("Sunset ");
+  Serial.print(setI);
+  Serial.println("pm");
   Serial.print("Time last updated ");
 #ifdef CONVERTTIMETOLOCAL
   Serial.println(timeS);
@@ -217,8 +222,7 @@
   Serial.print(timeS);
   Serial.println(" UTC");
 #endif
-
-#endif
+#endif // #ifdef DEBUG

   clearScreen();

@@ -416,7 +420,7 @@
   int TimeErrorOffset = -3;
   if (((time > 18) && (time < 21)) ||
       (time == 12) ||
-      (time == 0) ||
+//      (time == 0) ||
       (time == 15)) {
     time += (TimeErrorOffset + 2);
   }


Optimized the FastLED code a bit.

Optimized the FastLED code a bit.

--- firmware/examples/FastLedComparison/FastLedComparison.ino
+++ firmware/examples/FastLedComparison/FastLedComparison.ino
@@ -83,16 +83,12 @@
   void dimAll(byte value)
   {
     for (int i = 0; i < NUM_LEDS; i++) {
-      CRGB c = leds[i];
-      c.nscale8(value);
-      leds[i] = c;
+      leds[i].nscale8(value);
     }
   }
 #endif

-
 #define BRIGHTNESS 255
-

 void setup() {
 #if (SMARTMATRIX_ENABLED == 1)
@@ -127,7 +123,7 @@
 #if (SMARTMATRIX_ENABLED == 1)
       buffer[XY(x, y)] = CRGB(CHSV(x + hue, 255, 255));
 #else
-      leds[XY(x, y)] = CRGB(CHSV(x + hue, 255, 255));
+      leds[XY(x, y)] = CHSV(x + hue, 255, 255);
 #endif
     }


prefer const to define

prefer const to define

--- examples/skynetim_echo_cc3000/skynetim_echo_cc3000.ino
+++ examples/skynetim_echo_cc3000/skynetim_echo_cc3000.ino
@@ -57,8 +57,8 @@
                                    // received before closing the connection.  If you know the server
                                    // you're accessing is quick to respond, you can reduce this value.

-#define HOSTNAME      "skynet.im"
-#define PORT          80
+const char HOSTNAME[] = "skynet.im";
+const uint8_t PORT = 80;

 Adafruit_CC3000_Client client = Adafruit_CC3000_Client();


Modified formatting

Modified formatting

--- module/module.ino
+++ module/module.ino
@@ -123,7 +123,7 @@
   		// Push to ThingSpeak
 		digitalWrite(ledPin, LOW);
 		getStringFromMem(sendingLog);
-		Serial.print(elapsedTime); Serial.print(" ");
+		Serial.println(elapsedTime);
 		WIFI.listen();
 		lastSend = updateThingSpeak(userID, elapsedTime, existingTime, lastSend);
 		// --------------------------------------------------------------------


Update arduino_fibers.ino

Update arduino_fibers.ino

Fixed typos in the example fibers.restart() method calls. Use the index of the fiber to specify which fiber to restart.

--- arduino_fibers.ino
+++ arduino_fibers.ino
@@ -104,9 +104,9 @@

   delay(3000);

-  fibers.restart(0,foo,0);      // Restart foo(0) at next yield()
-  fibers.restart(1,bar,0);      // Restart bar(0) at next yield()
-  fibers.restart(2,zoo,0);      // etc..
+  fibers.restart(ffoo,foo,0);      // Restart foo(0) at next yield()
+  fibers.restart(fbar,bar,0);      // Restart bar(0) at next yield()
+  fibers.restart(fzoo,zoo,0);      // etc..
 }

 // End arduino_fibers.ino


Expand the receive window if any packet is lost, not if we're synced

--- examples/RF12/syncRecv/syncRecv.ino
+++ examples/RF12/syncRecv/syncRecv.ino
@@ -112,7 +112,7 @@

   // make a prediction for when the next packet should arrive
   uint32_t predict = lastRecv + (lost + 1) * estimate;
-  word sleep = predict - now - (lost ? 0 : window);
+  word sleep = predict - now - (lost ? window : 0);
   radioSleep(sleep);

   // listen to the radio until one window past predicted time


reading IR pins

reading IR pins

--- direct-servo-turns/direct-servo-turns.ino
+++ direct-servo-turns/direct-servo-turns.ino
@@ -1,29 +1,34 @@
 #include <Servo.h>
+
+const int DETECTOR_LEFT = 3;
+const int DETECTOR_RIGHT = 5;

 Servo myservo;  // create servo object to control a servo
                 // a maximum of eight servo objects can be created

 void setup()
 {
-  Serial.begin(9600);
+  Serial.begin(115200);  // 57600 * 2
+
+  // initialize detector input pins
+  pinMode(DETECTOR_LEFT, INPUT);
+  pinMode(DETECTOR_RIGHT, INPUT);
+
   myservo.attach(9);  // attaches the servo on pin 9 to the servo object
 }

 void loop()
 {
   rndTurn(70, 90);
-  rndDelay();
-
   rndTurn(120, 140);
-  rndDelay();
 }

 void rndDelay()
 {
-  int ms = random(3000, 7000);
+  int ms = random(4000, 7000);

-  Serial.print("delay:\t\t");
-  Serial.println(ms);
+  Serial.print("delay:");
+  Serial.print(ms);

   delay(ms);
 }
@@ -32,9 +37,30 @@
 {
   int angle = random(low, high);

-  Serial.print("angle:\t");
-  Serial.println(angle);
+  Serial.print("angle:");
+  Serial.print(angle);
+  Serial.print("\t");

   myservo.write(angle);
+
+  rndDelay();
+  Serial.print("\t");
+
+  readDetector(DETECTOR_LEFT, "left");
+  Serial.print("\t");
+
+  readDetector(DETECTOR_RIGHT, "right");
+  Serial.println("");
 }

+int readDetector(int detectorPin, char* label)
+{
+  int detectorValue = digitalRead(detectorPin);
+
+  Serial.print(label);
+  Serial.print(":");
+  Serial.print(detectorValue);
+
+  return detectorValue;
+}
+


MQTT433gateway.ino: correct spaces around operators

--- MQTT433gateway.ino
+++ MQTT433gateway.ino
@@ -52,7 +52,7 @@
 ESPiLight rf(TRANSMITTER_PIN);
 SHAauth otaAuth(myOTA_PASSWD);

-const String mainTopic = String("rfESP_")+String(ESP.getChipId(), HEX);;
+const String mainTopic = String("rfESP_") + String(ESP.getChipId(), HEX);
 const String globalTopic = "rf434";
 boolean logMode = false;
 boolean rawMode = false;
@@ -103,10 +103,10 @@
   Serial.print(" with protocol ");
   Serial.println(protocol);

-  if(protocol == "RAW") {
+  if (protocol == "RAW") {
     int rawpulses[MAXPULSESTREAMLENGTH];
     int rawlen = rf.stringToPulseTrain(message, rawpulses, MAXPULSESTREAMLENGTH);
-    if(rawlen > 0) {
+    if (rawlen > 0) {
       rf.sendPulseTrain(rawpulses, rawlen);
     }
   } else {
@@ -124,19 +124,19 @@
   Serial.println();

   String topic = topic_;
-  char payload[length+1];
+  char payload[length + 1];
   strncpy(payload, (char *)payload_, length);
-  payload[length]='\0';
+  payload[length] = '\0';

   String sendTopic = globalTopic + "/send/";
-  if(topic.startsWith(sendTopic)) {
+  if (topic.startsWith(sendTopic)) {
     transmitt(topic.substring(sendTopic.length()), payload);
   }
   sendTopic = mainTopic + "/send/";
-  if(topic.startsWith(sendTopic)) {
+  if (topic.startsWith(sendTopic)) {
     transmitt(topic.substring(sendTopic.length()), payload);
   }
-  if(topic == (mainTopic + "/set/raw")) {
+  if (topic == (mainTopic + "/set/raw")) {
     Serial.println("Change raw mode.");
     if (payload[0] == '1') {
       rawMode = true;
@@ -145,7 +145,7 @@
       rawMode = false;
     }
   }
-  if(topic == (mainTopic + "/set/log")) {
+  if (topic == (mainTopic + "/set/log")) {
     Serial.println("Change log mode.");
     if (payload[0] == '1') {
       logMode = true;
@@ -154,18 +154,18 @@
       logMode = false;
     }
   }
-  if(topic == (mainTopic + "/ota/url")) {
+  if (topic == (mainTopic + "/ota/url")) {
     otaURL = String(payload);
     mqtt.publish((mainTopic+ "/ota/nonce").c_str(), otaAuth.nonce().c_str());
   }
-  if((topic == (mainTopic + "/ota/passwd")) && (otaURL.length() > 7)) {
-    if(otaAuth.verify(payload)) {
+  if ((topic == (mainTopic + "/ota/passwd")) && (otaURL.length() > 7)) {
+    if (otaAuth.verify(payload)) {
       beatLED.on();
       Serial.print("Start OTA update from: ");
       Serial.println(otaURL);
       rf.disableReceiver();
       t_httpUpdate_return ret = ESPhttpUpdate.update(otaURL);
-      switch(ret) {
+      switch (ret) {
         case HTTP_UPDATE_FAILED:
           Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
           break;
@@ -176,8 +176,8 @@
           Serial.println("HTTP_UPDATE_OK"); // may not called ESPhttpUpdate reboot the ESP?
           ESP.restart();
           break;
-        }
-        rf.enableReceiver();
+      }
+      rf.enableReceiver();
     } else {
       Serial.println("OTA authentication failed!");
     }
@@ -197,23 +197,23 @@
   Serial.print(repeats);
   Serial.println(")");

-  if(status==VALID) {
+  if (status == VALID) {
     String topic = globalTopic + String("/recv/") + protocol;
     if (deviceID != NULL) {
       topic += String('/') + deviceID;
     }
     mqtt.publish(topic.c_str(), message.c_str(), true);
   }
-  if(logMode) {
+  if (logMode) {
     String topic = mainTopic + String("/log/") + String(status) + String('/') + protocol;
     mqtt.publish(topic.c_str(), message.c_str());
   }
 }

 void rfRawCallback(const int* pulses, int length) {
-  if(rawMode) {
+  if (rawMode) {
     String data = rf.pulseTrainToString(pulses, length);
-    if(data.length()>0) {
+    if (data.length() > 0) {
       Serial.print("RAW RF signal (");
       Serial.print(length);
       Serial.print("): ");


Tweek to frequency of connection checks.

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

--- zimodem/zimodem.ino
+++ zimodem/zimodem.ino
@@ -201,21 +201,22 @@

 static bool connectWifi(const char* ssid, const char* password)
 {
-  int WiFiCounter = 0;
   if(WiFi.status() == WL_CONNECTED)
     WiFi.disconnect();
   WiFi.mode(WIFI_STA);
   WiFi.begin(ssid, password);
-  boolean amConnected = false;
-  delay(1000);
+  boolean amConnected = (WiFi.status() == WL_CONNECTED) && (strcmp(WiFi.localIP().toString().c_str(), "0.0.0.0")!=0);
+  int WiFiCounter = 0;
   while ((!amConnected) && (WiFiCounter < 30))
   {
     WiFiCounter++;
+    if(!amConnected)
+      delay(500);
     amConnected = (WiFi.status() == WL_CONNECTED) && (strcmp(WiFi.localIP().toString().c_str(), "0.0.0.0")!=0);
-    if(!amConnected)
-      delay(1000);
   }
   wifiConnected = amConnected;
+  if(!amConnected)
+    WiFi.disconnect();
   return wifiConnected;
 }


Added light wake for history.

Added light wake for history.

--- hue-force.ino
+++ hue-force.ino
@@ -5,28 +5,108 @@
 #include <Wire.h>
 #include <Adafruit_NeoPixel.h>

-#include <QueueArray.h>
+//#include <QueueArray.h>
 #include <math.h>

 #define LIGHT_PIN 15
 #define LIGHT_COUNT 32
 #define G_FORCE 8
-#define DELAY_VALUE 500  // Delay for a period of time (in milliseconds).
-
-typedef struct {
+#define DELAY_VALUE 10  // Delay for a period of time (in milliseconds).
+#define DEBUG false
+
+// ----------- ACCEL AXIS STRUCT ------------
+typedef struct ANode{
   int x;
   int y;
   int z;
+  struct ANode * n;
 } Acceleration;
+
+// ----------- QUEUE ------------
+class AxisQueue
+{
+private:
+  Acceleration * front;                       // pointer to front of Queue
+  Acceleration * rear;                        // pointer to rear of Queue
+                        // current number of items in Queue
+
+
+public:
+  AxisQueue(int amount);                 // create queue with a qs limit
+  ~AxisQueue();
+  void addAxis(Acceleration * axis);
+  int * getAverage(void);
+  void printQueue(void);
+};
+
+AxisQueue::AxisQueue(int amount){
+    Acceleration * tmp;
+
+    front = NULL;
+    rear = NULL;
+
+    for(int x = 0; x < amount; x++){
+      tmp = new Acceleration;
+      *tmp = {1,1,1,NULL};
+      tmp->n = front;
+      front = tmp;
+      if (x == 0) rear = front;
+    }
+
+}
+
+void AxisQueue::addAxis(Acceleration * axis){
+    rear -> n = front;
+    rear = front;
+    front = front -> n;
+    rear -> n = NULL;
+
+    rear->x = axis->x;
+    rear->y = axis->y;
+    rear->z = axis->z;
+}
+
+int * AxisQueue::getAverage(){
+    Acceleration * iter = front;
+    int * avg = new (int[3]){0,0,0};
+    int counter = 0;
+
+    while (iter != NULL){
+          avg[0] += iter->x;
+          avg[1] += iter->y;
+          avg[2] += iter->z;
+          iter = iter->n;
+          counter++;
+    }
+    avg[0] = int(max(min(avg[0]/counter, 255), 0));
+    avg[1] = int(max(min(avg[1]/counter, 255), 0));
+    avg[2] = int(max(min(avg[2]/counter, 255), 0));
+    return avg;
+}
+
+void AxisQueue::printQueue(){
+    Acceleration * iter = front;
+    Serial.println("Queue Status!");
+    while (iter != NULL){
+        Serial.print("X: ");Serial.print(iter->x);Serial.print(" ");
+        Serial.print("Y: ");Serial.print(iter->y);Serial.print(" ");
+        Serial.print("Z: ");Serial.println(iter->z);
+        iter = iter->n;
+    }
+    Serial.println("");
+}
+
+
+// --------------- HueForce ----------------

 class HueForce {

  public:
   Acceleration*
     axis;
-
-  QueueArray <Acceleration*>
-    lightWake;
+
+  //QueueArray <Acceleration*>
+  AxisQueue * lightWake;

   // Constructor: number of LEDs, pin number, LED type
   HueForce(int force, int pixelCount, int lightPin);
@@ -50,7 +130,6 @@
   Adafruit_ADXL345_Unified accel;

   void setLimit(int force);
-  void initLightWake(int history);

   void mergeResults(void);
   void setAxis(void);
@@ -60,13 +139,13 @@

 };

-HueForce::HueForce(int force, int pixelCount, int pin) : delta(1), totalBrightness(0){
-    modifier = int(255.0 / force);
+HueForce::HueForce(int force, int pixelCount, int pin) : delta(2), totalBrightness(0){
+    modifier = float(255.0 / force);
     lighCount = pixelCount;
     lightPin = pin;
-
+    lightWake = new AxisQueue(5);
+
     axis = new Acceleration;
-    Serial.print("RUN AXIS1: "); Serial.println((int)axis);

     accel = Adafruit_ADXL345_Unified(12345);
     if(!accel.begin()){
@@ -80,8 +159,6 @@
     pixels.show();

     setLimit(force);
-    initLightWake(5);
-
 }

 HueForce::~HueForce(){
@@ -101,28 +178,15 @@
     }
 }

-void HueForce::initLightWake(int history){
-    Acceleration *initAxis;
-
-    for (int i = 0; i < history; ++i){
-        initAxis = new Acceleration;
-        initAxis->x = 1;
-        initAxis->y = 1;
-        initAxis->z = 1;
-
-        lightWake.push(initAxis);
-    }
-}
-
 void HueForce::setAxis(){
     sensors_event_t event;
     accel.getEvent(&event);

-    axis->x = int(abs(event.acceleration.x / SENSORS_GRAVITY_STANDARD));
-    axis->y = int(abs(event.acceleration.y / SENSORS_GRAVITY_STANDARD));
-    axis->z = int(abs(event.acceleration.z / SENSORS_GRAVITY_STANDARD));
+    axis->x = int(abs(event.acceleration.x * modifier / SENSORS_GRAVITY_STANDARD));
+    axis->y = int(abs(event.acceleration.y * modifier / SENSORS_GRAVITY_STANDARD));
+    axis->z = int(abs(event.acceleration.z * modifier / SENSORS_GRAVITY_STANDARD));

-    //mergeResults();
+    mergeResults();
 }

 void HueForce::mergeResults(){
@@ -130,47 +194,41 @@
     int x=0, y=0, z=0;
     int queueSize;

-    lightWake.push(axis);
-    queueSize = lightWake.count();
-
-    for (int i = 0; i < queueSize; i++){
-        iter = lightWake.pop();
-        x += iter->x;
-        y += iter->y;
-        z += iter->z;
-        lightWake.push(iter);
-    }
-
-    axis = lightWake.pop();
-
-    axis->x = int(max(min(x/queueSize, 255), 0));
-    axis->y = int(max(min(y/queueSize, 255), 0));
-    axis->z = int(max(min(z/queueSize, 255), 0));
+    lightWake->addAxis(axis);
+    int * average = lightWake->getAverage();
+
+    axis->x = average[0];
+    axis->y = average[1];
+    axis->z = average[2];
+    delete[] average;
 }

 void HueForce::drawBrightness(float bright){
-        bright = abs(float(pow(float(bright),1.5)/16));
-        bright = max(min(bright, 255), 15);
-
-        if (totalBrightness > 250)
-            delta = delta*0.05 ;
-        else if (totalBrightness > 240)
-            delta = delta;
-
-        if (bright < totalBrightness)
-          totalBrightness -= delta;
-        else
-          totalBrightness = bright ;
-
-        pixels.setBrightness(totalBrightness);
+      float newDelta;
+      bright = abs(float(pow(float(bright),1.5)/16));
+      bright = (bright * 1.1) - 25.5;
+      bright = max(min(bright, 255), 10);
+
+
+      if (totalBrightness > 250)
+          newDelta = delta * 0.05;
+      else
+          newDelta = delta;
+
+      if (bright < totalBrightness)
+        totalBrightness -= newDelta;
+      else
+        totalBrightness = bright ;
+
+      pixels.setBrightness(totalBrightness);
 }

 void HueForce::drawForce() {
     int red, blue, green;

-    red = abs(int(axis->x * modifier));
-    green = abs(int(axis->y * modifier));
-    blue = abs(int(axis->z * modifier));
+    red = abs(int(axis->x));
+    green = abs(int(axis->y));
+    blue = abs(int(axis->z));

     for(int i = 0; i < lighCount; i++){
         pixels.setPixelColor(i, pixels.Color(red, green, blue));
@@ -198,15 +256,16 @@

 void setup() {
   Serial.begin(9600);
-  while (!Serial) ;
+  if (DEBUG)
+      while (!Serial) ;
   hueForce = new HueForce(G_FORCE, LIGHT_COUNT, LIGHT_PIN);
 }

 void loop() {
-  hueForce->start();
-  hueForce->displayStatus(hueForce->axis);
-  //delay(DELAY_VALUE);
-  delay(5000);
-}
-
+    hueForce->start();
+    if (DEBUG)
+        hueForce->displayStatus(hueForce->axis);
+    delay(DELAY_VALUE);
+}
+


change min/max

change min/max

--- Controller/Tiny85-Standalone-22H/Tiny85-Standalone-22H.ino
+++ Controller/Tiny85-Standalone-22H/Tiny85-Standalone-22H.ino
@@ -14,8 +14,8 @@
 const byte LED_SPEED = 0;

 // convert max % to max pwm
-const byte MIN_PWM = 20;
-const byte MAX_PWM = 170;
+const byte MIN_PWM = 10;
+const byte MAX_PWM = 70;

 const byte SAMPLE_COUNT = 10;

@@ -54,15 +54,16 @@
   }
   in = in / SAMPLE_COUNT;
   // convert to a pwm value
-  out = map(in, 0, 1023, MIN_PWM - 5, MAX_PWM);
+  out = map(in, 0, 1023, MIN_PWM - 1, MAX_PWM);

   // reverse out -- pot hooked up backwards
   //out = ( 255 - out );

-  // turn on/off motor if above/below min volume %
+  // turn on/off motor if above/below min
   if ( out <= MIN_PWM )
   {
     digitalWrite(MOTOR_START, LOW);
+
   }
   else
   {
@@ -71,5 +72,5 @@
     OCR0B = out;
   }
   // PB0 (LED)
-  OCR0A = out - MIN_PWM;
+  OCR0A = out;
 }


added comments

added comments

--- GasSensor.ino
+++ GasSensor.ino
@@ -1,9 +1,15 @@
+// A program to send data to Raspberry PI using serial
 void setup() {
-  Serial.begin(9600);
+  Serial.begin(9600); // Start the serial monitor
 }
+
+//Loop
 void loop() {
+  // Assigning a variable that contains the data from the gas sensor
   int sersorValue;
+  // Reads the data through analog pin
   sersorValue = analogRead(A0);
+  // Checks the value if its higher than a certain level and sends them to the RPI
   if(sersorValue >= 150)
   {
     Serial.print('1');


Changed svg scales and positions, removed the hand drawing and made the LED blink when the project is waiting for input


Update MCU code for requirement doc specifications

--- src/microController/microController.ino
+++ src/microController/microController.ino
@@ -59,8 +59,7 @@
 int yDir; //Direction Y should move
 int rDir; //Direction R should move

-bool userControl = false; //Enable or disable user buttons
-int inputError = 0; //4 bit binary error check
+bool userControl = false; //Enable or disable user turn

 // Setup  /////////////////////////////////////////////////////////////////////////////////

@@ -110,19 +109,20 @@
 void loop()
 {

-  WaitForPCInstruction();
-  if(inputError == 0) //Only take action if all inputs are valid
+  PoseForPicture();
+  if(userControl == false) //Only take action if not user turn
+  {
+    RequestPCInstruction();
+  }
+  if(userControl == false)
   {
     MoveXYR();
-    TakeShot();
-    AllowUserTurn();
-    PoseForPicture();
-    RequestPCInstruction();
-  }
-  else
-  {
-    RequestPCInstruction();
-  }
+  }
+  if(userControl == false)
+  {
+    TakeShot();
+  }
+  AllowUserTurn();

 }

@@ -139,24 +139,30 @@
   currentR = UPPERBOUND_R / 2;
   MoveXYR();
   AllowUserTurn();
-  PoseForPicture();
-  RequestPCInstruction();
-
-}
-
-void WaitForPCInstruction() //Loop during PC operation
+
+}
+
+void RequestPCInstruction() //Loop during PC operation
 {

   char readline[32];
   char aChar;
   int val;
-  int count = 0;
+  int count = 1500;

   memset(&readline[0], 0, sizeof(readline));

   do {
-    delay(10);
+    count++;
+    if(count > 1500) //Send request every 15s
+    {
+      Serial.println("55");
+      count = 0;
+    }
+    delay(10);
   } while(Serial.available() <= 0); //Will loop forever until something entered into Serial Monitor
+
+  count = 0;

   do {
     aChar = Serial.read();
@@ -164,21 +170,31 @@
     count++;
     delay(10);
   } while(count != sizeof(readline) && Serial.available() > 0);
-
+
   val = atoi(strtok(readline, DELIMITER));
-  if (val >= 0 && val < UPPERBOUND_X) requestedX = val;
-  else inputError += 1; //0001 -> bad x
-  val = atoi(strtok(NULL, DELIMITER));
-  if (val >= 0 && val < UPPERBOUND_Y) requestedY = val;
-  else inputError += 2; //0010 -> bad y
-  val = atoi(strtok(NULL, DELIMITER));
-  if (val >= 0 && val < UPPERBOUND_R) requestedR = val;
-  else inputError += 4; //0100 -> bad r
-  val = atoi(strtok(NULL, ENDCHAR));
-  if (val >= 0 && val < UPPERBOUND_E) requestedE = val;
-  else inputError += 8; //1000 -> bad e
+  if (val == 170)
+  {
+    val = atoi(strtok(NULL, DELIMITER));
+    if (val < 0) requestedX = 0;
+    else if (val >= UPPERBOUND_X) rewuestedX = UPPERBOUND_X - 1;
+    else requestedX = val;
+    val = atoi(strtok(NULL, DELIMITER));
+    if (val < 0) requestedY = 0;
+    else if (val >= UPPERBOUND_Y) rewuestedY = UPPERBOUND_Y - 1;
+    else requestedY = val;
+    val = atoi(strtok(NULL, DELIMITER));
+    if (val < 0) requestedR = 0;
+    else if (val >= UPPERBOUND_R) requestedR = UPPERBOUND_R - 1;
+    else requestedR = val;
+    val = atoi(strtok(NULL, ENDCHAR));
+    if (val < 0) requestedE = 0;
+    else if (val >= UPPERBOUND_E) rewuestedE = UPPERBOUND_E - 1;
+    else requestedX = val;
+  }

   memset(&readline[0], 0, sizeof(readline));
+
+  Serial.println("200");

 }

@@ -322,34 +338,27 @@

 }

-void RequestPCInstruction()
-{
-
-  Serial.println(inputError); //Inform PC if any inputs are invlaid
-  inputError = 0;
-
-}
-
 void UserButton1() //Tell machine to move out of the way
 {

   if (userControl)
   {
-    if(requestedX != 0) requestedX = 0;
-    else requestedX = UPPERBOUND_X - 1;
-  }
-
-}
-
-void UserButton2() //Tell machine to take another turn
-{
-
-  if (userControl)
-  {
-    requestedX = currentX;
-    userControl = false;
-  }
-
+    if(requestedX == currentX && requestedX != 0) requestedX = 0; //Move to 0
+    else if(requestedX == 0) requestedX =  UPPERBOUND_X - 1; //Move to upperboundX - 1
+    else requestedX = currentX; //Stop moving
+  }
+
+}
+
+void UserButton2() //Give/relinquish user control
+{
+
+  userControl = !userControl;
+  requestedX = currentX;
+  requestedY = currentY;
+  requestedR = currentR;
+  requestedE = currentE;
+
 }

 ///////////////////////////////////////////////////////////////////////////////////////////


Dropped freqcount

Dropped freqcount

--- 2018-FirefighterL1/2018-FirefighterL1.ino
+++ 2018-FirefighterL1/2018-FirefighterL1.ino
@@ -280,14 +280,14 @@
   resetGyro();

   Serial.println("Listening for microphone");
-  FreqCount.begin(1000); // Begin measuring sound
+  FreqCount.begin(200); // Begin measuring sound
   checkMicrophone();  //robot stays in setup until frequency is heard
 }

 void loop() {
-
-  startUp();
-  levelOneNav();
-  getRotation();
+
+  //startUp();
+  //levelOneNav();
+  //getRotation();
   delay(100);
 }


now commands are non-blocking

now commands are non-blocking

--- jenny5-firmware/jenny5-firmware.ino
+++ jenny5-firmware/jenny5-firmware.ino
@@ -5,20 +5,24 @@
 #include "motors_control.h"
 #include "button_controller.h"
 #include "jenny5_types.h"
+#include "infrared_sensors_controller.h"

 byte potentiometers_pins[4] = {0, 1, 2, 3};
 t_limit_pair potentiometer_limits[4] = {{500, 1000}, {500, 1023}, {200, 600}, {300, 600}};

 byte ultrasonic_trig_pins[2] = {48, 50};
 byte ultrasonic_echo_pins[2] = {49, 51};
+
+byte infrared_pins[2] = {52, 53};

 t_motors_control motors_control(4);
 t_potentiometers_controller potentiometers_control (4, potentiometers_pins, potentiometer_limits);
 t_ultrasonic_sensors_controller ultrasonic_sensors_controller (2, ultrasonic_trig_pins, ultrasonic_echo_pins);
+t_infrared_sensors_controller infrared_sensors_control(2, infrared_pins);

 char is_command_running;

-char firmware_version[] = "2015.12.20.0";// year.month.day.built number
+char firmware_version[] = "2015.12.25.1";// year.month.day.build number

 char current_buffer[65];

@@ -54,9 +58,6 @@
   Serial.println();

   current_buffer[0] = 0;
-  is_command_running = 0;
-
-  //motors_control.add_sensor(0, senTypePotentiometer, 0); // THIS IS ONLY FOR TEST PURPOSE
 }

 //--------------------------------------------------------------------------------------------
@@ -69,6 +70,7 @@
         int motor_index, num_steps;
         sscanf(tmp_str + i + 1, "%d%d", &motor_index, &num_steps);
         motors_control.move_motor(motor_index, num_steps);
+        motors_control.set_motor_running(motor_index, 1);
         is_command_running = 1;
         i += 3;
       }
@@ -114,21 +116,27 @@
           if (tmp_str[i] == 'U' || tmp_str[i] == 'u'){// ultrasonic
             int sensor_index;
             sscanf(tmp_str + i + 1, "%d", &sensor_index);
+            Serial.write('U');
             Serial.print(ultrasonic_sensors_controller.getDistanceForSensor(sensor_index));
+            Serial.write('#');
             i++;
           }
         else
           if (tmp_str[i] == 'P' || tmp_str[i] == 'p'){// potentiometer
             int sensor_index;
             sscanf(tmp_str + i + 1, "%d", &sensor_index);
+            Serial.write('P');
             Serial.print(potentiometers_control.getPotentiometerValue(sensor_index));
+            Serial.write('#');
             i++;
           }
         else
           if (tmp_str[i] == 'I' || tmp_str[i] == 'i'){// infrared
             int sensor_index;
             sscanf(tmp_str + i + 1, "%d", &sensor_index);
-            //Serial.print(infrareds_control.get_infrared_value(sensor_index));
+            Serial.write('I');
+            Serial.print(infrared_sensors_control.get_distance(sensor_index));
+            Serial.write('#');
             i++;
           }
         else
@@ -158,19 +166,18 @@
       i++;
   }
 }
-
 //--------------------------------------------------------------------------------------------
 //Main loop
 void loop() {

-  if (!is_command_running && (Serial.available() || current_buffer[0])) {
+  if (Serial.available() || current_buffer[0]) {
     int num_read = 0;
-    char arduino_buffer[65];
-
-    num_read = Serial.readBytes(arduino_buffer, 64); //Read up to 64 bytes
-    arduino_buffer[num_read] = 0;// terminate the string
-    if (arduino_buffer[0] || current_buffer[0]){
-      strcat(current_buffer, arduino_buffer);
+    char serial_buffer[65];
+
+    num_read = Serial.readBytes(serial_buffer, 64); //Read up to 64 bytes
+    serial_buffer[num_read] = 0;// terminate the string
+    if (serial_buffer[0] || current_buffer[0]){
+      strcat(current_buffer, serial_buffer);

       #ifdef DEBUG
         Serial.write("initial buffer is=");
@@ -235,9 +242,7 @@
         if (POTENTIOMETER == type)
         {
             if (0 == potentiometers_control.isWithinLimits(sensor_index))
-            {
               limit_reached = true;
-            }
         }
         else if (ULTRASOUND == type)
         {
@@ -245,28 +250,29 @@
         }
       }

-      //Serial.write("limit_reached:");
-      //Serial.write(limit_reached);
-      //Serial.println();
-
-      if (false == limit_reached)
+      if (!limit_reached)
       {
         motors_control.steppers[m]->run();
         is_one_motor_running = true;
       }
-      else
-      {
+      else{
         motors_control.steppers[m]->setCurrentPosition(0);
-      }
-
+        motors_control.set_motor_running(m, 0);
+        Serial.write("M");
+        Serial.print(m);
+        Serial.write('#');
+      }
     }
     else{
       motors_control.steppers[m]->setCurrentPosition(0);
+// the motor has just finished the move, so we output that event
+      if (motors_control.is_motor_running(m)){
+        motors_control.set_motor_running(m, 0);
+        Serial.write("M");
+        Serial.print(m);
+        Serial.write('#');
+      }
     }
   }
-
-
-  if (!is_one_motor_running)
-    is_command_running = 0;
 }


Tower is rid of EMI noise with the addition of a TVS diode pair and a capacitor on the supply.

--- src/Tower/Tower.ino
+++ src/Tower/Tower.ino
@@ -32,10 +32,6 @@
 Metro flameOnTime(100UL);
 // but only fire this often.
 Metro flameCoolDownTime(1000UL);
-// there's quite a bit of EMI from the solenoid firing, so we add a cooldown on reading sensors
-#define EMI_COOLDOWN 1000UL
-Metro sensorEmiCooldown(EMI_COOLDOWN);
-boolean emiInterference = true;

 // when we're out of the network, update the lights on this interval (approx)
 #define SOLO_TEST_PATTERN_UPDATE 3000UL // ms
@@ -57,7 +53,7 @@
 // remote control
 #define RESET_PIN A0
 #define GAME_ENABLE_PIN A1
-#define DEBOUNCE_TIME 50UL // need a long debounce b/c electrical noise from solenoid.
+#define DEBOUNCE_TIME 100UL // need a long debounce b/c electrical noise from solenoid.
 Bounce systemReset = Bounce(RESET_PIN, DEBOUNCE_TIME);
 Bounce gameEnable = Bounce(GAME_ENABLE_PIN, DEBOUNCE_TIME);
 boolean gameEnableFlag = true;
@@ -111,26 +107,19 @@
   if ( flameOnTime.check() ) { // time to turn the flame off
     flameOff();
   }
-
-  // check to see if we can read sensors again after EMI burst.
-  if ( sensorEmiCooldown.check() && emiInterference == true ) {
-    Serial << F("EMI cooldown ended.") << endl;
-    emiInterference = false;
-  }
-  // put all sensor code inside of this cooldown check.
-  if ( !emiInterference ) {
-    // check system enable state
-    if ( systemReset.update() ) { // reset state change
-      Serial << F("Reset state change.  State: ");
-      systemResetFlag = systemReseted();
-      Serial << systemResetFlag << endl;
-    }
-    // check system enable state
-    if ( gameEnable.update() ) { // gameplay enable state change
-      Serial << F("Gameplay state change.  State: ");
-      gameEnableFlag = gameEnabled();
-      Serial << gameEnableFlag << endl;
-    }
+
+  // check system enable state
+  if ( systemReset.update() ) { // reset state change
+    Serial << F("Reset state change.  State: ");
+    systemResetFlag = systemReseted();
+    Serial << systemResetFlag << endl;
+  }
+
+  // check system enable state
+  if ( gameEnable.update() ) { // gameplay enable state change
+    Serial << F("Gameplay state change.  State: ");
+    gameEnableFlag = gameEnabled();
+    Serial << gameEnableFlag << endl;
   }

   // check for comms traffic
@@ -205,11 +194,21 @@
 }

 boolean systemReseted() {
+  // with EMI, be very sure.
+  Metro readTime(DEBOUNCE_TIME);
+  readTime.reset();
+  while( !readTime.check() ) systemReset.update();
+
   // at system power up, relay is open, meaning pin will read HIGH.
   return ( systemReset.read() == LOW );
 }

 boolean gameEnabled() {
+  // with EMI, be very sure.
+  Metro readTime(DEBOUNCE_TIME);
+  readTime.reset();
+  while( !readTime.check() ) gameEnable.update();
+
   // at system power up, relay is open, meaning pin will read HIGH.
   return ( gameEnable.read() == HIGH );
 }
@@ -432,11 +431,6 @@
     // start cooldown counter
     flameCoolDownTime.reset();

-    // when the solenoid closes, there's a lot of EMI that disrupts sensors.  Ignore the sensors for a period of time.
-    sensorEmiCooldown.interval( config.flameCoolDownTime + EMI_COOLDOWN ); // add a little more time.
-    sensorEmiCooldown.reset(); // sensing needs to pause.
-    emiInterference = true;
-
     Serial << F("Flame on! ") << fireLevel << F(" mapped [") << config.minFireTime << F(",") << config.maxFireTime << F("]");
     Serial << F(" -> ") << flameTime << F("ms.  Cooldown: ") << config.flameCoolDownTime << F("ms.") << endl;
   }


No need to time the payload roundtrip

No need to time the payload roundtrip

--- transmitter/TX/TX.ino
+++ transmitter/TX/TX.ino
@@ -150,7 +150,7 @@
   radio.stopListening();

   // Take the time, and send it.  This will block until complete
-  unsigned long time = micros();
+  //unsigned long time = micros();
   if (!radio.write( &tx_payload, sizeof(tx_t))) {
     // Got no ack.
     if (DEBUG) {
@@ -166,12 +166,12 @@
      } else {

        if (radio.available() ){
-          unsigned long tim = micros();
+          //unsigned long tim = micros();
           radio.read( &ack_payload, sizeof(ack_t) );
           ppsCounter++;
           monitor_sendData();
           if (DEBUG) {
-            printf("Got response %d, pps: %d , round-trip: %lu microseconds\n\r", ack_payload.val, pps, tim-time);
+            //printf("Got response %d, pps: %d , round-trip: %lu microseconds\n\r", ack_payload.val, pps, tim-time);
           }

         }


local variable as the payload gets zeroed

--- transmitter/TX/TX.ino
+++ transmitter/TX/TX.ino
@@ -64,6 +64,11 @@
 int ppsLost = 0;
 int ppsLostCounter = 0;

+uint16_t throttle;
+uint16_t yaw;
+uint16_t pitch;
+uint16_t roll;
+
 uint8_t switches = 0; // bit flag

 void resetPayload()
@@ -153,11 +158,11 @@
   static unsigned long debounce_sample_last = 0;

-  tx_payload.throttle = joystickMapValues(analogRead(PIN_THROTTLE), 125, 515, 1000);
-  tx_payload.yaw      = joystickMapValues(analogRead(PIN_YAW), 10, 521, 1000);
-  tx_payload.pitch    = joystickMapValues(analogRead(PIN_PITCH), 0, 511, 1023);
-  tx_payload.roll     = joystickMapValues(analogRead(PIN_ROLL), 0, 511, 1023);
-  tx_payload.switches = switches;
+  throttle = joystickMapValues(analogRead(PIN_THROTTLE), 125, 515, 1000);
+  yaw      = joystickMapValues(analogRead(PIN_YAW), 10, 521, 1000);
+  pitch    = joystickMapValues(analogRead(PIN_PITCH), 0, 511, 1023);
+  roll     = joystickMapValues(analogRead(PIN_ROLL), 0, 511, 1023);
+

   if (DEBUG) {
     //printf("val: %d\n\r ",tx_payload.throttle);
@@ -166,8 +171,11 @@
   // Stop listening so we can talk.
   radio.stopListening();

-  // Take the time, and send it.  This will block until complete
-  //unsigned long time = micros();
+  tx_payload.throttle = throttle;
+  tx_payload.yaw = yaw;
+  tx_payload.pitch = pitch;
+  tx_payload.roll = roll;
+  tx_payload.switches = switches;
   if (!radio.write( &tx_payload, sizeof(tx_t))) {
     // Got no ack.
     if (DEBUG) {
@@ -274,22 +282,22 @@
 }

 void monitor_setLocalData() {
-  static byte i = 5;
+  static uint8_t i = 5;

   comm_t payload;
   payload.key = i;
   switch (i) {
     case NRF24_KEY_THROTTLE:
-      payload.val = tx_payload.throttle;
+      payload.val = throttle;
       break;
     case NRF24_KEY_YAW:
-      payload.val = tx_payload.yaw;
+      payload.val = yaw;
       break;
     case NRF24_KEY_PITCH:
-      payload.val = tx_payload.pitch;
+      payload.val = pitch;
       break;
     case NRF24_KEY_ROLL:
-      payload.val = tx_payload.roll;
+      payload.val = roll;
       break;
   }

@@ -298,5 +306,6 @@
   if (++i > 8) {
     i = 5;
   }
-}
-
+
+}
+


Commit for runNum 217

Commit for runNum 217

--- src/Gortobot_v3c.ino
+++ src/Gortobot_v3c.ino
@@ -15,7 +15,7 @@
 #include "communication/gb_wifi.h"
 #include "power/gb_battery.h"
 #include "navigation/gb_gps.h"
-#include "communication/gb_sentence_builder.h"
+//#include "communication/gb_sentence_builder.h"

 // Pin assignments
 #define GPS_PORT Serial1
@@ -78,7 +78,7 @@
 IridiumSBD isbd(ISBD_PORT, SATELLITE_SLEEP_PIN);
 GbWifi wifi = GbWifi(WIFI_ENABLE_PIN, WIFI_PORT, WIFI_BAUD);
 GbBattery battery = GbBattery(BATTERY_VOLTAGE_PIN, MINIMUM_BATTERY_VOLTAGE, BATTERY_OKAY_VOLTAGE, BATTERY_WAIT_TIME, CHECKING_VOLTAGE);
-GbSentenceBuilder sentence_builder(MESSAGE_VERSION);
+//GbSentenceBuilder sentence_builder(MESSAGE_VERSION);

 void setup() {
         analogReference(EXTERNAL);
@@ -128,7 +128,7 @@
         }

         batteryVoltage = battery.GetVoltage(); // because makeLogSentence isn't classy yet
-        logSentence = sentence_builder.Sentence(runNum, loopCount);
+        //logSentence = sentence_builder.Sentence(runNum, loopCount);
         logSentence = makeLogSentence(fix);

         battery.Okay();


dostosowanie do struktury

dostosowanie do struktury

--- Arduino/temperatura/temperatura.ino
+++ Arduino/temperatura/temperatura.ino
@@ -32,8 +32,8 @@
 void loop() {
   float temp;
   temp=Thermistor(analogRead(ThermistorPIN));       // odczytaj
-  Serial.print("Celsius: ");
+  Serial.print("T,");
   Serial.print(temp,1);                             // temperatura w st.C
-  Serial.println("");
+  Serial.println();
   delay(500);
 }


Update Sketch

Update Sketch

Add Switch on/of test
Add Basic parsing of command

--- SensorBoard.ino
+++ SensorBoard.ino
@@ -5,7 +5,8 @@
 RF24 radio(9,10);

 const uint64_t pipes[2] = { 0xF0F0F0F001LL, 0xF0F0F0F002LL };
-
+const byte shortAddr = 0x02;
+int led = 13;
 void setup(void)
 {
   Serial.begin(57600);
@@ -19,6 +20,12 @@
   radio.openWritingPipe(pipes[0]);

   radio.startListening();
+
+  // Testing switch on/off
+   pinMode(led, OUTPUT);
+
+
+
 }

 void loop(void)
@@ -36,13 +43,28 @@
 	// make the transition to receiver
 	delay(20);
       }
-      runCommand(command[1]);
+      runCommand(command[1],command[2]);
     }

 }
-bool runCommand(byte command){Serial.println(command);}
+bool runCommand(byte command, byte parameter)
+{
+  Serial.println(command);
+  switch (command)
+  {
+    case 0:
+      break;
+    case 1:
+      switchOnLight(parameter);
+      break;
+    case 2:
+      switchOffLight(parameter);
+      break;
+  }
+
+}
 byte readTemp(void){}
 byte readHum(void){}
 byte readLight(void){}
-bool switchOnLight(void){}
-bool switchOffLight(void){}
+bool switchOnLight(byte number){digitalWrite(led, HIGH);}
+bool switchOffLight(byte number){digitalWrite(led, LOW);}