Updated to operate with new I2C PWM Shield

-Changed servoWrite function to use shield library
-Re-added hand angle as input to movements
-Updated variable names to improve consistency

--- AL5D/al5d.ino
+++ AL5D/al5d.ino
@@ -12,7 +12,8 @@
 /************/
 /* INCLUDES */
 /************/
-#include <Servo.h> // Use of the Servo library disables analogWrite() (PWM) functionality on pins 9 and 10
+#include <Wire.h>
+#include <Adafruit_PWMServoDriver.h>

 /*********************************/
 /* General system debugging code */
@@ -38,13 +39,6 @@
 // Wrist Servo =       HS-422
 // Gripper Servo =     HS-422 <-- Unsure if this is correct

-// Servo pins
-#define BAS_PIN  2
-#define SHL_PIN  3
-#define ELB_PIN  4
-#define WRI_PIN  10
-#define GRI_PIN  5
-
 // Analog pins used for accelerometers
 #define BAS_R_PIN 0
 #define BAS_H_PIN 1
@@ -120,10 +114,44 @@
 #define WRI 3
 #define GRI 4

+// Depending on your servo make, the pulse width min and max may vary, you
+// want these to be as small/large as possible without hitting the hard stop
+// for max range. You'll have to tweak them as necessary to match the servos you
+// have!
+#define BAS_MIN_D  0   // this is the 'minimum' angle in base servo range, 0 = -y direction
+#define BAS_MAX_D  180 // this is the 'maximum' angle in base servo range, 180 = +y direction
+#define SHL_MIN_D  0   // 0 = horizontal in +x direction
+#define SHL_MAX_D  180 // 180 = horizontal in -x direction
+#define ELB_MIN_D  0   // 0 = elbow closed
+#define ELB_MAX_D  180 // 180 = elbow open, ulna parallel to humerus
+#define WRI_MIN_D  0   // 0 = wrist closed
+#define WRI_MAX_D  180 // 180 = wrist open, hand parallel to ulna
+#define GRI_MIN_D  100 // 100 = gripper fully open
+#define GRI_MAX_D  180 // 180 = gripper fully closed
+
+#define BAS_MIN    146 // this is the pulse length count (out of 4096) that corresponds to BAS_MIN_D
+#define BAS_MAX    590 // this is the pulse length count (out of 4096) that corresponds to BAS_MAX_D
+#define SHL_MIN    186 // this is the pulse length count (out of 4096) that corresponds to SHL_MIN_D
+#define SHL_MAX    612 // this is the pulse length count (out of 4096) that corresponds to SHL_MAX_D //HS805BB 186-612
+#define ELB_MIN    590 // this is the pulse length count (out of 4096) that corresponds to ELB_MIN_D
+#define ELB_MAX    146 // this is the pulse length count (out of 4096) that corresponds to ELB_MAX_D
+#define WRI_MIN    146 // this is the pulse length count (out of 4096) that corresponds to WRI_MIN_D
+#define WRI_MAX    590 // this is the pulse length count (out of 4096) that corresponds to WRI_MAX_D
+#define GRI_MIN    382 // this is the pulse length count (out of 4096) that corresponds to GRI_MIN_D
+#define GRI_MAX    590 // this is the pulse length count (out of 4096) that corresponds to GRI_MAX_D
+
+#define BAS_PARK 90
+#define SHL_PARK 90
+#define ELB_PARK 180
+#define WRI_PARK 90
+
 /*****************/
 /* SERVO OBJECTS */
 /*****************/
-Servo servo[5]; // Array of servos, use ID to address each individual servo
+// called this way, it uses the default address 0x40
+Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
+// you can also call it with a different address you want
+//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

 /********************/
 /* GLOBAL VARIABLES */
@@ -131,11 +159,11 @@
 // 'current' variables store the intended angles and 'actual' variables store the real angles used by servos
 // e.g. for an elbow current angle of 180 (the elbow is in line with the shoulder) the real angle is around 0
 int     i,j,count=0;
-int     ret_val, move_delay = 50; // move_delay is defined at global scope and is used to control speed of arm
+int     ret_val, g_moveDelay = 50; // g_moveDelay is defined at global scope and is used to control speed of arm
 char    buf[MAX_BUFFER+1];
-float   number[4], current[4], actual[4];
-float   current_g, current_r, current_h, current_l;
-float   old_r, old_h, old_b;
+float   number[4], current[4], actual[4], g_angle_d[4];
+float   g_radius_mm, g_height_mm, g_hand_d, g_sliderPos;
+float   g_prevRadius_mm, g_prevHeight_mm, g_prevBase_d, g_prevHand_d;

 const float gradient[] = {BAS_GRADIENT, SHL_GRADIENT, ELB_GRADIENT, WRI_GRADIENT, GRI_GRADIENT};
 const float offset[] = {BAS_OFFSET, SHL_OFFSET, ELB_OFFSET, WRI_OFFSET, GRI_OFFSET};
@@ -144,11 +172,16 @@
 const float R_REF[] = {BAS_R_REF, SHL_R_REF, ELB_R_REF, WRI_R_REF};
 const float H_REF[] = {BAS_H_REF, SHL_H_REF, ELB_H_REF, WRI_H_REF};

+const float SERVO_MIN_D[] = {BAS_MIN_D, SHL_MIN_D, ELB_MIN_D, WRI_MIN_D, GRI_MIN_D};
+const float SERVO_MAX_D[] = {BAS_MAX_D, SHL_MAX_D, ELB_MAX_D, WRI_MAX_D, GRI_MAX_D};
+const float SERVO_MIN[] = {BAS_MIN, SHL_MIN, ELB_MIN, WRI_MIN, GRI_MIN};
+const float SERVO_MAX[] = {BAS_MAX, SHL_MAX, ELB_MAX, WRI_MAX, GRI_MAX};
+
 /********************/
 /* PRE CALCULATIONS */
 /********************/
-float hum_sq = HUMERUS*HUMERUS;
-float uln_sq = ULNA*ULNA;
+float HUM_SQ = HUMERUS*HUMERUS;
+float ULN_SQ = ULNA*ULNA;

 /*****************/
 /* RETURN VALUES */
@@ -163,67 +196,61 @@
 /* FUNCTIONS */
 /*************/
 // Moves arm to specified servo angles
-int moveArm( float bas_angle_d, float shl_angle_d, float elb_angle_d, float wri_angle_d )
+int moveArm( float basAngle_d, float shlAngle_d, float elbAngle_d, float wriAngle_d )
 {
    int ret_val;

-   DEBUG("moveArm("); DEBUG(bas_angle_d); DEBUG(","); DEBUG(shl_angle_d); DEBUG(","); DEBUG(elb_angle_d); DEBUG(","); DEBUG(wri_angle_d); DEBUG(")-->(");
-
-   DEBUG(adjust(BAS, bas_angle_d)); DEBUG(","); DEBUG(adjust(SHL, shl_angle_d)); DEBUG(","); DEBUG(adjust(ELB, elb_angle_d)); DEBUG(","); DEBUG(adjust(WRI, wri_angle_d)); DEBUGln(")");
+   DEBUG("moveArm("); DEBUG(basAngle_d); DEBUG(","); DEBUG(shlAngle_d); DEBUG(","); DEBUG(elbAngle_d); DEBUG(","); DEBUG(wriAngle_d); DEBUGln(")");
+
    //Drive servos
-   if ( ( ret_val = servoWrite( BAS, adjust(BAS, bas_angle_d) ) ) != 0 ) return ret_val;
-   if ( ( ret_val = servoWrite( SHL, adjust(SHL, shl_angle_d) ) ) != 0 ) return ret_val;
-   if ( ( ret_val = servoWrite( ELB, adjust(ELB, elb_angle_d) ) ) != 0 ) return ret_val;
-   if ( ( ret_val = servoWrite( WRI, adjust(WRI, wri_angle_d) ) ) != 0 ) return ret_val;
-
-   delay(move_delay);
+   if ( ( ret_val = servoWrite( BAS, basAngle_d ) ) != 0 ) return ret_val;
+   if ( ( ret_val = servoWrite( SHL, shlAngle_d ) ) != 0 ) return ret_val;
+   if ( ( ret_val = servoWrite( ELB, elbAngle_d ) ) != 0 ) return ret_val;
+   if ( ( ret_val = servoWrite( WRI, wriAngle_d ) ) != 0 ) return ret_val;
+
+   delay(g_moveDelay);

    return ret_val;
 }

 // Moves the arm slowly to a new position, depending on the specified delay
 // If the last input angle is negative, the function will determine the wrist angle required to achieve horizontal position
-int slowMoveArm( float bas_angle_d, float shl_angle_d, float elb_angle_d, float wri_angle_d )
+int slowMoveArm( float basAngle_d, float shlAngle_d, float elbAngle_d, float wriAngle_d )
 {
-   if ( wri_angle_d < 0 ) wri_angle_d = current[WRI] + current[SHL] - shl_angle_d + current[ELB] - elb_angle_d;
-
-   if ( wri_angle_d < 0 ) wri_angle_d = 0;
-   else if ( wri_angle_d > 180 ) wri_angle_d = 180;
-
-   DEBUG("slowMoveArm("); DEBUG(bas_angle_d); DEBUG(","); DEBUG(shl_angle_d); DEBUG(","); DEBUG(elb_angle_d); DEBUG(","); DEBUG(wri_angle_d); DEBUGln(")");
+   DEBUG("slowMoveArm("); DEBUG(basAngle_d); DEBUG(","); DEBUG(shlAngle_d); DEBUG(","); DEBUG(elbAngle_d); DEBUG(","); DEBUG(wriAngle_d); DEBUGln(")");

    int ret_val;
-   float diff_b = abs( bas_angle_d - current[BAS] );
-   float diff_s = abs( shl_angle_d - current[SHL] );
-   float diff_e = abs( elb_angle_d - current[ELB] );
-   float diff_w = abs( wri_angle_d - current[WRI] );
-
-   float steps = max( diff_b, diff_s );
-   steps = max( steps, diff_e );
-   steps = max( steps, diff_w );
+   float bDiff = abs( basAngle_d - g_angle_d[BAS] );
+   float sDiff = abs( shlAngle_d - g_angle_d[SHL] );
+   float eDiff = abs( elbAngle_d - g_angle_d[ELB] );
+   float wDiff = abs( wriAngle_d - g_angle_d[WRI] );
+
+   float steps = max( bDiff, sDiff );
+   steps = max( steps, eDiff );
+   steps = max( steps, wDiff );
    steps = round(steps);
    DEBUG("Steps: "); DEBUGln(steps);

    if( steps < 2 )
    {
-      ret_val = moveArm( bas_angle_d, shl_angle_d, elb_angle_d, wri_angle_d );
+      ret_val = moveArm( basAngle_d, shlAngle_d, elbAngle_d, wriAngle_d );
    }
    else
    {
-      float b_step = (bas_angle_d - current[BAS])/steps;
-      float s_step = (shl_angle_d - current[SHL])/steps;
-      float e_step = (elb_angle_d - current[ELB])/steps;
-      float w_step = (wri_angle_d - current[WRI])/steps;
+      float bStep = (basAngle_d - g_angle_d[BAS])/steps;
+      float sStep = (shlAngle_d - g_angle_d[SHL])/steps;
+      float eStep = (elbAngle_d - g_angle_d[ELB])/steps;
+      float wStep = (wriAngle_d - g_angle_d[WRI])/steps;

-      float b_move = current[BAS] + b_step;
-      float s_move = current[SHL] + s_step;
-      float e_move = current[ELB] + e_step;
-      float w_move = current[WRI] + w_step;
+      float bMove = g_angle_d[BAS] + bStep;
+      float sMove = g_angle_d[SHL] + sStep;
+      float eMove = g_angle_d[ELB] + eStep;
+      float wMove = g_angle_d[WRI] + wStep;

       for(int i=0; i<steps; i++)
       {
-         if( ( ret_val = moveArm( b_move, s_move, e_move, w_move ) ) != 0 ) break;
-         b_move += b_step; s_move += s_step; e_move += e_step; w_move += w_step;
+         if( ( ret_val = moveArm( bMove, sMove, eMove, wMove ) ) != 0 ) break;
+         bMove += bStep; sMove += sStep; eMove += eStep; wMove += wStep;
       }
    }

@@ -231,78 +258,76 @@
 }

 // Arm positioning routine utilizing inverse kinematics in cylindrical coordinates
-// (r = radius, h = height, b = azimuth = base servo angle
-int moveArmCoord( float radius_mm, float height_mm, float bas_angle_d )
-{
-   DEBUG("moveArmCoord("); DEBUG(radius_mm); DEBUG(","); DEBUG(height_mm); DEBUG(","); DEBUG(bas_angle_d); DEBUGln(")");
-   /* Wrist position */
-   float wri_h = height_mm - BASE_HEIGHT;
-   float wri_r = radius_mm;
-   /* Shoulder to wrist distance ( AKA sw ) */
-   float s_w = ( wri_h * wri_h ) + ( wri_r * wri_r );
-   float s_w_sqrt = sqrt( s_w ); // Length of line from shoulder to wrist (S-W)
-   /* s_w angle to ground */
-   float a1 = atan2( wri_h, wri_r ); // Angle between S-W line and ground
-   /* s_w angle to humerus */
-   float a2 = acos((( hum_sq - uln_sq ) + s_w ) / ( 2 * HUMERUS * s_w_sqrt )); // Angle between S-W line and humerus
+// (r = radius, h = height, b = azimuth = base servo angle, handAngle = angle of hand from horizontal)
+int moveArmCoord( float radius_mm, float height_mm, float basAngle_d, float handAngle_d )
+{
+   DEBUG("moveArmCoord("); DEBUG(radius_mm); DEBUG(","); DEBUG(height_mm); DEBUG(","); DEBUG(basAngle_d); DEBUGln(")");
+   /* Lengths from shoulder to wrist in cylindrical coordinates */
+   float s2w_h = height_mm - BASE_HEIGHT - HAND*sin( radians( handAngle_d) );
+   float s2w_r = radius_mm - HAND*cos( radians( handAngle_d) );
+   /* Shoulder to wrist distance ( AKA s2w ) */
+   float s2w = ( s2w_h * s2w_h ) + ( s2w_r * s2w_r );
+   float s2w_sqrt = sqrt( s2w ); // Length of line from shoulder to wrist (S-W)
+   /* s2w angle to ground */
+   float a1 = atan2( s2w_h, s2w_r ); // Angle between S-W line and ground
+   /* s2w angle to humerus */
+   float a2 = acos((( HUM_SQ - ULN_SQ ) + s2w ) / ( 2 * HUMERUS * s2w_sqrt )); // Angle between S-W line and humerus
    /* shoulder angle */
-   float shl_angle_r = a1 + a2;
-   float shl_angle_d = degrees( shl_angle_r );
+   float shlAngle_r = a1 + a2;
    /* elbow angle */
-   float elb_angle_r = acos(( hum_sq + uln_sq - s_w ) / ( 2 * HUMERUS * ULNA )); // Angle between humerus and ulna
-   float elb_angle_d = degrees( elb_angle_r ); // Shifted so that neutral position is 180 degrees
-
-   return ( s_w_sqrt > HUMERUS + ULNA ) ? -3 : slowMoveArm( bas_angle_d, shl_angle_d, elb_angle_d, -1 ); // Return -3 if no solution exists (out of range)
+   float elbAngle_r = acos(( HUM_SQ + ULN_SQ - s2w ) / ( 2 * HUMERUS * ULNA )); // Angle between humerus and ulna
+   /* wrist angle */
+   float wriAngle_d = 360 - degrees(shlAngle_r + elbAngle_r);
+
+   return ( s2w_sqrt > HUMERUS + ULNA ) ? -3 : slowMoveArm( basAngle_d, degrees(shlAngle_r), degrees(elbAngle_r), wriAngle_d ); // Return -3 if no solution exists (out of range)
 }

 // Moves the arm slowly to a new position, depending on the specified delay using cylindrical coordinates
 // (r = radius, h = height, b = azimuth = base servo angle)
-int slowMoveArmCoord( float radius_mm, float height_mm, float bas_angle_d )
-{
-   DEBUG("slowMoveArmCoord("); DEBUG(radius_mm); DEBUG(","); DEBUG(height_mm); DEBUG(","); DEBUG(bas_angle_d); DEBUGln(")");
+int slowMoveArmCoord( float radius_mm, float height_mm, float basAngle_d, float handAngle_d )
+{
+   DEBUG("slowMoveArmCoord("); DEBUG(radius_mm); DEBUG(","); DEBUG(height_mm); DEBUG(","); DEBUG(basAngle_d); DEBUG(","); DEBUG(handAngle_d); DEBUGln(")");

    calcPosition();

-   old_r = current_r; old_h = current_h; old_b = current[BAS]; // Use with feedback to allow reversing after a collision
+   g_prevRadius_mm = g_radius_mm; g_prevHeight_mm = g_height_mm; g_prevBase_d = g_angle_d[BAS]; g_prevHand_d = g_hand_d;// Use with feedback to allow reversing after a collision

    int ret_val;
-   float diff_r = abs( radius_mm - current_r );
-   float diff_h = abs( height_mm - current_h );
-   float diff_b = abs( bas_angle_d - current[BAS] );
-
-   int steps = max( diff_r, diff_h );
-   steps = max( steps, diff_b );
+   float rDiff = abs( radius_mm - g_radius_mm );
+   float hDiff = abs( height_mm - g_height_mm );
+   float bDiff = abs( basAngle_d - g_angle_d[BAS] );
+   float dDiff = abs( handAngle_d - g_hand_d );
+
+   int steps = max( rDiff, hDiff );
+   steps = max( steps, bDiff );
+   steps = max( steps, dDiff );
    DEBUG("Steps: "); DEBUGln(steps);

-   float r_step = ( radius_mm - current_r )/steps;
-   float h_step = ( height_mm - current_h )/steps;
-   float b_step = ( bas_angle_d - current[BAS] )/steps;
-
-   float r_move = current_r + r_step;
-   float h_move = current_h + h_step;
-   float b_move = current[BAS] + b_step;
+   float rStep = ( radius_mm - g_radius_mm )/steps;
+   float hStep = ( height_mm - g_height_mm )/steps;
+   float bStep = ( basAngle_d - g_angle_d[BAS] )/steps;
+   float dStep = ( handAngle_d - g_hand_d )/steps;
+
+   float rMove = g_radius_mm + rStep;
+   float hMove = g_height_mm + hStep;
+   float bMove = g_angle_d[BAS] + bStep;
+   float dMove = g_hand_d + dStep;

    for(int i=0; i<steps; i++)
    {
-     if ( ( ret_val = moveArmCoord( r_move, h_move, b_move ) )  != 0 ) return ret_val;
-     r_move += r_step; h_move += h_step; b_move += b_step;
-   }
-
-   delay(100); // Wait for arm to stop moving
-
-   levelGripper();
-
-   delay(100); // Wait for arm to stop moving
-
-   if ( checkPosition() != 0 ) return -4; // Stall detection
+     if ( ( ret_val = moveArmCoord( rMove, hMove, bMove, dMove ) )  != 0 ) return ret_val;
+     rMove += rStep; hMove += hStep; bMove += bStep; dMove += dStep;
+   }
+
+   //delay(100); // Wait for arm to stop moving
+
+   //levelGripper();
+
+   //delay(100); // Wait for arm to stop moving
+
+   //if ( checkPosition() != 0 ) return -4; // Stall detection

    return 0;
-}
-
-// Adjust the servo angle to compensate for servo error
-float adjust( int id, float angle_d )
-{
-   return gradient[id]*angle_d + offset[id];
 }

 // Sends signal to stepper motor to move slider in a given direction
@@ -317,7 +342,7 @@
       delay(1);
       digitalWrite(STEP_PIN, LOW);
       delay(1);
-      dir ? current_l++ : current_l--;
+      dir ? g_sliderPos++ : g_sliderPos--;
    }
    DEBUGln();
 }
@@ -330,7 +355,7 @@
    {
       if(digitalRead(LSWITCH_PIN))
       {
-         current_l = 0;
+         g_sliderPos = 0;
          return -1;
       }
    }
@@ -338,11 +363,11 @@
    {
       if(digitalRead(RSWITCH_PIN))
       {
-         current_l = MAX_STEPS;
+         g_sliderPos = MAX_STEPS;
          return -2;
       }
    }
-   DEBUG(current_l); DEBUG(" ");
+   DEBUG(g_sliderPos); DEBUG(" ");
    return 0;
 }

@@ -414,11 +439,11 @@
 int checkPosition()
 {
    float angle_d = getAngle(SHL);
-   if ( abs( angle_d - current[SHL] ) > THRESHOLD3 ) return 1;
-   DEBUG("Check1: "); DEBUGln(angle_d - current[SHL]);
+   if ( abs( angle_d - g_angle_d[SHL] ) > THRESHOLD3 ) return 1;
+   DEBUG("Check1: "); DEBUGln(angle_d - g_angle_d[SHL]);
    angle_d = getAngle(ELB) - angle_d;
-   DEBUG("Check2: "); DEBUGln(angle_d - current[ELB] + 180);
-   return ( abs( angle_d - current[ELB] + 180 ) > THRESHOLD3 );
+   DEBUG("Check2: "); DEBUGln(angle_d - g_angle_d[ELB] + 180);
+   return ( abs( angle_d - g_angle_d[ELB] + 180 ) > THRESHOLD3 );
 }

 // Read from accelerometers and determine angle from horizontal
@@ -432,24 +457,17 @@
 }

 // Write angle to servo using microseconds for added precision
-int servoWrite( int id, float angle_deg )
+int servoWrite( int id, float angle_d )
 {
 //   DEBUG("servoWrite("); DEBUG(id); DEBUG(", "); DEBUG(angle_deg); DEBUGln(")");
-   int angle_us = round( 600 + 10*angle_deg );
-   if ( angle_us < 600 )
-   {
-      if ( angle_deg < round( gradient[id] * (gradient[id] > 0 ? 0 : 180) + offset[id] ) ) return -1; // Allows inputs from 0-180 before adjustments are made
-      angle_us = 600; DEBUGln("Clipped at 0");
-   }
-   if ( angle_us > 2400 )
-   {
-      if ( angle_deg > round( gradient[id] * (gradient[id] > 0 ? 180 : 0) + offset[id] ) ) return -2; // Allows inputs from 0-180 before adjustments are made
-      angle_us = 2400; DEBUGln("Clipped at 180");
-   }
-
-   servo[id].writeMicroseconds( angle_us );
-   actual[id] = angle_deg;
-   current[id] = (angle_deg - offset[id])/gradient[id];
+   if (angle_d < SERVO_MIN_D[id]) { DEBUG(angle_d); DEBUG("<"); DEBUGln(SERVO_MIN_D[id]); return -1; }
+   if (angle_d > SERVO_MAX_D[id]) { DEBUG(angle_d); DEBUG(">"); DEBUGln(SERVO_MAX_D[id]); return -2; }
+
+   float pulseLength = map(angle_d, 0, 180, SERVO_MIN[id], SERVO_MAX[id]);
+
+   pwm.setPWM(id, 0, pulseLength);
+
+   g_angle_d[id] = angle_d;

    return 0;
 }
@@ -457,13 +475,13 @@
 // Calculates the cylindrical coordinates of the wrist from the servo angles
 void calcPosition()
 {
-   float s = current[SHL]; float e = current[ELB] - 180;
-
-   current_r = HUMERUS*cos( radians(s) ) + ULNA*cos( radians(s + e) );
-
-   current_h = BASE_HEIGHT + HUMERUS*sin( radians(s) ) + ULNA*sin( radians(s + e) );
-
-   DEBUG("current_r: "); DEBUG(current_r); DEBUG(", current_h: "); DEBUGln(current_h);
+   float s = g_angle_d[SHL], e = g_angle_d[ELB] - 180, w = g_angle_d[WRI] - 180;
+
+   g_radius_mm = HUMERUS*cos( radians(s) ) + ULNA*cos( radians(s + e) ) + HAND*cos( radians(s + e + w) );
+
+   g_height_mm = BASE_HEIGHT + HUMERUS*sin( radians(s) ) + ULNA*sin( radians(s + e) ) + HAND*sin( radians(s + e + w) );
+
+   DEBUG("g_radius_mm: "); DEBUG(g_radius_mm); DEBUG(", g_height_mm: "); DEBUGln(g_height_mm);
 }

 /*********/
@@ -480,26 +498,27 @@
    pinMode(RSWITCH_PIN, INPUT);
    pinMode(LIGHT_PIN, OUTPUT);

-   servo[BAS].attach(BAS_PIN, 600, 2400);
-   servo[GRI].attach(GRI_PIN, 600, 2400);
-   servo[WRI].attach(WRI_PIN, 600, 2400);
-   servo[SHL].attach(SHL_PIN, 600, 2400);
-   servo[ELB].attach(ELB_PIN, 600, 2400);
-
+   pwm.begin();
+
+   pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
+
    // Move arm to rest position and calculate position
-   servoWrite(BAS,adjust(BAS,90));
-   servoWrite(SHL,adjust(SHL,90));
-   servoWrite(ELB,adjust(ELB,180));
-   servoWrite(WRI,adjust(WRI,0));
-   servoWrite(GRI,GRI_OPEN);
+   servoWrite( BAS, BAS_PARK );
+   servoWrite( SHL, SHL_PARK );
+   servoWrite( ELB, ELB_PARK );
+   servoWrite( WRI, WRI_PARK );
+   servoWrite( GRI, GRI_OPEN );
+   DEBUG("Robot parked: {"); DEBUG(g_angle_d[BAS]); DEBUG(","); DEBUG(g_angle_d[SHL]); DEBUG(","); DEBUG(g_angle_d[ELB]); DEBUG(","); DEBUG(g_angle_d[WRI]); DEBUGln(",delay}");
    calcPosition();
-   slide(LEFT,MAX_STEPS);
+   DEBUG("Robot parked: <"); DEBUG(g_radius_mm); DEBUG(","); DEBUG(g_height_mm); DEBUG(","); DEBUG(g_angle_d[BAS]); DEBUG(","); DEBUG(g_hand_d); DEBUGln(",delay>");
+   DEBUGln("Enter r to return robot to park position\n");
+   //slide(LEFT,MAX_STEPS);

-   DEBUGln("Base Servo Attached - Pin 2");
-   DEBUGln("Shoulder Servo Attached - Pin 3");
-   DEBUGln("Elbow Servo Attached - Pin 4");
-   DEBUGln("Wrist Servo Attached - Pin 10");
-   DEBUGln("Gripper Servo Attached - Pin 11\n");
+   DEBUGln("Base Servo = 0");
+   DEBUGln("Shoulder Servo = 1");
+   DEBUGln("Elbow Servo = 2");
+   DEBUGln("Wrist Servo = 3");
+   DEBUGln("Gripper Servo = 4\n");
 }

 /********/
@@ -514,7 +533,9 @@
       switch( buf[i] )
       {
          case 'o':
-            servoWrite(GRI,GRI_OPEN); Serial.println("Gripper Opened"); break;
+            if( ( ret_val = servoWrite(GRI,GRI_OPEN) ) == 0 ) Serial.println("Gripper Opened");
+            else Serial.println(ret_val);
+            break;
          case 'c':
             servoWrite(GRI,GRI_CLOSED); Serial.println("Gripper Closed"); break;
          case 's':
@@ -522,12 +543,12 @@
          case 'p':
             servoWrite(GRI,GRI_MICROPLATE); Serial.println("Gripped Microplate"); break;
          case 'r':
-            move_delay = 20;
-            if( ( ret_val = slowMoveArm(90,90,180,0) ) == 0 ) Serial.println("Arm moved to rest position");
+            g_moveDelay = 20;
+            if( ( ret_val = slowMoveArm(BAS_PARK,SHL_PARK,ELB_PARK,WRI_PARK) ) == 0 ) Serial.println("Arm returned to park position");
             else Serial.println(ret_val);
             break;
          case 'R':
-            moveArm(90,90,180,0); Serial.println("Arm moved to rest position"); break;
+            moveArm(BAS_PARK,SHL_PARK,ELB_PARK,WRI_PARK); Serial.println("ARM PARKED!"); break;

          case 'l': //start of setting light PWM value
             i=0; buf[i] = Serial.read(); delay(1);
@@ -578,12 +599,12 @@
             }
             buf[i] = '\0';
             number[0] = atof(buf);
-            move_delay = 50;
-            Serial.println(slowMoveArm(current[BAS],current[SHL],number[0],-1));
+            g_moveDelay = 50;
+            Serial.println(slowMoveArm(number[0],g_angle_d[SHL],g_angle_d[ELB],g_angle_d[WRI]));
             break;

          case '<': // start of coordinate move packet
-            for(j=0; j<3; j++) // capture first 4 arguments: depth, height, base angle, hand angle
+            for(j=0; j<4; j++) // capture first 4 arguments: depth, height, base angle, hand angle
             {
                i=0;
                buf[i] = Serial.read(); delay(1);
@@ -605,24 +626,24 @@
                buf[i] = Serial.read(); delay(1);
             }
             buf[i] = '\0';
-            move_delay = atof( buf ); // move_delay
-            ret_val = slowMoveArmCoord( number[0], number[1], number[2] );
+            g_moveDelay = atof( buf ); // g_moveDelay
+            ret_val = slowMoveArmCoord( number[0], number[1], number[2], number[3] );
             if( ret_val == 0 )
             {
-               Serial.print(number[0]); Serial.print(","); Serial.print(number[1]); Serial.print(","); Serial.println(number[2]);
+               Serial.print(number[0]); Serial.print(","); Serial.print(number[1]); Serial.print(","); Serial.print(number[2]); Serial.print(","); Serial.println(number[3]);
             }
             else
             {
                Serial.println(ret_val);
                if ( ret_val == -4 ) // If the arm did not reach the destination, return to previous position
                {
-                  slowMoveArmCoord( old_r, old_h, old_b );
+                  slowMoveArmCoord( g_prevRadius_mm, g_prevHeight_mm, g_prevBase_d, g_prevHand_d );
                }
             }
             break;

          case '{': // start of servo angle move packet
-            for(j=0; j<4; j++) // capture first 4 arguments: bas_angle_d, shl_angle_d, elb_angle_d & wri_angle_d
+            for(j=0; j<4; j++) // capture first 4 arguments: basAngle_d, shlAngle_d, elbAngle_d & wriAngle_d
             {
                i=0;
                buf[i] = Serial.read(); delay(1);
@@ -644,11 +665,11 @@
                buf[i] = Serial.read(); delay(1);
             }
             buf[i] = '\0';
-            move_delay = atof( buf ); // move_delay
+            g_moveDelay = atof( buf ); // g_moveDelay
             ret_val = slowMoveArm( number[0], number[1], number[2], number[3] );
             if( ret_val == 0 )
             {
-               Serial.print(number[0]); Serial.print(","); Serial.print(number[1]); Serial.print(","); Serial.println(number[2]);
+               Serial.print(number[0]); Serial.print(","); Serial.print(number[1]); Serial.print(","); Serial.print(number[2]); Serial.print(","); Serial.println(number[3]);
             }
             else
             {
@@ -657,4 +678,4 @@
             break;
       }
    }
-}+}


Adding Motion Check

Adding Motion Check

--- knot/arduino/bath.ino
+++ knot/arduino/bath.ino
@@ -17,16 +17,17 @@
 #define PIN_SCK    13 // Programming
 #define PIN_BUTTON A0 // Button
 #define PIN_LIGHT  A1 // Light
-#define PIN_A2     A2 //
+#define PIN_MOTION A2 // Motion
 #define PIN_A3     A3 //
 #define PIN_A4     A4 //
 #define PIN_A5     A5 //

 #define AVERAGE_COUNTER  100

-CmdMessenger cmdMessenger = CmdMessenger(Serial, ',', ';');
+CmdMessenger cmdMessenger          = CmdMessenger(Serial, ',', ';');
 DHT          dht(PIN_DHT, DHT22);
-bool         reported = false;
+bool         reported              = false;
+uint64_t     motionreportedCounter = 0;

 enum{
   kAcknowledge,     // 0
@@ -43,6 +44,7 @@
   kHumidity,        // 11
   kLight,           // 12
   kButtonPressed,   // 13
+  kMotionDetected,  // 14
 };

 void attachCommandCallbacks(){
@@ -205,8 +207,24 @@

 }

+void checkMotion(){
+   bool motion = digitalRead(PIN_MOTION);
+   if (motion){
+    if (motionreportedCounter == 0){
+     cmdMessenger.sendCmd(kMotionDetected, 23);
+    }
+    motionreportedCounter++;
+    if (motionreportedCounter > 50000){
+      motionreportedCounter = 0;
+    }
+   }else{
+    motionreportedCounter = 0;
+   }
+}
+
 void loop() {
   cmdMessenger.feedinSerialData();
   wdt_reset();
   checkButtons();
-}
+  checkMotion();
+}


Delete proton_pack_state_machine.ino

Delete proton_pack_state_machine.ino


Added comment.

Added comment.

--- things/examples/arduino/Lightbulb/Lightbulb.ino
+++ things/examples/arduino/Lightbulb/Lightbulb.ino
@@ -310,7 +310,7 @@
          Serial.println(F("Got HELLO response"));

          // CHECK FOR ERROR
-         if( responseData.indexOf("error") != -1 ) {
+         if( responseData.indexOf("error") != -1 ) { // if we have an 'error' the index will be a positive integer
            Serial.println(F("Error authenticating with steward. Updating boot time."));
            int startoftag = responseData.indexOf("\"timestamp\":");
            int startofquotes = responseData.indexOf(":", startoftag);


--- ptw-wheel.ino
+++ ptw-wheel.ino
@@ -32,15 +32,15 @@
 int i_color_r = 255;
 int i_color_g = 0;
 int i_color_b = 0;
+float instrument_brightness_min = 0.5; // default brightness
+float instrument_brightness = 1;

 // effect color
 int e_color_r = 0;
 int e_color_g = 0;
 int e_color_b = 255;
-
-float instrument_brightness_min = 0.5; // default brightness
-float instrument_brightness = 1;
 float effect_brightness = 0;
+float effect_brightness_target = 0;

 int divide = 2; // LEDパターンの分割数
 float slit_position = 0.5; // 0~1 分割された区分の中のどこまでがinstrumentにするか。0だと全部effect color。1だと全部instrument color。
@@ -106,6 +106,16 @@
         Serial.println(argument);
       }
     }
+    // set effect_brightness_target value
+    // "b:[0.0-1.0];"
+    else if(command=="E") {
+      // TODO argument check
+      // argument is float
+      effect_brightness_target = argument.toFloat();
+      // Serial.print("set effect_brightness_target value: ");
+      // Serial.println(effect_brightness_target);
+      updateLED();
+    }
     // sound trigger
     // "s:;"
     else if(command=="s") {
@@ -119,8 +129,8 @@
       if(argument.length()==1) {
         // argument is int
         divide = argument.toInt();
-        Serial.print("set divide number: ");
-        Serial.println(divide);
+        // Serial.print("set divide number: ");
+        // Serial.println(divide);
         updateLED();
       }
       else {
@@ -134,18 +144,18 @@
       // TODO argument check
       // argument is float
       slit_position = argument.toFloat();
-      Serial.print("set position: ");
-      Serial.println(slit_position);
-      updateLED();
-    }
-    // set instrument_brightness min value
+      // Serial.print("set position: ");
+      // Serial.println(slit_position);
+      updateLED();
+    }
+    // set instrument_brightness_min value
     // "b:[0.0-1.0];"
     else if(command=="b") {
       // TODO argument check
       // argument is float
       instrument_brightness_min = argument.toFloat();
-      Serial.print("set instrument_brightness min value: ");
-      Serial.println(instrument_brightness_min);
+      // Serial.print("set instrument_brightness min value: ");
+      // Serial.println(instrument_brightness_min);
       updateLED();
     }
     else {
@@ -154,9 +164,27 @@
     }
   }
   else {
+
+    // instrument brightness
     if(instrument_brightness_min+0.01 <= instrument_brightness) {
       instrument_brightness -= 0.01;
       updateLED();
+    }
+
+    // effect brightness
+    // fade effect brightness to effect_brightness_target value
+    float diff = abs(effect_brightness_target-effect_brightness);
+    if(0.01<diff){
+      if(effect_brightness_target < effect_brightness) {
+        effect_brightness -= 0.01;
+      }
+      else {
+        effect_brightness += 0.01;
+      }
+      updateLED();
+    }
+    else if(diff != 0.0){
+      effect_brightness = effect_brightness_target;
     }
   }
 }


メモリ節約のためエラーレスポンスのhintを削除.

メモリ節約のためエラーレスポンスのhintを削除.


Slight cleanup

Slight cleanup


Commented a line

Commented a line

--- ps2_controller_v2/ps2_controller_v2.ino
+++ ps2_controller_v2/ps2_controller_v2.ino
@@ -60,7 +60,7 @@
 bool defaultStatus[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, HIGH, LOW, HIGH, LOW, HIGH, LOW, HIGH, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW};
 bool inputStatus[] =   {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, HIGH, LOW, HIGH, LOW, HIGH, LOW, HIGH, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW};
 unsigned int commandArray[] = {buttonSelect, buttonL3, buttonR3, buttonStart, buttonDUp, buttonDRight, buttonDDown, buttonDLeft, buttonL2, buttonR2, buttonL1, buttonR1, buttonTriangle, buttonCircle, buttonCross, buttonSquare, axisRxHalf, axisRxFull, axisRyHalf, axisRyFull, axisLxHalf, axisLxFull, axisLyHalf, axisLyHalf, buttonAnalog, 25, 26, 27, 28, 29, 30, 31};
-unsigned int motorArray[] = {leftMotor, rightMotor, analogLed};
+unsigned int motorArray[] = {leftMotor, rightMotor, analogLed}; // Big motor, Small Motor, Analog LED

 boolean isInputting = false;
 boolean isInputtingDelayed = false;


Add matrix for Guppy

Add matrix for Guppy


Display gate.

Display gate.

--- examples/vseg/vseg.ino
+++ examples/vseg/vseg.ino
@@ -55,7 +55,8 @@
   0x3e, 0x7f, 0x7b, 0x41, 0x7f, 0x3e, 0x00,  // 1
   0x3e, 0x5b, 0x4d, 0x55, 0x5b, 0x3e, 0x00,  // 2
   0x3e, 0x6b, 0x5d, 0x55, 0x6b, 0x3e, 0x00,  // 3
-  0x3e, 0x73, 0x75, 0x77, 0x41, 0x3e, 0x00   // 4
+  0x3e, 0x73, 0x75, 0x77, 0x41, 0x3e, 0x00,  // 4
+  0x1c, 0x22, 0x41, 0x41, 0x41, 0x22, 0x1c   // jack
 };

 static const uint16_t rate_lut[] PROGMEM =
@@ -133,12 +134,13 @@
   {
     // initialize values
     gate_ = retrigger_ = false;
+    last_gate_ = false;

     // build widget hierarchy
     widget_save_ = new DUINO_SaveWidget<ParameterValues>(121, 0);
     widget_loop_ = new DUINO_DisplayWidget(0, 12, 96, 7, DUINO_Widget::Corners);
     widget_loop_->attach_scroll_callback(loop_scroll_callback);
-    widget_repeat_ = new DUINO_DisplayWidget(115, 11, 13, 9, DUINO_Widget::Full);
+    widget_repeat_ = new DUINO_DisplayWidget(102, 11, 13, 9, DUINO_Widget::Full);
     widget_repeat_->attach_scroll_callback(repeat_scroll_callback);
     container_loop_repeat_ = new DUINO_WidgetContainer<2>(DUINO_Widget::Click);
     container_loop_repeat_->attach_child(widget_loop_, 0);
@@ -172,6 +174,7 @@

     // draw fixed elements
     Display.draw_char(widget_repeat_->x() + 1, widget_repeat_->y() + 1, 'x', DUINO_SH1106::White);
+    Display.draw_bitmap_7(121, 12, icons, 5, DUINO_SH1106::White);

     // draw parameters
     display_loop(false);
@@ -193,6 +196,14 @@
     // TODO: envelope function

     widget_loop();
+
+    // display gate
+    if (gate_ != last_gate_)
+    {
+      last_gate_ = gate_;
+      Display.fill_rect(123, 14, 3, 3, gate_ ? DUINO_SH1106::White : DUINO_SH1106::Black);
+      Display.display(123, 125, 1, 2);
+    }
   }

   void gate_callback()
@@ -535,6 +546,7 @@
   DU_VSEG_PointWidget * widgets_points_[8];

   volatile bool gate_, retrigger_;
+  bool last_gate_;
 };

 DU_VSEG_Function * function;


add some delay, remove old flag

add some delay, remove old flag

--- pingpong/pingpong.ino
+++ pingpong/pingpong.ino
@@ -36,6 +36,8 @@
     }
   }
   lastp2State = p2State;
+
+  delay(100);
 }

 void showScore()
@@ -67,5 +69,4 @@
 {
   p1Score = 0;
   p2Score = 0;
-  gameOver = 0;
 }


RoboClaw transmission enable/disable

RoboClaw transmission enable/disable

Fixed an issue when powering up the RoboClaw. The BMSerial must be
disabled while RC is not powered.

--- RobotBase.ino
+++ RobotBase.ino
@@ -18,6 +18,11 @@
 #define RC_RX_PIN 12
 #define RC_TX_PIN 11
 RoboClaw roboclaw(RC_RX_PIN, RC_TX_PIN);
+
+//
+#define AUX_PIN 7
+#define MOTORS_PIN 8
+#define UPS_PIN 9

 // common vars //
 unsigned long lastCommandTime;
@@ -50,15 +55,24 @@
   pinMode(4, INPUT_PULLUP);
   pinMode(5, INPUT_PULLUP);
   pinMode(6, INPUT_PULLUP);
-  pinMode(7, INPUT_PULLUP);
-  pinMode(8, INPUT_PULLUP);
-  pinMode(9, INPUT_PULLUP);
   pinMode(10, INPUT_PULLUP);

-  // start ports
-  roboclaw.begin(38400);
+  pinMode(AUX_PIN, OUTPUT);
+  pinMode(MOTORS_PIN, OUTPUT);
+  pinMode(UPS_PIN, OUTPUT);
+  digitalWrite(AUX_PIN, LOW);
+  digitalWrite(MOTORS_PIN, LOW);
+  digitalWrite(UPS_PIN, LOW);
+  pulsePin(AUX_PIN, 20);
+
+  //
   Serial.begin(38400);
-}
+  //
+  driveInit(true);
+  driveInit(false);
+}
+
+//=======================================

 void loop()
 {
@@ -82,7 +96,7 @@
     if (buf[bytes] == 10 || buf[bytes] == 13 || bytes >= MAX_COMMAND)
     {
       if (bytes > 0) Execute();
-			//if (bytes > 0) if (crc8_ok()) Execute();
+      //if (bytes > 0) if (crc8_ok()) Execute();
       return;
     }
     bytes++;
@@ -120,6 +134,7 @@

 void CheckCommandTimeout()
 {
+  if (cmdTimeout == 0) return;
   commandTime = millis();
   if (commandTime >= lastCommandTime) commandTime -= lastCommandTime; else lastCommandTime = 0;
   if (commandTime > cmdTimeout) OnDisconnected();
@@ -168,7 +183,9 @@
   else
   if (cmd == 'V' || cmd == 'v') ver();
   else
-  if (cmd == 'P' || cmd == 'p') param();
+  if (cmd == 'P' || cmd == 'p') power();
+  else
+  if (cmd == 'S' || cmd == 's') settings();
   else
   if (cmd == 'B' || cmd == 'b') battery();
   else
@@ -230,14 +247,14 @@
   }
   else
   if (cmd == 'Z' || cmd == 'z') // stop immediately
-	{
-		motor1_target = MOTOR_VELOCITY_0;
-		motor1 = MOTOR_VELOCITY_0;
-		motor2_target = MOTOR_VELOCITY_0;
-		motor2 = MOTOR_VELOCITY_0;
-		roboclaw.ForwardBackwardM1(RC_ADDR, motor1);
-		roboclaw.ForwardBackwardM2(RC_ADDR, motor2);
-	}
+  {
+    motor1_target = MOTOR_VELOCITY_0;
+    motor1 = MOTOR_VELOCITY_0;
+    motor2_target = MOTOR_VELOCITY_0;
+    motor2 = MOTOR_VELOCITY_0;
+    roboclaw.ForwardBackwardM1(RC_ADDR, motor1);
+    roboclaw.ForwardBackwardM2(RC_ADDR, motor2);
+  }
   else
   if (cmd == 'F' || cmd == 'f') { motor1_target = MOTOR_VELOCITY_0 + motor_velocity; motor2_target = motor1_target; }
   else
@@ -248,6 +265,8 @@
   if (cmd == 'R' || cmd == 'r') { motor1_target = MOTOR_VELOCITY_0 + motor_velocity; motor2_target = MOTOR_VELOCITY_0 - motor_velocity; }
   else
   if (cmd == 'S' || cmd == 's') { driveStop(); }
+  else
+  if (cmd == 'E' || cmd == 'e') { driveInit(buf[2] == '1'); }
   else
   if (cmd == 'V' || cmd == 'v')
   {
@@ -309,17 +328,49 @@
     roboclaw.ForwardBackwardM2(RC_ADDR, motor2);
   }
 }
+
+void driveInit(boolean action)
+{
+  if (action) roboclaw.begin(38400);
+  else roboclaw.end();
+}
+
+//=======================================
+
+
+
+
+
+
+
+
+
+
+
+
+//=======================================

 // 'version' command
 // ex: V
 void ver()
 {
-  Serial.println("V2");
+  Serial.println("V3");
+}
+
+// 'power' command
+void power()
+{
+  cmd = buf[1];
+  if (cmd == 'A' || cmd == 'a') { pulsePin(AUX_PIN, 20); delay(3000); pulsePin(AUX_PIN, 20);  }
+  else
+  if (cmd == 'M' || cmd == 'm') pulsePin(MOTORS_PIN, 20);
+  else
+  if (cmd == 'U' || cmd == 'u') pulsePin(UPS_PIN, 5500);
 }

 // 'set parameter' command
-// ex: PT2500
-void param()
+// ex: ST2500
+void settings()
 {
   cmd = buf[1];
   // command timeout
@@ -377,6 +428,14 @@
   Serial.println(a);
 }

+//
+void pulsePin(int pin, int ms)
+{
+  digitalWrite(pin, HIGH);
+  delay(ms);
+  digitalWrite(pin, LOW);
+}
+
 // converts string to number. reads 'count' chars starting at 'index' position in buffer
 byte bctoi(byte index, byte count)
 {


Update RovMain.ino

Update RovMain.ino

--- Software/OpenCM9.04/RovMain/RovMain.ino
+++ Software/OpenCM9.04/RovMain/RovMain.ino
@@ -42,9 +42,9 @@
   Serial.begin(115200);

   RovSerial.begin(115200);
-  RovServo[RC_MOTOR_L].attach(RC_MOTOR_PIN_L, 100, 2000, 0, 255 );
-  RovServo[RC_MOTOR_C].attach(RC_MOTOR_PIN_C, 100, 2000, 0, 255 );
-  RovServo[RC_MOTOR_R].attach(RC_MOTOR_PIN_R, 100, 2000, 0, 255 );
+  RovServo[RC_MOTOR_L].attach(RC_MOTOR_PIN_L, 1000, 2000, 0, 255 );
+  RovServo[RC_MOTOR_C].attach(RC_MOTOR_PIN_C, 1000, 2000, 0, 255 );
+  RovServo[RC_MOTOR_R].attach(RC_MOTOR_PIN_R, 1000, 2000, 0, 255 );

   RovServo[RC_MOTOR_L].write(0);
   RovServo[RC_MOTOR_C].write(0);
@@ -111,7 +111,7 @@
     //시동
     if( ch == 'o' )
     {
-      rc_pwm_L = 100, rc_pwm_R = 100, rc_pwm_T = 100;
+      rc_pwm_L = 0, rc_pwm_R = 0, rc_pwm_T = 0;
       RovServo[0].write(rc_pwm_L);
       RovServo[1].write(rc_pwm_R);
       RovServo[2].write(rc_pwm_T);
@@ -120,7 +120,7 @@
     //정지 (시동끄기)
     if( ch == 'p' )
     {
-      rc_pwm_L = 100, rc_pwm_R = 100, rc_pwm_T = 100;
+      rc_pwm_L = 0, rc_pwm_R = 0, rc_pwm_T = 0;
       RovServo[0].write(rc_pwm_L);
       RovServo[1].write(rc_pwm_R);
       RovServo[2].write(rc_pwm_T);
@@ -129,8 +129,8 @@
     //전진 모터 가속
     if( ch == 'w' )
     {
-      rc_pwm_L = constrain(rc_pwm_L++, 100, 2000);
-      rc_pwm_R = constrain(rc_pwm_R++, 100, 2000);
+      rc_pwm_L = constrain(rc_pwm_L++, 0, 2000);
+      rc_pwm_R = constrain(rc_pwm_R++, 0, 2000);
       RovServo[0].write(rc_pwm_L);
       RovServo[2].write(rc_pwm_R);
       Serial.println("Left=");
@@ -141,8 +141,8 @@
     //전진 모터 감속
     if( ch == 's' )
     {
-      rc_pwm_L = constrain(rc_pwm_L--, 100, 2000);
-      rc_pwm_R = constrain(rc_pwm_R--, 100, 2000);
+      rc_pwm_L = constrain(rc_pwm_L--, 0, 2000);
+      rc_pwm_R = constrain(rc_pwm_R--, 0, 2000);
       RovServo[0].write(rc_pwm_L);
       RovServo[2].write(rc_pwm_R);
       Serial.println("Left=");
@@ -153,8 +153,8 @@
     //좌회전
     if( ch == 'a' )
     {
-      rc_pwm_L = constrain(rc_pwm_L--, 100, 2000);
-      rc_pwm_R = constrain(rc_pwm_R++, 100, 2000);
+      rc_pwm_L = constrain(rc_pwm_L--, 0, 2000);
+      rc_pwm_R = constrain(rc_pwm_R++, 0, 2000);
       RovServo[0].write(rc_pwm_L);    //좌측모터 출력 감소
       RovServo[2].write(rc_pwm_R);    //우측모터 출력 증가
       Serial.println("Left=");
@@ -165,8 +165,8 @@
     //우회전
     if( ch == 'd' )
     {
-      rc_pwm_L = constrain(rc_pwm_L++, 100, 2000);
-      rc_pwm_R = constrain(rc_pwm_R--, 100, 2000);
+      rc_pwm_L = constrain(rc_pwm_L++, 0, 2000);
+      rc_pwm_R = constrain(rc_pwm_R--, 0, 2000);
       RovServo[0].write(rc_pwm_L);   // 좌측모터 출력 증가
       RovServo[2].write(rc_pwm_R);    //우측모터 출력 감소
       Serial.println("Left=");
@@ -177,7 +177,7 @@
     //상단모터 가속
     if( ch == 'q' )
     {
-      rc_pwm_T = constrain(rc_pwm_T++, 100, 2000);
+      rc_pwm_T = constrain(rc_pwm_T++, 0, 2000);
       RovServo[1].write(rc_pwm_T);
       Serial.println("Top=");
       Serial.println(rc_pwm_T);
@@ -185,7 +185,7 @@
     //상단모터 감속
     if( ch == 'e' )
     {
-      rc_pwm_T = constrain(rc_pwm_T--, 100, 2000);
+      rc_pwm_T = constrain(rc_pwm_T--, 0, 2000);
       RovServo[1].write(rc_pwm_T);
       Serial.println("Top=");
       Serial.println(rc_pwm_T);


Corrected comments in oha_gateway_rf_v0_2.


Update checks for talking, handle checks for talking

--- Skulleyes.ino
+++ Skulleyes.ino
@@ -35,10 +35,18 @@

 Skulleyes_8x8matrix matrix = Skulleyes_8x8matrix();

-boolean playMode = false;
-boolean played = false;
-
-const int wait = 500;
+const boolean eyeDbg = false;
+boolean talkMode = false;
+boolean talkPlayed = false;
+int talkModeChecked = 0;
+
+int lastTalkChoice = -1;
+int lastTalk = -1;
+
+const int wait_eyes = 128;
+const int wait_events = 1024;
+int wait_events_multiplier = 5;
+int wait_talk = -1;

 static const uint8_t PROGMEM
 eye_off[] =
@@ -149,18 +157,15 @@
   "HASKULL.mp3",
   "ICDEADCD.mp3",

-  "JSTNSCAP.mp3",
   "MNSTERHM.mp3",
   "NOBODY.mp3",
   "PUMPKNPI.mp3",
   "SPIRITS.mp3",
-
   "TOBNOTB.mp3",
+
   "TRVRSCRY.mp3",
   "UNLBYTES.mp3",
   "WWW.mp3",
-  "YEARBOO.mp3",
-
   "TRVRSCRY.mp3"
 };

@@ -172,104 +177,162 @@
   matrix.begin(0x70);
 }

+void eyesOff(void) {
+  eyesDraw(eye_off, 0, 0);
+}
+
+void eyesDrawDelayOff(void) {
+  eyesDrawDelay(eye_off);
+}
+
 void eyesWait(int minWait, int maxWait) {
   delay(random(minWait, maxWait));
 }

-void eyesDraw(const uint8_t *bitmap) {
+void eyesDraw(const uint8_t *bitmap, int minWait, int maxWait) {
   matrix.clear();
   matrix.drawBitmap(0, 0, bitmap, 8, 8, LED_ON);
   matrix.writeDisplay();
-  eyesWait(wait, wait);
-}
-
-void eyesUp() {
-  eyesDraw(eye_off);
-  eyesDraw(eye_up_left);
-  eyesDraw(eye_up_center);
-  eyesDraw(eye_up_right);
-  eyesDraw(eye_up_center);
-  eyesDraw(eye_up_left);
-  eyesDraw(eye_off);
-}
-
-void eyesMiddle() {
-  eyesDraw(eye_off);
-  eyesDraw(eye_left);
-  eyesDraw(eye_center);
-  eyesDraw(eye_right);
-  eyesDraw(eye_center);
-  eyesDraw(eye_left);
-  eyesDraw(eye_off);
-}
-
-void eyesDown() {
-  eyesDraw(eye_off);
-  eyesDraw(eye_down_left);
-  eyesDraw(eye_down_center);
-  eyesDraw(eye_down_right);
-  eyesDraw(eye_down_center);
-  eyesDraw(eye_down_left);
-  eyesDraw(eye_off);
-}
-
-void eyesClock() {
-  eyesDraw(eye_off);
-  eyesDraw(eye_up_center);
-  eyesDraw(eye_up_right);
-  eyesDraw(eye_right);
-  eyesDraw(eye_down_right);
-  eyesDraw(eye_down_center);
-  eyesDraw(eye_down_left);
-  eyesDraw(eye_left);
-  eyesDraw(eye_up_left);
-  eyesDraw(eye_up_center);
-  eyesDraw(eye_off);
-}
-
-void eyesTalk() {
-  int choice = random(15);
-  char* fn = soundFiles[choice];
-  Serial.println("Playing choice[" + String(choice) + "], fn[" + String(fn) + "]");
+
+  if (maxWait > 0) {
+    eyesWait(minWait, maxWait);
+  }
+}
+
+void eyesDrawDelay(const uint8_t *bitmap) {
+  eyesDraw(bitmap, wait_eyes, wait_eyes);
+}
+
+void eyesChoiceUp() {
+  eyesDrawDelayOff();
+  eyesDrawDelay(eye_up_left);
+  eyesDrawDelay(eye_up_center);
+  eyesDrawDelay(eye_up_right);
+  eyesDrawDelay(eye_up_center);
+  eyesDrawDelay(eye_up_left);
+  eyesDrawDelayOff();
+}
+
+void eyesChoiceMiddle() {
+  eyesDrawDelayOff();
+  eyesDrawDelay(eye_left);
+  eyesDrawDelay(eye_center);
+  eyesDrawDelay(eye_right);
+  eyesDrawDelay(eye_center);
+  eyesDrawDelay(eye_left);
+  eyesDrawDelayOff();
+}
+
+void eyesChoiceDown() {
+  eyesDrawDelayOff();
+  eyesDrawDelay(eye_down_left);
+  eyesDrawDelay(eye_down_center);
+  eyesDrawDelay(eye_down_right);
+  eyesDrawDelay(eye_down_center);
+  eyesDrawDelay(eye_down_left);
+  eyesDrawDelayOff();
+}
+
+void eyesChoiceClock() {
+  eyesDrawDelayOff();
+  eyesDrawDelay(eye_up_center);
+  eyesDrawDelay(eye_up_right);
+  eyesDrawDelay(eye_right);
+  eyesDrawDelay(eye_down_right);
+  eyesDrawDelay(eye_down_center);
+  eyesDrawDelay(eye_down_left);
+  eyesDrawDelay(eye_left);
+  eyesDrawDelay(eye_up_left);
+  eyesDrawDelay(eye_up_center);
+  eyesDrawDelayOff();
+}
+
+void eyesChoiceTalk() {
+  int talkChoice = -1;
+  while (talkChoice == -1 || talkChoice == lastTalkChoice) {
+    talkChoice = random(13);
+  }
+  lastTalkChoice = talkChoice;
+  char* fn = soundFiles[talkChoice];
+  if (eyeDbg) Serial.println("Playing talkChoice[" + String(talkChoice) + "], fn[" + String(fn) + "]");
+  talkMode = true;
+  talkPlayed = false;
+  talkModeChecked = 0;
+  wait_talk = 0;
   player.playOne(fn);
-  playMode = true;
-  played = false;
+}
+
+void eyesTalkStep() {
+  if (eyeDbg) Serial.println("playing");
+  wait_talk--;
+  if (wait_talk < 1) {
+    int eyeSize = random(1000);
+    if (eyeSize > 0) {
+      eyeSize = 1;
+    }
+    if (lastTalk != eyeSize) {
+      if (eyeSize == 0) {
+        eyesOff();
+        wait_talk = random(2 * wait_eyes, 6 * wait_eyes);
+      } else {
+        eyesDraw(eye_center, 0, 0);
+        wait_talk = random(4 * wait_eyes, 10 * wait_eyes);
+      }
+      lastTalk = eyeSize;
+    }
+  }
+
+  talkPlayed = true;
+  player.play();
+}
+
+void eyesTalkCheck() {
+  String state = player.getPlayingState();
+    if (eyeDbg) Serial.println("state[" + state + "], talkPlayed[" + talkPlayed + "]");
+
+    if (talkPlayed && state != "1" && state != "3") {
+      talkModeChecked++;
+
+      eyesOff();
+
+      if (talkModeChecked > 20) {
+        if (eyeDbg) Serial.println("was playing but do not think so now, state[" + state + "]");
+        talkMode = false;
+        eyesWait(wait_events, wait_events);
+      }
+
+    } else {
+      eyesTalkStep();
+    }
 }

 void eyesRandom() {
-  int choice = random(3);
-  switch (choice) {
+  int eyeChoice = random(5);
+  switch (eyeChoice) {
     case 0:
-      eyesUp();
+      eyesChoiceUp();
       break;
     case 1:
-      eyesMiddle();
+      eyesChoiceMiddle();
       break;
     case 2:
-      eyesDown();
+      eyesChoiceDown();
       break;
     case 3:
-      eyesClock();
+      eyesChoiceClock();
+      break;
+    case 4:
+      eyesChoiceTalk();
       break;
   }
 }

 void loop() {
-  String state = player.getPlayingState();
-  if (playMode) {
-    if (played && state != "1" && state != "3") {
-      Serial.println("was playing but do not think so now, state[" + state + "]");
-      playMode = false;
-      eyesRandom();
-      eyesWait(1000,1000);
-    } else {
-      Serial.println("playing");
-      played = true;
-      player.play();
-    }
-    return;
-  }
-
-  eyesTalk();
-  eyesWait(1000,1000);
-}
+  // if talking, keep talking
+  if (talkMode) {
+    eyesTalkCheck();
+  } else {
+    eyesWait(wait_events, wait_events_multiplier * wait_events);
+    eyesRandom();
+  }
+}


Latest

Latest

--- firmware/Example_2.ino
+++ firmware/Example_2.ino
@@ -1,3 +1,6 @@
+// This #include statement was automatically added by the Particle IDE.
+#include "SparkJson/SparkJson.h"
+
 // This #include statement was automatically added by the Particle IDE.
 #include "ncd_gateway.h"

@@ -7,29 +10,29 @@
 // This #include statement was automatically added by the Particle IDE.
 #include "S3B.h"

-SYSTEM_THREAD(ENABLED);
+unsigned long tOut = 3000;
+
+void commandHandler(const char *event, const char *data);

 S3B module;

-byte S3BAddress[7][8] = {{0x00, 0x13, 0xA2, 0x00, 0x41, 0x02, 0x20, 0xD8},
-                        {0x00, 0x13, 0xA2, 0x00, 0x41, 0x02, 0x20, 0x43},
-                        {0x00, 0x13, 0xA2, 0x00, 0x40, 0xF2, 0x74, 0x79},
-                        {0x00, 0x13, 0xA2, 0x00, 0x41, 0x02, 0x20, 0xD8},
-                        {0x00, 0x13, 0xA2, 0x00, 0x41, 0x02, 0x20, 0xD8},
-                        {0x00, 0x13, 0xA2, 0x00, 0x41, 0x02, 0x20, 0xD8},
-                        {0x00, 0x13, 0xA2, 0x00, 0x41, 0x02, 0x20, 0xD8}};
+byte receiveBuffer[256];

-int relayStatus = 0;

 void setup() {
     Particle.function("deviceComm", gatewayCommand);
+    Particle.subscribe("deviceCom", commandHandler);
+    Particle.function("clearInit", clearInit);
     Serial1.begin(115200);
     Wire.begin();
-
-  String initCommands = "i2c,32,write,0,0|6,0";
-	byte initCommandBytes[initCommands.length()+1];
-	initCommands.getBytes(initCommandBytes, initCommands.length()+1);
-    module.transmit(S3BAddress[0], initCommandBytes, initCommands.length());
+    int initCommandsRan = runInitCommands();
+    Serial.printf("Ran %i init commands \n", initCommandsRan);
+}
+
+void commandHandler(const char *event, const char *data){
+    Serial.println("Got Event");
+    String newCommand = String(data);
+    gatewayCommand(newCommand);
 }

 void loop() {
@@ -47,20 +50,33 @@
             byte lenMSB = Serial1.read();
             byte lenLSB = Serial1.read();
             int newDataLength = (lenMSB*256)+lenLSB;
-            while(Serial1.available() < newDataLength+1 && millis() <= tOut+startTime);
-            if(Serial1.available() < newDataLength+1){
+
+            int count = 0;
+            while(count != newDataLength+1 && millis() <= tOut+startTime){
+                if(Serial1.available() != 0){
+                    receiveBuffer[count] = Serial1.read();
+                    count++;
+                }
+            }
+            if(count < newDataLength+1){
                 Serial.println("Timeout2");
-                Serial.printf("Serial1.available(): %i, expected %i \n", Serial1.available(), newDataLength+1);
+                Serial.printf("Received Bytes: %i, expected %i \n", count, newDataLength+1);
                 return;
             }
+            Serial.printf("Received %i bytes \n", count);
             //We have all our data.
             byte newData[newDataLength+4];
             newData[0] = startDelimiter;
             newData[1] = lenMSB;
             newData[2] = lenLSB;
             for(int i = 3; i < newDataLength+4; i++){
-                newData[i] = Serial1.read();
+                newData[i] = receiveBuffer[i-3];
             }
+            Serial.print("Received: ");
+            for(int i = 0; i < sizeof(newData); i++){
+                Serial.printf("%x, ", newData[i]);
+            }
+            Serial.println();
             //validate data
             if(!module.validateReceivedData(newData, newDataLength+4)){
                 Serial.println("Invalid Data");
@@ -74,6 +90,7 @@

             }
             String stringCommand = String(receivedData);
+            Serial.println("Command: "+stringCommand);
             gatewayCommand(stringCommand);
         }else{
             Serial.printf("First byte not valid, it was: 0x%x \n", startDelimiter);
@@ -81,5 +98,3 @@
     }
 }

-//Command format
-//I2CAddress,cmd1|,cmd2|cmd3


RX filter not needed on 2nd radio

RX filter not needed on 2nd radio

--- V0p2_Main/V0p2_Main.ino
+++ V0p2_Main/V0p2_Main.ino
@@ -277,7 +277,7 @@
   // Check that the radio is correctly connected; panic if not...
   if(!SecondaryRadio.configure(1, &SecondaryRadioConfig) || !SecondaryRadio.begin()) { panic(); }
   // Apply filtering, if any, while we're having fun...
-  SecondaryRadio.setFilterRXISR(FilterRXISR);
+//  SecondaryRadio.setFilterRXISR(FilterRXISR); // Assume no RX on secondary radio.
 #endif // ENABLE_RADIO_SECONDARY_MODULE


paul's suggestion for png. compiles clean but doesn't work


test code

test code

--- YaesuTest/YaesuTest.ino
+++ YaesuTest/YaesuTest.ino
@@ -136,7 +136,7 @@
       break;

     case 2:
-      if ( (millis() - tx_init) > 5000 ) {
+      if ( (millis() - tx_init) > 500 ) {
         FT817.requestFrequencyAndMode();
         tx_init = millis();
       }
@@ -163,7 +163,8 @@
   } // txSerial.available()

   // display of frequency and mode from time to time
-  if ( millis() - loop_init > 2000 ) {
+  if (    (txState != 2 && (millis() - loop_init > 200))
+       || (txState == 2 && (millis() - loop_init > 2000)) ) {

     loop_init = millis();

@@ -208,4 +209,4 @@
   return __brkval ? &top - __brkval : &top - &__bss_end;
 #endif  // __arm__
 }
-
+


rename 'display' to 'arduboy' in breakout example

--- ArduBreakout.ino
+++ ArduBreakout.ino
@@ -21,7 +21,7 @@
 #define OLED_MOSI 11   // hardware SPI MOSI
 #define OLED_RESET 7

-Arduboy display;
+Arduboy arduboy;

 const byte width = 128;   //Width of screen
 const byte height = 64;   //Hight of screen
@@ -72,10 +72,10 @@
 {
   for(int i = -8; i < 28; i = i + 2)
   {
-    display.clearDisplay();
-    display.setCursor(46, i);
-    display.print("ARDUBOY");
-    display.display();
+    arduboy.clearDisplay();
+    arduboy.setCursor(46, i);
+    arduboy.print("ARDUBOY");
+    arduboy.display();
   }

   tone(A2, 987, 160);
@@ -86,9 +86,9 @@

 void setup()
 {
-  display.start();
-  display.print("Hello World!");
-  display.display();
+  arduboy.start();
+  arduboy.print("Hello World!");
+  arduboy.display();
   intro();
 }

@@ -97,7 +97,7 @@
   //Move right
   if(xPaddle < width - 12)
   {
-    if (display.pressed(RIGHT_BUTTON))
+    if (arduboy.pressed(RIGHT_BUTTON))
     {
       xPaddle++;
     }
@@ -106,7 +106,7 @@
   //Move left
   if(xPaddle > 0)
   {
-    if (display.pressed(LEFT_BUTTON))
+    if (arduboy.pressed(LEFT_BUTTON))
     {
       xPaddle--;
     }
@@ -138,7 +138,7 @@
     //Lose a life if bottom edge hit
     if (yb >= 64)
     {
-      display.drawRect(xPaddle, 63, 11, 1, 0);
+      arduboy.drawRect(xPaddle, 63, 11, 1, 0);
       xPaddle = 54;
       yb=60;
       released = false;
@@ -199,7 +199,7 @@
             Score();
             brickCount++;
             isHit[row][column] = true;
-            display.drawRect(10*column, 2+6*row, 8, 4, 0);
+            arduboy.drawRect(10*column, 2+6*row, 8, 4, 0);

             //Vertical collision
             if (bottomBall > bottomBrick || topBall < topBrick)
@@ -239,7 +239,7 @@
     xb=xPaddle + 5;

     //Release ball if FIRE pressed
-    pad3 = display.pressed(B_BUTTON);
+    pad3 = arduboy.pressed(B_BUTTON);
     if (pad3 == 1 && oldpad3 == 0)
     {
       released=true;
@@ -262,10 +262,10 @@

 void drawBall()
 {
-  display.drawPixel(xb,   yb,   0);
-  display.drawPixel(xb+1, yb,   0);
-  display.drawPixel(xb,   yb+1, 0);
-  display.drawPixel(xb+1, yb+1, 0);
+  arduboy.drawPixel(xb,   yb,   0);
+  arduboy.drawPixel(xb+1, yb,   0);
+  arduboy.drawPixel(xb,   yb+1, 0);
+  arduboy.drawPixel(xb+1, yb+1, 0);

   if(ballclock>4)
   {
@@ -275,37 +275,37 @@

   ballclock++;

-  display.drawPixel(xb,   yb,   1);
-  display.drawPixel(xb+1, yb,   1);
-  display.drawPixel(xb,   yb+1, 1);
-  display.drawPixel(xb+1, yb+1, 1);
+  arduboy.drawPixel(xb,   yb,   1);
+  arduboy.drawPixel(xb+1, yb,   1);
+  arduboy.drawPixel(xb,   yb+1, 1);
+  arduboy.drawPixel(xb+1, yb+1, 1);
 }

 void drawPaddle()
 {
-  display.drawRect(xPaddle, 63, 11, 1, 0);
+  arduboy.drawRect(xPaddle, 63, 11, 1, 0);
   movePaddle();
-  display.drawRect(xPaddle, 63, 11, 1, 1);
+  arduboy.drawRect(xPaddle, 63, 11, 1, 1);
 }

 void drawLives()
 {
   sprintf(text, "LIVES:%u", lives);
-  display.setCursor(0, 90);
-  display.print(text);
+  arduboy.setCursor(0, 90);
+  arduboy.print(text);
 }

 void drawGameOver()
 {
-  display.drawPixel(xb,   yb,   0);
-  display.drawPixel(xb+1, yb,   0);
-  display.drawPixel(xb,   yb+1, 0);
-  display.drawPixel(xb+1, yb+1, 0);
-  display.setCursor(52, 42);
-  display.print( "Game");
-  display.setCursor(52, 54);
-  display.print("Over");
-  display.display();
+  arduboy.drawPixel(xb,   yb,   0);
+  arduboy.drawPixel(xb+1, yb,   0);
+  arduboy.drawPixel(xb,   yb+1, 0);
+  arduboy.drawPixel(xb+1, yb+1, 0);
+  arduboy.setCursor(52, 42);
+  arduboy.print( "Game");
+  arduboy.setCursor(52, 54);
+  arduboy.print("Over");
+  arduboy.display();
   delay(4000);
 }

@@ -313,17 +313,17 @@
 {
   paused = true;
   //Draw pause to the screen
-  display.setCursor(52, 45);
-  display.print("PAUSE");
-  display.display();
+  arduboy.setCursor(52, 45);
+  arduboy.print("PAUSE");
+  arduboy.display();
   while (paused)
   {
     delay(150);
     //Unpause if FIRE is pressed
-    pad2 = display.pressed(B_BUTTON);
+    pad2 = arduboy.pressed(B_BUTTON);
     if (pad2 > 1 && oldpad2 == 0 && released)
     {
-        display.fillRect(52, 45, 30, 11, 0);
+        arduboy.fillRect(52, 45, 30, 11, 0);

         paused=false;
     }
@@ -335,19 +335,19 @@
 {
   score += (level*10);
   sprintf(text, "SCORE:%u", score);
-  display.setCursor(80, 90);
-  display.print(text);
+  arduboy.setCursor(80, 90);
+  arduboy.print(text);
 }

 void newLevel(){
   //Undraw paddle
-  display.drawRect(xPaddle, 63, 11, 1, 0);
+  arduboy.drawRect(xPaddle, 63, 11, 1, 0);

   //Undraw ball
-  display.drawPixel(xb,   yb,   0);
-  display.drawPixel(xb+1, yb,   0);
-  display.drawPixel(xb,   yb+1, 0);
-  display.drawPixel(xb+1, yb+1, 0);
+  arduboy.drawPixel(xb,   yb,   0);
+  arduboy.drawPixel(xb+1, yb,   0);
+  arduboy.drawPixel(xb,   yb+1, 0);
+  arduboy.drawPixel(xb+1, yb+1, 0);

   //Alter various variables to reset the game
   xPaddle = 54;
@@ -360,7 +360,7 @@
     for (byte column = 0; column < 13; column++)
     {
       isHit[row][column] = false;
-      display.drawRect(10*column, 2+6*row, 8, 4, 1);
+      arduboy.drawRect(10*column, 2+6*row, 8, 4, 1);
     }
   }

@@ -369,8 +369,8 @@

   //Draws the initial score
   sprintf(text, "SCORE:%u", score);
-  display.setCursor(80, 90);
-  display.print(text);
+  arduboy.setCursor(80, 90);
+  arduboy.print(text);
 }

 //Used to delay images while reading button input
@@ -379,7 +379,7 @@
   for(int i = 0; i < n; i++)
   {
     delay(15);
-    pad = display.pressed(B_BUTTON);
+    pad = arduboy.pressed(B_BUTTON);
     if(pad == 1 && oldpad == 0)
     {
       oldpad3 = 1; //Forces pad loop 3 to run once
@@ -399,17 +399,17 @@
   // is 5 bytes long:  3 bytes for initials and two bytes for score.
   int address = file*10*5;
   byte hi, lo;
-  display.clearDisplay();
-  display.setCursor(32, 0);
-  display.print("HIGH SCORES");
-  display.display();
+  arduboy.clearDisplay();
+  arduboy.setCursor(32, 0);
+  arduboy.print("HIGH SCORES");
+  arduboy.display();

   for(int i = 0; i < 10; i++)
   {
     sprintf(text, "%2d", i+1);
-    display.setCursor(x,y+(i*8));
-    display.print( text);
-    display.display();
+    arduboy.setCursor(x,y+(i*8));
+    arduboy.print( text);
+    arduboy.display();
     hi = EEPROM.read(address + (5*i));
     lo = EEPROM.read(address + (5*i) + 1);

@@ -429,9 +429,9 @@
     if (score > 0)
     {
       sprintf(text, "%c%c%c %u", initials[0], initials[1], initials[2], score);
-      display.setCursor(x + 24, y + (i*8));
-      display.print(text);
-      display.display();
+      arduboy.setCursor(x + 24, y + (i*8));
+      arduboy.print(text);
+      arduboy.display();
     }
   }
   if (pollFireButton(300))
@@ -439,18 +439,18 @@
     return true;
   }
   return false;
-  display.display();
+  arduboy.display();
 }

 boolean titleScreen()
 {
   //Clears the screen
-  display.clearDisplay();
-  display.setCursor(16,22);
-  display.setTextSize(2);
-  display.print("ARAKNOID");
-  display.setTextSize(1);
-  display.display();
+  arduboy.clearDisplay();
+  arduboy.setCursor(16,22);
+  arduboy.setTextSize(2);
+  arduboy.print("ARAKNOID");
+  arduboy.setTextSize(1);
+  arduboy.display();
   if (pollFireButton(25))
   {
     return true;
@@ -460,24 +460,24 @@
   for(byte i = 0; i < 5; i++)
   {
     //Draws "Press FIRE"
-    //display.bitmap(31, 53, fire);  display.display();
-    display.setCursor(31, 53);
-    display.print("PRESS FIRE!");
-    display.display();
+    //arduboy.bitmap(31, 53, fire);  arduboy.display();
+    arduboy.setCursor(31, 53);
+    arduboy.print("PRESS FIRE!");
+    arduboy.display();

     if (pollFireButton(50))
     {
       return true;
     }
     //Removes "Press FIRE"
-    display.clearDisplay();
-    display.setCursor(16,22);
-    display.setTextSize(2);
-    display.print("ARAKNOID");
-    display.setTextSize(1);
-    display.display();
-
-    display.display();
+    arduboy.clearDisplay();
+    arduboy.setCursor(16,22);
+    arduboy.setTextSize(2);
+    arduboy.print("ARAKNOID");
+    arduboy.setTextSize(1);
+    arduboy.display();
+
+    arduboy.display();
     if (pollFireButton(25))
     {
       return true;
@@ -492,7 +492,7 @@
 {
   char index = 0;

-  display.clearDisplay();
+  arduboy.clearDisplay();

   initials[0] = ' ';
   initials[1] = ' ';
@@ -500,29 +500,29 @@

   while (true)
   {
-    display.display();
-    display.clearDisplay();
-
-    display.setCursor(16,0);
-    display.print("HIGH SCORE");
+    arduboy.display();
+    arduboy.clearDisplay();
+
+    arduboy.setCursor(16,0);
+    arduboy.print("HIGH SCORE");
     sprintf(text, "%u", score);
-    display.setCursor(88, 0);
-    display.print(text);
-    display.setCursor(56, 20);
-    display.print(initials[0]);
-    display.setCursor(64, 20);
-    display.print(initials[1]);
-    display.setCursor(72, 20);
-    display.print(initials[2]);
+    arduboy.setCursor(88, 0);
+    arduboy.print(text);
+    arduboy.setCursor(56, 20);
+    arduboy.print(initials[0]);
+    arduboy.setCursor(64, 20);
+    arduboy.print(initials[1]);
+    arduboy.setCursor(72, 20);
+    arduboy.print(initials[2]);
     for(byte i = 0; i < 3; i++)
     {
-      display.drawLine(56 + (i*8), 27, 56 + (i*8) + 6, 27, 1);
-    }
-    display.drawLine(56, 28, 88, 28, 0);
-    display.drawLine(56 + (index*8), 28, 56 + (index*8) + 6, 28, 1);
+      arduboy.drawLine(56 + (i*8), 27, 56 + (i*8) + 6, 27, 1);
+    }
+    arduboy.drawLine(56, 28, 88, 28, 0);
+    arduboy.drawLine(56 + (index*8), 28, 56 + (index*8) + 6, 28, 1);
     delay(150);

-    if (display.pressed(RIGHT_BUTTON))
+    if (arduboy.pressed(RIGHT_BUTTON))
     {
       index--;
       if (index < 0)
@@ -534,7 +534,7 @@
       }
     }

-    if (display.pressed(LEFT_BUTTON))
+    if (arduboy.pressed(LEFT_BUTTON))
     {
       index++;
       if (index > 2)
@@ -545,7 +545,7 @@
       }
     }

-    if (display.pressed(UP_BUTTON))
+    if (arduboy.pressed(UP_BUTTON))
     {
       initials[index]++;
       tone(A2, 523, 250);
@@ -568,7 +568,7 @@
       }
     }

-    if (display.pressed(DOWN_BUTTON))
+    if (arduboy.pressed(DOWN_BUTTON))
     {
       initials[index]--;
       tone(A2, 523, 250);
@@ -586,7 +586,7 @@
       }
     }

-    if (display.pressed(B_BUTTON))
+    if (arduboy.pressed(B_BUTTON))
     {
       if (index < 2)
       {
@@ -674,7 +674,7 @@

 void loop()
 {
-  display.display();
+  arduboy.display();

   //Title screen loop switches from title screen
   //and high scores until FIRE is pressed
@@ -691,8 +691,8 @@
   if (!initialDraw)
   {
     //Clears the screen
-    display.display();
-    display.clearDisplay();
+    arduboy.display();
+    arduboy.clearDisplay();
     //Selects Font
     //Draws the new level
     newLevel();
@@ -704,7 +704,7 @@
     drawPaddle();

     //Pause game if FIRE pressed
-    pad = display.pressed(B_BUTTON);
+    pad = arduboy.pressed(B_BUTTON);

     if(pad >1 && oldpad==0 && released)
     {
@@ -729,7 +729,7 @@
       enterHighScore(2);
     }

-    display.clearDisplay();
+    arduboy.clearDisplay();
     initialDraw=false;
     start=false;
     lives=3;


x360 fixes

x360 fixes

--- gamecubecontroller.ino
+++ gamecubecontroller.ino
@@ -166,7 +166,11 @@
   pinMode(ledPinID, OUTPUT);

   EEPROM8_init();
-  int i = EEPROM8_getValue(EEPROM_VARIABLE_INJECTION_MODE);
+  int i;
+  if (debounceDown.getRawState() && debounceUp.getRawState())
+    i = 0;
+  else
+    i = EEPROM8_getValue(EEPROM_VARIABLE_INJECTION_MODE);
   if (i < 0)
     injectionMode = 0;
   else


Let the Arduino + WiFly do it all

Let the Arduino + WiFly do it all

--- RightpointLabs.Pourcast.Arduino/RightpointLabs.Pourcast.Arduino.ino
+++ RightpointLabs.Pourcast.Arduino/RightpointLabs.Pourcast.Arduino.ino
@@ -1,3 +1,16 @@
+#define DEBUG_LEVEL 5
+
+#include <SPI.h>
+#include <Configuration.h>
+#include <Debug.h>
+#include <ParsedStream.h>
+#include <SpiUart.h>
+#include <WiFly.h>
+#include <WiFlyClient.h>
+#include <WiFlyDevice.h>
+#include <WiFlyServer.h>
+#include <_Spi.h>
+
 const long _startThreshold = 30;
 const long _continueThreshold = 5;
 class Reporter {
@@ -58,6 +71,70 @@
   }
 }

+class MultiReporter: public Reporter {
+public:
+  MultiReporter(Reporter* reporter1, Reporter* reporter2, Reporter* reporter3);
+  virtual void ReportStop(long pulses);
+  virtual void ReportContinue(long pulses);
+  virtual void ReportStart(long pulses);
+  virtual void ReportIgnore(long pulses);
+private:
+  Reporter* _reporter1;
+  Reporter* _reporter2;
+  Reporter* _reporter3;
+};
+
+MultiReporter::MultiReporter(Reporter* reporter1, Reporter* reporter2, Reporter* reporter3) {
+  _reporter1 = reporter1;
+  _reporter2 = reporter2;
+  _reporter3 = reporter3;
+}
+
+void MultiReporter::ReportStop(long pulses){
+  if(_reporter1 != NULL) {
+    _reporter1->ReportStop(pulses);
+  }
+  if(_reporter2 != NULL) {
+    _reporter2->ReportStop(pulses);
+  }
+  if(_reporter3 != NULL) {
+    _reporter3->ReportStop(pulses);
+  }
+}
+void MultiReporter::ReportContinue(long pulses) {
+  if(_reporter1 != NULL) {
+    _reporter1->ReportContinue(pulses);
+  }
+  if(_reporter2 != NULL) {
+    _reporter2->ReportContinue(pulses);
+  }
+  if(_reporter3 != NULL) {
+    _reporter3->ReportContinue(pulses);
+  }
+}
+void MultiReporter::ReportStart(long pulses){
+  if(_reporter1 != NULL) {
+    _reporter1->ReportStart(pulses);
+  }
+  if(_reporter2 != NULL) {
+    _reporter2->ReportStart(pulses);
+  }
+  if(_reporter3 != NULL) {
+    _reporter3->ReportStart(pulses);
+  }
+}
+void MultiReporter::ReportIgnore(long pulses){
+  if(_reporter1 != NULL) {
+    _reporter1->ReportIgnore(pulses);
+  }
+  if(_reporter2 != NULL) {
+    _reporter2->ReportIgnore(pulses);
+  }
+  if(_reporter3 != NULL) {
+    _reporter3->ReportIgnore(pulses);
+  }
+}
+
 class SerialReporter: public Reporter {
 public:
   SerialReporter(byte number);
@@ -99,16 +176,127 @@
 }

+class LEDReporter: public Reporter {
+public:
+  LEDReporter(byte pin);
+  virtual void ReportStop(long pulses);
+  virtual void ReportContinue(long pulses);
+  virtual void ReportStart(long pulses);
+  virtual void ReportIgnore(long pulses);
+private:
+  byte _pin;
+};
+
+LEDReporter::LEDReporter(byte pin) {
+  _pin = pin;
+  pinMode(_pin, OUTPUT);
+}
+
+void LEDReporter::ReportStop(long pulses){
+  digitalWrite(_pin, LOW);
+}
+void LEDReporter::ReportContinue(long pulses) {
+}
+void LEDReporter::ReportStart(long pulses){
+  digitalWrite(_pin, HIGH);
+}
+void LEDReporter::ReportIgnore(long pulses){
+}
+
+class WiFlyHttp  {
+  public:
+    WiFlyHttp(const char* host, int port, byte pin);
+    void MakeRequest(String url);
+  private:
+    WiFlyClient* _client;
+    byte _pin;
+};
+WiFlyHttp::WiFlyHttp(const char* host, int port, byte pin) {
+  _client = new WiFlyClient(host, port);
+  _pin = pin;
+  pinMode(_pin, OUTPUT);
+  digitalWrite(_pin, HIGH);
+}
+
+void WiFlyHttp::MakeRequest(String url){
+  digitalWrite(_pin, LOW);
+  Serial.println(url);
+  if (_client->connect()) {
+    _client->println("GET " + url + " HTTP/1.0");
+    _client->println();
+    while(_client->available() || _client->connected()) {
+      Serial.print(_client->read());
+    }
+  }
+  digitalWrite(_pin, HIGH);
+}
+
+class WiFlyReporter: public Reporter {
+public:
+  WiFlyReporter(WiFlyHttp* http, String tapId);
+  virtual void ReportStop(long pulses);
+  virtual void ReportContinue(long pulses);
+  virtual void ReportStart(long pulses);
+  virtual void ReportIgnore(long pulses);
+  void Heartbeat();
+private:
+  void MakeRequest(String url);
+  String _tapId;
+  WiFlyHttp* _http;
+};
+
+WiFlyReporter::WiFlyReporter(WiFlyHttp* http, String tapId) {
+  _http = http;
+  _tapId = tapId;
+}
+
+void WiFlyReporter::MakeRequest(String url){
+  _http->MakeRequest(url);
+}
+void WiFlyReporter::ReportStop(long pulses){
+  MakeRequest("/api/Tap/" + _tapId + "/StopPour?volume=" + (pulses / 1000));
+}
+void WiFlyReporter::ReportContinue(long pulses) {
+  MakeRequest("/api/Tap/" + _tapId + "/Pouring?volume=" + (pulses / 1000));
+}
+void WiFlyReporter::ReportStart(long pulses){
+  MakeRequest("/api/Tap/" + _tapId + "/StartPour");
+}
+void WiFlyReporter::ReportIgnore(long pulses){
+}
+void WiFlyReporter::Heartbeat(){
+  MakeRequest("/api/Status/heartbeat");
+}
+
+
 Tap* tap1;
 Tap* tap2;
+WiFlyHttp* http;

 // prep - initialize serial (TX on pin 1) and wire up the interrupts for pulses from the taps (pins 2 and 3)
 void setup() {
   Serial.begin(9600);
   while(!Serial);
-  tap1 = new Tap(new SerialReporter(1));
+
+  Serial.println("Starting");
+  WiFly.begin();
+  Serial.println("Joining");
+  if (!WiFly.join("Rightpoint-Guest", "RP@29NWacker")) {
+     // Handle the failure
+     Serial.println("Failed to connect");
+  }
+  else{
+     Serial.println("Connected");
+  }
+
+  WiFly.configure(WIFLY_BAUD, 38400);
+
+  Serial.println(WiFly.ip());
+
+  http = new WiFlyHttp("pourcast.labs.rightpoint.com", 80, 9);
+  tap1 = new Tap(new MultiReporter(new SerialReporter(1), new LEDReporter(10), new WiFlyReporter(http, "535c61a951aa0405287989ec")));
   attachInterrupt(0, tap1Pulse, RISING);
-  tap2 = new Tap(new SerialReporter(2));
+  tap2 = new Tap(new MultiReporter(new SerialReporter(2), new LEDReporter(11), new WiFlyReporter(http, "537d28db51aa04289027cde5")));
   attachInterrupt(1, tap2Pulse, RISING);
 }


Whisker bump

Whisker bump

--- alan/alan.ino
+++ alan/alan.ino
@@ -157,6 +157,8 @@
   A_STOPPED,
   A_TRUNDLE,
   A_PINGSEARCH,
+  A_WHISKERSEARCH_LEFT,
+  A_WHISKERSEARCH_RIGHT,
   A_DANCE1,
   A_DANCE2,
   A_BORED,
@@ -362,30 +364,56 @@

       break;

+    case A_WHISKERSEARCH_LEFT:
     case A_PINGSEARCH:
       switch (motion_state) {
         case M_STOP:
            // reverse for 1 second
            actionTimeoutStart(1000);
            motionRev();
-           Serial.println("SEARCH REVERSE");
+           Serial.println("REVERSE");
           break;

         case M_REV:
           if (action_done) {
-            Serial.println("SEARCH LEFT");
-            // Start pinging
-            pingStart();
-
-            actionTimeoutStart(500); //@todo not fake the search!
+            long randNumber = random(400, 600);
+            //Serial.println(randNumber);
+            // Rotate for a random amount of time.
+            actionTimeoutStart(randNumber);
+            Serial.println("ROTATE LEFT");
             motionRotateLeft();
           }
           break;

         case M_ROTATE_LEFT:
           if (action_done) {
-            Serial.println("SEARCH RIGHT");
-            actionTimeoutStart(2000); //@todo not fake the search!
+            Serial.println("SEARCH DONE");
+            // Trundle away
+            actionTrundle();
+          }
+          break;
+
+        case M_ROTATE_RIGHT:
+          break;
+      }
+      break;
+
+    case A_WHISKERSEARCH_RIGHT:
+        switch (motion_state) {
+        case M_STOP:
+           // reverse for 1 second
+           actionTimeoutStart(1000);
+           motionRev();
+           Serial.println("REVERSE");
+          break;
+
+        case M_REV:
+          if (action_done) {
+            long randNumber = random(400, 600);
+            //Serial.println(randNumber);
+            // Rotate for a random amount of time.
+            actionTimeoutStart(randNumber);
+            Serial.println("ROTATE RIGHT");
             motionRotateRight();
           }
           break;
@@ -393,17 +421,11 @@
         case M_ROTATE_RIGHT:
           if (action_done) {
             Serial.println("SEARCH DONE");
-            // Done the sweep, stop.
-            actionStop();
-
-            // Stop pinging
-            pingStop();
-
-
             // Trundle away
             actionTrundle();
           }
           break;
+
       }
       break;

@@ -465,6 +487,26 @@
   Serial.println("SEARCHING");
   // Set the state, so the action can be handeled by the state machine.
   action_state = A_PINGSEARCH;
+}
+
+/**
+ * Look for somewhare to go.
+ */
+void actionWhiskerSearchLeft()
+{
+  Serial.println("WHISKERSEARCH LEFT");
+  // Set the state, so the action can be handeled by the state machine.
+  action_state = A_WHISKERSEARCH_LEFT;
+}
+
+/**
+ * Look for somewhare to go.
+ */
+void actionWhiskerSearchRight()
+{
+  Serial.println("WHISKERSEARCH RIGHT");
+  // Set the state, so the action can be handeled by the state machine.
+  action_state = A_WHISKERSEARCH_RIGHT;
 }

 void actionTimeoutStart(int duration)
@@ -575,22 +617,29 @@

   // If the reading of the thumbstick is not the same as when calibrated,
   // we've hit something.
-  if (action_state == A_PINGSEARCH) {
-
-    // Doing a ping search already, so don't interfere with a whiskers bump.
-
-  } else if ( (val > whiskers_horiz_default + whiskers_threshold) || (val < whiskers_horiz_default - whiskers_threshold) ) {
+  if (action_state == A_PINGSEARCH || action_state == A_WHISKERSEARCH_LEFT || action_state == A_WHISKERSEARCH_RIGHT) {
+
+    // Doing a search already, so don't interfere with a whiskers bump.
+
+  } else if (val > whiskers_horiz_default + whiskers_threshold) {
     Serial.println(whiskers_horiz_default);
-       Serial.println("BUMP!");
-
-      // Don't hit the obstacle.
-      motionStop();
-
-      soundDamage();
-
-      actionPingSearch();
+    Serial.println("BUMP LEFT!");
+    // Don't hit the obstacle.
+    motionStop();
+    soundDamage();
+
+    actionWhiskerSearchLeft();
+
+  } else if (val < whiskers_horiz_default - whiskers_threshold) {
+    Serial.println(whiskers_horiz_default);
+    Serial.println("BUMP RIGHT!");
+    // Don't hit the obstacle.
+    motionStop();
+    soundDamage();
+
+    actionWhiskerSearchRight();
   }
-
+
 }

 /********************************************************************************


use pin 2 instead of 13

use pin 2 instead of 13

--- Christmas/Christmas.ino
+++ Christmas/Christmas.ino
@@ -4,13 +4,11 @@
    by Ben Torkington <ben@torkington.com>

    16 December 2016
-
-
 */

 // change the following two lines to match the number of LEDs you have connected
-#define PINMIN 3      // the first pin with an LED connected
-#define PINMAX 13     // the last pin with an LED connected
+#define PINMIN 2      // the first pin with an LED connected
+#define PINMAX 12     // the last pin with an LED connected

 // the setup function runs once when you press reset or power the board
 void setup() {
@@ -48,11 +46,11 @@
   digitalWrite(7, value);
   digitalWrite(9, value);
   digitalWrite(11, value);
-  digitalWrite(13, value);
 }

 // set all of the Green LEDs at once, either HIGH or LOW
 void allGreen(int value) {
+  digitalWrite(2, value);
   digitalWrite(4, value);
   digitalWrite(6, value);
   digitalWrite(8, value);
@@ -160,5 +158,3 @@
   // now we start all over again!
   // Merry Christmas!
 }
-
-


ajout comments temp pour Louis

ajout comments temp pour Louis

--- scripts-arduino/bp_led_lp.ino
+++ scripts-arduino/bp_led_lp.ino
@@ -5,7 +5,7 @@
 const String CONST_TYPE = "01";     // the id of press button

 // ######## DEF ########
-#define LONGPRESS_LEN    25         // Min nr of loops for a long press
+#define LONGPRESS_LEN    40         // Min nr of loops for a long press
 #define DELAY            20        // Delay per loop in ms

 // ######## VAR ########
@@ -33,11 +33,12 @@

 // ######## LOOP ########
 void loop(){
-    boolean eventResult = handle_button();
+    int eventResult = handle_button();

     switch(eventResult){
         case EV_NONE:               // if nothing append
             //TODO : Ne rien faire de particulier, ou attendre la fin d'une synchronisation
+
             break;
         case EV_SHORTPRESS:         // if short press
             //TODO : Allumer ou éteindre la LED (a check)
@@ -50,6 +51,7 @@
             break;
         case EV_LONGPRESS:          // if long press
             //TODO : Faire clignoter la LED et attendre la fin d'une synchronisation.
+            Serial.println(CONST_ID+":"+CONST_TYPE+":4");
             break;
     }
     delay(DELAY);
@@ -58,22 +60,22 @@
 // ####### Function ########
 int handle_button(){
     int event;
-    int button_now_pressed = !digitalRead(BUTTON_PIN);  // pin low -> pressed
+    int button_now_pressed = !digitalRead(BUTTON_PIN); // pin low -> pressed

-    if (!button_now_pressed && button_was_pressed) {    // TODO : TEMP COMMENT : Si button n'est pas pressé mais l'était avant
-        if (button_pressed_counter < LONGPRESS_LEN)     // et si le counter n'avait pas dépassé la limite counter
-            event = EV_SHORTPRESS;                      // alors c'est un short press
-        else{
-            event = EV_LONGPRESS;                       // Si il a dépassé la limite alors long press
-            Serial.println(CONST_ID+":"+CONST_TYPE+":4");
-        }
+    if (!button_now_pressed && button_was_pressed) {
+        if (button_pressed_counter < LONGPRESS_LEN)
+            event = EV_SHORTPRESS;
+        else
+            event = EV_LONGPRESS;
     }
-    else                                                // Sinon si le bouton est pressé ou n'était pas pressé avant
-            event = EV_NONE;
-    if (button_now_pressed)                             // Si le button est pressé alors on incremente le counter
+    else
+        event = EV_NONE;
+
+    if (button_now_pressed)
         ++button_pressed_counter;
-    else                                                // Sinon si le button n'est pas pressé
-        button_pressed_counter = 0;                     // On met le counter a zéro
+    else
+        button_pressed_counter = 0;
+
     button_was_pressed = button_now_pressed;
     return event;
 }
@@ -84,6 +86,7 @@
     digitalWrite(LED_PIN, HIGH);
     Serial.println(CONST_ID+":"+CONST_TYPE+":1");
 }
+
 // turn LED Off:
 void turnOff(){
     digitalWrite(LED_PIN, LOW);


Fixed type

Fixed type

--- arduino/src/IRrecvSerial.ino
+++ arduino/src/IRrecvSerial.ino
@@ -1,7 +1,7 @@
 #include <IRremote.h>

 int RECV_PIN = 11;
-int WAIT = 50;
+unsigned int WAIT = 50;

 IRrecv irrecv(RECV_PIN);


Print error messages to Serial as well

Print error messages to Serial as well


formatting

formatting

--- main/sketch/arduino/arduino.ino
+++ main/sketch/arduino/arduino.ino
@@ -15,7 +15,7 @@
 LiquidCrystal lcd(RS, EN, D4, D5, D6, D7);

 const uint8_t __degree__ = 0;
-byte symbolDegree[8] ={  B00001100,
+byte symbolDegree[8] ={   B00001100,
                           B00010010,
                           B00010010,
                           B00001100,


Higher debounce on anemometer. Divide by 2 as it provides two interrupts per rotation, apparently.


Fixed typos in MailboxReadMessage example

--- libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino
+++ libraries/Bridge/examples/MailboxReadMessage/MailboxReadMessage.ino
@@ -1,8 +1,8 @@
 /*
   Read Messages from the Mailbox

- This example for the Arduino Yún sdemonstrate how to
- read the messages queue, called Mailbox using the
+ This example for the Arduino Yún shows how to
+ read the messages queue, called Mailbox, using the
  Bridge library.
  The messages can be sent to the queue through REST calls.
  Appen the message in the URL after the keyword "/mailbox".


Changed Serial Baud for convenience

Changed Serial Baud for convenience

Also added a comment with code to set clock.

--- src/clock.ino
+++ src/clock.ino
@@ -17,15 +17,15 @@
 #ifndef ESP8266
   while (!Serial); // for Leonardo/Micro/Zero
 #endif
-  Serial.begin(57600);
+  Serial.begin(9600);
   if (! rtc.begin()) {
     Serial.println("Couldn't find RTC");
     while (1);
   }
   if (! rtc.isrunning()) {
     Serial.println("RTC is NOT running!");
+  //  rtc.adjust(DateTime(__DATE__, __TIME__));
   }
-
   alarm = new AlarmClock();
   display = new Display();
   pinMode(VIEW_BUTTON, INPUT_PULLUP);


Only forward dropping when in alert mode

Preventing this message to never be stopped being send around

--- resilient-network.ino
+++ resilient-network.ino
@@ -157,11 +157,13 @@
         }
         break;
       case DROPPING_CONNECTOR: // some connector in the network is dropped
-        // relax alert state and timer
-        removeTimer(alertTimer); // cancel dropping connector
-        alertState = false;
-        // propagate signal though network
-        for (int j=0; j<NUM_CONN; j++) if (j!=i) bus[j]->write(c);
+        if(alertState) {
+          // relax alert state and timer
+          removeTimer(alertTimer); // cancel dropping connector
+          alertState = false;
+          // propagate signal though network
+          for (int j=0; j<NUM_CONN; j++) if (j!=i) bus[j]->write(c);
+        }
         break;
       default: // distance to source
         if (!isSource) {


fix a spelling error of JsonParserExample.ino

--- examples/JsonParserExample/JsonParserExample.ino
+++ examples/JsonParserExample/JsonParserExample.ino
@@ -19,9 +19,9 @@
   StaticJsonDocument<200> doc;

   // StaticJsonDocument<N> allocates memory on the stack, it can be
-  // replaced by DynamicJsonObject which allocates in the heap.
+  // replaced by DynamicJsonDocument which allocates in the heap.
   //
-  // DynamicJsonObject doc(200);
+  // DynamicJsonDocument doc(200);

   // JSON input string.
   //


fixed commenting

fixed commenting

--- examples/netstrings_decode/netstrings_decode.ino
+++ examples/netstrings_decode/netstrings_decode.ino
@@ -1,4 +1,4 @@
-/* Read a string from Serial (do NOT send a new line after it) and print out the equivalent string it contains
+/* Read a Netstring from Serial (do NOT send a new line after it) and print out the string it contains
 "error" is printed when the netstring supplied is empty.

 Example


update example

update example

--- examples/ESP32-DMX_rdm/ESP32-DMX_rdm.ino
+++ examples/ESP32-DMX_rdm/ESP32-DMX_rdm.ino
@@ -117,6 +117,7 @@
 }

 void artTodRequestReceived(uint8_t* pdata) {
+  rdm_discovery_enable = 10;
   artNetInterface->send_art_tod(&aUDP, tableOfDevices.rawBytes(), tableOfDevices.count());
 }

@@ -334,26 +335,15 @@
   //debugging

-  uint8_t bootStatus = DMXWiFiConfig.begin(1);
-  uint8_t dhcpStatus = 0;
+  uint8_t bootStatus = DMXWiFiConfig.begin(1);//aparently need to read from persistent to be able to write to it
+  uint8_t dhcpStatus = 0;                     //hence, read in begin and replace below if startup pin is low

   if ( digitalRead(STARTUP_MODE_PIN) == 0 ) {
-    DMXWiFiConfig.initConfig();
-    //DMXWiFiConfig.commitToPersistentStore();
+    DMXWiFiConfig.initConfig();
   }

   dmx_direction = DMXWiFiConfig.inputToNetworkMode();
   rdm_enabled   = DMXWiFiConfig.rdmMode();
-
-  if ( dmx_direction == OUTPUT_FROM_NETWORK_MODE ) {					      // DMX Driver startup based on direction flag
-    Serial.println("starting DMX");
-    ESP32DMX.startRDM(DIRECTION_PIN);
-  } else {
-    Serial.println("starting DMX input");
-    ESP32DMX.setDirectionPin(DIRECTION_PIN);
-    ESP32DMX.setDataReceivedCallback(&gotDMXCallback);
-    ESP32DMX.startInput();
-  }

   if ( DMXWiFiConfig.APMode() ) {            // WiFi startup
     Serial.print("AP_MODE ");
@@ -385,11 +375,24 @@
     while (WiFi.status() != WL_CONNECTED)  {
       delay(100);
       blinkLED();
+
     }

   }
   Serial.print("wifi started ");
   Serial.println(WiFi.localIP());
+
+  //------------------- Initialize serialDMX  -------------------
+
+  if ( dmx_direction == OUTPUT_FROM_NETWORK_MODE ) {                // DMX Driver startup based on direction flag
+    Serial.println("starting DMX");
+    ESP32DMX.startRDM(DIRECTION_PIN);
+  } else {
+    Serial.println("starting DMX input");
+    ESP32DMX.setDirectionPin(DIRECTION_PIN);
+    ESP32DMX.setDataReceivedCallback(&gotDMXCallback);
+    ESP32DMX.startInput();
+  }

   //------------------- Initialize network<->DMX interfaces -------------------

@@ -439,6 +442,10 @@

   Serial.println(" setup complete.");
   blinkLED();
+
+  // trial:  Increase loop priority to 2 above DMX, which is 1
+  vTaskPrioritySet(xTaskGetCurrentTaskHandle(), 2);
+
 } //setup

 /************************************************************************
@@ -566,11 +573,15 @@
 		if ( art_packet_result == RESULT_NONE ) {
 			checkConfigReceived(artNetInterface, &aUDP);
 		}
+    esp_task_wdt_feed();
+    vTaskDelay(1);

 		acn_packet_result = sACNInterface->readDMXPacket(&sUDP);
 		if ( acn_packet_result == RESULT_NONE ) {
 			checkConfigReceived(sACNInterface, &sUDP);
 		}
+    esp_task_wdt_feed();
+    vTaskDelay(1);

 		if ( (art_packet_result == RESULT_DMX_RECEIVED) || (acn_packet_result == RESULT_DMX_RECEIVED) ) {
 			copyDMXToOutput();
@@ -595,7 +606,9 @@
 		}

 	}
+
   esp_task_wdt_feed();
-  taskYIELD();
+  vTaskDelay(1);
+  //taskYIELD();
 }// loop()


Testing LCD SR3W and Rotary Encoder controller with LCD Menu Handler.

--- examples/LCD/CosaLCDmenu/CosaLCDmenu.ino
+++ examples/LCD/CosaLCDmenu/CosaLCDmenu.ino
@@ -38,8 +38,9 @@

 // LCD Device  ---------------------------------------------------------------
 // Select port type to use with the LCD device driver.
-HD44780::Port4b port;
+// HD44780::Port4b port;
 // HD44780::SR3W port;
+HD44780::SR4W port;
 HD44780 lcd(&port);

 // Menu Action ---------------------------------------------------------------
@@ -151,8 +152,8 @@
 // Control the menu walker with keypad (analog pin) or rotary encoder with
 // push button.
 Menu::Walker walker(&lcd, &root_menu);
-Menu::KeypadController keypad(&walker);
-// Menu::RotaryController rotary(&walker);
+// Menu::KeypadController keypad(&walker);
+Menu::RotaryController rotary(&walker);

 void setup()
 {
@@ -161,5 +162,5 @@
   lcd.puts_P(PSTR("CosaLCDmenu: started"));
   SLEEP(2);
   walker.begin();
-  // rotary.begin();
+  rotary.begin();
 }


Add code to be compatible with Teensy 3.1

--- XV_Lidar_Controller.ino
+++ XV_Lidar_Controller.ino
@@ -61,7 +61,14 @@

 SerialCommand sCmd;

-const int ledPin = 11;
+
+  #if defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY)  // if Teensy 2.0
+  const int ledPin = 11;
+  #endif
+
+  #if defined(__MK20DX256__)  // if Teensy 3.1
+  const int ledPin = 13;
+  #endif
 boolean ledState = LOW;

 void setup() {
@@ -71,7 +78,13 @@
   }
   pinMode(xv_config.motor_pwm_pin, OUTPUT);
   Serial.begin(115200);  // USB serial
+  #if defined(__AVR_ATmega32U4__) && defined(CORE_TEENSY) // if Teensy 2.0
   Serial1.begin(115200);  // XV LDS data
+  #endif
+
+  #if defined(__MK20DX256__) // if Teensy 3.1
+  Serial1.begin(115200);  // XV LDS data
+  #endif

   Timer3.initialize(30); // set PWM frequency to 32.768kHz


cosmetics

cosmetics

--- status.ino
+++ status.ino
@@ -10,7 +10,6 @@
 #define RESPONSE_SCALE_UP 2
 #define RESPONSE_SCALE_DOWN 3
 #define RESPONSE_RESTART 4
-

 SparkButton strip = SparkButton();


update to wifi101 library

update to wifi101 library

--- examples/mqtt_winc1500/mqtt_winc1500.ino
+++ examples/mqtt_winc1500/mqtt_winc1500.ino
@@ -11,16 +11,13 @@
 #include <SPI.h>
 #include "Adafruit_MQTT.h"
 #include "Adafruit_MQTT_Client.h"
-#include <Adafruit_WINC1500.h>
-
+#include <WiFi101.h>

 /************************* WiFI Setup *****************************/
 #define WINC_CS   8
 #define WINC_IRQ  7
 #define WINC_RST  4
 #define WINC_EN   2     // or, tie EN to VCC
-
-Adafruit_WINC1500 WiFi(WINC_CS, WINC_IRQ, WINC_RST);

 char ssid[] = "yournetwork";     //  your network SSID (name)
 char pass[] = "yourpassword";    // your network password (use for WPA, or use as key for WEP)
@@ -38,7 +35,7 @@
 /************ Global State (you don't need to change this!) ******************/

 //Set up the wifi client
-Adafruit_WINC1500Client client;
+WiFiClient client;

 Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

@@ -60,10 +57,7 @@

 void setup() {
-#ifdef WINC_EN
-  pinMode(WINC_EN, OUTPUT);
-  digitalWrite(WINC_EN, HIGH);
-#endif
+  WiFi.setPins(WINC_CS, WINC_IRQ, WINC_RST, WINC_EN);

   while (!Serial);
   Serial.begin(115200);
@@ -154,4 +148,4 @@
        delay(5000);  // wait 5 seconds
   }
   Serial.println("MQTT Connected!");
-}+}


Minor edit

Minor edit

--- arduino/gslc_ex04_ard/gslc_ex04_ard.ino
+++ arduino/gslc_ex04_ard/gslc_ex04_ard.ino
@@ -225,4 +225,3 @@
   }
 }

-


liquidTraffic | added bounds and pulse reaction

--- excercises/xiel/03_remote-car-hack/liquidTraffic_03_remoteservo_with_pulse/liquidTraffic_03_remoteservo_with_pulse.ino
+++ excercises/xiel/03_remote-car-hack/liquidTraffic_03_remoteservo_with_pulse/liquidTraffic_03_remoteservo_with_pulse.ino
@@ -7,39 +7,52 @@
  */

 /*
- * just a test to get forward / backward signals from the toy car board
- * added servo
  * now moves accordingly to remote control
  */

 //servo
 Servo myservo;
+
+int servoMin = 45;
+int servoMax = 105;
+
 int servoPin = 9;
-int servoCurrentPos = 90;
+int servoCurrentPos = servoMin;
+int servoDirBefore = 0;
 int servoDir = 0;
-int servoStep = 5;
+long updateEvery = 1000 * 10;
+long latestDirUpdate = updateEvery * -1;
+int servoStep = 1;
+int servoLockPosEvery = 10;
+int lockPosToReach = servoCurrentPos;

 //forward
-int analogFwdPin = 0;
+int analogFwdPin = A0;
 int valFwd = 0;

 //backwards
-int analogBwdPin = 1;
+int analogBwdPin = A1;
 int valBwd = 0;

 //pulse (left)
-int pulsePin = 2;
+int pulsePin = A5;
 int valPulse = 0;
+int currentPulseState = 0;
+int pulseAmplitude = 10;
+int pulseStep = 2;
+boolean doPulse = false;
+int pulsePhase = 0;

 //misc
 int ledPin = 13;
-
+int maxWaitPoints = 0;

 void setup(){

   //are we living?
   pinMode(ledPin, OUTPUT);
-  digitalWrite(ledPin,HIGH);
+
+  digitalWrite(ledPin, HIGH);

   //servo is connected to digital pin
   myservo.attach(servoPin);
@@ -63,47 +76,132 @@
   int servoBeforePos = servoCurrentPos;

   //reset servo moving direction
+  servoDirBefore = servoDir;
   servoDir = 0;

   //read analog pins for signals
   valFwd = analogRead(analogFwdPin);
   valBwd = analogRead(analogBwdPin);
-  valPulse = analogRead(pulsePin);
+//  valPulse = analogRead(pulsePin);
+  valPulse = digitalRead(pulsePin);

   //log values, if we get a fwd or bwd signal
-  if(valFwd > 100 || valBwd > 100 || valPulse > 100){
+  if(valFwd > 100 || valBwd > 100){

     //log the values
-    Serial.print("fwd: ");
-    Serial.println(valFwd);
-    Serial.print("bwd: ");
-    Serial.println(valBwd);
-    Serial.print("pulse (left): ");
-    Serial.println(valPulse);
-    Serial.println("---------");
+//    Serial.print("fwd: ");
+//    Serial.println(valFwd);
+//    Serial.print("bwd: ");
+//    Serial.println(valBwd);
+//    Serial.print("pulse (left): ");
+//    Serial.println(valPulse);
+
+
+      Serial.println("time since update");
+      Serial.println( (millis() - latestDirUpdate) );

     //are we moving forward or backwards?
-    if(valFwd > 50 && valFwd > valBwd && valBwd == 0){
-      servoDir = servoStep;
-    } else if(valBwd > 50 && valFwd < valBwd && valFwd == 0){
-      servoDir = servoStep * -1;
-    }
-  }
-
-  //add direction, if it's not getting out of degree bounds (min 0; max 179)
-  if(servoCurrentPos+servoDir <= 179 && servoCurrentPos+servoDir >= 0){
-    servoCurrentPos = servoCurrentPos + servoDir;
-  }
+    if(valFwd > 50 && valFwd > valBwd && valBwd < 50){
+
+      if( (millis() - latestDirUpdate) > updateEvery ){
+        latestDirUpdate = millis();
+        lockPosToReach = constrain(servoCurrentPos + servoLockPosEvery, servoMin, servoMax);
+      }
+
+      Serial.println("--- > > > > > fwd");
+    } else if(valBwd > 50 && valFwd < valBwd && valFwd < 50){
+
+      if( (millis() - latestDirUpdate) > updateEvery ){
+        latestDirUpdate = millis();
+        lockPosToReach = constrain(servoCurrentPos + servoLockPosEvery * -1, servoMin, servoMax);
+      }
+
+      Serial.println("< < < < < --- bwd");
+    }
+
+
+  }
+
+  Serial.println("lockPosToReach ");
+  Serial.println(lockPosToReach);
+
+  //check if lock pos is reached
+  if(servoCurrentPos < lockPosToReach){
+    servoDir = servoStep;
+  } else if(servoCurrentPos > lockPosToReach){
+    servoDir = servoStep * -1;
+  }
+
+  if(valPulse == LOW){
+    Serial.println("PULSE!!! !!! !!! !!!");
+    doPulse = true;
+  } else {
+    doPulse = false;
+  }
+
+  if(doPulse || pulsePhase != 0){
+
+    servoDir = 0;
+
+    if(pulsePhase == 0){
+      pulsePhase = 1;
+    }
+
+    if(pulsePhase == 1){
+
+      currentPulseState += pulseStep;
+      servoCurrentPos += pulseStep;
+
+      if(currentPulseState >= pulseAmplitude){
+         pulsePhase++;
+      }
+
+      Serial.println("pulsePhase 0");
+    }
+    else if(pulsePhase == 2){
+
+      currentPulseState += pulseStep * -1;
+      servoCurrentPos += pulseStep * -1;
+
+      if(currentPulseState <= (pulseAmplitude * -1) ){
+         pulsePhase++;
+      }
+
+      Serial.println("pulsePhase 1");
+    } else if(pulsePhase == 3) {
+
+      currentPulseState += pulseStep;
+      servoCurrentPos += pulseStep;
+
+      if(currentPulseState >= 0){
+        pulsePhase = 0;
+        Serial.println("pulseEnd!");
+      }
+
+      Serial.println("pulsePhase 3");
+    }
+  }
+
+  //add direction, if it's not getting out of degree bounds (min 0; max 179)
+  servoCurrentPos = constrain(servoCurrentPos + servoDir, servoMin, servoMax);

   //update servo, if position changed
   if(servoCurrentPos != servoBeforePos){
-    Serial.print("new pos ");
     Serial.println(servoCurrentPos);
     myservo.write(servoCurrentPos);
-    Serial.println("---------");
-    Serial.println("---------");
-  }
+  }
+
+  //just log something
+  maxWaitPoints++;
+
+  if(maxWaitPoints < 50){
+    Serial.print(".");
+  } else {
+    Serial.println(".");
+    maxWaitPoints = 0;
+  }
+

   //give servo time to reach position
-  delay(15);
+  delay( 50 );
 }


power digit limit

power digit limit

--- _04-mqtt-lcd-dust-sensor/_04-mqtt-lcd-dust-sensor-esp-12/_04-mqtt-lcd-dust-sensor-esp-12.ino
+++ _04-mqtt-lcd-dust-sensor/_04-mqtt-lcd-dust-sensor-esp-12/_04-mqtt-lcd-dust-sensor-esp-12.ino
@@ -388,7 +388,7 @@
 }

 void checkDisplayValue() {
-  if ( PW != OLD_PW )
+  if (( PW != OLD_PW ) && ( 0 <= PW < 10000 ))
   {
     displaypowerAvg(PW);
     OLD_PW = PW;


rename publisher and topics

rename publisher and topics

--- testing/arduino/servo-radar3-ros-v3.ino
+++ testing/arduino/servo-radar3-ros-v3.ino
@@ -11,17 +11,17 @@
 ros::NodeHandle  nh;

 sensor_msgs::Range rangeMessage;
-ros::Publisher rangePublisher1("/ultrasound1", &rangeMessage);
-ros::Publisher rangePublisher2("/ultrasound2", &rangeMessage);
+ros::Publisher rangePublisher1("/ultrasound/1", &rangeMessage);
+ros::Publisher rangePublisher2("/ultrasound/2", &rangeMessage);

 const char rangeFrameid[] = "/ultrasound";

 sensor_msgs::JointState jointMessage;
-ros::Publisher odometryPublisher("/odometry", &jointMessage);
+ros::Publisher odometryPublisher("/ultrasound/joint", &jointMessage);

-const char jointFrameid[] = "/ultrasound/joint";
-const char *jointNames[] = {"FRONT", "BACK"};
+const char jointFrameid[] = "/odometry";
+char* jointNames[] = {"FRONT", "BACK"};

 // Ultrasonic Sensor
@@ -77,7 +77,7 @@

     // attach servo pin and set to initial direction
-    ServoMotor.attach(servoPin, 400, 2600); // 400, 2600 to fix rotation issues
+    ServoMotor.attach(servoPin, 400, 2350); // 400, 2600 to fix rotation issues
     ServoMotor.write(servoPos);
 }


arduino code

arduino code

--- arduino/medox/medox.ino
+++ arduino/medox/medox.ino
@@ -5,20 +5,20 @@
 ////////////////////////////////////////////////////////////

 //Arduino Pins definition
-//stepper-1
-#define    stepper11       2
-#define    stepper12       3
-#define    stepper13       4
-#define    stepper14       5
-//stepper-2
-#define    stepper21       6
-#define    stepper22       7
-#define    stepper23       8
-#define    stepper24       9
+//Up-Down stepper
+#define    upPin1       2
+#define    upPin2       3
+#define    upPin3       4
+#define    upPin4       5
+//Rotation stepper
+#define    roPin1       6
+#define    roPin2       7
+#define    roPin3       8
+#define    roPin4       9
 //other outputs
 #define    drawer         10
 #define    warehouse      11
-#define    relay          12
+#define    pump          12
 //sensors
 #define    infrared        13
 #define    current         A0
@@ -27,23 +27,42 @@

 #define    doorDelay        1000
 #define    warehouseDelay   1000
+#define    roMotorDelay   10
+#define    upMotorDelay   3
+#define    i72   10
+#define    j72   8
+#define    iup   50
+#define    jup   8
+

 //variables definition
 char  serialData; //for storing serial string
 float tempFloat = 0; //for saving sensor data temporary
 int billCount = 0; //for storing bill count added by ISR

+int i,j;
+
+/// using half step mode
+int seq[8][4]={1,0,0,0,
+               1,1,0,0,
+               0,1,0,0,
+               0,1,1,0,
+               0,0,1,0,
+               0,0,1,1,
+               0,0,0,1,
+               1,0,0,1 };
+
 void setup() {
   //Setting input/output Pins
   //outputs
-  pinMode(  stepper11,  OUTPUT);
-  pinMode(  stepper12,  OUTPUT);
-  pinMode(  stepper13,  OUTPUT);
-  pinMode(  stepper14,  OUTPUT);
-  pinMode(  stepper21,  OUTPUT);
-  pinMode(  stepper22,  OUTPUT);
-  pinMode(  stepper23,  OUTPUT);
-  pinMode(  stepper24,  OUTPUT);
+  pinMode(  upPin1,  OUTPUT);
+  pinMode(  upPin2,  OUTPUT);
+  pinMode(  upPin3,  OUTPUT);
+  pinMode(  upPin4,  OUTPUT);
+  pinMode(  roPin1,  OUTPUT);
+  pinMode(  roPin2,  OUTPUT);
+  pinMode(  roPin3,  OUTPUT);
+  pinMode(  roPin4,  OUTPUT);
   pinMode(  drawer,     OUTPUT);
   pinMode(  warehouse,  OUTPUT);
   pinMode(  relay,      OUTPUT);
@@ -137,3 +156,55 @@
 void counter() {
   billCount = billCount + 1;
 }
+
+//Dispensing functions
+//up down motor control
+void moveUp(){
+  for(i=0;i<iup;i++){
+    for(j=0;j<jup;j++){
+      digitalWrite(upPin1,seq[j][0]);
+      digitalWrite(upPin2,seq[j][1]);
+      digitalWrite(upPin3,seq[j][2]);
+      digitalWrite(upPin4,seq[j][3]);
+      delay(upMotorDelay);
+    }
+  }
+}
+void moveDown(){
+  for(i=0;i<iup;i++){
+    for(j=jup;j>0;j--){
+      digitalWrite(upPin1,seq[j][0]);
+      digitalWrite(upPin2,seq[j][1]);
+      digitalWrite(upPin3,seq[j][2]);
+      digitalWrite(upPin4,seq[j][3]);
+      delay(upMotorDelay);
+    }
+  }
+}
+
+//// stop motors
+void roMotorStop(){
+  digitalWrite(roPin1,LOW);
+  digitalWrite(roPin2,LOW);
+  digitalWrite(roPin3,LOW);
+  digitalWrite(roPin4,LOW);
+}
+void upMotorStop(){
+  digitalWrite(upPin1,LOW);
+  digitalWrite(upPin2,LOW);
+  digitalWrite(upPin3,LOW);
+  digitalWrite(upPin4,LOW);
+}
+
+/// use to move 72 degree
+void medicineMove(){
+  for(i=0;i<i72;i++){
+    for(j=0;j<j72;j++){
+      digitalWrite(roPin1,seq[j][0]);
+      digitalWrite(roPin2,seq[j][1]);
+      digitalWrite(roPin3,seq[j][2]);
+      digitalWrite(roPin4,seq[j][3]);
+      delay(roMotorDelay);
+    }
+  }
+}