move serial_led.ino into it's own folder

 /***********************************************************************
 *  Copyright (c) 2014 - Matthew Fatheree <greymattr@gmail.com>
 *  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES.  THE USER(S) ARE HEREBY NOTIFIED THAT USE OF THIS SOFTWARE MAY
 * MAY CAUSE LOSS OF DATA, DATA DESTRUCTION, HEALTH AND MENTAL PROBLEMS. IT
 * MAY CAUSE YOU TO START DRINKING, INCREASE YOUR STUPIDITY LEVEL, CLUB
 * BABY SEALS, AND OVERALL BECOME A BAD PERSON.
 *
 * PLEASE USE AT YOUR OWN RISK
 * ____    ________
 * \   \  /    ___/
 * |    \/     __|
 * |  |\__/|  |
 * /  \atthew \atheree
 ************************************************************************/

#include <stdarg.h>

#define	min(a,b)	  ((a) < (b) ? (a) : (b))
#define	max(a,b)	  ((a) > (b) ? (a) : (b))

#define SET_BIT(p,n)      ((p) |= (1 << (n)))
#define CLR_BIT(p,n)      ((p) &= (~(1) << (n)))
#define IS_BIT_SET(val, bit_no) (((val) >> (bit_no)) & 1)

#define INTENSE_MIN        0
#define INTENSE_MAX        255

//#define FADE_STEPS         8
#define FADE_STEPS         16
//#define FADE_STEPS         32

#define SL_VERSION         "v0.1.1"

#define BORDER             "\n--------------------\n"
#define LED_CHOICE         "Which LED would you like to"
#define FREQ_CHOICE        "How quickly would you like it to"
#define REPEAT_CHOICE      "How many times should it"
#define INTENSE_CHOICE     "How bright"
#define MODE_SEL_ERR       "mode select error\n"
#define PARAM_ERR          "parameter error\n"

#define HIGH_VAL_STR       "High Value"
#define MID_VAL_STR        "Mid Value"
#define LOW_VAL_STR        "Low Value"

#define CONTROL_SETTINGS   "Control Settings"
#define START_INTS         "Start Intensity"
#define END_INTS           "End Intensity"
#define TXT_MACRO          "\n\n macro = "

#define MAX_MACRO_LEN      128
#define SMALL_BUFF         8

#define LED1_FLAG          1
#define LED2_FLAG          2
#define LED3_FLAG          4
#define LED4_FLAG          8
#define LED5_FLAG          16
#define LED6_FLAG          32
#define LED7_FLAG          64
#define LED8_FLAG          128
#define LED9_FLAG          256
#define LED10_FLAG         512
#define LED11_FLAG         1024
#define LED12_FLAG         2048
#define LED13_FLAG         4096

//macro modes
#define MODE_BLINK         1
#define MODE_PULSE         2
#define MODE_FADE          3
#define MODE_WAIT          4
#define MODE_SET           5

#define MAX_LEDS           13
#define ALL_LEDS           8191
#define NONE_LEDS          0

#define POWER_SAVE

int HighVal = INTENSE_MAX;
int MidVal = INTENSE_MAX / 2;
int LowVal = INTENSE_MIN;
int UserLed = 10;
int UserVal = INTENSE_MAX;
int UserFreq = 1000;
int UserRepeat = 1;
int UserState1 = LowVal;
int UserState2 = HighVal;
char Uinput[ MAX_MACRO_LEN ];

void setup()
{
  int x = 0;

  for( x=0; x<=MAX_LEDS; x++ ) {
    pinMode( UserLed,OUTPUT );    // Configure the onboard LED for output
    analogWrite( UserLed,0 );  // default to LED off
  }
  Serial.begin( 57600 );
  while( !Serial ) {
    delay( 500 );
  }
  delay( 1000 ); // because Arduino,... am I right?...

}

void p( char *fmt, ... )
{
  char buf[MAX_MACRO_LEN]; // resulting string limited to 128 chars
  va_list args;
  va_start ( args, fmt );
  memset( buf, 0, sizeof( buf ) );
  vsnprintf( buf, MAX_MACRO_LEN, fmt, args );
  va_end ( args );
  Serial.print( buf );
}

void display_menu()
{
  delay( 500 );
  p( "\n\n    LED %s %s\n", CONTROL_SETTINGS, SL_VERSION );
  p( " I. Intensity %s\n", CONTROL_SETTINGS );
  p( " F. Fade  %s\n", CONTROL_SETTINGS );
  p( " P. Pulse %s\n", CONTROL_SETTINGS );
  p( " B. Blink %s\n", CONTROL_SETTINGS );
  p( " C. Clear all LEDS off\n" );
#if 0
  p( " M. Macro %s\n", CONTROL_SETTINGS );
#endif
  p( "%s", BORDER);
  p( " > " );
}

void loop()
{
  char *selection;
  int a = 0;
  int ok;

  display_menu();
  selection = get_user_input();
  memset( Uinput, 0, sizeof( Uinput ) );
  for( a=0; a<( MAX_MACRO_LEN-1 ); a++ ) {
    Uinput[a] = ( char ) *( selection + a );
    if( Uinput[a] == '\0' ) {
      break;
    }
  }
  switch ( Uinput[0] ) {
  case 'I':
  case 'i':
    IntensityControls();
    break;
  case 'F':
  case 'f':
    FadeControls();
    break;
  case 'P':
  case 'p':
    PulseControls();
    break;
  case 'B':
  case 'b':
    BlinkControls();
    break;
  case 'C':
  case 'c':
    p( "\n All LEDS OFF\n\n" );
    a = 8191;
    p("%s c\n", TXT_MACRO);
    set_leds( a, 0 );
    break;
  case '*':
    SayHello();
    break;
#if 1
  case 't':
    // put test functions here
    unrecognized();
    break;
  case 'M':
  case 'm':
    //unrecognized();
    parse_macro( ( char * )( Uinput + 1 ) );
    break;
#endif
  default:
    unrecognized();
    break;
  }

}

void set_leds( int leds, int brightness )
{
  int x;
  //p("\nset led(s) %d at %d\n", leds, brightness);
  for( x=1; x<=MAX_LEDS; x++ ) {
    if( IS_BIT_SET( leds, x ) ) {
      analogWrite( x,brightness );
    }
  }
}

void leds_off( int leds )
{
  set_leds( leds,0 );
}

void leds_on( int leds )
{
  set_leds( leds,255 );
}

void blink_leds( int leds, int brightness, int freq, int repeat )
{
  int i = 0, x = 0;
  int led;

  set_leds( leds, 0 );
  //p( "\n blink led(s) %d at %d/%dms %d times\n", leds, brightness, freq, repeat );
  for( i=0; i<repeat; i++ ) {
    set_leds( leds, brightness );
    delay( freq / 2 );
    set_leds( leds, 0 );
    delay( freq/2 );
  }
}

void blink_led( int led, int b, int f, int r )
{
  int ls = 0;
  SET_BIT( ls, led );
  blink_leds( ls, b, f, r );
}

void fade_leds( int leds, int from, int to, int freq, int repeat )
{
  int total_time = freq;
  int steps = FADE_STEPS;
  int total_range = ( ( max( from,to ) ) - min( from,to ) );
  int step_value =  ( total_range / steps );
  int sleep_value = ( total_time / steps );
  int i, y;
  int curval;
  int led = 0;

  //p( "\n fade led(s) %d from %d to %d/%dms %d times\n", leds, from, to, freq, repeat );
  for( i=0; i<repeat; i++ ) {
    curval = from;
    for ( y=0; y<=steps; y++ ) {
      if( curval < 0 ) {
        curval = 0;
      }
      set_leds( leds, curval );
      if( curval > to ) {
        curval = curval - step_value;
      } else {
        curval = curval + step_value;
      }
      delay( sleep_value );
    }
  }
  set_leds( leds, to );
}

void fade_led( int leds, int from, int to, int freq, int repeat )
{
  int ls = 0;
  SET_BIT( ls, leds );
  fade_leds( ls, from, to, freq, repeat );
}

void pulse_leds( int leds, int from, int to, int freq, int repeat )
{
  int i;
  int new_freq = freq / 2;
  for( i=0; i<repeat; i++ ) {
    fade_leds( leds, from, to, new_freq, 1 );
    fade_leds( leds, to, from, new_freq, 1 );
  }

}

void pulse_led( int led, int from, int to, int freq, int repeat )
{
  int ls = 0;
  SET_BIT( ls, led );
  pulse_leds( ls, from, to, freq, repeat );
}

void SayHello()
{
  p( "%s", BORDER );
  p( "\n Hey Matt... greymattr want a beer?... You're awesome!...\n" );
  p( "%s", BORDER );
}

char *get_user_input()
{
  int i=0;
  char b = 0;
  char commandbuffer[MAX_MACRO_LEN];

  memset( commandbuffer, 0, sizeof( commandbuffer ) );
  while( i < ( sizeof( commandbuffer )-1 ) ) {
    if( Serial.available() ) {
      b = Serial.read();
      if( b != 0x08 ){
        commandbuffer[i++] = b;
      } else {
        commandbuffer[i] = '\0';
        i--;
      }
      if( ( b == 0x0a ) || ( b== 0x0d ) ) {
        break;
      } else {
        Serial.write( b );
      }
    }
  }
  if( i<2 ) {
    return "\0";
  }
  commandbuffer[i]='\0';
  //p("\ncmd buffer = %s\n", commandbuffer);
  return commandbuffer;
}

int get_user_int( int orig )
{
  char *arg = '\0';
  int val = 0;
  arg = get_user_input();
  if( *arg != '\0' ) {
    val=atoi( arg );
    if( ( val >= INTENSE_MIN ) && ( val <= INTENSE_MAX ) ) {
      return val;
    } else {
      return orig;
    }
  }
  return orig;
}

int get_user_intlarge( int orig )
{
  char *arg = '\0';
  int val = 0;
  arg = get_user_input();
  if( *arg != '\0' ) {
    val=atoi( arg );
    if( ( val >= 0 ) && ( val <= 0xFFFF ) ) {
      return val;
    } else {
      return orig;
    }
  }
  return orig;
}

void BlinkControls()
{
  int aNumber;
  char resp;
  char *arg = '\0';
  int ok;
  int val;

  Serial.flush();
  p( "\n\nBlink %s\n", CONTROL_SETTINGS );
  p( "%s blink [ %d ]?: ", LED_CHOICE, UserLed );
  while( !Serial.available() ) {
    ;
  }
  UserLed = get_user_int( UserLed );
  p( "\n%s blink [ %dms ]?: ", FREQ_CHOICE, UserFreq );
  while( !Serial.available() ) {
    ;
  }
  UserFreq = get_user_intlarge( UserFreq );
  p( "\n%s (1-255) [ %d ]?: ", INTENSE_CHOICE, UserVal );
  while( !Serial.available() ) {
    ;
  }
  UserVal = get_user_int( UserVal );
  p( "\n%s should it blink [ %d ]?: ", REPEAT_CHOICE, UserRepeat );
  while( !Serial.available() ) {
    ;
  }
  UserRepeat = get_user_int( UserRepeat );
  p("%s ml(%d)b(%d,%d,%d)\n", TXT_MACRO,UserLed, UserVal, UserFreq, UserRepeat);
  blink_led( UserLed, UserVal, UserFreq, UserRepeat );
}

void IntensityControls()
{
  char *arg = NULL;
  int val = 0;
  int ok;

  Serial.flush();
  p( "\n\nIntensity %s ( 1 - 255 )\n", CONTROL_SETTINGS );
  p( "%s [ %d ]?: ",HIGH_VAL_STR, HighVal );
  while( !Serial.available() ) {
    ;
  }
  HighVal = get_user_int( HighVal );
  p( "\n %s [ %d ]?: ",MID_VAL_STR, MidVal );
  while( !Serial.available() ) {
    ;
  }
  MidVal = get_user_int( MidVal );
  p( "\n %s [ %d ]?: ",LOW_VAL_STR, LowVal );
  while( !Serial.available() ) {
    ;
  }
  LowVal = get_user_int( LowVal );
  p( "%s", BORDER );
  p( "%s=%d, %s=%d, %s=%d\n",HIGH_VAL_STR,HighVal,MID_VAL_STR, MidVal,LOW_VAL_STR, LowVal );
  p( "%s", BORDER );
  p( "\n%s set [ %d ]?: ", LED_CHOICE, UserLed );
  while( !Serial.available() ) {
    ;
  }
  UserLed = get_user_int( UserLed );
  p( "\n%s [ %d ]?: ", INTENSE_CHOICE, UserVal );
  while( !Serial.available() ) {
    ;
  }
  UserVal = get_user_intlarge( UserVal );
  p( "%s", BORDER );
  p( "\nLED %d set to %d\n", UserLed, UserVal );
  p("%s ml(%d)i(%d)\n", TXT_MACRO,UserLed, UserVal);
  analogWrite( UserLed, UserVal );
  p( "%s", BORDER );
}

void intensity_menu()
{
  p( "\n a. %s ( %d )\n", HIGH_VAL_STR, HighVal );
  p( " b.  %s ( %d )\n", MID_VAL_STR, MidVal );
  p( " c.  %s ( %d )\n", LOW_VAL_STR, LowVal );
}

void FadeControls()
{
  char *arg = '\0';
  int state1 = UserState1;
  int state2 = UserState2;

  Serial.flush();
  p( "\n\nFade %s\n", CONTROL_SETTINGS );
  p( "%s fade [ %d ]?: ", LED_CHOICE, UserLed );
  while( !Serial.available() ) {
    ;
  }
  UserLed = get_user_int( UserLed );
  intensity_menu();
  p( "%s [ %d ]?: ", START_INTS, UserState1 );
  while( !Serial.available() ) {
    ;
  }
  arg = get_user_input();
  switch( *arg ) {
  case 'A':
  case 'a':
    UserState1 = HighVal;
    break;
  case 'B':
  case 'b':
    UserState1 = MidVal;
    break;
  case 'C':
  case 'c':
    UserState1 = LowVal;
    break;
  default:
    state1 = atoi( arg );
    if( ( state1 > 255 ) || ( state1 < 0 ) ) {
      state1=UserState1;
    } else {
      state1 = UserState1;
    }
    break;
  }
  intensity_menu();
  p( "%s [ %d ]?: ",END_INTS, UserState2 );
  while( !Serial.available() ) {
    ;
  }
  arg = get_user_input();
  switch( *arg ) {
  case 'A':
  case 'a':
    state2 = HighVal;
    break;
  case 'B':
  case 'b':
    state2 = MidVal;
    break;
  case 'c':
  case 'C':
    state2 = LowVal;
    break;
  default:
    state2 = atoi( arg );
    if( ( state2 > 255 ) || ( state2 < 0 ) ) {
      state2=UserState2;
    } else {
      state2 = UserState2;
    }
    break;
  }
  UserState2 = state2;
  p( "\n%s fade [ %d ]?: ", FREQ_CHOICE, UserFreq );
  while( !Serial.available() ) {
    ;
  }
  UserFreq = get_user_intlarge( UserFreq );
  p( "\n%s fade [ %d ]?: ", REPEAT_CHOICE, UserRepeat );
  while( !Serial.available() ) {
    ;
  }
  UserRepeat = get_user_int( UserRepeat );
  p("%s ml(%d)f(%d,%d,%d,%d)\n", TXT_MACRO,UserLed, UserState1, UserState2, UserFreq, UserRepeat);
  fade_led( UserLed, UserState1, UserState2, UserFreq, UserRepeat );
}

void PulseControls()
{
  char *arg = '\0';
  int sel = 0;
  int state1, state2;
  int ok;

  Serial.flush();
  p( "\n\nPulse %s\n", CONTROL_SETTINGS );
  p( "%s Pulse [ %d ]?: ",LED_CHOICE, UserLed );
  while( !Serial.available() ) {
    ;
  }
  UserLed = get_user_int( UserLed );
  intensity_menu();
  p( "%s [ %d ]?: ", START_INTS, UserState1 );
  while( !Serial.available() ) {
    ;
  }
  arg = get_user_input();
  switch( arg[0] ) {
  case 'a':
  case 'A':
    state1 = HighVal;
    break;
  case 'b':
  case 'B':
    state1 = MidVal;
    break;
  case 'c':
  case 'C':
    state1 = LowVal;
    break;
  default:
    state1 = atoi( arg );
    if( ( state1 > 255 ) || ( state1 < 0 ) ) {
      state1=UserState1;
    } else {
      state1 = UserState1;
    }
    break;
  }
  UserState1 = state1;
  p( "\n%s %d\n", START_INTS, UserState1 );
  intensity_menu();
  p( "%s [ %d ]?: ",END_INTS, UserState2 );
  while( !Serial.available() ) {
    ;
  }
  arg = get_user_input();
  switch( arg[0] ) {
  case 'a':
  case 'A':
    state2 = HighVal;
    break;
  case 'b':
  case 'B':
    state2 = MidVal;
    break;
  case 'c':
  case 'C':
    state2 = LowVal;
    break;
  default:
    state2 = atoi( arg );
    if( ( state2 > 255 ) || ( state2 < 0 ) ) {
      state2=UserState2;
    } else {
      state2 = UserState2;
    }
    break;
  }
  UserState2 = state2;
  p( "\n%s pulse [ %d ]?: ", FREQ_CHOICE, UserFreq );
  while( !Serial.available() ) {
    ;
  }
  UserFreq=get_user_intlarge( UserFreq );
  p( "\n%s pulse [ %d ]?: ", REPEAT_CHOICE, UserRepeat );
  while( !Serial.available() ) {
    ;
  }
  UserRepeat=get_user_int( UserRepeat );
  p("%s ml(%d)p(%d,%d,%d,%d)\n", TXT_MACRO,UserLed, UserState1, UserState2, UserFreq, UserRepeat);
  pulse_led( UserLed, UserState1, UserState2, UserFreq, UserRepeat );
}

int parse_macro( char *macro )
{
  int ok = 0;
  long int leds = 0;
  char *ch;
  char buf[ SMALL_BUFF ];
  int val1 = -1;
  int val2 = -1;
  int freq = -1;
  int repeat = -1;
  int wait = -1;
  int state = 0;
  int i, x;
  int scratch = 0;
  int mode = 0;

  set_leds( ALL_LEDS, 0 );
  p( "\nRun Macro [ %s ]\n", macro-1 );
  for( i=0; i<( MAX_MACRO_LEN - 1 ); i++ ) {
    ch = ( char * )( macro + i );
    switch( *ch ) {
    case 'l':
    case 'L':
      leds = 0;
      if( *( ch + 1 ) == '(' ) {
        i++;  // skip char
        memset( buf, 0, sizeof( buf ) );
        for( x=0; x<sizeof( buf ); x++ ) {
          i++;
          ch = ( char * )( macro + i );
          switch( *ch ) {
          case ',':
          case ')':
            scratch = atoi( buf );
            //p("got led #%d\n", scratch);
            SET_BIT( leds, scratch );
            if( *ch == ')' ) {
              for( x=0; x<MAX_LEDS; x++ ) {
                if( IS_BIT_SET( leds, x ) ) {
                  p( "+ LED #%d\n", x );
                }
              }
              x = sizeof( buf ); // stop here
            } else {
              memset( buf, 0, sizeof( buf ) );
              x = -1;
            }
            break;
          default:
            buf[x] = *ch;
            //p("buf[%d] = %c\n", x, *ch);
            break;
          }
        }
      } else {
        p( "LED err: %s", PARAM_ERR );
        ok = -1;
      }
      //leds = 0;
      val1 = -1;
      val2 = -1;
      freq = -1;
      wait = - 1;
      repeat = -1;
      mode = 0;
      break;
    case 'b':
    case 'B':
      i++;
      if( mode == 0 ) {
        p("\nBlink\n");
        mode = MODE_BLINK;
      } else {
        p( "%s",MODE_SEL_ERR );
      }
      for( x=0; x<sizeof( buf ); x++ ) {
        i++;
        ch = ( char * )( macro + i );
        switch( *ch ) {
        case ',':
        case ')':
          scratch = atoi( buf );
          //p("got led #%d\n", scratch);
          if( val1 == -1 ) {
            p( "got %s %d\n", END_INTS, scratch );
            val1 = scratch;
            x = -1;
          } else {
            if( freq == -1 ) {
              p( "got frequency %d\n", scratch );
              freq = scratch;
              x = -1;
            } else {
              if( repeat == -1 ) {
                p( "got repeat %d\n", scratch );
                repeat = scratch;
                blink_leds( leds, val1, freq, repeat );
                x = sizeof( buf );
              } else {
                p( "Blink set %s", PARAM_ERR );
              }
            }
          }
          memset( buf, 0, sizeof( buf ) );
          break;
        default:
          buf[x] = *ch;
          //p("buf[%d] = %c\n", x, *ch);
          break;
        }
      }
      //leds = 0;
      val1 = -1;
      val2 = -1;
      freq = -1;
      wait = - 1;
      repeat = -1;
      mode = 0;
      break;
    case 'f':
    case 'F':
    case 'p':
    case 'P':
      i++;
      if( mode == 0 ) {
        if( ( *ch == 'f' ) || ( *ch == 'F' ) ) {
          mode = MODE_FADE;
          p( "\nFade\n" );
        } else {
          mode = MODE_PULSE;
          p( "\nPulse\n" );
        }
      } else {
        p( "%s",MODE_SEL_ERR );
      }
      for( x=0; x<sizeof( buf ); x++ ) {
        i++;
        ch = ( char * )( macro + i );
        switch( *ch ) {
        case ',':
        case ')':
          scratch = atoi( buf );
          //p("got led #%d\n", scratch);
          if( val1 == -1 ) {
            p( "got %s %d\n",START_INTS, scratch );
            val1 = scratch;
            x = -1;
          } else {
            if ( val2 == -1 ) {
              p( "got %s %d\n",END_INTS, scratch );
              val2 = scratch;
              x = -1;
            } else {
              if( freq == -1 ) {
                p( "got frequency %d\n", scratch );
                freq = scratch;
                x = -1;
              } else {
                if( repeat == -1 ) {
                  p( "got repeat %d\n", scratch );
                  repeat = scratch;
                  if( mode == MODE_FADE ) {
                    fade_leds( leds, val1, val2, freq, repeat );
                  } else {
                    pulse_leds( leds, val1, val2, freq, repeat );
                  }
                  x = sizeof( buf );
                } else {
                  p( "set %s", PARAM_ERR );
                }
              }
            }
          }
          memset( buf, 0, sizeof( buf ) );
          break;
        default:
          buf[x] = *ch;
          //p("buf[%d] = %c\n", x, *ch);
          break;
        }
      }
      //leds = 0;
      val1 = -1;
      val2 = -1;
      freq = -1;
      wait = - 1;
      repeat = -1;
      mode = 0;
      break;
    case 'i':
    case 'I':
      if( mode == 0 ) {
        mode = MODE_SET;
        p( "\nIntensity\n" );
      } else {
        p( "%s",MODE_SEL_ERR );
      }
      i++;
      mode = MODE_SET;
      memset( buf,0, sizeof( buf ) );
      for( x=0; x<sizeof( buf ); x++ ) {
        i++;
        ch = ( char * )( macro + i );
        switch( *ch ) {
        case ')':
          if( freq == -1 ) {
            scratch = atoi( buf );
            p( "got %s %d\n", END_INTS, scratch );
            val1 = scratch;
            set_leds( leds, val1 );
            x = sizeof( buf );
          } else {
            p( "intensity %s", PARAM_ERR );
          }
          break;
        default:
          buf[x] = *ch;
          break;
        }
      }
      //leds = 0;
      val1 = -1;
      val2 = -1;
      freq = -1;
      wait = - 1;
      repeat = -1;
      mode = 0;
      break;
    case 'w':
    case 'W':
      if( ( mode == 0 ) &&  ( *( ch+1 ) == '(' ) ) {
        i++;
        p( "\nWait\n" );
        mode = MODE_WAIT;
        memset( buf,0, sizeof( buf ) );
        for( x=0; x<sizeof( buf ); x++ ) {
          i++;
          ch = ( char * )( macro + i );
          switch( *ch ) {
          case ')':
            if( freq == -1 ) {
              scratch = atoi( buf );
              p( "got freq %d\n", scratch );
              freq = scratch;
              delay( freq );
              x = sizeof( buf );
            } else {
              p( "Wait set %s", PARAM_ERR );
            }
            break;
          default:
            buf[x] = *ch;
            break;
          }
        }
      } else {
        p( "%s",MODE_SEL_ERR );
      }
      //leds = 0;
      val1 = -1;
      val2 = -1;
      freq = -1;
      wait = - 1;
      repeat = -1;
      mode = 0;
      break;
    case 'c':
    case 'C':
      i++;
      p( "Clear\n" );
      set_leds( ALL_LEDS, 0 );
      //leds = 0;
      val1 = -1;
      val2 = -1;
      freq = -1;
      wait = - 1;
      repeat = -1;
      mode = 0;
      break;
    }
  }// end of loop through macro
  //p("led = %d\n", leds );
  return ok;
}

void unrecognized()
{
  p( "\nError!\n" );
}

error: pathspec 'Arduino/SerialLed/serial-led.ino' did not match any file(s) known to git


Update if/else statement in _ard/_sensorTesting/sensor.ino

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/onordbo/mood-cloud.git/'


fixed receiver pin/value

fixed receiver pin/value

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/Duke-Medical-Instrumentation/Inception.git/'


Create Lee's Retirement countdown clock

Create Lee's Retirement countdown clock

/*
 Testing buttons as well
*/
#include <LiquidCrystal.h>

// initialize the library with the numbers of the interface pins
/* LCD Shield mappings:
 D8, // RS
 D9, // Enable
 D4, // bit 4
 D5, // bit 5
 D6, // bit 6
 D7  // bit 7
 D10 // backlight brightness
 A0  // buttons
 So, LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
*/
LiquidCrystal lcd(
 8, // RS
 9, // Enable
 4, // bit 4
 5, // bit 5
 6, // bit 6
 7  // bit 7
);

#define PinBacklight 10
#define PinButton    0

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

String line1 = "";
String line2 = "";
String secs;
String key;

#define BrightMax 255
#define BrightMin 0
int brightness_increment = -2;
int brightness = BrightMax;

// read the buttons
int read_LCD_buttons()
{
 adc_key_in = analogRead(PinButton);      // read the value from the sensor
 //return adc_key_in;
 // example buttons when read are centered at these valies: 0, 144, 329, 504, 741
 // values measured in Lee's display: 0, 143, 328, 503, 741 (really close to the author's, apparently)
 // we add half the distance to the next button to allow for as much variance as is reasonably likely
 //
 // I picked 1000 as the top value mostly arbitrarily; ~1024 is the select, due to being a "short"
 // I suppose the "right" way would be to do 741+(1024-741/2) to be consistent
 if (adc_key_in > 1000) return btnNONE; // We make this the 1st option for speed reasons since it will be the most likely result
 // For V1.1 us this threshold
 if (adc_key_in < (0   + (143 - 0)   / 2 ))  return btnRIGHT;
 if (adc_key_in < (143 + (328 - 143) / 2 ))  return btnUP;
 if (adc_key_in < (328 + (503 - 328) / 2 ))  return btnDOWN;
 if (adc_key_in < (503 + (741 - 503) / 2 ))  return btnLEFT;
 if (adc_key_in <= 1000)                     return btnSELECT;

 // For V1.0 comment the other threshold and use the one below:
/*
 if (adc_key_in < 50)   return btnRIGHT;
 if (adc_key_in < 195)  return btnUP;
 if (adc_key_in < 380)  return btnDOWN;
 if (adc_key_in < 555)  return btnLEFT;
 if (adc_key_in < 790)  return btnSELECT;
*/

 return btnNONE;  // when all others fail, return this...
}

void setup() {
  // define PWM brightness pin for output
  pinMode(PinBacklight, OUTPUT);
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {
  lcd_key = read_LCD_buttons();
  switch (lcd_key){
    case btnNONE: {
      key = "NONE";
      break;
    }
    case btnRIGHT: {
      key = "RIGHT";
      brightness += 1;
      if( brightness >= BrightMax ){
        brightness = BrightMax;
      }
      break;
    }
    case btnLEFT: {
      key = "LEFT";
      brightness -= 1;
      if( brightness <= BrightMin ){
        brightness = BrightMin;
      }
      break;
    }
    case btnUP: {
      key = "UP";
      lcd.display();
      brightness = BrightMax;
      break;
    }
    case btnDOWN: {
      key = "DOWN";
      brightness = BrightMin;
      lcd.noDisplay();
      break;
    }
    case btnSELECT: {
      key = "SELECT";
      break;
    }
  }
  analogWrite(PinBacklight, brightness);

  // assemble LCD line
  line1 = "";
  line1 = "ADC:" + String(adc_key_in);
  while( line1.length() < 16 - key.length() ){
    line1 = line1 + " ";
  }
  line1 = line1 + key;
  lcd.setCursor(0,0);
  lcd.print(line1);

  // assemble second LCD line
  line2 = "inc:" + String(brightness_increment);
  secs = String(millis()/1000);
  while( line2.length() < 16 - secs.length() ){
    line2 = line2 + " ";
  }
  line2 = line2 + secs;
  lcd.setCursor(0,1);
  lcd.print(line2);
}

error: pathspec 'Lee_Retirement/Lee_Retirement.ino' did not match any file(s) known to git


Add Arduino sketch to test encoders and leds

// Total number of input channels supported by the hardware
const uint8_t numChannels = 5;
const uint8_t ledPins[] = {2, 4, 7, 8, 12};
const uint8_t encoderPins[] = {5, 6, 9, 10, 11};
unsigned long currentEncoderValues[] = {0, 0, 0, 0, 0};
unsigned long previousEncoderValues[] = {0, 0, 0, 0, 0};
const unsigned long encoderValueThreshold = 2048;

// Number of active parameters in the sketch
const uint8_t numParams = 4;

/*
 * Tests the LEDs and encoders.
 * If the encoder value is over a given threshold, the corresponding LED is lit.
 */
void setup()
{
  Serial.begin(57600);
  for (uint8_t i = 0; i < numChannels; i++)
  {
    pinMode(ledPins[i], OUTPUT);
    pinMode(encoderPins[i], INPUT);
  }
}

void loop()
{
  for (uint8_t i = 0; i < numParams; i++)
  {
    previousEncoderValues[i] = currentEncoderValues[i];
    currentEncoderValues[i] = pulseIn(encoderPins[i], HIGH);

    Serial.print(currentEncoderValues[i]);
    if (i < numParams - 1)
    {
      Serial.print(" ");
    }
    if (currentEncoderValues[i] > encoderValueThreshold)
    {
      digitalWrite(ledPins[i], HIGH);
    }
    else
    {
      digitalWrite(ledPins[i], LOW);
    }
  }
  Serial.println();
}

error: pathspec 'arduino/encoders_and_leds_test/encoders_and_leds_test.ino' did not match any file(s) known to git


Broke out DigitalOutPin to Pin, created Channel, and added unit tests: Added new files

#include <Pin.h>
#include <DigitalOutPin.h>
#include <Channel.h>
#include <ArduinoUnit.h>

#define TEST_PIN 13

Pin testPin1(TEST_PIN);

DigitalOutPin testDOPin1(TEST_PIN);
Channel testChannel1(testPin1);

test(PinPin)
{
  Pin testPinL1(TEST_PIN);
  assertEqual(TEST_PIN, testPinL1.getPin());
  testPinL1.setPin(11);
  assertEqual(11, testPinL1.getPin());
}

test(PinValue)
{
  testPin1.off();
  testPin1.on();
  assertEqual(PIN_MAX_VALUE, testPin1.getValue());

  testPin1.off();
  assertEqual(PIN_MIN_VALUE, testPin1.getValue());

  testPin1.setValue(PIN_MAX_VALUE);
  assertEqual(PIN_MAX_VALUE, testPin1.getValue());

  testPin1.setValue(10);
  assertEqual(10, testPin1.getValue());

  testPin1.setValue(0);
  assertEqual(0, testPin1.getValue());
}

test(PinMockMode)
{
  testPin1.setMock(false);
  testPin1.setMock(true);
  assertEqual(true, testPin1.getMock());
  testPin1.setMock(false);
  assertEqual(false, testPin1.getMock());
}

test(PinDebugMode)
{
  testPin1.setDebug(false);
  testPin1.setDebug(true);
  assertEqual(true, testPin1.getDebug());
  testPin1.setDebug(false);
  assertEqual(false, testPin1.getDebug());
}

test(DOPinOnOff)
{
  testDOPin1.off();
  testDOPin1.on();
  assertEqual(HIGH, testDOPin1.getValue());
  testDOPin1.off();
  assertEqual(LOW, testDOPin1.getValue());
}

test(ChannelPin)
{
  assertEqual(TEST_PIN, testChannel1.getPin().getPin());
}

test(ChannelLevel)
{
  testPin1.setDebug(true);
  testChannel1.setLevel(42);
  assertEqual(42, testChannel1.getPin().getValue());

  testChannel1.setMasterLevel(50);
  assertEqual(21, testChannel1.getPin().getValue());

  testChannel1.setMasterLevel(10);
  assertEqual(4, testChannel1.getPin().getValue());

  testChannel1.off();
  assertEqual(0, testChannel1.getPin().getValue());

  testChannel1.on();
  assertEqual(10, testChannel1.getPin().getValue());

  testChannel1.setMasterLevel(100);
}

void setup()
{
  Serial.begin(9600);
  Serial.println(testPin1.getDebug());

}

void loop()
{
  Test::run();
}

error: pathspec 'lightbright/LightBrightLibTest/LightBrightLibTest.ino' did not match any file(s) known to git


changed start text

changed start text

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/ekwoodrich/nirha.git/'


Se crea proyecto de servomotor

Se crea proyecto de servomotor

//Se llama la libreria del servo
#include <Servo.h>

//Pin a conectar el servo
int pinServo = 2;

//Se crea un nuevo objeto del servo
Servo servo;

void setup() {
  //Inicializamos el servo con el pin declarado
  servo.attach(pinServo);
  Serial.begin(9600);
}

void loop() {
  //Movemos el servomotor a 10°
  servo.write(30);
  delay(2000);
  //Leemos la posición de servomotor y la mostramos
  Serial.println(servo.read());
  servo.write(90);
  delay(2000);
  Serial.println(servo.read());
  servo.write(160);
  delay(2000);
  Serial.println(servo.read());
}

error: pathspec 'servomotor/servomotor.ino' did not match any file(s) known to git


#2 Lights/Led sample

#2 Lights/Led sample

/***************************************************
This file is designed for the Simula project by Chicago Robotics Corp.
http://www.chicagorobotics.net/products

Copyright (c) 2016, Chicago Robotics Corp.
See README.md for license details

Example Notes:
* There are 10 LEDs mapped into the unit. 5 Left and 5 Right LEDs.
* Each of the 10 LEDs is a RGB LED, and is accessed by Index into the CRC_Lights module
* L1: 0, L2: 1, L3: 2, L4: 3, L5:4
* R1: 5, R2: 6, R3: 7, R4: 8, R5: 9
****************************************************/

#include "CRC_Hardware.h"
#include "CRC_Lights.h"

/** Start Instantiate all CRC Modules here **/
CRC_HardwareClass hardware;
CRC_LightsClass crcLights(hardware.i2cPca9635Left, hardware.i2cPca9635Right);
/** End Instantiate all CRC Modules here **/

/**
 * Initialize all Modules in the setup function
 */
void setup()
{
  hardware.init();
  crcLights.init();
}

/**
 * Demo's various LED effects in a loop. You can comment each of these functions out to explore the specific sample behaviors
 */
void loop()
{
  runwayEffects();
  fadeInOutButton();
  cycleLeds();
  fadeInOutLeds();
}

/**
 * This is a special effects method with pre-defined behavior. It is typically used on startup since its a blocking method.
 */
void runwayEffects()
{
  crcLights.setRandomColor(); // Init runway
  crcLights.showRunwayWithDelay(); // Demo random runway lights
}

/**
 * Fade the Top Button In/Out
 */
void fadeInOutButton()
{
  uint8_t intensity = 0;
  int dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    crcLights.setButtonLevel(intensity);
    delay(10);
    if(intensity == 255 && dir== 1)
      dir = -1;
    else if (intensity == 0 && dir == -1)
      break;

    intensity += dir;
  }
}

/**
 * Cycle each LED one at a time
 */
void cycleLeds()
{
  int delayTime=300;
  // Just rotate colors all the way through
  for(uint8_t  ledId=0; ledId < 10; ledId++) {
    crcLights.setLed(ledId, 0, 0, 255);
    delay(delayTime);

    crcLights.setLed(ledId, 0, 255, 0);
    delay(delayTime);

    crcLights.setLed(ledId, 255, 0, 0);
    delay(delayTime);

    crcLights.setLed(ledId, 0, 255, 255);
    delay(delayTime);

    crcLights.setLed(ledId, 255, 255, 0);
    delay(delayTime);

    crcLights.setLed(ledId, 255, 255, 255);
    delay(delayTime);

    crcLights.setLed(ledId, 0, 0, 0);
  }
}

/**
 * Fade all Leds in/out 1 color at a time.
 */
void fadeInOutLeds()
{
  uint8_t intensity;
  int dir;

  // Fade Up/Down Red
  intensity = 0;
  dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    for(uint8_t  ledId=0; ledId < 10; ledId++) {
      crcLights.setLed(ledId, intensity, 0, 0);
    }
    if(intensity == 255 && dir== 1)
      dir = -1;

    intensity += dir;
  }

  // Fade Up/Down Green
  intensity = 0;
  dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    for(uint8_t  ledId=0; ledId < 10; ledId++) {
      crcLights.setLed(ledId, 0, intensity, 0);
    }
    if(intensity == 255 && dir== 1)
      dir = -1;
    else if (intensity == 0 && dir == -1)
      break;

    intensity += dir;
  }

  // Fade Up/Down Blue
  intensity = 0;
  dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    for(uint8_t  ledId=0; ledId < 10; ledId++) {
      crcLights.setLed(ledId, 0, 0, intensity);
    }
    if(intensity == 255 && dir== 1)
      dir = -1;
    else if (intensity == 0 && dir == -1)
      break;

    intensity += dir;
  }

  // Fade Up/Down Red+Green
  intensity = 0;
  dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    for(uint8_t  ledId=0; ledId < 10; ledId++) {
      crcLights.setLed(ledId, intensity, intensity, 0);
    }
    if(intensity == 255 && dir== 1)
      dir = -1;
    else if (intensity == 0 && dir == -1)
      break;

    intensity += dir;
  }

  // Fade Up/Down Red+Blue
  intensity = 0;
  dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    for(uint8_t  ledId=0; ledId < 10; ledId++) {
      crcLights.setLed(ledId, intensity, 0, intensity);
    }
    if(intensity == 255 && dir== 1)
      dir = -1;
    else if (intensity == 0 && dir == -1)
      break;

    intensity += dir;
  }

  // Fade Up/Down Green+Blue
  intensity = 0;
  dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    for(uint8_t  ledId=0; ledId < 10; ledId++) {
      crcLights.setLed(ledId, 0, intensity, intensity);
    }
    if(intensity == 255 && dir== 1)
      dir = -1;
    else if (intensity == 0 && dir == -1)
      break;

    intensity += dir;
  }

  // Fade Up/Down Red+Green+Blue
  intensity = 0;
  dir = 1;
  while(! (intensity == 0 && dir == -1) ) {
    for(uint8_t  ledId=0; ledId < 10; ledId++) {
      crcLights.setLed(ledId, intensity, intensity, intensity);
    }
    if(intensity == 255 && dir== 1)
      dir = -1;
    else if (intensity == 0 && dir == -1)
      break;

    intensity += dir;
  }
}

error: pathspec 'examples/Example01_Lights/Example01_Lights.ino' did not match any file(s) known to git


Added blink

Added blink

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/manashmndl/bluebrain.git/'


added JSON Parser test

added JSON Parser test

// This code tests JSON parsing for the Pawn's LED functionalities
// Code based on RFDUINO hardware

#include <ArduinoJson.h>
#include <RFduinoBLE.h>

int led_green = 0;
int led_red = 1;
int led_blue = 2;

//Test JSON strings
String OFF= "{\"device\":\"LED\",\"event\":\"off\"}";
String GREEN = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"green\"}";
String RED = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"red\"}";
String BLUE = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"blue\"}";
String WHITE = "{\"device\":\"LED\",\"event\":\"on\",\"color\":\"white\"}";

void setup() {
  //Serial.begin(9600); //Streams debug messagges over the serial port DEFAULT: OFF
  pinMode(led_green, OUTPUT);
  pinMode(led_red, OUTPUT);
  pinMode(led_blue, OUTPUT);
  delay(500);
}

void loop() {
  // Iterates different JSON messages
  parseJSON(OFF);
  delay(1000);
  parseJSON(GREEN);
  delay(1000);
  parseJSON(RED);
  delay(1000);
  parseJSON(BLUE);
  delay(1000);
  parseJSON(WHITE);
  delay(1000);
}

//Parses JSON messages
void parseJSON(String payload) {
  char sel;
  char json[200];
  payload.toCharArray(json, 50);
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& root = jsonBuffer.parseObject(json);

 // Serial.print("DEBUG: "); Serial.println(json);
  if (!root.success()) {
    Serial.println("parseObject() failed");
    return;
  }

  const char* device = root["device"];
  const char* event = root["event"];
  const char* color = root["color"];

  if(strcmp(device, "LED") == 0)
  {
    if(strcmp(event, "on") == 0)
    {
     sel = color[0];
     ledON(sel);
    }
    if (strcmp(event, "off") == 0)
    {
      ledOFF();
    }
  }
}

// Turns the LED off
void ledOFF(){
  digitalWrite(led_red, LOW);
  digitalWrite(led_green, LOW);
  digitalWrite(led_blue, LOW);
}

// Turns on the LED on a specific color: r=red, g=gree, osv..
void ledON(char sel){
  switch(sel)
  {
        case 'r':
    {
        digitalWrite(led_red, HIGH);
        digitalWrite(led_green, LOW);
        digitalWrite(led_blue, LOW);
        Serial.println("DEBUG: LED RED ON");
        break;
    }
        case 'g':
    {
        digitalWrite(led_red, LOW);
        digitalWrite(led_green, HIGH);
        digitalWrite(led_blue, LOW);
        Serial.println("DEBUG: LED GREEN ON");
        break;
    }
        case 'b':
    {
        digitalWrite(led_red, LOW);
        digitalWrite(led_green, LOW);
        digitalWrite(led_blue, HIGH);
        Serial.println("DEBUG: LED BLUE ON");
        break;
    }
        case 'w':
    {
        digitalWrite(led_red, HIGH);
        digitalWrite(led_green, HIGH);
        digitalWrite(led_blue, HIGH);
        Serial.println("DEBUG: LED WITHE ON");
        break;
    }
  }
}

error: pathspec 'tangibles/JSONParserTest/JSONParserTest.ino' did not match any file(s) known to git


and let's try with shield again

and let's try with shield again

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/lgramatikov/celeste.git/'


move to arduino 1.0 beta 3

move to arduino 1.0 beta 3

// Copyright (c) 2011, Ward Cunningham
// Released under MIT and GPLv2

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <OneWire.h>
#define num(array) (sizeof(array)/sizeof(array[0]))

// Ethernet Configuration

byte mac[] = { 0xEE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED   };
//byte ip[] = { 10, 94, 54, 2   };
//byte gateway[] = { 10, 94, 54, 1 };
IPAddress ip(10, 0, 3, 201 );
IPAddress gateway( 10, 0, 3, 1 );
IPAddress subnet( 255, 255, 255, 0 );

EthernetServer server(1111);
EthernetClient client(255);

unsigned long requests = 0;

// Sensor Configuration

OneWire ds(8);

int analog[2];
struct Temp {
  unsigned int code;
  int data;
} temp[4] = {{0,0}};

unsigned int last = 100;
unsigned long crc_errs = 0;

// Arduino Setup and Loop

void setup() {
  Serial.begin(115200L);
  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
}

void loop() {
  sample();    // every second or so
  pinMode(13,OUTPUT);
  digitalWrite(13,HIGH);
  serve();     // whenever web requests come in
  digitalWrite(13,LOW);
}

// Sample and Hold Analog and One-Wire Temperature Data

void sample() {
  unsigned int now = millis();
  if ((now-last) >= 1000) {
    last = now;
    analogSample();
    tempSample();
  }
}

void analogSample() {
  for (int i = 0; i < num(analog); i++) {
    analog[i] = analogRead(i);
  }
}

byte data[12];
unsigned int id;
int ch = -1;

void tempSample() {
  finishTempSample();
  startTempSample();
}

void startTempSample() {
  if (ch < 0) {
    ds.reset_search();
  }
  if (!ds.search(data)) {
    ch = -1;
  }
  else {
    if (OneWire::crc8(data, 7) == data[7] && 0x28 == data[0]) {
      id = data[2]*256u+data[1];
      ch = channel (id);
      ds.reset();
      ds.select(data);
      ds.write(0x44,1);         // start conversion, with parasite power on at the end
    } else {
      crc_errs++;
      Serial.print(id);
      Serial.println(F(" a-err"));
    }
  }
}

void finishTempSample() {
  if (ch >= 0) {                // if we've discovered a devise and started a conversion
    ds.reset();
    ds.select(data);
    ds.write(0xBE);             // Read Scratchpad
    for (int i = 0; i < 9; i++) {
      data[i] = ds.read();
    }
    if (OneWire::crc8(data, 8) == data[8]) {
      temp[ch].data = data[1]*256+data[0];
      temp[ch].code = id;      // don't set this too early or we could report bad data
    } else {
      crc_errs++;
      Serial.print(id);
      Serial.println(F(" d-err"));
    }
  }
}

int channel(int id) {
  for (int ch=0; ch<num(temp); ch++) {
    if (temp[ch].code == id || temp[ch].code == 0) {
      return ch;
    }
  }
  return 0;
}

// Accept Web Requests for Held Data

void serve() {
  client = server.available();
  if (client) {
    requests++;
    boolean blank = true;
    boolean slash = false;
    char code = 0;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
        if (c == '\n' && blank) {
          report(code);
          break;
        }
        if (c == '\n') {
          blank = true;
        }
        else if (c != '\r') {
          blank = false;
          if (slash && code == 0) {
            code = c;
          }
          slash = c == '/';
        }
      }
    }
    client.stop();
  }
}

// Respond to Web Requests in HTML and JSON

void report(char code) {
  if (code == ' ') {
    htmlReport();
  } else if (code == 'g') {
    jsonReport();
  } else if (code == 'f') {
    faviconReport();
  } else {
    errorReport();
  }
}

void p(char s) { client.print(s); }
void p(__FlashStringHelper* s) { client.print(s); }
void n(char s) { p(s); p(F("\r\n")); }
void n(__FlashStringHelper* s) { p(s); p(F("\r\n")); }
void a() { p(F("http://wiki.org/")); }

void code(__FlashStringHelper* s) { p(F("HTTP/1.1 ")); n(s);}
void mime(__FlashStringHelper* s) { p(F("Content-Type: ")); n(s); n(F("")); }
void link(__FlashStringHelper* s) { p(F("<link href='")); a(); p(s); n(F("' rel='stylesheet' type='text/css'>")); }
void scpt(__FlashStringHelper* s) { p(F("")); }
void stag(__FlashStringHelper* s) { p('<'); p(s); p('>'); }
void etag(__FlashStringHelper* s) { p('<'); p('/'); p(s); p('>'); }

void htmlReport () {
  code(F("200 OK"));
  mime(F("text/html"));
  stag(F("html"));
    stag(F("head"));
      link(F("style.css"));
      scpt(F("js/jquery.min.js"));
      scpt(F("js/jquery-ui.custom.min.js"));
      scpt(F("client.js"));
    etag(F("head"));
    stag(F("body"));
      p(F("
"));
        p(F("
"));
        etag(F("div"));
      etag(F("div"));
    etag(F("body"));
  etag(F("html"));
}

boolean more;

void sh () { if (more) { p(','); } p('{'); more = false; }
void sa () { if (more) { p(','); } p('['); more = false; }
void eh () { p('}'); more = true; }
void ea () { p(']'); more = true; }
void k (__FlashStringHelper* s) {  if (more) { p(','); } p('"'); p(s); p('"'); p(':'); more = false; }
void v (__FlashStringHelper* s) {  if (more) { p(','); } p('"'); p(s); p('"'); more = true; }
void v (long  s) {  if (more) { p(','); } client.print(s); more = true; }
void v (int   s) {  if (more) { p(','); } client.print(s); more = true; }
void v (float s) {  if (more) { p(','); } client.print(s); more = true; }

void jsonReport () {
  more = false;
  long id = 472647400L;

  code(F("200 OK"));
  mime(F("application/json"));
  sh();
    k(F("title")); v(F("garden-report"));
    k(F("logo"));
      sh();
        k(F("nw")); sa(); v(127); v(255); v(127); ea();
        k(F("se")); sa(); v(63); v(63); v(16); ea();
      eh();
    k(F("story"));
      sa();
        sh();
          k(F("type")); v(F("paragraph"));
          k(F("id")); v(id++);
          k(F("text")); v(F("Experimental data from Nike's Community Garden. This content is being served on the open-source hardware Arduino platform running the [[smallest-federated-wiki]] server application."));
        eh();
        for (int ch=0; ch<num(temp); ch++) {
          if (temp[ch].code == 0) {break;}
          sh();
            k(F("type")); v(F("chart"));
            k(F("id")); v((long)temp[ch].code);
            k(F("caption")); v(F("Degrees Fahrenheit
Updated in Seconds"));
            k(F("data"));
              sa();
                sa(); v(1314306006L); v(temp[ch].data * (9.0F/5/16) + 32); ea();
              ea();
          eh();
        }
        for (int ch=0; ch<num(analog); ch++) {
          sh();
            k(F("type")); v(F("chart"));
            k(F("id")); v(201100L+ch);
            k(F("caption")); (ch == 1 ? v(F("Battery
Volts")) : v(F("Daylight
Percent")));
            k(F("data"));
              sa();
                sa(); v(1314306006L); v(analog[ch] * (ch==1 ? (1347.0F/89.45F/1024) : (100.0F/1024))); ea();
              ea();
          eh();
        }
        sh();
          k(F("type")); v(F("chart"));
          k(F("id")); v(id++);
          k(F("caption")); v(F("Wiki Server
Requests"));
          k(F("data"));
            sa();
              sa(); v(1314306006L); v((long)requests); ea();
            ea();
        eh();
      ea();
    k(F("journal"));
      sa();
      ea();
  eh();
}

void errorReport () {
  code(F("404 Not Found"));
  mime(F("text/html"));
  n(F("404 Not Found"));
}

void faviconReport () {
  code(F("200 OK"));
  mime(F("image/png"));
  client.write((uint8_t*)F("\0211\0120\0116\0107\015\012\032\012\0\0\0\015\0111\0110\0104\0122\0\0\0\05\0\0\0\010\010\02\0\0\0\0276\0223\0242\0154\0\0\0\025\0111\0104\0101\0124\010\0231\0143\0374\0377\0277\0203\01\011\0260\074\0370\0372\0236\0236\0174\0\0366\0225\026\0\0105\030\0216\0134\0\0\0\0\0111\0105\0116\0104\0256\0102\0140\0202"), 78);
}

error: pathspec 'Wikiduino/Wikiduino.ino' did not match any file(s) known to git


Add BlinkX3

Add BlinkX3

/*
  blink
  http://arduino.cc/en/tutorial/blink
  Turns a LED on and off repeatedly
  This example code is in the public domain
*/

// Connect the anode of the LED to a pin, assign that pin number to variable led
// Connect the cathode of the LED to GND with a resistor inline
int led = 13;
// Create array with the times to wait between blinks
int waitArray[] = {50,100,300};
int wait = 0;

// The setup routine runs once when you press the reset button
void setup() {
  // initialize the pin as output
  pinMode(led, OUTPUT);
}

// The loop will repeat indefinately
void loop() {
  // Use a for loop, blink the LED with times from waitArray
  for (wait=0; wait<3; wait++) {
     digitalWrite(led,HIGH);
     delay(waitArray[wait]);
     digitalWrite(led,LOW);
     delay(waitArray[wait]);
  }
}

error: pathspec 'blinkX3/blinkX3.ino' did not match any file(s) known to git


Added HelloBlinky.ino example

Added HelloBlinky.ino example

/****************/
 /* Hello Blinky */
/****************/
#include "mcp23s17/mcp23s17.h"

const int LED_PIN = 7;
mcp23s17 gpio_x(mcp23s17::HardwareAddress::HW_ADDR_0); // All addressing pins set to GND

void setup (void) {
    gpio_x.pinMode(LED_PIN, mcp23s17::PinMode::OUTPUT);
}

void loop (void) {
    gpio_x.digitalWrite(LED_PIN, HIGH);
    delay(500);
    gpio_x.digitalWrite(LED_PIN, LOW);
    delay(500);
}

error: pathspec 'firmware/examples/HelloBlinky.ino' did not match any file(s) known to git


Update bb-8-Head-stabiliser-controller.ino

/*
  - OPEN BB-X -
 A open source BB-8 for create you own BB-8!
 ###########################################

 https://github.com/Gruniek/OPEN-BB-X
 Made by Daniel M/Gruniek/

 Compatible only with an Arduino Nano and the specific PCB.
 PCB Link : https://github.com/Gruniek/OPEN-BB-X/tree/master/Head/Stabiliser/PCB

 --------------
 - Change log -
 --------------

 10/1016
 ==========
 - Add PID for X and Y

 To do list
 ==========
 - Add Z rotation controller
 - Add Rx/Tx from the motherboard for change de coordinate of the head,
  rotate the head and report to the remote the status off all sensors/positiom.

  Big thanks for http://r2builders.fr/ !
  Initial project : http://r2builders.fr/forum/viewtopic.php?f=26&t=3928&hilit=BB8+par+MOUS

*/

#include "Wire.h"
#include "MPU6050.h"

// MOTOR CONFIGURATION // YOU CAN TOUCH THIS

#define pinEnable        4      // Activation off all stepper

#define pinStepX         3      // PIN STEP FOR X
#define pinDirX          2      // PIN DIRECTION FOR X

#define pinStepY         6      // PIN STEP FOR Y
#define pinDirY          5      // PIN DIRECTION FOR Y

#define pinStepZ         8      // PIN STEP FOR Y
#define pinDirZ          7      // PIN DIRECTION FOR Y

#define Z_POSITION       9      // PIN FOR THE DIGITAL INPUT FOR THE HEAD POSITION

bool    invertX        = false; // INVERT THE X MOTOR DIRECTION
bool    invertY        = true;  // INVERT THE Y MOTOR DIRECTION
bool    invertXY       = false; // INVERT X Y AXIAL

int     minX           = 45;    // SET THE MIN INCLINAISON FOR X
int     maxX           = 135;   // SET THE MAX INCLINAISON FOR X
int     minY           = 45;    // SET THE MIN INCLINAISON FOR Y
int     maxY           = 135;   // SET THE MAX INCLINAISON FOR Y

int     etalonX        = 0;     // AJUSTEMENT FOR X
int     etalonY        = -6;    // AJUSTEMENT FOR Y

int     hysteresis     = 1;     // HYSTERESSIS FOR THE ANGLE CALCULATION

//=====================//
// NOW YOU CAN'T TOUCH //
//=====================//

// MPU6050
MPU6050 accelgyro;

int16_t ax, ay, az;
int16_t gx, gy, gz;

// I2C
int adress = 2;
int PING   = 13; // PIN

// VARIABLE
int x              = 0;
int y              = 0;
int vx             = 0;
int vy             = 0;

int speedX         = 0;
int speedY         = 0;
int speedZ         = 0;
int setpointX      = 90;
int setpointY      = 90;

int Zangle         = 0;

int multiplier     = 15;
int emergencyStop  = 11; // PIN
int eStop          = 12; // PIN

bool runX          = false;
bool runY          = false;
bool runZ          = false;
bool directX       = false; // false = Gauche / true = droite
bool directY       = false; // false = Gauche / true = droite
bool directZ       = false; // false = Gauche / true = droite

bool xok           = false;
bool yok           = false;
bool zok           = false;

// PID
unsigned long previousMillisX = 0;
unsigned long previousMillisY = 0;
unsigned long previousMillisZ = 0;

long                    intX  = 0;
long                    intY  = 0;

unsigned long trigGyro = 100;
unsigned long trigSec  = 1000;
unsigned long trigG    = 0;
unsigned long trigS    = 0;

bool production = false;
bool LED_PING   = false;
bool BOOT = false;

//=============================================================================//
//   SETUP
//=============================================================================//
void setup()
{
	pinMode( pinEnable , OUTPUT );
    pinMode( pinDirX   , OUTPUT );
    pinMode( pinStepX  , OUTPUT );
    pinMode( pinDirY   , OUTPUT );
    pinMode( pinStepY  , OUTPUT );
    pinMode( PING      , OUTPUT );
    pinMode( Z_POSITION, INPUT  );

    Serial.begin(9600);

    Serial.println("Initializing I2C devices...");
    Serial.print("I2C Adress = ");
    Serial.println(adress);

    Wire.begin(adress);
    //Wire.onReceive(); // register event

    accelgyro.initialize();

    Serial.println("Testing device connections...");
    Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

}

//=============================================================================//
//   LOOP
//=============================================================================//
void loop()
{
    // GET MOTION
    //-------------------------------------------------------------------------//
    unsigned long currentG = millis(); // millis();

    if (currentG - trigG  >= trigGyro)
    {
    	trigG = currentG;

    	accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
		if(invertXY)
		{
			y = (((ax/180)+etalonX)+90);
  			x = (((ay/180)+etalonY)+90);
		}
		else
		{
			x = (((ax/180)+etalonX)+90);
  			y = (((ay/180)+etalonY)+90);
		}
    }

    // GET SERIAL DATA
    //-------------------------------------------------------------------------//

    char msg[30];
    if (Serial.available() > 0)
    {
    	Serial.readBytesUntil('\n', msg, sizeof msg);

    	if (strcmp(strtok(msg, " "), "SET") == 0)
    	{
        	Serial.println("UPDATE SETPOINT");
      		// trouvé le message
      		char *p;
      		while ((p = strtok(NULL, " ")) != NULL)
      		{
        		int val = atoi(p + 1);
        		switch (*p)
        		{
          			case 'x': setpointX  = val; break;
          			case 'y': setpointY  = val; break;
      	  			case 'm': multiplier = val; break;
      				case 'i': invertXY   = val; break;
      				case 'j': invertX    = val; break;
      				case 'k': invertX    = val; break;
      				case 'h': hysteresis = val; break;
        		}
      		}
    	}

    	if (strcmp(strtok(msg, " "), "RUN") == 0)
    	{
        	Serial.println("ROll BB-8 ROLL !");
      	    production = true;
    	}

    	if (strcmp(strtok(msg, " "), "STOP") == 0)
    	{
    		Serial.println("STOP");
    	    production = false;
    	}

    	if (strcmp(strtok(msg, " "), "BOOT") == 0)
    	{
    		Serial.println("STOP");
    	    BOOT = true;
    	    Serial.println("BOOTING UP...");
    	    delay(2000);
    	}

    	if (strcmp(strtok(msg, " "), "ROTATE") == 0) // ROTATE d1 s100  <-- Rotate Z right, 18c/sec
    	{
      		// trouvé le message
      		char *p;
      		while ((p = strtok(NULL, " ")) != NULL)
      		{
        		int val = atoi(p + 1);
        		switch (*p)
        		{
          			case 'd': directZ  = val; break;
          			case 's': speedZ   = val; break;
        		}
      		}
    	}

  }

   if(BOOT)
   {
   	    // SET X IN POSITION
   		if(x < 90) directX = false;
  		else directX = true;

  		if(invertX)
  		{
    		if(directX) directX = false;
    		else directX = true;
  		}
  		digitalWrite(pinDirX, directX); // dirX

  		if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis ))
  		{
  	        digitalWrite(pinStepX, 1);
        	delayMicroseconds( 500 );
    	    digitalWrite(pinStepX, 0);
    	    delayMicroseconds( 500 );
  		}
  		else
  		{
  			if(!xok)
  			{
  				Serial.println("STAT x1");
  				xok = true;
  				delay(2000);
  			}
  		}

  		// SET Y IN POSITION
   		if(y < 90) directY = false;
  		else directY = true;

  		if(invertY)
  		{
    		if(directY) directY = false;
    		else directY = true;
  		}
  		digitalWrite(pinDirY, directY); // dirX

  		if(x > (setpointY + hysteresis) || (y < setpointY - hysteresis ))
  		{
  	        digitalWrite(pinStepY, 1);
        	delayMicroseconds( 500 );
    	    digitalWrite(pinStepY, 0);
    	    delayMicroseconds( 500 );
  		}
  		else
  		{
  			if(!yok)
  			{
  				Serial.println("STAT y1");
  				yok = true;
  				delay(2000);
  			}
  		}

  		// SET W IN POSITION

  		if(!Z_POSITION)
  		{
  		  	digitalWrite(pinStepZ, 1);
        	delayMicroseconds( 500 );
    	    digitalWrite(pinStepZ, 0);
    	    delayMicroseconds( 500 );
  		}
  		else
  		{
  		  	if(!zok)
  			{
  				Serial.println("STAT z1");
  				zok = true;
  				Zangle = 0;
  				delay(2000);
  			}
  		}

  		if( xok && yok && zok)
  		{
  			Serial.println("Booting UP OK!");
  			Serial.println("SEND 'RUN \n' for start the production");
  			BOOT = false;
  		}

   }

	// PRODUCTION CODE
    //-------------------------------------------------------------------------//
    if(production)  //-
    {

  		// X //

		// Direction
  		if(x < 90) directX = false;
  		else directX = true;

  		if(invertX)
  		{
    		if(directX) directX = false;
    		else directX = true;
  		}
  		digitalWrite(pinDirX, directX); // dirX

  		// Si ont doit demarer le moteur
  		if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis ))
  		{
    		if(x > minX && x < maxX) runX = true;
    		else runX = false;
  		}
  		else runX = false;

  		// Calcul du PID X
  		if(x < 90) vx = (90 - x);
  		if(x == 0) vx = 0;
  		if(x > 90) vx = (x - 90);

  		speedX = 1000 / (vx);
  		speedX = speedX * multiplier; // DEL
  		if(speedX < 15) speedX = 15;

		// Mise en route du moteur
  		unsigned long currentX = millis();

    	if (currentX - previousMillisX >= speedX)
    	{
      		previousMillisX = currentX;

      		if(runX)
      		{
        		digitalWrite(pinStepX, 1);
        		delayMicroseconds( 500 );
        		digitalWrite(pinStepX, 0);
    	 		delayMicroseconds( 500 );
      		}
  		}

  		// Y //
  		// Direction
  		if(y < 90) directY = false;
  		else directY = true;
  		if(invertY)
  		{
    		if(directY) directY = false;
    		else directY = true;
  		}
  		digitalWrite(pinDirY, directY);

		// Si ont doit demarer le moteur
  		if(y > (setpointY + hysteresis) || (y < setpointY - hysteresis ))
  		{
    		if(y > minY && y < maxY) runY = true;
    		else runY = false;
  		}
  		else runY = false;

  		// Calcul du PID Y
  		if(y < 90) vy = (90 - y);
  		if(y == 0) vy = 0;
  		if(y > 90) vy = (y - 90);

  		speedY = 1000 / (vy);
  		speedY = speedY * multiplier; // DEL
  		if(speedY < 15) speedY = 15;

  		// Mise en route du moteur
  		unsigned long currentY = millis(); // millis();

    	if (currentY - previousMillisY >= speedY)
    	{
      		previousMillisY = currentY;

      		if(runY)
      		{
        		digitalWrite(pinStepY, 1);
        		delayMicroseconds( 500 );
        		digitalWrite(pinStepY, 0);
        		delayMicroseconds( 500 );
      		}
  		}

  		//--- Z
  		if(speedZ != 0)
  		{
  			unsigned long currentZ = millis();
  			if (currentZ - previousMillisZ >= speedZ)
    		{
      			previousMillisZ = currentZ;

    	 		digitalWrite(pinStepY, 1);
    	    	delayMicroseconds( 500 );
    	    	digitalWrite(pinStepY, 0);
    	    	delayMicroseconds( 500 );
    	    	if(directZ) Zangle++;
    	    	else Zangle--;
  			}
  		}
  		if(Zangle == 201) Zangle = 0;
  		if(Zangle == -1)  Zangle = 0;

  } //-

  	// SEND SERIAL DATA
    //-------------------------------------------------------------------------//
    unsigned long currentS = millis(); // millis();

    if (currentS - trigS  >= trigSec)
    {
    	trigS = currentS;

    	// PING
    	if(LED_PING) LED_PING = false;
    	else LED_PING = true;
    	digitalWrite(PING, LED_PING);

    	// SEND STATUT
    	Serial.print("SEND x");
    	Serial.print(x);
    	Serial.print(" y");
    	Serial.print(y);
    	Serial.print(" i");
    	Serial.print(invertXY);
    	Serial.print(" j");
    	Serial.print(invertX);
    	Serial.print(" k");
    	Serial.print(invertY);
    	Serial.print(" m");
    	Serial.print(multiplier);
    	Serial.print(" z");
    	Serial.print(Zangle);

    	Serial.println(" ");
    }
}

/*
  - OPEN BB-X -
 A open source BB-8 for create you own BB-8!
 ###########################################

 https://github.com/Gruniek/OPEN-BB-X
 Made by Daniel M/Gruniek/

 Compatible only with an Arduino Nano and the specific PCB.
 PCB Link : https://github.com/Gruniek/OPEN-BB-X/tree/master/Head/Stabiliser/PCB

 --------------
 - Change log -
 --------------

 10/1016
 ==========
 - Add PID for X and Y

 To do list
 ==========
 - Add Z rotation controller
 - Add Rx/Tx from the motherboard for change de coordinate of the head,
  rotate the head and report to the remote the status off all sensors/positiom.

  Big thanks for http://r2builders.fr/ !
  Initial project : http://r2builders.fr/forum/viewtopic.php?f=26&t=3928&hilit=BB8+par+MOUS

*/

#include "Wire.h"
#include "MPU6050.h"

// MOTOR CONFIGURATION // YOU CAN TOUCH THIS

#define pinEnable        4      // Activation off all stepper

#define pinStepX         3      // PIN STEP FOR X
#define pinDirX          2      // PIN DIRECTION FOR X

#define pinStepY         6      // PIN STEP FOR Y
#define pinDirY          5      // PIN DIRECTION FOR Y

#define pinStepY         8      // PIN STEP FOR Y
#define pinDirY          7      // PIN DIRECTION FOR Y

#define Z_POSITION       9      // PIN FOR THE DIGITAL INPUT FOR THE HEAD POSITION

bool    invertX        = false; // INVERT THE X MOTOR DIRECTION
bool    invertY        = true;  // INVERT THE Y MOTOR DIRECTION
bool    invertXY       = false; // INVERT X Y AXIAL

int     minX           = 45;    // SET THE MIN INCLINAISON FOR X
int     maxX           = 135;   // SET THE MAX INCLINAISON FOR X
int     minY           = 45;    // SET THE MIN INCLINAISON FOR Y
int     maxY           = 135;   // SET THE MAX INCLINAISON FOR Y

int     etalonX        = 0;     // AJUSTEMENT FOR X
int     etalonY        = -6;    // AJUSTEMENT FOR Y

int     hysteresis     = 1;     // HYSTERESSIS FOR THE ANGLE CALCULATION

//=====================//
// NOW YOU CAN'T TOUCH //
//=====================//

// MPU6050
MPU6050 accelgyro;

int16_t ax, ay, az;
int16_t gx, gy, gz;

// I2C
int adress = 2;
int PING   = 13; // PIN

// VARIABLE
int x              = 0;
int y              = 0;
int vx             = 0;
int vy             = 0;

int speedX         = 0;
int speedY         = 0;

int setpointX      = 90;
int setpointY      = 90;

int multiplier     = 15;
int emergencyStop  = 11; // PIN
int eStop          = 12; // PIN

bool runX          = false;
bool runY          = false;
bool directX       = false; // false = Gauche / true = droite
bool directY       = false; // false = Gauche / true = droite

bool xok           = false;
bool yok           = false;
bool zok           = false;

// PID
unsigned long previousMillisX = 0;
unsigned long previousMillisY = 0;
long                    intX  = 0;
long                    intY  = 0;

unsigned long trigGyro = 100;
unsigned long trigSec  = 1000;
unsigned long trigG    = 0;
unsigned long trigS    = 0;

bool production = false;
bool LED_PING   = false;
bool BOOT = false;

//=============================================================================//
//   SETUP
//=============================================================================//
void setup()
{
	pinMode( pinEnable , OUTPUT );
    pinMode( pinDirX   , OUTPUT );
    pinMode( pinStepX  , OUTPUT );
    pinMode( pinDirY   , OUTPUT );
    pinMode( pinStepY  , OUTPUT );
    pinMode( PING      , OUTPUT );
    pinMode( Z_POSITION, INPUT  );

    Serial.begin(9600);

    Serial.println("Initializing I2C devices...");
    Serial.print("I2C Adress = ");
    Serial.println(adress);

    Wire.begin(adress);
    //Wire.onReceive(); // register event

    accelgyro.initialize();

    Serial.println("Testing device connections...");
    Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

}

//=============================================================================//
//   LOOP
//=============================================================================//
void loop()
{
    // GET MOTION
    //-------------------------------------------------------------------------//
    unsigned long currentG = millis(); // millis();

    if (currentG - trigG  >= trigGyro)
    {
    	trigG = currentG;

    	accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
		if(invertXY)
		{
			y = (((ax/180)+etalonX)+90);
  			x = (((ay/180)+etalonY)+90);
		}
		else
		{
			x = (((ax/180)+etalonX)+90);
  			y = (((ay/180)+etalonY)+90);
		}
    }

    // GET SERIAL DATA
    //-------------------------------------------------------------------------//

    char msg[30];
    if (Serial.available() > 0)
    {
    	Serial.readBytesUntil('\n', msg, sizeof msg);

    	if (strcmp(strtok(msg, " "), "SET") == 0)
    	{
        	Serial.println("UPDATE SETPOINT");
      		// trouvé le message
      		char *p;
      		while ((p = strtok(NULL, " ")) != NULL)
      		{
        		int val = atoi(p + 1);
        		switch (*p)
        		{
          			case 'x': setpointX  = val; break;
          			case 'y': setpointY  = val; break;
      	  			case 'm': multiplier = val; break;
      				case 'i': invertXY   = val; break;
      				case 'j': invertX    = val; break;
      				case 'k': invertX    = val; break;
      				case 'h': hysteresis = val; break;
        		}
      		}
    	}

    	if (strcmp(strtok(msg, " "), "RUN") == 0)
    	{
        	Serial.println("ROll BB-8 ROLL !");
      	    production = true;
    	}

    	if (strcmp(strtok(msg, " "), "STOP") == 0)
    	{
    		Serial.println("STOP");
    	    production = false;
    	}

    	if (strcmp(strtok(msg, " "), "BOOT") == 0)
    	{
    		Serial.println("STOP");
    	    BOOT = true;
    	    Serial.println("BOOTING UP...");
    	    delay(2000);
    	}

  }

   if(boot)
   {
   	    // SET X IN POSITION
   		if(x < 90) directX = false;
  		else directX = true;

  		if(invertX)
  		{
    		if(directX) directX = false;
    		else directX = true;
  		}
  		digitalWrite(pinDirX, directX); // dirX

  		if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis ))
  		{
  	        digitalWrite(pinStepX, 1);
        	delayMicroseconds( 500 );
    	    digitalWrite(pinStepX, 0);
    	    delayMicroseconds( 500 );
  		}
  		else
  		{
  			if(!xok)
  			{
  				Serial.println(STAT x1);
  				xok = true;
  				delay(2000);
  			}
  		}

  		// SET Y IN POSITION
   		if(y < 90) directY = false;
  		else directY = true;

  		if(invertY)
  		{
    		if(directY) directY = false;
    		else directY = true;
  		}
  		digitalWrite(pinDirY, directY); // dirX

  		if(x > (setpointY + hysteresis) || (y < setpointY - hysteresis ))
  		{
  	        digitalWrite(pinStepY, 1);
        	delayMicroseconds( 500 );
    	    digitalWrite(pinStepY, 0);
    	    delayMicroseconds( 500 );
  		}
  		else
  		{
  			if(!yok)
  			{
  				Serial.println(STAT y1);
  				yok = true;
  				delay(2000);
  			}
  		}

  		// SET W IN POSITION

  		if()

   }

	// PRODUCTION CODE
    //-------------------------------------------------------------------------//
    if(production)  //-
    {

  // X //

  // Direction
  if(x < 90) directX = false;
  else directX = true;

  if(invertX)
  {
    if(directX) directX = false;
    else directX = true;
  }

  digitalWrite(pinDirX, directX); // dirX

  // Si ont doit demarer le moteur
  if(x > (setpointX + hysteresis) || (x < setpointX - hysteresis ))
  {
    if(x > minX && x < maxX) runX = true;
    else runX = false;
  }
  else runX = false;

  // Calcul du PID X
  if(x < 90) vx = (90 - x);
  if(x == 0) vx = 0;
  if(x > 90) vx = (x - 90);

  speedX = 1000 / (vx);
  speedX = speedX * multiplier; // DEL
  if(speedX < 15) speedX = 15;

  // Mise en route du moteur
  unsigned long currentX = millis();

    if (currentX - previousMillisX >= speedX)
    {
      previousMillisX = currentX;

      if(runX)
      {
        digitalWrite(pinStepX, 1);
        delayMicroseconds( 500 );
        digitalWrite(pinStepX, 0);
        delayMicroseconds( 500 );
      }
  }

  // Y //

  // Direction
  if(y < 90) directY = false;
  else directY = true;
  if(invertY)
  {
    if(directY) directY = false;
    else directY = true;
  }
  digitalWrite(pinDirY, directY);

  // Si ont doit demarer le moteur
  if(y > (setpointY + hysteresis) || (y < setpointY - hysteresis ))
  {
    if(y > minY && y < maxY) runY = true;
    else runY = false;
  }
  else runY = false;

  // Calcul du PID X
  if(y < 90) vy = (90 - y);
  if(y == 0) vy = 0;
  if(y > 90) vy = (y - 90);

  speedY = 1000 / (vy);
  speedY = speedY * multiplier; // DEL
  if(speedY < 15) speedY = 15;

  // Mise en route du moteur
  unsigned long currentY = millis(); // millis();

    if (currentY - previousMillisY >= speedY)
    {
      previousMillisY = currentY;

      if(runY)
      {
        digitalWrite(pinStepY, 1);
        delayMicroseconds( 500 );
        digitalWrite(pinStepY, 0);
        delayMicroseconds( 500 );
      }
  }

  } //-

  	// SEND SERIAL DATA
    //-------------------------------------------------------------------------//
    unsigned long currentS = millis(); // millis();

    if (currentS - trigS  >= trigSec)
    {
    	trigS = currentS;

    	// PING
    	if(LED_PING) LED_PING = false;
    	else LED_PING = true;
    	digitalWrite(PING, LED_PING);

    	// SEND STATUT
    	Serial.print("SEND x");
    	Serial.print(x);
    	Serial.print(" y");
    	Serial.print(y);
    	Serial.print(" i");
    	Serial.print(invertXY);
    	Serial.print(" j");
    	Serial.print(invertX);
    	Serial.print(" k");
    	Serial.print(invertY);
    	Serial.print(" m");
    	Serial.print(multiplier);
    	Serial.println(" ");
    }
}


Experimental Code

Experimental Code

Two modes: 1) Quantised and 0) UnQuantised.
In Quantised, the note that is coming out of CV Out is accented.
In UnQuatised mode, CV In goes straight through to CV Out, with the LEDs lighting to show the level if CV In.

If any LEDs are pressed, the module is in Quantised mode. With all LEDs out, it's in UnQuantised mode.

/*
  Test Code for the Pure Quantiser LEDs.

  LEDs should light in the following in order from top to bottom, for 1/2sec each
*/

#include "SPI.h"
#include <EEPROM.h>

//Setup LED Pin Varibles
const byte LR_0 = A3;
const byte LR_1 = A4;
const byte LR_2 = A5;
const byte LR_3 = 7;
const byte LC_0 = A0;
const byte LC_1 = A1;
const byte LC_2 = A2;

//Setup Button Pin Variable
const byte BC_0 = 2;
const byte BC_1 = 1;
const byte BC_2 = 0;
const byte BR_0 = 3;
const byte BR_1 = 4;
const byte BR_2 = 5;
const byte BR_3 = 6;

//Setup variable for the buttons, LEDs and temperament
int note;
int notes[13];

//Setup program control variables
int mode = 0;
int i = 1;

//Setup switch debounce variables
unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 500;
int buttonState;
int lastButtonState[13];

//Setup SPI Bus Pin Variables
const byte csADC = 9;
const byte csDAC = 10;

//Setup CV and Trigger Pin Variables
int cvIn;
int cvOut;
int lastCvOut;
int lastCvChange;
int triggerOnTime = 10;
const byte trig = 8;

void setup() {

  //Setup LED Pins
  pinMode(LR_0, OUTPUT);
  pinMode(LR_1, OUTPUT);
  pinMode(LR_2, OUTPUT);
  pinMode(LR_3, OUTPUT);
  pinMode(LC_0, OUTPUT);
  pinMode(LC_1, OUTPUT);
  pinMode(LC_2, OUTPUT);

  digitalWrite(LR_0, HIGH);
  digitalWrite(LR_1, HIGH);
  digitalWrite(LR_2, HIGH);
  digitalWrite(LR_3, HIGH);
  digitalWrite(LC_0, LOW);
  digitalWrite(LC_1, LOW);
  digitalWrite(LC_2, LOW);

  //Setup Button Pins
  pinMode(BC_0, OUTPUT);
  pinMode(BC_1, OUTPUT);
  pinMode(BC_2, OUTPUT);
  pinMode(BR_0, INPUT);
  pinMode(BR_1, INPUT);
  pinMode(BR_2, INPUT);
  pinMode(BR_3, INPUT);

  digitalWrite(BC_0, LOW);
  digitalWrite(BC_1, LOW);
  digitalWrite(BC_2, LOW);

  //Setup SPI Chip Select Pins
  pinMode(csADC, OUTPUT);
  pinMode(csDAC, OUTPUT);

  digitalWrite(csADC, HIGH);
  digitalWrite(csDAC, HIGH);
  SPI.begin();

  //Setup Trigger Pin
  pinMode(trig, OUTPUT);
  digitalWrite(trig, LOW);

  for (int k = 0; k <= 12; k++) {
    notes[k] = EEPROM[k];
  }
}

void loop() {

  readNoteButton(i);

  if (notes[i] == 1) {
    writeLED(i);
  } else {
    writeLED(0);
  }

  //Read ADC
  cvIn = adcRead(1);

  //Only Quantise if buttons are pressed.
  mode = 0;
  for (int j = 1; j <= 12; j++) {
    mode = mode + notes[j];
  }
  if (mode == 0) {
    cvOut = cvIn >> 1;
    dacWrite(cvOut);
    vuMeter();
  } else {
    quantiseCV(cvIn);
  }

  //Write CVOut and Trigger Out
  if (lastCvOut != cvOut) {
    digitalWrite(trig, HIGH);
    lastCvOut = cvOut;
    lastCvChange = millis();
  } else if ((millis() - lastCvChange) > triggerOnTime) {
    digitalWrite(trig, LOW);
  }

  if (i == 12) {
    i = 0;
  } else {
    i++;
  }

  delay(1);

}

void readNoteButton(byte button) {
  switch (button) {
    case 1:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_2, HIGH);
      note = digitalRead(BR_0);
      digitalWrite(BC_2, LOW);
      break;

    case 2:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_2, HIGH);
      note = digitalRead(BR_1);
      digitalWrite(BC_2, LOW);
      break;

    case 3:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_2, HIGH);
      note = digitalRead(BR_2);
      digitalWrite(BC_2, LOW);
      break;

    case 4:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_2, HIGH);
      note = digitalRead(BR_3);
      digitalWrite(BC_2, LOW);
      break;

    case 5:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_1, HIGH);
      note = digitalRead(BR_0);
      digitalWrite(BC_1, LOW);
      break;

    case 6:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_1, HIGH);
      note = digitalRead(BR_1);
      digitalWrite(BC_1, LOW);
      break;

    case 7:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_1, HIGH);
      note = digitalRead(BR_2);
      digitalWrite(BC_1, LOW);
      break;

    case 8:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_1, HIGH);
      note = digitalRead(BR_3);
      digitalWrite(BC_1, LOW);
      break;

    case 9:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_0, HIGH);
      note = digitalRead(BR_0);
      digitalWrite(BC_0, LOW);
      break;

    case 10:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_0, HIGH);
      note = digitalRead(BR_1);
      digitalWrite(BC_0, LOW);
      break;

    case 11:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_0, HIGH);
      note = digitalRead(BR_2);
      digitalWrite(BC_0, LOW);
      break;

    case 12:
      //Turn on BC_0 and read BR_0
      digitalWrite(BC_0, HIGH);
      note = digitalRead(BR_3);
      digitalWrite(BC_0, LOW);
      break;
  }

  //Debounce and toggle
  if ((millis() - lastDebounceTime) > debounceDelay) {

    if (note != buttonState) {
      buttonState = note;
      if (buttonState == HIGH) {
        notes[button] = !notes[button];
        EEPROM[button] = notes[button];
        lastDebounceTime = millis();
      }
    }
  }
  lastButtonState[button] = notes[button];

}

void writeLED(byte LED) {
  switch (LED) {
    case 0:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, LOW);
      break;

    case 1:
      digitalWrite(LR_0, LOW);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, HIGH);
      break;

    case 2:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, LOW);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, HIGH);
      break;

    case 3:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, LOW);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, HIGH);
      break;

    case 4:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, LOW);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, HIGH);
      break;

    case 5:
      digitalWrite(LR_0, LOW);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, HIGH);
      digitalWrite(LC_2, LOW);
      break;

    case 6:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, LOW);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, HIGH);
      digitalWrite(LC_2, LOW);
      break;

    case 7:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, LOW);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, HIGH);
      digitalWrite(LC_2, LOW);
      break;

    case 8:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, LOW);
      digitalWrite(LC_0, LOW);
      digitalWrite(LC_1, HIGH);
      digitalWrite(LC_2, LOW);
      break;

    case 9:
      digitalWrite(LR_0, LOW);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, HIGH);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, LOW);
      break;

    case 10:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, LOW);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, HIGH);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, LOW);
      break;

    case 11:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, LOW);
      digitalWrite(LR_3, HIGH);
      digitalWrite(LC_0, HIGH);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, LOW);
      break;

    case 12:
      digitalWrite(LR_0, HIGH);
      digitalWrite(LR_1, HIGH);
      digitalWrite(LR_2, HIGH);
      digitalWrite(LR_3, LOW);
      digitalWrite(LC_0, HIGH);
      digitalWrite(LC_1, LOW);
      digitalWrite(LC_2, LOW);
      break;
  }
}

void dacWrite(int value) {

  digitalWrite(csDAC, LOW);
  byte data = value >> 8;
  data = data & B00001111;
  data = data | B00110000;
  SPI.transfer(data);

  data = value;
  SPI.transfer(data);

  digitalWrite(csDAC, HIGH);
}

int adcRead(byte channel) {

  byte commandbits = B00001101;          //command bits - 0000, start, mode, chn, MSBF
  unsigned int b1 = 0;                   // get the return var's ready
  unsigned int b2 = 0;
  commandbits |= ((channel - 1) << 1);   // update the command bit to select either ch 1 or 2
  digitalWrite(csADC, LOW);
  SPI.transfer(commandbits);             // send out the command bits
  const int hi = SPI.transfer(b1);       // read back the result high byte
  const int lo = SPI.transfer(b2);       // then the low byte
  digitalWrite(csADC, HIGH);
  b1 = lo + (hi << 8);                   // assemble the two bytes into a word
  return (b1 >> 2);                      // We have got a 12bit answer but strip LSB's if
  // required >>4 ==10 bit (0->1024), >>2 ==12bit (0->4096)
}

int quantiseCV(int cvIn) {

  int octave = cvIn / 815;
  int vOct = octave * 815;
  int vOffset = 0;

  for (int index = 1; index < 13; index ++) {
    if (notes[index] == 1 && (cvIn - vOct) > index * 68) {
      vOffset = (index * 68) - 68;
      cvOut = vOct + vOffset;
      writeLED(index);
      cvOut = cvOut >> 1;
    }
  }
        dacWrite(cvOut);

}

void vuMeter() {
  for (int l = 1; l <= 12; l++) {
    if (cvIn > (341 * l)) {
      writeLED(l);
    }
  }
}

error: pathspec 'puremodular/pureQuantiser/GMSN_Quantiser_Experimental_Code_20170926/GMSN_Quantiser_Experimental_Code_20170926.ino' did not match any file(s) known to git


Modifie selon les specifications de protypage rapide

error: pathspec 'Module' did not match any file(s) known to git
error: pathspec 'Moteur/Software/Asservissement/CaracterisationVitessePWM/CaracterisationVitessePWM/CaracterisationVitessePWM.ino' did not match any file(s) known to git


Asservissment: PWM correction du code

Asservissment: PWM correction du code


intial version

intial version

/*
   1MB flash sizee

   sonoff header
   1 - vcc 3v3
   2 - rx
   3 - tx
   4 - gnd
   5 - gpio 14

   esp8266 connections
   gpio  0 - button
   gpio 12 - relay
   gpio 13 - green led - active low
   gpio 14 - pin 5 on header

*/
#define SONOFF_BUTTON    0
#define SONOFF_RELAY    12
#define SONOFF_LED      13
#define SONOFF_INPUT    14

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

static bool BLYNK_ENABLED = true;

#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

#include <EEPROM.h>

#define EEPROM_SALT 12663
typedef struct {
  int   salt = EEPROM_SALT;
  char  blynkToken[33]  = "";
  char  blynkServer[33] = "blynk-cloud.com";
  char  blynkPort[6]    = "8442";
} WMSettings;

WMSettings settings;

#include <ArduinoOTA.h>

//for LED status
#include <Ticker.h>
Ticker ticker;

const int CMD_WAIT = 0;
const int CMD_BUTTON_CHANGE = 1;

int cmd = CMD_WAIT;
int state = HIGH;

void tick()
{
  //toggle state
  int state = digitalRead(SONOFF_LED);  // get the current state of GPIO1 pin
  digitalWrite(SONOFF_LED, !state);     // set pin to the opposite state
}

//gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
  Serial.println("Entered config mode");
  Serial.println(WiFi.softAPIP());
  //if you used auto generated SSID, print it
  Serial.println(myWiFiManager->getConfigPortalSSID());
  //entered config mode, make led toggle faster
  ticker.attach(0.2, tick);
}

static int relayState = 0;
static long startPress = 0;

void setState(int s) {
  digitalWrite(SONOFF_RELAY, s);
  digitalWrite(SONOFF_LED, (s + 1) % 2); // led is active low
}

void toggleState() {
  cmd = CMD_BUTTON_CHANGE;
}

//flag for saving data
bool shouldSaveConfig = false;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

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

  //set led pin as output
  pinMode(SONOFF_LED, OUTPUT);
  // start ticker with 0.5 because we start in AP mode and try to connect
  ticker.attach(0.6, tick);

  const char *hostname = "ambient";

  WiFiManager wifiManager;
  //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
  wifiManager.setAPCallback(configModeCallback);

  //timeout

  //custom params
  EEPROM.begin(512);
  EEPROM.get(0, settings);
  EEPROM.end();

  if(settings.salt != EEPROM_SALT) {
    Serial.println("Invalid settings in EEPROM, trying with defaults");
    WMSettings defaults;
    settings = defaults;
  }

  Serial.println(settings.blynkToken);
  Serial.println(settings.blynkServer);
  Serial.println(settings.blynkPort);

  WiFiManagerParameter custom_blynk_text("Blynk config. <br/> No token to disable.");
  wifiManager.addParameter(&custom_blynk_text);

  WiFiManagerParameter custom_blynk_token("blynk-token", "blynk token", settings.blynkToken, 33);
  wifiManager.addParameter(&custom_blynk_token);

  WiFiManagerParameter custom_blynk_server("blynk-server", "blynk server", settings.blynkServer, 33);
  wifiManager.addParameter(&custom_blynk_server);

  WiFiManagerParameter custom_blynk_port("blynk-port", "blynk port", settings.blynkPort, 6);
  wifiManager.addParameter(&custom_blynk_port);

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  if (!wifiManager.autoConnect(hostname)) {
    Serial.println("failed to connect and hit timeout");
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(1000);
  }

  //Serial.println(custom_blynk_token.getValue());
  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("Saving config");

    strcpy(settings.blynkToken, custom_blynk_token.getValue());
    strcpy(settings.blynkServer, custom_blynk_server.getValue());
    strcpy(settings.blynkPort, custom_blynk_port.getValue());

    Serial.println(settings.blynkToken);
    Serial.println(settings.blynkServer);
    Serial.println(settings.blynkPort);

    EEPROM.begin(512);
    EEPROM.put(0, settings);
    EEPROM.end();
  }

  //config blynk
  if(strlen(settings.blynkToken) == 0) {
    BLYNK_ENABLED = false;
  }
  if(BLYNK_ENABLED) {
    Blynk.config(settings.blynkToken, settings.blynkServer, atoi(settings.blynkPort));
  }

  //OTA
  ArduinoOTA.onStart([]() {
    Serial.println("Start OTA");
  });
  ArduinoOTA.onEnd([]() {
    Serial.println("\nEnd");
  });
  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
    Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  });
  ArduinoOTA.onError([](ota_error_t error) {
    Serial.printf("Error[%u]: ", error);
    if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
    else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
    else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
    else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
    else if (error == OTA_END_ERROR) Serial.println("End Failed");
  });
  ArduinoOTA.setHostname(hostname);
  ArduinoOTA.begin();

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");
  ticker.detach();

  //setup button
  pinMode(SONOFF_BUTTON, INPUT);
  attachInterrupt(SONOFF_BUTTON, toggleState, CHANGE);

  //setup relay
  pinMode(SONOFF_RELAY, OUTPUT);

  setState(HIGH);

  Serial.println("done setup");
}

void loop()
{

  //ota loop
  ArduinoOTA.handle();
  //blynk connect and run loop
  if(BLYNK_ENABLED) {
    Blynk.run();
  }
  //delay(200);
  //Serial.println(digitalRead(SONOFF_BUTTON));
  switch (cmd) {
    case CMD_WAIT:
      break;
    case CMD_BUTTON_CHANGE:
      int currentState = digitalRead(SONOFF_BUTTON);
      if (currentState != state) {
        if (state == LOW && currentState == HIGH) {
          long duration = millis() - startPress;
          if (duration < 1000) {
            Serial.println("short press - toggle relay");
            relayState = !relayState;
            setState(relayState);
          } else if (duration < 5000) {
            Serial.println("medium press - reset");
            ESP.reset();
            delay(1000);
          } else if (duration < 60000) {
            Serial.println("long press - reset settings");
            //reset settings to defaults
            /*
            WMSettings defaults;
            settings = defaults;
            EEPROM.begin(512);
            EEPROM.put(0, settings);
            EEPROM.end();
            */
            //reset wifi credentials
            WiFi.disconnect();
            delay(1000);
            ESP.reset();
            delay(1000);
          }
        } else if (state == HIGH && currentState == LOW) {
          startPress = millis();
        }
        state = currentState;
      }
      break;
  }

}

error: pathspec 'SonoffBoilerplate.ino' did not match any file(s) known to git


Added arduino file

Added arduino file

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// How to run it: upload to arduino with the dynamixel_serial library installed in your arduino libraries folder.             //
//                After upload, disconnect usb from arduino and add power to CrustCrawler and the arduino board.              //
//                The program should start by it self. :)                                                                     //
//                                                                                //
//                PIN Setup:  Green wire to PIN 10,                                                                           //
//                            Yellow wire to PIN 11,                                                                          //
//                            Black wire to ground,                                                                           //
//                            Red wire to 5v,                                                                                //
//                            Blue wire to PIN2                                                                               //
//                                                                                //
//                This code was developed in collaboration with several groups, to enable all the groups a good               //
//                base code to start programming the CrustCrawler from. ;)                                                    //
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#include <Arduino.h>
#include "Dynamixel_Serial.h"
#include <SoftwareSerial.h>

#define SERVO_ControlPin 0x02       // Control pin of buffer chip, NOTE: this does not matter becasue we are not using a half to full contorl buffer.
#define SERVO_SET_Baudrate 57600    // Baud rate speed which the Dynamixel will be set too (57600)
#define LED13 0x0D
#define CW_LIMIT_ANGLE 0x001        // lowest clockwise angle is 1, as when set to 0 it set servo to wheel mode
#define CCW_LIMIT_ANGLE 0xFFF       // Highest anit-clockwise angle is 0XFFF, as when set to 0 it set servo to wheel mode

SoftwareSerial mySerial(10, 11);    // RX, TX

int *data;

void setup(){

  Serial.flush();                                       // Clear the serial buffer of garbage data before running the code.
  mySerial.begin(SERVO_SET_Baudrate);                   // We now need to set Ardiuno to the new Baudrate speed 115200
  Serial.begin(57600);                                  // Start serial communication on baudrate 57600
  Dynamixel.begin(mySerial);                            // Calling mySerial function which sets 10 pin as the 2nd RX serial pin, and sets pin 11 as the 2nd TX serial pin
  Dynamixel.setDirectionPin(SERVO_ControlPin);          // Optional. Set direction control pin which control if the program writes or reads to and from the robot

  // Turn on hold on the servos:
  Dynamixel.setHoldingTorque(0x01, true);               //Turn on hold torque on servo 1
  Dynamixel.setHoldingTorque(0x02, true);               //Turn on hold torque on servo 2
  Dynamixel.setHoldingTorque(0x03, true);               //Turn on hold torque on servo 3
  //Dynamixel.setHoldingTorque(0x04, true);               //Turn on hold torque on servo 4
  //Dynamixel.setHoldingTorque(0x05, true);               //Turn on hold torque on servo 5

  // Set the Profile acceleration.
  Dynamixel.setProfileAcceleration(0x01, 10);  //Set the Profile Acceleration for each servo. (max. is 32767)
  Dynamixel.setProfileAcceleration(0x02, 10);  //Set the Profile Acceleration for each servo. (max. is 32767)
  Dynamixel.setProfileAcceleration(0x03, 10);  //Set the Profile Acceleration for each servo. (max. is 32767)
  /*
  Dynamixel.setProfileAcceleration(0x04, 300);  //Set the Profile Acceleration for each servo. (max. is 32767)
  Dynamixel.setProfileAcceleration(0x05, 300);  //Set the Profile Acceleration for each servo. (max. is 32767)
  */

  // Set the Profile velocity.
  Dynamixel.setProfileVelocity(0x01, 100);  //Set the Profile Velocity for each servo. (max. is 1023)
  Dynamixel.setProfileVelocity(0x02, 100);  //Set the Profile Velocity for each servo. (max. is 1023)
  Dynamixel.setProfileVelocity(0x03, 100);  //Set the Profile Velocity for each servo. (max. is 1023)
  /*
  Dynamixel.setProfileVelocity(0x04, 200);  //Set the Profile Velocity for each servo. (max. is 1023)
  Dynamixel.setProfileVelocity(0x05, 200);  //Set the Profile Velocity for each servo. (max. is 1023)
  */

  /*
  //Get position for servos in steps
  Dynamixel.getPosition(0x01);
  Dynamixel.getPosition(0x02);
  Dynamixel.getPosition(0x03);
  Dynamixel.getPosition(0x04);
  Dynamixel.getPosition(0x05);

  //Get position for servos in degrees
  Dynamixel.getPositionD(0x01);
  Dynamixel.getPositionD(0x02);
  Dynamixel.getPositionD(0x03);
  Dynamixel.getPositionD(0x04);
  Dynamixel.getPositionD(0x05);

  //Get load on servos in maximum procent (The power required by the servo to hold its current position)
  Dynamixel.getLoad(0x02);

  //Saving and printing positon from all servos
  data = Dynamixel.getPositionN();

  for(int i = 0; i < 5; i++){
    Serial.println(data[i]);
  }

  */
}

void loop(){

  int id1 = 2071; //Servo 1 goal position
  int id2 = 2048; //Servo 2 goal position
  int id3 = 2048; //Servo 3 goal position
  //int id4 = 2548; //Servo 4 goal position
  //int id5 = 1548; //Servo 5 goal position

 Dynamixel.setNGoalPositions(-1, id2, id3, -1, -1);  //Set goal position of all the servos

  int i = 1;
  int id2P;

  // This while loop keeps putting servo 2's current potition into an integer
  while(i > 0){
    id2P =  Dynamixel.getPosition(0x02);  //Servo 2 current position in steps

    // This if statement checks if servo 2 have reached goal position, before it starts the next move
    if(id2==id2P){
       Dynamixel.setNGoalPositions(id1, -1, -1, id4, id5);  //Set goal position of all the servos
       i = 0; //just to end the while loop
    }
  }
}

error: pathspec 'Main-UPDATE/Main-UPDATE.ino' did not match any file(s) known to git


Create DMASpi_example1.ino

Create DMASpi_example1.ino

#include <ChipSelect.h>
#include <DmaSpi.h>

// create a chip select object. This one uses the pin that the built-in LED is connected to.
ActiveLowChipSelect<LED_BUILTIN> cs;

void setup() {
  DMASPI0.begin();
  // create a transfer object
  DmaSpi0::Transfer trx(nullptr, 100, nullptr, 0xFF, &cs);

  // and register it. If the DMA SPI is idle, it will immediately start transmitting. Otherwise the transfer is added to a queue.
  DMASPI0.registerTransfer(trx);

  /** FREE CPU TIME YOU DIDN'T HAVE BEFORE! DO SOMETHING USEFUL! **/

  // wait for the transfer to finish
  while(trx.busy());
}

void loop() {

}

error: pathspec 'examples/DMASpi_example1/DMASpi_example1.ino' did not match any file(s) known to git


Fix scoping errors

Fix scoping errors

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/jaredkotoff/CSUFIEEECS.git/'


Initalize arduino file

Initalize arduino file


Fix NewPing hang issue in firmware

Fix NewPing hang issue in firmware

https://code.google.com/p/arduino-new-ping/issues/detail?id=5

remote: Support for password authentication was removed on August 13, 2021.
remote: Please see https://docs.github.com/en/get-started/getting-started-with-git/about-remote-repositories#cloning-with-https-urls for information on currently recommended modes of authentication.
fatal: Authentication failed for 'https://github.com/qiwi/parking.git/'


Create HelloWorld.ino

Create HelloWorld.ino

#include "microbit_Screen.h"

void setup() {
  SCREEN.begin();
}

void loop() {
  SCREEN.showString("HELLO,WORLD.");
  SCREEN.showString("micro:bit!");
}

error: pathspec 'examples/HelloWorld/HelloWorld.ino' did not match any file(s) known to git


Copy FW to WearButton Arduino example

Copy FW to WearButton Arduino example

#include <Adafruit_NeoPixel.h>

#define LED_COUNT 60
#define THRESHOLD 1

Adafruit_NeoPixel strip = Adafruit_NeoPixel(LED_COUNT, 5, NEO_GRB + NEO_KHZ800);

uint8_t pixel_index;

long last_time;

void setup()
{
  // Set the MOSI pin as digital output
  // (only for BB RevA)
//  DDRB |= _BV(2);

  Serial.begin(57600);

  strip.begin();
  strip.show();
  last_time = millis();
}

uint8_t i = 0;
int j = 0;
int f = 0;
int k = 0;

int count;

void color_loop() {
  float brightness = random(100,100)/100.0;

  for (uint8_t i = 0; i < LED_COUNT; i++) {
    uint8_t red =   64*(1+sin(i/2.0 + j/4.0       ))*brightness;
    uint8_t green = 64*(1+sin(i/1.0 + f/9.0  + 2.1))*brightness;
    uint8_t blue =  64*(1+sin(i/3.0 + k/14.0 + 4.2))*brightness;

    uint32_t pix = green;
    pix = (pix << 8) | red;
    pix = (pix << 8) | blue;

    strip.setPixelColor(i, pix);

    if ((millis() - last_time > 15) && pixel_index <= LED_COUNT + 1) {
      last_time = millis();
      count = LED_COUNT - pixel_index;
      pixel_index++;
    }

    for (int x = count; x >= 0; x--) {
      strip.setPixelColor(x, strip.Color(0,0,0));
    }

  }

  strip.show();

  j = j + random(1,2);
  f = f + random(1,2);
  k = k + random(1,2);
}

void serialLoop() {

  while(true) {

    if(Serial.available() > 2) {

      int buffer[3]; // Buffer to store three incoming bytes used to compile a single LED color
      int x;
      for (x=0; x<3; x++) { // Read three incoming bytes
        int c = Serial.read();
        if (c < 255) buffer[x] = c; // Using 255 as a latch semaphore
        else {
          strip.show();
          pixel_index = 0;
          break;
        }

        if (x == 2) {   // If we received three serial bytes

          uint32_t color = strip.Color(buffer[0], buffer[1], buffer[2]);
          strip.setPixelColor(pixel_index, color);
          pixel_index++;

        }
      }
    }
  }
}

void loop()
{
  // If'n we get some data, switch to passthrough mode
  if(Serial.available() > 0) {
    serialLoop();
  }

  color_loop();
}

error: pathspec 'examples/WearButton/WearButton.ino' did not match any file(s) known to git