Initial commit

Initial commit

/*
Copyright (C) 2012-2013 Chris Osgood <chris at luadev.com>

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.  No
other versions are acceptable.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/

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

// Check for MultiWii
#if defined(MSP_VERSION)
  #define MULTIWII
#else
  #include <EEPROM.h>
#endif

#define AUL_SERIALRATE 19200

#define AUL_MIN_BITTIME 4
#define AUL_MAX_BITTIME 136
#define AUL_DEFAULT_BITTIME 32

#define AUL_MICROS_TO_TICKS(x)  ((x) * (F_CPU / 1000000) / g_timerScale)
#define AUL_MICROS_TO_TICKS_R(x) ((x) * g_timerScale / (F_CPU / 1000000))

#if defined(__AVR_ATmega8__)
#define AUL_SET_TIMER_MODE TCCR2 = g_timerConfig
#else
#define AUL_SET_TIMER_MODE TCCR2B = g_timerConfig
#endif

// Default PD2/INT0
#define AUL_DEFAULT_PIN 18

#define AUL_BUFSIZE 300

#define AUL_SERIALTIMEOUT ((F_CPU >> 7) / (9600 >> 4))

#define AUL_PININPUT  ((*g_signalDDR)  &= ~(g_signalPinPortNum))
#define AUL_PINOUTPUT ((*g_signalDDR)  |=  (g_signalPinPortNum))
#define AUL_PINHIGH   ((*g_signalPORT) |=  (g_signalPinPortNum))
#define AUL_PINLOW    ((*g_signalPORT) &= ~(g_signalPinPortNum))

#define AUL_PINREAD   ((*g_signalPIN) & (g_signalPinPortNum))

#define AUL_DELAYTICKS(x) \
  TCNT2 = 0; \
  while (TCNT2 < (x));

#if defined(__AVR_ATmega8__)
#define AUL_SYNC_PRESCALER \
  SFIOR = (1 << PSR2); \
  while (SFIOR & (1 << PSR2));
#else
#define AUL_SYNC_PRESCALER \
  GTCCR = (1 << PSRASY); \
  while (GTCCR & (1 << PSRASY));
#endif

// Save space on MultWii since baud rate changes are not supported and it is the
// only thing that requires a value greater than uint8
#if defined(MULTIWII)
  #define AUL_ASCII_INT_TYPE uint8_t
#else
  #define AUL_ASCII_INT_TYPE uint32_t
#endif

#define AUL_EEPROM_PIN 4
#define AUL_EEPROM_BITTIME 5
#define AUL_EEPROM_BAUD 6

///////////////////////////////////////////////////////////////////////////////
// Globals
///////////////////////////////////////////////////////////////////////////////

static uint8_t g_timerConfig;
static uint16_t g_timerScale;

// Approximate microseconds for each bit when sending
static uint8_t g_bitTimeSend;
static uint8_t g_bitTimeSendHalf;

// Calculated leader timing for receive
static uint8_t g_bitTime, g_shortBitTime;

static volatile uint8_t* g_signalDDR;
static volatile uint8_t* g_signalPORT;
static volatile uint8_t* g_signalPIN;
static int8_t g_signalPinPortNum, g_signalPinNum;

#if defined(MULTIWII)
static uint32_t g_baudRate = 0;
#else
static uint32_t g_baudRate = AUL_SERIALRATE;
#endif

///////////////////////////////////////////////////////////////////////////////
// stdlib type utility functions (mostly to save space)
///////////////////////////////////////////////////////////////////////////////

// int to ASCII base 10
// Returns the address of the null terminator
static char* AUL_itoa(AUL_ASCII_INT_TYPE n, char *b)
{
   uint8_t i = 0, s;

   do {
      s = n % 10;
      n = n / 10;
      b[i++] = '0' + s;
   } while (n > 0);

   b[i] = '\0';

   strrev(b);

   return &b[i];
}

// ASCII to int base 10
static AUL_ASCII_INT_TYPE AUL_atoi(const char* s)
{
  AUL_ASCII_INT_TYPE b = 0;
  while (*s) b = (b << 3) + (b << 1) + (*s++ - '0');
  return(b);
}

///////////////////////////////////////////////////////////////////////////////
// Serial port.  MultiWii helpers.
///////////////////////////////////////////////////////////////////////////////

#if !defined(MULTIWII)

#define AUL_SerialInit(x) Serial.begin(g_baudRate)
#define AUL_SerialAvailable() Serial.available()
#define AUL_SerialRead() Serial.read()
#define AUL_SerialWrite(x) Serial.write(x)
#define AUL_SerialWriteBuf(x,y) Serial.write(x,y)
#define AUL_SerialWriteStr(x) Serial.write((const char*)x)

#else // MULTIWII

static volatile uint8_t* g_serialUCSRA;
static volatile uint8_t* g_serialUDR;
static uint8_t g_serialRXC, g_serialUDRE;

static void AUL_SerialInit(uint8_t port)
{
  #define AUL_INIT_PORT(x) \
    UCSR##x##C = (1 << UCSZ##x##1) | (1 << UCSZ##x##0); \
    UCSR##x##B = (1 << RXEN##x) | (1 << TXEN##x); \
    g_serialUCSRA = &UCSR##x##A; \
    g_serialUDR = &UDR##x; \
    g_serialRXC = (1 << RXC##x); \
    g_serialUDRE = (1 << UDRE##x);

  switch (port)
  {
  case 0:
    AUL_INIT_PORT(0)
    break;
  #if defined(UBRR1H)
  case 1:
    AUL_INIT_PORT(1)
    break;
  #endif
  #if defined(UBRR2H)
  case 2:
    AUL_INIT_PORT(2)
    break;
  #endif
  #if defined(UBRR3H)
  case 3:
    AUL_INIT_PORT(3)
    break;
  #endif
  #if defined(UBRR4H)
  case 4:
    AUL_INIT_PORT(4)
    break;
  #endif
  default:
    break;
  }
}

#define AUL_SerialAvailable() \
  ((*g_serialUCSRA) & g_serialRXC)

#define AUL_SerialRead() \
  (*g_serialUDR)

#define AUL_SerialWrite(x) \
  { while (!((*g_serialUCSRA) & g_serialUDRE)); (*g_serialUDR) = (x); }

static void AUL_SerialWriteBuf(const uint8_t* b, int16_t len)
{
  int16_t i;
  for (i = 0; i < len; i++)
    AUL_SerialWrite(b[i]);
}

static void AUL_SerialWriteStr(const char* b)
{
  int16_t i;
  for (i = 0; b[i] != '\0'; i++)
    AUL_SerialWrite(b[i]);
}

#endif // MULTIWII

///////////////////////////////////////////////////////////////////////////////
// Signal pin
///////////////////////////////////////////////////////////////////////////////

// Clear all timers and PWM settings
static void DisableAllTimers()
{
  #define AUL_RESET_PORT(x) \
    TCCR##x##B = 0; \
    TCCR##x##A = 0;

  // For mega8 and similar
  #if defined(TCCR0)
    TCCR0 = 0;
  #endif
  #if defined(TCCR1)
    TCCR1 = 0;
  #endif
  #if defined(TCCR2)
    TCCR2 = 0;
  #endif

  #if defined(TCCR0B)
    AUL_RESET_PORT(0)
  #endif
  #if defined(TCCR1B)
    AUL_RESET_PORT(1)
  #endif
  #if defined(TCCR2B)
    AUL_RESET_PORT(2)
  #endif
  #if defined(TCCR3B)
    AUL_RESET_PORT(3)
  #endif
  #if defined(TCCR4B)
    AUL_RESET_PORT(4)
  #endif
  #if defined(TCCR5B)
    AUL_RESET_PORT(5)
  #endif
  #if defined(TCCR6B)
    AUL_RESET_PORT(6)
  #endif
}

static void SignalPinStatus(char* buf)
{
  #define AUL_WRITE_PORT_INFO(x) \
    *pos++ = #x[0]; \
    pos = AUL_itoa(pincnt, pos); \
    *pos++ = ':'; \
    pincnt += 8;

  char* pos = buf;
  int8_t pincnt = 0;

  pos[0] = 'P';
  pos[1] = 'I';
  pos[2] = 'N';
  pos[3] = 'S';
  pos[4] = ':';
  pos += 5;

  #if defined(PORTB)
    AUL_WRITE_PORT_INFO(B)
  #endif
  #if defined(PORTC)
    AUL_WRITE_PORT_INFO(C)
  #endif
  #if defined(PORTD)
    AUL_WRITE_PORT_INFO(D)
  #endif
  #if defined(PORTE)
    AUL_WRITE_PORT_INFO(E)
  #endif
  #if defined(PORTF)
    AUL_WRITE_PORT_INFO(F)
  #endif
  #if defined(PORTG)
    AUL_WRITE_PORT_INFO(G)
  #endif
  #if defined(PORTH)
    AUL_WRITE_PORT_INFO(H)
  #endif
  #if defined(PORTI)
    AUL_WRITE_PORT_INFO(I)
  #endif
  #if defined(PORTJ)
    AUL_WRITE_PORT_INFO(J)
  #endif
  #if defined(PORTK)
    AUL_WRITE_PORT_INFO(K)
  #endif
  #if defined(PORTL)
    AUL_WRITE_PORT_INFO(L)
  #endif

  #if defined(PORTA)
    AUL_WRITE_PORT_INFO(A)
  #endif

  *pos = '\0';
}

static void SignalPinInit(int8_t pin)
{
  #define AUL_SETUP_PORT(x) \
    if (pin < (pincnt += 8)) \
    { \
      g_signalDDR = &DDR##x; \
      g_signalPORT = &PORT##x; \
      g_signalPIN = &PIN##x; \
      g_signalPinPortNum = (1 << (pin - (pincnt - 8))); \
      goto finished; \
    }

  int8_t pincnt = 0;

  g_signalPinNum = pin;

  #if defined(PORTB)
    AUL_SETUP_PORT(B);
  #endif
  #if defined(PORTC)
    AUL_SETUP_PORT(C);
  #endif
  #if defined(PORTD)
    AUL_SETUP_PORT(D);
  #endif
  #if defined(PORTE)
    AUL_SETUP_PORT(E);
  #endif
  #if defined(PORTF)
    AUL_SETUP_PORT(F);
  #endif
  #if defined(PORTG)
    AUL_SETUP_PORT(G);
  #endif
  #if defined(PORTH)
    AUL_SETUP_PORT(H);
  #endif
  #if defined(PORTI)
    AUL_SETUP_PORT(I);
  #endif
  #if defined(PORTJ)
    AUL_SETUP_PORT(J);
  #endif
  #if defined(PORTK)
    AUL_SETUP_PORT(K);
  #endif
  #if defined(PORTL)
    AUL_SETUP_PORT(L);
  #endif

  #if defined(PORTA)
    AUL_SETUP_PORT(A);
  #endif

finished:
  AUL_PINHIGH; // Enable pull-up
  AUL_PININPUT;
}

///////////////////////////////////////////////////////////////////////////////
// SENDING on signal pin
///////////////////////////////////////////////////////////////////////////////

static void SendByte(uint8_t b)
{
  uint8_t i;
  for (i = 1; i; i <<= 1)
  {
    if (b & i)
    {
      AUL_PINHIGH;
      AUL_DELAYTICKS(g_bitTimeSend);
      AUL_PINLOW;
      AUL_DELAYTICKS(g_bitTimeSend);
    }
    else
    {
      AUL_PINHIGH;
      AUL_DELAYTICKS(g_bitTimeSendHalf);
      AUL_PINLOW;
      AUL_DELAYTICKS(g_bitTimeSendHalf);
      AUL_PINHIGH;
      AUL_DELAYTICKS(g_bitTimeSendHalf);
      AUL_PINLOW;
      AUL_DELAYTICKS(g_bitTimeSendHalf);
    }
  }
}

///////////////////////////////////////////////////////////////////////////////
// RECEIVE on signal pin
///////////////////////////////////////////////////////////////////////////////

#define AUL_SPINPINHIGH \
  TCNT2 = 0; \
  while (AUL_PINREAD) { if (TCNT2 > 250) goto timeout; }

#define AUL_SPINPINLOW \
  TCNT2 = 0; \
  while (!AUL_PINREAD) { if (TCNT2 > 250) goto timeout; }

#define AUL_NT_SPINPINHIGH \
  while (AUL_PINREAD) { if (TCNT2 > 250) goto timeout; }

#define AUL_NT_SPINPINLOW \
  while (!AUL_PINREAD) { if (TCNT2 > 250) goto timeout; }

#define AUL_READBIT \
  AUL_SPINPINHIGH \
  AUL_NT_SPINPINLOW \
  if (TCNT2 <= g_shortBitTime) \
  { \
    AUL_SPINPINHIGH \
    AUL_NT_SPINPINLOW \
    b = 0; \
  } \
  else \
    b = 1;

static int8_t ReadLeader()
{
  uint8_t i;

  // Skip the first few to let things stabilize
  for (i = 0; i < 9; i++)
  {
    AUL_SPINPINHIGH
    AUL_NT_SPINPINLOW
  }

#ifndef AUL_FIXED_TIMING
  // Calculate timing from header
  AUL_SPINPINHIGH
  AUL_NT_SPINPINLOW
  g_bitTime = TCNT2;
  g_shortBitTime = (g_bitTime >> 1) + (g_bitTime >> 2);
#else
  // Use fixed timing
  g_bitTime = g_bitTimeSend << 1;
  g_shortBitTime = g_bitTimeSend + g_bitTimeSendHalf;
#endif

  // Read until we get a 0 bit
  while (1)
  {
    uint8_t b;
    AUL_READBIT // Sets b to the bit value

    if (!b)
      return 0;
  }

timeout:
  return -1;
}

static void SetBitTime(uint16_t t)
{
  if (t < AUL_MIN_BITTIME)
    t = AUL_MIN_BITTIME;
  else if (t > AUL_MAX_BITTIME)
    t = AUL_MAX_BITTIME;

  if (t * (F_CPU / 1000000) < 242)
  {
    g_timerScale = 2;
    g_timerConfig = (1 << CS20);
  }
  else if (t * (F_CPU / 1000000) / 8 < 242)
  {
    g_timerScale = 16;
    g_timerConfig = (1 << CS21);
  }
  else if (t * (F_CPU / 1000000) / 32 < 242)
  {
    g_timerScale = 64;
    g_timerConfig = (1 << CS21) | (1 << CS20);
  }
  else
  {
    return; // invalid time, no change
  }

  g_bitTimeSend = AUL_MICROS_TO_TICKS(t);
  g_bitTimeSendHalf = (g_bitTimeSend >> 1);
}

#if !defined(MULTIWII)
static uint32_t EERead32(int pos)
{
  uint32_t value;
  ((char*)&value)[0] = EEPROM.read(pos);
  ((char*)&value)[1] = EEPROM.read(pos + 1);
  ((char*)&value)[2] = EEPROM.read(pos + 2);
  ((char*)&value)[3] = EEPROM.read(pos + 3);
  return value;
}

static void EEWrite32(int pos, uint32_t value)
{
  EEPROM.write(pos, ((char*)&value)[0]);
  EEPROM.write(pos + 1, ((char*)&value)[1]);
  EEPROM.write(pos + 2, ((char*)&value)[2]);
  EEPROM.write(pos + 3, ((char*)&value)[3]);
}
#endif // !MULTIWII

///////////////////////////////////////////////////////////////////////////////
// Main
///////////////////////////////////////////////////////////////////////////////

void AUL_loop(uint8_t port)
{
  // Disable interrupts and timers
  cli();
  DisableAllTimers();

  #if defined(MULTIWII)
    #if defined(BUZZERPIN_OFF)
      BUZZERPIN_OFF;
    #endif
    #if defined(LEDPIN_OFF)
      LEDPIN_OFF;
    #endif
  #endif

  #if defined(MULTIWII)
    AUL_SerialInit(port);
    SetBitTime(AUL_DEFAULT_BITTIME);
    SignalPinInit(AUL_DEFAULT_PIN);
  #else
    if (EEPROM.read(0) != 'a' ||
        EEPROM.read(1) != 'u' ||
        EEPROM.read(2) != 'l')
    {
      EEPROM.write(0, 'a');
      EEPROM.write(1, 'u');
      EEPROM.write(2, 'l');
      EEPROM.write(3, 1); // version
      EEPROM.write(AUL_EEPROM_PIN, AUL_DEFAULT_PIN);
      EEPROM.write(AUL_EEPROM_BITTIME, AUL_DEFAULT_BITTIME);
      EEWrite32(AUL_EEPROM_BAUD, AUL_SERIALRATE);
    }

    SignalPinInit(EEPROM.read(AUL_EEPROM_PIN));
    SetBitTime(EEPROM.read(AUL_EEPROM_BITTIME));

    g_baudRate = EERead32(AUL_EEPROM_BAUD);
    AUL_SerialInit(port);

    sei(); // Re-enable interrupts for Serial
  #endif

  // Set timer2 to count ticks
  AUL_SET_TIMER_MODE;

  // The buffer always has the leader at the start
  uint8_t buf[AUL_BUFSIZE] = { 0xFF, 0xFF, 0x7F };
  uint8_t lastPin = 0;
  int16_t buflen, i;

  while (1)
  {
    if (AUL_SerialAvailable())
    {
      buflen = 3;
      buf[buflen++] = AUL_SerialRead();

      // Temporarily set timer2 to count ticks/128
#if defined(__AVR_ATmega8__)
      TCCR2 = (1 << CS22) | (1 << CS20);
#else
      TCCR2B = (1 << CS22) | (1 << CS20);
#endif
      AUL_SYNC_PRESCALER;
      TCNT2 = 0;
      // Buffer data until the serial timeout
      do {
         if (AUL_SerialAvailable())
         {
           buf[buflen++] = AUL_SerialRead();
           TCNT2 = 0;
         }
      } while (TCNT2 < AUL_SERIALTIMEOUT);

      // Set timer2 back to normal
      AUL_SET_TIMER_MODE;

      if (buf[3] == '$' && buf[4] == 'M' && buf[5] == '<')
      {
#if !defined(MULTIWII)
        int8_t setbaud = 0;
#endif

        buf[buflen] = '\0';

        switch(buf[6])
        {
        case 'B': { // BITTIME
          SetBitTime(AUL_atoi((const char*)&buf[7]));
          break; }
        case 'P': // SELECT PORT
          SignalPinInit(AUL_atoi((const char*)&buf[7]));
          break;
#if !defined(MULTIWII)
        case 'R': // BAUD RATE
          g_baudRate = AUL_atoi((const char*)&buf[7]);

          if (g_baudRate < 9600)
            g_baudRate = 9600;

          setbaud = 1;
          break;
        case 'W': // WRITE EEPROM settings
          EEPROM.write(AUL_EEPROM_PIN, g_signalPinNum);
          EEPROM.write(AUL_EEPROM_BITTIME, AUL_MICROS_TO_TICKS_R(g_bitTimeSend));
          EEWrite32(AUL_EEPROM_BAUD, g_baudRate);
          AUL_SerialWriteStr("saved:");
          break;
#endif // !MULTIWII
        default:
          break;
        }

        // Send status afterwards
        char* pos = (char*)&buf[3];
        *pos++ = 'P';
        pos = AUL_itoa(g_signalPinNum, pos);
        pos[0] = ':';
        pos[1] = 'B';
        pos += 2;
        pos = AUL_itoa(AUL_MICROS_TO_TICKS_R(g_bitTimeSend), pos);
        pos[0] = ':';
        pos[1] = 'R';
        pos += 2;
        pos = AUL_itoa(g_baudRate, pos);
        *pos++ = ':';

        SignalPinStatus(pos);

        AUL_SerialWriteStr((const char*)&buf[3]);
        AUL_SerialWrite('\n');

#if !defined(MULTIWII)
        if (setbaud)
        {
          // Arduino Serial.flush does not work correctly
          Serial.flush();

          // Temporarily set timer2 to count ticks/128
#if defined(__AVR_ATmega8__)
          TCCR2 = (1 << CS22) | (1 << CS20);
#else
          TCCR2B = (1 << CS22) | (1 << CS20);
#endif
          AUL_DELAYTICKS(AUL_SERIALTIMEOUT);
          AUL_DELAYTICKS(AUL_SERIALTIMEOUT);
          AUL_SET_TIMER_MODE;

          AUL_SerialInit(port);
        }
#endif // !MULTIWII
      }
      else
      {
        AUL_PINOUTPUT;
        AUL_SYNC_PRESCALER;

        // Send data over signal pin
        for (i = 0; i < buflen; i++)
          SendByte(buf[i]);

        // Trailer
        AUL_PINHIGH;
        AUL_DELAYTICKS(g_bitTimeSendHalf);

        AUL_PININPUT; // Pull-up is enabled from previous PINHIGH
        lastPin = 1;
      }
    }
    else
    {
      // Here we look for a low to high transition on the signal pin
      uint8_t curPin = AUL_PINREAD;

      if (!lastPin && curPin)
      {
        AUL_SYNC_PRESCALER;

        // Buffer data from signal pin then write to serial port
        if (ReadLeader() == 0)
        {
          uint8_t i, byt, b;
          buflen = 3;

          // Read bytes until timeout
          while (1)
          {
            for (i = 0, byt = 0; i < 8; i++)
            {
              AUL_READBIT // Sets b to the bit value
              byt |= b << i;
            }

            buf[buflen++] = byt;
          }

timeout:
          AUL_SerialWriteBuf(&buf[3], buflen - 3);
        }
      }

      lastPin = curPin;
    }
  }
}

#if !defined(MULTIWII)

int main(int argc, char* argv[])
{
  AUL_loop(0);
  return 0;
}

#endif // !MULTIWII

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


New default board

New default board

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/DanNixon/Alice.git/'


a new rain pattern, optimized just enough that it should work on the staff and the lamp

/*
simlated a mesh of springs, where brightness is the height each light
is away from the "mesh"
*/

#include "FastLED.h"
#define LED_DT 7              // Data pin to connect to the strip.
#define COLOR_ORDER GRB       // Are they RGB, GRB or what??
#define LED_TYPE WS2812B      // Don't forget to change LEDS.addLeds
#define TRUE_LED_COUNT 300 /// 1500 if this is a staff, 300 if it is a lamp.
// #define NUM_LEDS 150
#define BRIGHTNESS_GAIN 1.0
#define MAX_BRIGHTNESS 80

#define DROP_FORCE 30

#define TRANSITION_LENGTH 30
#define TRANSITION_DELAY 80
#define TRANSITION_LENGTH_VARIANCE 30
#define TRANSITION_DELAY_VARIANCE 300

#define L 8 // LIGHTS_PER_WRAP
#define O 2 // LOOP_OFFSET_MM
#define W 10 // HORIZONTAL_SPACE_MM
#define H 10 // VERTICAL_SPACE_MM
// #define K 3 // SPRING_CONST

#define VEL_DAMPING .9 // number between 0 and 1;
#define MAX_VEL 1.5
#define FALL_SPEED 0

/* non-default */
#define NUM_LEDS 100 //1500
#define K 1 // SPRING_CONST
// #define DROP_FORCE 60
// #define MAX_BRIGHTNESS 128
// #define BRIGHTNESS_GAIN 1.0
/* end non-default */

struct CRGB leds[TRUE_LED_COUNT];
float aleds_vel[NUM_LEDS];
float aleds_brightness[NUM_LEDS];
float anext_leds_brightness[NUM_LEDS];
float bleds_vel[NUM_LEDS];
float bleds_brightness[NUM_LEDS];
float bnext_leds_brightness[NUM_LEDS];

int counter = 0;

///* begin neighborhood
int neighbor_count = 8;
float neighbor_dist[8];
int idx_offset[8];

void init_helper_values() {
  neighbor_dist[0] = sqrt((H*H)+((W-O)*(W-O)));
  neighbor_dist[1] = sqrt((H*H)+(O*O));
  neighbor_dist[2] = sqrt((H*H)+((W+O)*(W+O)));
  neighbor_dist[3] = W;
  neighbor_dist[4] = neighbor_dist[0];
  neighbor_dist[5] = neighbor_dist[1];
  neighbor_dist[6] = neighbor_dist[2];
  neighbor_dist[7] = neighbor_dist[3];

  idx_offset[0] = -L-1;
  idx_offset[1] = -L;
  idx_offset[2] = -L+1;
  idx_offset[3] = -1;
  idx_offset[4] = 1;
  idx_offset[5] = L-1;
  idx_offset[6] = L;
  idx_offset[7] = L+1;
}
//*/ // end neighborhood

void setup() {
  delay(1000);
  Serial.begin(57600);
  LEDS.addLeds<LED_TYPE, LED_DT, COLOR_ORDER>(leds, TRUE_LED_COUNT);
  FastLED.setBrightness(255);
  set_max_power_in_volts_and_milliamps(5, 10000);
  randomSeed(analogRead(0));
  init_helper_values();

  for (int i = 0; i < TRUE_LED_COUNT; i++) {
    leds[i] = CRGB(0, 0, 0);
  }
}

float accel(float brightness, float dist){
  // assume a mass of one and compute the force vector from the sprint.
  float delta = (sqrt((dist*dist)+(brightness*brightness)) - dist);
  float force = K * delta;
  // only want the vertical component of the force vector
  return force * (brightness / (delta + dist));
}

float get_brightness(int idx, float *leds_brightness){
  if ((idx < 0) || (idx >= NUM_LEDS)) {
    return leds_brightness[(idx + NUM_LEDS) % NUM_LEDS];
    // return 0;
  } else {
    return leds_brightness[idx];
  }
}

float apply_acc(float vel, float acc){
  float ret_vel = vel+acc;
  if (ret_vel > MAX_VEL){
    ret_vel = MAX_VEL;
  }
  if (ret_vel < -MAX_VEL){
    ret_vel = -MAX_VEL;
  }
  return ret_vel * VEL_DAMPING;
}

float next_for_idx(int idx, float *leds_brightness, float *leds_vel){
  float a = 0;
  float dist;
  float brightness;
  float force;
  // how hard does each spring pull on light `idx`?
  for (int i = 0; i < neighbor_count; i++){
    dist = neighbor_dist[i];
    brightness = (
      get_brightness(idx, leds_brightness) -
      get_brightness(idx + idx_offset[i], leds_brightness)
    );
    force = accel(brightness, dist);
    a -= force; // assume mass is 1.
  }
  leds_vel[idx] = apply_acc(leds_vel[idx], a);

  return leds_brightness[idx] + leds_vel[idx];
}

CRGB bright2CRGB(float brightness){
  if (brightness <= 0) {
    return CRGB(-brightness, 0, -brightness);
  } else if (brightness > 0) {
    return CRGB(0,brightness / 4,brightness / 2);
  } else {
    return CRGB(0,0,0);
  }
}

float color_rotate = 0.0;
float color_a[6];
float color_b[6];

void change_color(float *color_array){
  for (int i = 0; i < 6; i++)
    color_array[i] = ((float)random(255)) / 255.0;
  Serial.printf("\n%.2f %.2f %.2f\n%.2f %.2f %.2f",
    color_array[0],
    color_array[1],
    color_array[2],
    color_array[3],
    color_array[4],
    color_array[5]
  );
  Serial.println();
}

int color_transition = 1;
int color_transition_len = 0;
int color_transition_delay = 20;
float color_transition_inc = 0.0;

void transition(){
  if (color_transition-- <= 0){
    if (color_transition_len > 0){
      color_transition_len = 0;
      color_transition = random(TRANSITION_DELAY_VARIANCE) + TRANSITION_DELAY;
      color_transition_delay = color_transition;
    } else {
      color_transition_delay = 0;
      color_transition = random(TRANSITION_LENGTH_VARIANCE) + TRANSITION_LENGTH;
      color_transition_len = color_transition;
      if (color_rotate < .1){
        change_color(color_a);
        color_transition_inc = (1-color_rotate) / color_transition_len;
      } else {
        change_color(color_b);
        color_transition_inc = -(color_rotate / color_transition_len);
      }
    }
    Serial.println();
  } else {
    if (color_transition_len > 0){
      color_rotate += color_transition_inc;
    }
    if (color_transition_delay > 0){
      // waiting
    }
  }
}

CRGB dualbright2CRGB(float abright, float bbright){
  float r=0, b=0, g=0;
  if (abright > 0) {
    r += color_rotate * abright * color_a[0];
    g += color_rotate * abright * color_a[1];
    b += color_rotate * abright * color_a[2];
  } else if (abright <= 0) {
    r -= color_rotate * abright * color_a[3];
    g -= color_rotate * abright * color_a[4];
    b -= color_rotate * abright * color_a[5];
  }
  if (bbright > 0) {
    r += (1 - color_rotate) * bbright * color_b[0];
    g += (1 - color_rotate) * bbright * color_b[1];
    b += (1 - color_rotate) * bbright * color_b[2];
  } else if (bbright <= 0) {
    r -= (1 - color_rotate) * bbright * color_b[3];
    g -= (1 - color_rotate) * bbright * color_b[4];
    b -= (1 - color_rotate) * bbright * color_b[5];
  }
  return CRGB(
    min(BRIGHTNESS_GAIN * r, MAX_BRIGHTNESS),
    min(BRIGHTNESS_GAIN * g, MAX_BRIGHTNESS),
    min(BRIGHTNESS_GAIN * 4 * b/3, MAX_BRIGHTNESS)
  );
}

bool atoggle = true;
bool btoggle = true;
CRGB temp_led_val;

float drop_force;

void rain() {
  transition();
  for (int i = 0; i < NUM_LEDS; i++) {
    anext_leds_brightness[i] = next_for_idx(i, aleds_brightness, aleds_vel);
    bnext_leds_brightness[i] = next_for_idx(i, bleds_brightness, bleds_vel);
  }
  if (random(10) == 0){
    drop_force = random(10) + DROP_FORCE;
    if (atoggle) anext_leds_brightness[random(NUM_LEDS)] = drop_force;
    else anext_leds_brightness[random(NUM_LEDS)] = -drop_force;
    atoggle = !atoggle;
  }
  if (random(10) == 0){
    drop_force = random(10) + DROP_FORCE;
    if (btoggle) bnext_leds_brightness[random(NUM_LEDS)] = drop_force;
    else bnext_leds_brightness[random(NUM_LEDS)] = -drop_force;
    btoggle = !btoggle;
  }
  for (int _k = 0, k=0; _k<TRUE_LED_COUNT; _k++){
    k =  _k%NUM_LEDS;
    k = 20 / NUM_LEDS % 2 == 0 ? k : (NUM_LEDS - k);
    aleds_brightness[k] = anext_leds_brightness[k];
    bleds_brightness[k] = bnext_leds_brightness[k];
    temp_led_val = dualbright2CRGB(aleds_brightness[k], bleds_brightness[k]);
    leds[_k] = temp_led_val;
    leds[_k] = temp_led_val;
  }
  show_at_max_brightness_for_power();
  counter++;
  counter = counter % (TRUE_LED_COUNT * FALL_SPEED * 10);
}

void loop(){
  rain();
}

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


Added files via upload

Added files via upload

#include <Adafruit_NeoPixel.h>
#include "Time.h"

#define PIN 6

// Parameter 1 = number of pixels in strip
// Parameter 2 = pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800);

void setup() {
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  Serial.begin(9600);
  Serial.println("alkaa");

}

int i = 0;
int p = 0;

void loop() {
   //i = (i +1) % 4;
   //strip.setPixelColor(i, 255, 0, 255);
   strip.show();

   //Serial.println("mika ledi");
   //int led_nro = read_serial();
   //Serial.println("anna rgb arvoja");
   //int r = read_serial();
   //int g = read_serial();
   //int b = read_serial();
   while(true) {

     unsigned long startt = micros();
     unsigned long endt = micros();

     strip.setPixelColor(0, 255, 255, 255);
     //strip.setPixelColor((i-1)%8, 0, 0, 0);
     strip.show();
     strip.setPixelColor(0,0,0,0);
     strip.show();
     i = (i+1)%100;
     if (i == 0) {
       if (p==1) {
         startt = millis();
         Serial.print("alku:");
         Serial.println(startt);
         strip.setPixelColor(1,255,0,0);
         strip.show();
         p = 0;
       } else {
         endt = millis();
         Serial.print("loppu: ");
         Serial.println(endt);
         Serial.print("aikaa menee: ");
         unsigned long diff = endt-startt;
         Serial.println(diff);
         strip.setPixelColor(1,0,0,0);
         strip.show();
         p = 1;
   }
     }
   }
}

/* reads the serial for user inputted numbers*/
int read_serial()
{
  char intBuffer[12];
  String intData = "";
  int delimiter = (int) '\n';

  while(!Serial.available());
    while(1){
      int ch = Serial.read();
      if(ch == -1) {}
      else if (ch == delimiter) {
        break;
      }
      else {
        intData += (char) ch;
    }
  }
  int intLength = intData.length() +1;
  intData.toCharArray(intBuffer, intLength);
  intData = "";
  int i = atoi(intBuffer);
  return i;
}

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


extend transform

extend transform

#include <ros.h>
#include <ros/time.h>
#include <tf/transform_broadcaster.h>

ros::NodeHandle  nh;

geometry_msgs::TransformStamped t;
tf::TransformBroadcaster broadcaster;

char max_was_here[] = "/max_was_here";
char base_link[] = "/base_link";
char odom[] = "/odom";

static geometry_msgs::Quaternion createQuaternionFromRPY(double roll, double pitch, double yaw) {
    geometry_msgs::Quaternion q;
    double t0 = cos(yaw * 0.5);
    double t1 = sin(yaw * 0.5);
    double t2 = cos(roll * 0.5);
    double t3 = sin(roll * 0.5);
    double t4 = cos(pitch * 0.5);
    double t5 = sin(pitch * 0.5);
    q.w = t0 * t2 * t4 + t1 * t3 * t5;
    q.x = t0 * t3 * t4 - t1 * t2 * t5;
    q.y = t0 * t2 * t5 + t1 * t3 * t4;
    q.z = t1 * t2 * t4 - t0 * t3 * t5;
    return q;
}

void setup()
{
    nh.initNode();
    broadcaster.init(nh);
}

float tempNumber = 0;

void loop()
{
    tempNumber += 0.1;

    t.header.frame_id = odom;
    t.child_frame_id = base_link;
    t.transform.translation.x = 0.0;
    t.transform.translation.y = 0.0;
    t.transform.translation.z = 1.0;

    t.transform.rotation = createQuaternionFromRPY(0.0, 0.0, tempNumber);
    /*
    t.transform.rotation.x = 0.0;
    t.transform.rotation.y = 0.0;
    t.transform.rotation.z = 0.0;
    t.transform.rotation.w = 1.0;
    */

    t.header.stamp = nh.now();

    broadcaster.sendTransform(t);

    t.header.frame_id = base_link;
    t.child_frame_id = max_was_here;
    t.transform.translation.x = 0.0;
    t.transform.translation.y = 1.0;
    t.transform.translation.z = 0.0;

    t.transform.rotation = createQuaternionFromRPY(0.0, 0.0, 0.0);
    /*
    t.transform.rotation.x = 0.0;
    t.transform.rotation.y = 0.0;
    t.transform.rotation.z = 0.0;
    t.transform.rotation.w = 1.0;
    */

    t.header.stamp = nh.now();

    broadcaster.sendTransform(t);
    nh.spinOnce();

    delay(1);
}

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


i2cdetect

#include <Wire.h>
#include <i2cdetect.h>

void setup() {
  Serial.begin(9600);
  Serial.println("\n=============");
  Serial.println(__FILE__);
  Serial.println(__DATE__);
  Serial.println(__TIME__);
  Wire.begin();
  Serial.println("i2cdetect example\n");
  Serial.print("Scanning address range 0x03-0x77\n\n");
}

void loop() {
  i2cdetect();  // default range from 0x03 to 0x77
  delay(4000);
}

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


Firmware initial commit.

Firmware initial commit.

#define LED_PIN D7
#define MAX_CARDS
int state = 0;

typedef struct {
  char* rfid;
  bool allow;
  char* greeting;
} Card;

Card cards[1000];
int numCards = 0;

void setup() {
  numCards = 2;

  cards[0].rfid = "0000000001";
  cards[0].allow = true;
  cards[0].greeting = "Welcome, Batman.";

  cards[1].rfid = "0000000002";
  cards[1].allow = false;
  cards[1].greeting = "No way, Joker!";

  pinMode(LED_PIN, OUTPUT);
}
void loop() {
  digitalWrite(LED_PIN, (state) ? HIGH : LOW);

  //invert the state
  state = !state;

  //wait half a second
  delay(1000);
}

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


WiFly_Shield loopback test

WiFly_Shield loopback test

#include <SPI.h>
#include <WiFly.h>

#define WLAN_SSID       "ssid"
#define WLAN_PASS       "pass"
#define SerialWiFly     Serial1

//#include <SoftwareSerial.h>
//SoftwareSerial SerialWiFly(2, 3);

const char* host = "192.168.0.104";
uint16_t port = 8888;

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

  SerialWiFly.begin(9600);
  WiFly.setUart(&SerialWiFly);
  WiFly.begin();

  Serial.println("Join....");
  if (!WiFly.join(WLAN_SSID, WLAN_PASS)) {
    Serial.println("Association failed.");
    while (1) {
      // Hang on failure.
    }
  }
}

void draw(char c, int qty = 1) {
  static int col = 0;
  while (qty-- > 0) {
    Serial.print(c);
    col = (col + 1) % 80;
    if (!col) {
      Serial.println();
    }
  }
}

void loop(void)
{
  delay(5000);
  Serial.print("Connecting...");

  WiFlyClient client(host, port);
  if (client.connect()) {
    Serial.println(F("Connected."));
    /* Echo incoming data */
    while (client.connected()) {
      byte buf[128];
      int qty = client.available();
      if (qty) {
        qty = client.readBytes(buf, qty);
        qty = client.write((const uint8_t*)buf, qty);
        draw('.');
      }
    }
  } else {
    Serial.println(F("Connection failed"));
  }
  client.stop();
}


Easing function to write pins too.

Easing function to write pins too.

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/daithiocrualaoich/nightlight.git/'


CRGBSet_example.ino

CRGBSet_example.ino

Basic example of using CRGBSet with CRGBArray.

#include "FastLED.h"
#define NUM_LEDS 32

//CRGB leds[NUM_LEDS];  // Not using this.  Using CRGBArray instead.
CRGBArray<NUM_LEDS> leds;

CRGBSet partA(leds(6,9));  // Define custom pixel range with a name.
CRGBSet partB(leds(22,25));  // Define custom pixel range with a name.

CHSV colorOne(0,222,255);  // Define a custom color.
CHSV colorTwo(82,222,255);  // Define a custom color.

//---------------------------------------------------------------
void setup() {
  FastLED.addLeds<LPD8806, 11, 13, GRB>(leds, NUM_LEDS);
  FastLED.setBrightness(255);
}

//---------------------------------------------------------------
void loop()
{
  fill_rainbow(leds, NUM_LEDS, millis()/10);  // fill strip with moving rainbow.
  leds.fadeToBlackBy(230);  // fade the whole strip down some.
  partA = colorOne;  // set partA pixel color.
  partB = colorTwo;  // set partB pixel color.
  FastLED.show();

  EVERY_N_SECONDS(4){  // Swaps the two custom colors every four seconds.
    CHSV temp = colorOne;
    colorOne = colorTwo;
    colorTwo = temp;
  }
}

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


better smoothing

better smoothing

/**********************************************************
                Fast PWM Test
Demostrates the generation of high speed PWM
using timers 1 and 4
There are two pieces of code:
One for pins 9, 10 and 11 using TIMER 1
with frequencies up to 62kHz
Other for pins 6 and 13 using TIMER 4
with frequencies up to 187kHz
History:
  12/12/2014 - Version 1.0
  22/12/2014 - Adding a missing OCR4C value

  http://r6500.blogspot.com/2014/12/fast-pwm-on-arduino-leonardo.html

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

// https://web.archive.org/web/20140101032749/http://coolarduino.wordpress.com/2012/09/19/quasi-real-time-oscilloscope-remix/

/**********************************************************
   Fast PWM on pins 9,10,11 (TIMER 1)

   Do not use analogWrite to pins 9, 10 or 11 if using
   this functions as they use the same timer.

   Those functions will probably conflict with the
   servo library.

   Uses 5 PWM frequencies between 61Hz and 62.5kHz

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

/**********************************************************
   Fast PWM on pins 6, 13 (High Speed TIMER 4)

   Do not use analogWrite to pins 6 or 13 if using
   this functions as they use the same timer.

   Those functions will conflict with the
   MSTIMER2 library.
   Uses 7 PWM frequencies between 2930Hz and 187.5kHz

   Timer 4 uses a PLL as input so that its clock frequency
   can be up to 96MHz on standard Arduino Leonardo.
   We limit imput frequency to 48MHz to generate 187.5kHz PWM
   If needed, we can double that up to 375kHz
**********************************************************/

// Frequency modes for TIMER4
#define PWM187k 1   // 187500 Hz
#define PWM94k  2   //  93750 Hz
#define PWM47k  3   //  46875 Hz
#define PWM23k  4   //  23437 Hz
#define PWM12k  5   //  11719 Hz
#define PWM6k   6   //   5859 Hz
#define PWM3k   7   //   2930 Hz

// Direct PWM change variables
#define PWM6        OCR4D
#define PWM13       OCR4A

// Terminal count
#define PWM6_13_MAX OCR4C

// Configure the PWM clock
// The argument is one of the 7 previously defined modes
void pwm613configure(int mode)
{
// TCCR4A configuration
TCCR4A=0;

// TCCR4B configuration
TCCR4B=mode;

// TCCR4C configuration
TCCR4C=0;

// TCCR4D configuration
TCCR4D=0;

// TCCR4D configuration
TCCR4D=0;

// PLL Configuration
// Use 96MHz / 2 = 48MHz
// PLLFRQ=(PLLFRQ&0xCF)|0x30;
 PLLFRQ=(PLLFRQ&0xCF)|0x10; // Will double all frequencies

// Terminal count for Timer 4 PWM
OCR4C=255;
}

// Set PWM to D6 (Timer4 D)
// Argument is PWM between 0 and 255
void pwmSet6(int value)
{
OCR4D=value;   // Set PWM value
DDRD|=1<<7;    // Set Output Mode D7
TCCR4C|=0x09;  // Activate channel D
}

// Set PWM to D13 (Timer4 A)
// Argument is PWM between 0 and 255
void pwmSet13(int value)
{
OCR4A=value;   // Set PWM value
DDRC|=1<<7;    // Set Output Mode C7
TCCR4A=0x82;  // Activate channel A
}

/*************** ADDITIONAL DEFINITIONS ******************/

// Macro to converts from duty (0..100) to PWM (0..255)
#define DUTY2PWM(x)  ((255*(x))/100)

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

////////////////////////////////////////
//////////        WHOA        //////////
//////////        WHOA        //////////
//////////        WHOA        //////////
//////////        WHOA        //////////
//////////        WHOA        //////////
////////////////////////////////////////

// Pins

int hvDigitalIn = 19; // pf6 -> A1   D19
int hvClock = 18;     // pf7 -> A0   D18

int clearPin = 6;     // pd7 -> A7   D6#
int sense1 = A6;      // pd4 -> A6   D4
int sense2 = A11;     // pd6 -> A11  D12
int sense3 = 8;       // pb4 -> A8   D8
int sense4 = 9;       // pb5 -> A9   D9

int elEnable = 20;    // pf5 -> A2   D20

int detect = 5;

int rxled = 30;
int txled = 22;
int rstled = 7;

// This is hacky.
// Work around from this changing when the program is loaded from the IDE.
int capSenseFrequency = 1;

// State

#define channelCount 4
int switched[] = {0, 0, 0, 0};
bool glow[] = {true, true, true, true};
bool allGlow[] = {true, true, true, true};
bool noGlow[] = {false, false, false, false};

#define prevValSize 50
int prevVal[prevValSize][channelCount];

#define sampleCount 3
int sampleAll[channelCount][sampleCount];
int sampleAllVal[channelCount];

int samples[sampleCount];
int sampleVal = 0;

// Helpers

int tempGlow[channelCount];
byte tempGlow_unroll[channelCount * 2];
void switchOutputs(bool* glow) {
  // Make pins on the layout correspond to the pins on the switch
  tempGlow[2] = glow[0];
  tempGlow[3] = glow[1];
  tempGlow[1] = glow[2];
  tempGlow[0] = glow[3];

  // Process bit flips ahead of sending serial signal
  PORTF = PORTF | B10000000;
  for (int i = 0; i < 8; i++) {
    if (tempGlow[i / 2] == 1) {
      tempGlow_unroll[i] = PORTF | B01000000;
    }
    else {
      tempGlow_unroll[i] = PORTF & B10111111;
    }
  }

  for (int i = 0; i < 8; i++) {
    PORTF = tempGlow_unroll[i];
    //   digitalWrite(hvClock, LOW);
    PORTF = PORTF & B01111111;
    //   digitalWrite(hvClock, HIGH);
//    PORTF = PORTF | B10000000;
  }
  PORTF = PORTF | B10000000;

}

void switchHalfOutputsA() {
  for (int i = 0; i < 4; i++) {
    PORTF = PORTF | B01000000;
    PORTF = PORTF & B01111111;
    PORTF = PORTF | B10000000;

    PORTF = PORTF & B10111111;
    PORTF = PORTF & B01111111;
    PORTF = PORTF | B10000000;
  }
}

void switchHalfOutputsB() {
  for (int i = 0; i < 4; i++) {
    PORTF = PORTF & B10111111;
    PORTF = PORTF & B01111111;
    PORTF = PORTF | B10000000;

    PORTF = PORTF | B01000000;
    PORTF = PORTF & B01111111;
    PORTF = PORTF | B10000000;
  }
}

// This could be fancier...
void sort(int *a, int len)
{
   for (int i = 1; i < len; ++i)
   {
     int j = a[i];
     int k;
     for (k = i - 1; (k >= 0) && (j < a[k]); k--)
     {
       a[k + 1] = a[k];
     }
     a[k + 1] = j;
   }
}

// This mutates the input array! Beware!
float getMedian(int* array, int len) {
//  int len = sizeof(array);
  sort(array, len);
  float tempVal = 0;
  return array[(len / 2) + 1];

//  for (int i = (len / 2) - 1; i < (len / 2) + 2; i++) {
//    tempVal += array[i];
//  }
//  return tempVal / 3;
}

void ledsOff() {
  digitalWrite(rxled, LOW);
  digitalWrite(txled, LOW);
  digitalWrite(rstled, LOW);
}

void ledsOn() {
  digitalWrite(rxled, HIGH);
  digitalWrite(txled, HIGH);
  digitalWrite(rstled, HIGH);
}

unsigned long microsdelay;

// Arduino I/O is real slow.  Opaque bitwise port manipulation ftw!
int adcSensePorts[] = {B00000000, B00000001, B00000011, B00000100};

// this is internal, use the interface functions below!
bool toSense_internal[] = {true, true, true, true};
int senseResults_internal[] = {0, 0, 0, 0};

void initSense_withResistor(){
 // listen to resistor

    switchOutputs(noGlow);
    //  digitalWrite(elEnable, HIGH);
    PORTF = PORTF | B00100000;
    delayMicroseconds(100);

//    microsdelay = micros();
    while(bitRead(PINC, 6));
    switchOutputs(allGlow);
    switchHalfOutputsA();
    while(!bitRead(PINC, 6));
    while(bitRead(PINC, 6));
    while(!bitRead(PINC, 6));
    while(bitRead(PINC, 6));

    switchOutputs(noGlow);
    delayMicroseconds(30);

//    microsdelay = micros() - microsdelay;
}

int spinner = 0;
void initSense_withoutResistor() {
    // Hacky.  Allows charge to disappate faster - kills flicker.

//    switchOutputs(allGlow);
//    microsdelay = 0;
//    while(bitRead(PINC, 6) || microsdelay < 20){
//      microsdelay++;
//    }
    // digitalWrite(elEnable, LOW);
    PORTF = PORTF & B11011111;
    for (int i = 0; i < 70; i++) {
      switchHalfOutputsA();
      spinner = 0;
      while(spinner < 50) {
        spinner++;
      }

      switchHalfOutputsB();
      spinner = 0;
      while(spinner < 50) {
        spinner++;
      }
    }

    // Make EL lamps float
    switchOutputs(noGlow);
    delayMicroseconds(30);
}

void senseChannels_internal(int chargeDelay_micros = 1000) {
    noInterrupts();

    // make sure pwm oscillator is running.
    pwm613configure(capSenseFrequency);
    pwmSet13(127);

    // digitalWrite(clearPin, HIGH);
    PORTD = PORTD | B10000000;

    if (chargeDelay_micros < 1) {
      chargeDelay_micros = 1000;
    }

// Set ADC initialization bits - make sure things haven't gotten misconfigured.
    // 6: right adjust bits // last 5 bits select ADC.
    ADMUX = adcSensePorts[3];
    // high speed mode / 0 / analog selection, extra bit.
    ADCSRB = B10100000;
    // disable adc
    ADCSRA = B00000110;

    initSense_withoutResistor();

// Begin measurement sequence
    // digitalWrite(clearPin, LOW);
    PORTD = PORTD & B01111111;

    delayMicroseconds(chargeDelay_micros);
// start measurement
// Go backwords so that channel 4 has the lowest sensitivity and 1 has the highest.
    for(int i = 3; i >= 0; i--) {
      if (toSense_internal[i]) {
        // enable / start / auto trigger / interrupt flag / interrupt enable /// scale /// p.315
        ADCSRA = B11000110;
        delayMicroseconds(50);
        ADMUX = adcSensePorts[(i + 3) % 4];
        while ((ADCSRA & B01000000));
        sampleVal = ADCL;    // store lower byte ADC
        sampleVal += ADCH << 8;  // store higher bytes ADC
        senseResults_internal[i] = sampleVal;
      }
      else {
        ADMUX = adcSensePorts[(i + 3) % 4];
        senseResults_internal[i] = -1;
      }
    }

   //  digitalWrite(elEnable, HIGH);
   PORTF = PORTF | B00100000;
   interrupts();
   //    digitalWrite(clearPin, HIGH);
   PORTD = PORTD | B10000000;
   return;
}

// Sensing interfaces!
// Note that the channel here corresponds to the number written on the board,
// which is shifted up by one from the indicies in the senseResults array.
int senseChannel(int channel, int chargeDelay_micros = 1000, bool isGlow = true) {
  if (channel < 0 || channel > 4) {
    Serial.println("Warning: you might not be measuring the channel you intend to!");
    ledsOn();
  }
  channel = (channel - 1) % 4; // sanitize your inputs.
  for (int i = 0; i < 4; i++) {
    toSense_internal[i] = false;
  }
  toSense_internal[channel] = true;
  senseChannels_internal(chargeDelay_micros);
  if (isGlow) {
    switchOutputs(glow);
  }
  return senseResults_internal[channel];
}

int* senseAll(int chargeDelay_micros = 1000, bool isGlow = true) {
  for (int i = 0; i < 4; i++) {
    toSense_internal[i] = true;
  }
  senseChannels_internal(chargeDelay_micros);

  if (isGlow) {
    switchOutputs(glow);
  }
  return senseResults_internal;
}

// The ardunio IDE insists on changing the frequency of the fast pwm when the board is programmed
// This is a hack that accounts for that.
void ensureCorrectFrequency() {
  switchOutputs(noGlow);
  ledsOff();

  capSenseFrequency = PWM187k;
  int read187k = senseChannel(1, 5000);
  read187k = senseChannel(1, 5000);
  read187k = senseChannel(1, 5000);
//  Serial.print("187: ");
//  Serial.println(read187k);

  capSenseFrequency = PWM94k;
  int read94k = senseChannel(1, 5000);
  read94k = senseChannel(1, 5000);
  read94k = senseChannel(1, 5000);
//  Serial.print("94: ");
//  Serial.println(read94k);

  if (read94k > read187k) {
    capSenseFrequency = PWM94k;
    digitalWrite(rxled, HIGH);
    if (read94k > 150) {
      digitalWrite(txled, HIGH);
    }
    delay(200);
  }
  else{
    capSenseFrequency = PWM187k;
    digitalWrite(rstled, HIGH);
    if (read187k > 150) {
      digitalWrite(txled, HIGH);
    }
    delay(200);
  }
  ledsOff();
}

//////////~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~///////////

int* senseResults;

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

  // hvSwitch communication
  pinMode(hvDigitalIn, OUTPUT);
  pinMode(hvClock, OUTPUT);

  pinMode(clearPin, OUTPUT);
  digitalWrite(clearPin, LOW);

  pinMode(10, OUTPUT);

  pinMode(elEnable, OUTPUT);
  digitalWrite(elEnable, HIGH);

  pinMode(detect, INPUT);

  pinMode(sense1, INPUT);
  pinMode(sense2, INPUT);
  pinMode(sense3, INPUT);
  pinMode(sense4, INPUT);

  pinMode(rxled, OUTPUT);
  pinMode(txled, OUTPUT);
  pinMode(rstled, OUTPUT);

  analogReference(DEFAULT);

  // this should be called after the clear pin is set low
  ensureCorrectFrequency();
}

#define ENABLE_LOGGING

// Do this instead of using a bunch of individual Serial.print statements to save time!
// If your wire starts flashing when you are logging, this might be why!
#define printLineSize 200
char logBuffer[printLineSize];

#ifdef ENABLE_LOGGING
char tempLogBuffer[printLineSize];

//
#define subBufferSize 50
char signalBuffer[subBufferSize];
char impulseBuffer[subBufferSize];
// These are in reference to the impulse, which is itself a funny denoising derivative-y thing
char tailMeanBufferBuffer[subBufferSize];
char derivativeBuffer[subBufferSize];

#endif

int val = 0;

int minimum = 10000;
int maximum = 0;

#define senseSize 31
int senseHistory[channelCount][senseSize];
int senseHistoryTemp[senseSize];
int senseHistoryIter = 0;

bool isTouched = false;
bool whereTouched[] = {false, false, false, false};

float change = 0;

bool shouldGlow = true;

bool isOn = true;
bool justSwitched = false;
int switchedCount = 0;

#define smoothedSenseSize 15
int smoothedSenseHistory[channelCount][smoothedSenseSize];
int smoothedSenseIter = 0;

#define smoothedTouchWindow 4
float smoothedSampleMedian = 0;
float smoothedSampleMin = 0;
float smoothedSampleNew = 0;
int smoothedSampleTemp[smoothedSenseSize - smoothedTouchWindow];

int channelMean[] = {0, 0, 0, 0};
int chanImpulse;
int chanPrevImpulse;
int chanChangeCount;

// Here are the main levers which control the operation of this program
#define increaseWindow 11
#define pureIncreaseThreshold 7
#define increaseThresholdWithImpulse 5
#define impulseThreshold 6
#define glowTime_us 6800

void loop() {
    senseResults = senseAll(1300, true);

    smoothedSenseIter = (smoothedSenseIter + 1) % smoothedSenseSize;

    // Get new smoothed value
    for (int channel = 0; channel < channelCount; channel++) {
      senseHistory[channel][senseHistoryIter] = senseResults[channel];
      senseHistoryIter++;
      if (senseHistoryIter == senseSize) {
        senseHistoryIter = 0;
      }

      for (int i = 0; i < senseSize; i++) {
        senseHistoryTemp[i] = senseHistory[channel][i];
      }

      sort(senseHistoryTemp, senseSize);

      smoothedSenseHistory[channel][smoothedSenseIter] = senseHistoryTemp[0];

      for (int i = 0; i < 10; i++) {
        if (senseHistoryTemp[i + 1] - senseHistoryTemp[i] > 6) {
          smoothedSenseHistory[channel][smoothedSenseIter] = senseHistoryTemp[i + 1];
        }
      }

//    if(senseHistoryIter==0  && channel == 2){
//      for(int i=0; i<25; i++){
//        Serial.print(senseHistoryTemp[i]);
//        Serial.print(", ");
//      }
//      Serial.println();
//
//    }

    }

    for (int channel = 0; channel < channelCount; channel++) {
      channelMean[channel] = (channelMean[channel] +
                              smoothedSenseHistory[channel][(smoothedSenseIter + 1 + smoothedSenseSize) % smoothedSenseSize]) / 2;

      chanImpulse = channelMean[channel] - smoothedSenseHistory[channel][smoothedSenseIter];
      chanPrevImpulse = channelMean[channel] - smoothedSenseHistory[channel][(smoothedSenseIter + smoothedSenseSize - 1) % smoothedSenseSize];
      chanChangeCount = 0;

      int senseDiff;
      for (int steps = 0; steps < increaseWindow; steps++) {
        senseDiff = smoothedSenseHistory[channel][(smoothedSenseIter - (steps + 1) + smoothedSenseSize) % smoothedSenseSize]
            - smoothedSenseHistory[channel][(smoothedSenseIter - (steps) + smoothedSenseSize) % smoothedSenseSize];

        if (senseDiff > 0) {
          chanChangeCount += 1;
          if (steps < 3) {
            chanChangeCount += 1;
          }
          if (steps == 0) {
            chanChangeCount += 1;
          }
        }
      }

      if (switchedCount == 0 &&
           ((chanImpulse > impulseThreshold && chanChangeCount >= increaseThresholdWithImpulse) ||
            (chanChangeCount >= pureIncreaseThreshold)) ){
        isTouched = true;
        whereTouched[channel] = true;
#ifndef ENABLE_LOGGING
        sprintf(logBuffer, "Switched channel: %d Measurement: %d Impulse: %d Recent transition count: %d",
          channel, smoothedSenseHistory[channel][smoothedSenseIter], chanImpulse, chanChangeCount);
        Serial.println(logBuffer);
#endif
      }

#ifdef ENABLE_LOGGING

    // EXEX - Logging inline - pull into a function!
    int tailMeanlen;
    int derivativelen;
    int impulselen;

    switch (channel) {
      case 0:
        impulselen = sprintf(impulseBuffer, "Imp: %d, ",
                             chanImpulse);
        derivativelen = sprintf(derivativeBuffer, "Inc Adj: %d, ",
                                chanChangeCount);
        tailMeanlen = sprintf(tailMeanBufferBuffer, "Tail Diff: %d, ",
                              chanPrevImpulse);

        break;

      case 1:
      case 2:
      case 3:
        impulselen += sprintf(impulseBuffer + impulselen, "%d, ",
                              chanImpulse);
        derivativelen += sprintf(derivativeBuffer + derivativelen, "%d, ",
                                 chanChangeCount);
        tailMeanlen += sprintf(tailMeanBufferBuffer + tailMeanlen, "%d, ",
                               chanPrevImpulse);

        break;

      default:
        break;
    }
#endif

    }

#ifdef ENABLE_LOGGING
  int signallen;
  for (int chan = 0; chan < channelCount; chan++) {
    switch (chan) {
      case 0:
        for (int l = 0; l < printLineSize; l++) {
          tempLogBuffer[l] = logBuffer[l];
        }
        signallen = sprintf(signalBuffer, "Signal: %d, ", smoothedSenseHistory[chan][smoothedSenseIter]);
        break;

      case 1:
      case 2:
      case 3:
        signallen += sprintf(signalBuffer + signallen, "%d, ", smoothedSenseHistory[chan][smoothedSenseIter]);
        break;

      default:
        Serial.print("blah ");
        break;
    }
  }

  snprintf(logBuffer, printLineSize, "%s %s %s %s %s",
           signalBuffer,
           impulseBuffer, "",
        //   tailMeanBufferBuffer,
           derivativeBuffer, "");

  Serial.println(logBuffer);
#endif

    if (isTouched && switchedCount == 0) {
      isTouched = false;
      for (int chan = 0; chan < channelCount; chan++) {
        if (whereTouched[chan]) {
#ifdef ENABLE_LOGGING
          Serial.println("SWITCHED CHANNEL!");
          Serial.println(chan);
#endif
          whereTouched[chan] = false;
          glow[chan] = !glow[chan];
        }
      }
      switchedCount = 1.5 * smoothedSenseSize;
    }

    switchOutputs(glow);

    if (switchedCount > 0) {
      switchedCount--;
    }

    delayMicroseconds(glowTime_us);
}

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


Create MRLCommOculus.ino

Create MRLCommOculus.ino

/**
*
* @author GroG (at) myrobotlab.org
*
* This file is part of MyRobotLab.
*
* Enjoy !
*
* MRLComm.ino
* -----------------
* Purpose: support servos, sensors, analog & digital polling
* oscope, motors, range sensors, pingdar & steppers.
*
* Requirements: MyRobotLab running on a computer & a serial connection
*
*/

#include <Servo.h>

// ----------  MRLCOMM FUNCTION INTERFACE BEGIN -----------
#define MRLCOMM_VERSION				20

// serial protocol functions
#define MAGIC_NUMBER  					170 // 10101010

// MRL ---> Arduino methods
#define DIGITAL_WRITE        			0
#define DIGITAL_VALUE        			1
#define ANALOG_WRITE         			2
#define ANALOG_VALUE         			3
#define PINMODE              			4
#define PULSE_IN             			5
#define SERVO_ATTACH         			6
#define SERVO_WRITE          			7
#define SERVO_SET_MAX_PULSE  			8
#define SERVO_DETACH         			9
#define SET_PWM_FREQUENCY    			11
#define SET_SERVO_SPEED           		12
#define ANALOG_READ_POLLING_START	 	13
#define ANALOG_READ_POLLING_STOP	 	14
#define DIGITAL_READ_POLLING_START	 	15
#define DIGITAL_READ_POLLING_STOP		16
#define SET_ANALOG_TRIGGER				17
#define REMOVE_ANALOG_TRIGGER			18
#define SET_DIGITAL_TRIGGER				19
#define REMOVE_DIGITAL_TRIGGER			20
#define DIGITAL_DEBOUNCE_ON				21
#define DIGITAL_DEBOUNCE_OFF			22
#define DIGITAL_TRIGGER_ONLY_ON			23
#define DIGITAL_TRIGGER_ONLY_OFF		24
#define SET_SERIAL_RATE					25
#define GET_MRLCOMM_VERSION				26
#define SET_SAMPLE_RATE					27
#define SERVO_WRITE_MICROSECONDS		28
#define MRLCOMM_ERROR					29

#define PINGDAR_ATTACH              	30
#define PINGDAR_START             		31
#define PINGDAR_STOP              		32
#define PINGDAR_DATA 					33

#define SENSOR_ATTACH 					34
#define SENSOR_POLLING_START			35
#define SENSOR_POLLING_STOP				36
#define SENSOR_DATA 					37

#define SERVO_SWEEP_START				38
#define SERVO_SWEEP_STOP				39

// callback event - e.g. position arrived
// MSG MAGIC | SZ | SERVO-INDEX | POSITION
#define SERVO_EVENTS_ENABLE				40
#define SERVO_EVENT					41

#define LOAD_TIMING_ENABLE				42
#define LOAD_TIMING_EVENT				43

#define STEPPER_ATTACH					44
#define STEPPER_MOVE					45
#define STEPPER_STOP					46
#define STEPPER_RESET					47

#define STEPPER_EVENT					48
#define STEPPER_EVENT_STOP				1

#define STEPPER_TYPE_POLOLU  			1

#define CUSTOM_MSG						50

// servo event types
#define  SERVO_EVENT_STOPPED			1
#define  SERVO_EVENT_POSITION_UPDATE 	2

// error types
#define ERROR_SERIAL					1
#define ERROR_UNKOWN_CMD				2

// sensor types
#define SENSOR_ULTRASONIC				1

// need a method to identify type of board
// http://forum.arduino.cc/index.php?topic=100557.0

#define COMMUNICATION_RESET	   252
#define SOFT_RESET			   253
#define NOP  255

// ----------  MRLCOMM FUNCTION INTERFACE END -----------

// MAX definitions
// MAX_SERVOS defined by boardtype/library
#define PINGDARS_MAX		6
#define SENSORS_MAX			12
#define STEPPERS_MAX		6

#define MAX_MOTORS 10

#define ECHO_STATE_START 1
#define ECHO_STATE_TRIG_PULSE_BEGIN 2
#define ECHO_STATE_TRIG_PULSE_END 3
#define ECHO_STATE_MIN_PAUSE_PRE_LISTENING 4
#define ECHO_STATE_LISTENING 5
#define ECHO_STATE_GOOD_RANGE	6
#define ECHO_STATE_TIMEOUT	7

// --VENDOR DEFINE SECTION BEGIN--
// --VENDOR DEFINE SECTION END--

// FIXME FIXME FIXME
// -- FIXME - modified by board type BEGIN --
// Need Arduino to do a hardware abstraction layer
// https://code.google.com/p/arduino/issues/detail?id=59
// AHAAA !! - many defintions in - pins_arduino.h !!!
// Need a "board" identifier at least !!!

#define ANALOG_PIN_COUNT 16 // mega
#define DIGITAL_PIN_COUNT 54 // mega
// #define MAX_SERVOS 48 - is defined @ compile time !!
// -- FIXME - modified by board type END --

#define ARDUINO_TYPE_INT 16; // :) type identifier - not size - but what the hell ;)

/*
* TODO - CRC for last byte
* getCommand - retrieves a command message
* inbound and outbound messages are the same format, the following represents a basic message
* format
*
* MAGIC_NUMBER|NUM_BYTES|FUNCTION|DATA0|DATA1|....|DATA(N)
*              NUM_BYTES - is the number of bytes after NUM_BYTES to the end
*
*/

int msgSize = 0; // the NUM_BYTES of current message

unsigned int debounceDelay = 50; // in ms
long lastDebounceTime[DIGITAL_PIN_COUNT];
byte msgBuf[64];

typedef struct
  {
      int type;
      int trigPin;
      int echoPin;
      bool isRunning;
      int timeoutUS;
      unsigned long ts;
      unsigned long lastValue;
      int state;
      //NewPing* ping;
  }  sensor_type;

sensor_type sensors[SENSORS_MAX];

typedef struct
  {
  	  int ts;
      int type;
      int index;
      int currentPos;
      int targetPos;
      int speed;
      int dir;
      bool isRunning;
      int state;
      // int dirPin;
      int step0; // step0 is dirPin is POLOLU TYPE
      int step1;
      int step2;
      int step3;
  }  stepper_type;

stepper_type steppers[STEPPERS_MAX];

// Servos
typedef struct
{
    Servo* servo;
    int index; // index of this servo
    int speed;
    int targetPos;
    int currentPos;
    bool isMoving;

    int step; // affects speed usually 1

    // sweep related
    int min;
    int max;
    // int delay; - related to speed
    int increment;
    bool isSweeping;

    // event related
    bool eventsEnabled;
} servo_type;

servo_type servos[MAX_SERVOS];

// Motors
typedef struct
{
    int index; // index of this motor
    int speed;
    int targetPos;
    int currentPos;
    bool isMoving;

    int step; // affects speed usually 1

    // sweep related
    int min;
    int max;
    // int delay; - related to speed
    int increment;
    bool isSweeping;

    // event related
    bool eventsEnabled;
} motor_type;

motor_type motors[MAX_MOTORS];

unsigned long loopCount     = 0;
unsigned long lastMicros 	= 0;
int byteCount               = 0;
unsigned char newByte 		= 0;
unsigned char ioCmd[64];  // message buffer for all inbound messages
int readValue;

// FIXME - normalize with sampleRate ..
int loadTimingModulus = 1000;

boolean loadTimingEnabled = false;
unsigned long loadTime = 0;
// TODO - avg load time

unsigned int sampleRate = 1; // 1 - 65,535 modulus of the loopcount - allowing you to sample less

int digitalReadPin[DIGITAL_PIN_COUNT];        // array of pins to read from
int digitalReadPollingPinCount = 0;           // number of pins currently reading
int lastDigitalInputValue[DIGITAL_PIN_COUNT]; // array of last input values
bool digitalTriggerOnly	= false;      // send data back only if its different

int analogReadPin[ANALOG_PIN_COUNT];          // array of pins to read from
int analogReadPollingPinCount = 0;            // number of pins currently reading
int lastAnalogInputValue[ANALOG_PIN_COUNT];   // array of last input values
bool analogTriggerOnly = false;         // send data back only if its different

unsigned int errorCount = 0;

//---- data record definitions begin -----

// TODO - all well and good .. but you dont control Servo's data (yet)
// should have a struct for it too - contains all the data info you'd want to have
// in a servo - same with stepper

typedef struct
  {
      int servoIndex; // id of servo in servos array
      //int servoPos; in servo
      int sensorIndex;
      int sweepMin;
      int sweepMax;
      int step;
      bool isRunning; // needed ? - is combo of two
  }  pingdar_type;

pingdar_type pingdars[PINGDARS_MAX];
//===custom msg interface begin===
	byte customParams[256];
	int paramBuffIndex;
	int paramCnt;
//===custom msg interface end===

/* could optimize - but makes for ugly code - just to save a couple clock cycles - counting to 6 :P
not worth it
int pingdarsRunningCount = 0;
int pingdarsRunning[6]; // map array of running pingdars
*/

void sendServoEvent(servo_type& s, int eventType);
unsigned long getUltrasonicRange(sensor_type& sensor);
// void sendMsg ( int num, ... );

//---- data record definitions end -----

void append(const int& data) {
	++paramCnt;
	customParams[paramBuffIndex] = ARDUINO_TYPE_INT;
	customParams[++paramBuffIndex] = (byte)(data >> 8);
	customParams[++paramBuffIndex] = ((byte) data & 0xFF);
	++paramBuffIndex;
}

void startMsg() {
}

void setup() {
	Serial.begin(57600);        // connect to the serial port

	softReset();

	// --VENDOR SETUP BEGIN--
	// --VENDOR SETUP END--
}

void sendMsg(){

	// unbox
	Serial.write(MAGIC_NUMBER);
	Serial.write(paramBuffIndex + 2); // = param buff size + FN + paramCnt
	//Serial.write(2); // = param buff size + FN + paramCnt
	Serial.write(CUSTOM_MSG);
	Serial.write(paramCnt);

	for (int i = 0; i < paramBuffIndex; ++i){
		Serial.write(customParams[i]);
	}

	paramCnt = 0;
	paramBuffIndex = 0;
}

void softReset()
{
	for (int i = 0; i < MAX_SERVOS - 1; ++i)
	{
                servo_type& s = servos[i];
		s.speed = 100;
                if (s.servo != 0){
		  s.servo->detach();
                }
	}

	for (int j = 0; j < DIGITAL_PIN_COUNT - 1; ++j)
	{
		pinMode(j, OUTPUT);
	}

	digitalReadPollingPinCount = 0;
	analogReadPollingPinCount = 0;
	loopCount = 0;

}

void setPWMFrequency (int address, int prescalar)
{
	int clearBits = 0x07;
	if (address == 0x25)
	{
		TCCR0B &= ~clearBits;
		TCCR0B |= prescalar;
	} else if (address == 0x2E)
	{
		TCCR1B &= ~clearBits;
		TCCR1B |= prescalar;
	} else if (address == 0xA1)
	{
		TCCR2B &= ~clearBits;
		TCCR2B |= prescalar;
	}

}

void removeAndShift (int array [], int& len, int removeValue)
{
	int pos = -1;

	if (len == 0)
	{
		return;
	}

	// find position of value
	for (int i = 0; i < len; ++i)
	{
		if (removeValue == array[i])
		{
			pos = i;
			break;
		}
	}
	// if at the end just decrement size
	if (pos == len - 1)
	{
		--len;
		return;
	}

	// if found somewhere else shift left
	if (pos < len && pos > -1)
	{
		for (int j = pos; j < len - 1; ++j)
		{
			array[j] = array[j+1];
		}
		--len;
	}
}

boolean getCommand ()
{
	// handle serial data begin
	if (Serial.available() > 0)
	{
		// read the incoming byte:
		newByte = Serial.read();
		++byteCount;

		// checking first byte - beginning of message?
		if (byteCount == 1 && newByte != MAGIC_NUMBER)
		{
			++errorCount;
			sendError(ERROR_SERIAL);

			// reset - try again
			byteCount = 0;
			return false;
		}

		if (byteCount == 2)
		{
		   // get the size of message
		   // todo check msg < 64 (MAX_MSG_SIZE)
		   msgSize = newByte;
		}

		if (byteCount > 2) {
		  // fill in msg data - (2) headbytes -1 (offset)
		  ioCmd[byteCount - 3] = newByte;
		}

		// if received header + msg
		if (byteCount == 2 + msgSize)
		{
          return true;
		}
	} // if Serial.available

	return false;
}

void loop () {

	++loopCount;

	if (getCommand())
	{
		switch (ioCmd[0])
		{

		case DIGITAL_WRITE:{
			digitalWrite(ioCmd[1], ioCmd[2]);
			break;
		}

		case ANALOG_WRITE:{
			analogWrite(ioCmd[1], ioCmd[2]);
			break;
		}

		case PINMODE:{
			pinMode(ioCmd[1], ioCmd[2]);
			break;
		}

		case SERVO_ATTACH:{
			servo_type& s = servos[ioCmd[1]];
			s.index = ioCmd[1];
			if (s.servo == NULL){
				s.servo = new Servo();
			}
			s.servo->attach(ioCmd[2]);
			s.step = 1;
			s.eventsEnabled = false;
			break;
		}

		case SERVO_SWEEP_START:{
			servo_type& s = servos[ioCmd[1]];
			s.min = ioCmd[2];
			s.max = ioCmd[3];
			s.step = ioCmd[4];
			s.isMoving = true;
			s.isSweeping = true;
			break;
		}

		case SERVO_SWEEP_STOP:{
			servo_type& s = servos[ioCmd[1]];
			s.isMoving = false;
			s.isSweeping = false;
			break;
		}

		case SERVO_WRITE:{
			servo_type& s = servos[ioCmd[1]];
			if (s.speed == 100 && s.servo != 0)// move at regular/full 100% speed
			{
				s.targetPos = ioCmd[2];
				s.currentPos = ioCmd[2];
				s.isMoving = false;
				s.servo->write(ioCmd[2]);
				if (s.eventsEnabled) sendServoEvent(s, SERVO_EVENT_STOPPED);
			} else if (s.speed < 100 && s.speed > 0) {
				s.targetPos = ioCmd[2];
				s.isMoving = true;
			}
			break;
		}

		case SERVO_EVENTS_ENABLE:{
			servo_type& s = servos[ioCmd[1]];
			s.eventsEnabled = ioCmd[2];
			break;
		}

		case LOAD_TIMING_ENABLE:{
			loadTimingEnabled = ioCmd[1];
			//loadTimingModulus = ioCmd[2];
			loadTimingModulus = 1000;
			break;
		}

		case SERVO_WRITE_MICROSECONDS:{
			// TODO - incorporate into speed control etc
			// normalize - currently by itself doesn't effect events
			// nor is it involved in speed control
			servo_type& s = servos[ioCmd[1]];
			if (s.servo != 0) {
				// 1500 midpoint
				s.servo->writeMicroseconds(ioCmd[2]);
			}

			break;
		}

		case SET_SERVO_SPEED:{
			// setting the speed of a servo
			servo_type& servo = servos[ioCmd[1]];
			servo.speed = ioCmd[2];
			break;
		}

		case SERVO_DETACH:{
			servo_type& s = servos[ioCmd[1]];
			if (s.servo != 0){
			  s.servo->detach();
			}
			break;
		}

		case SET_PWM_FREQUENCY:{
			setPWMFrequency (ioCmd[1], ioCmd[2]);
			break;
		}

		case ANALOG_READ_POLLING_START:{
			analogReadPin[analogReadPollingPinCount] = ioCmd[1]; // put on polling read list
			// TODO - if POLLING ALREADY DON'T RE-ADD - MAKE RE-ENTRANT - if already set don't increment
			++analogReadPollingPinCount;
			break;
		}

		case ANALOG_READ_POLLING_STOP:{
			// TODO - MAKE RE-ENRANT
			removeAndShift(analogReadPin, analogReadPollingPinCount, ioCmd[1]);
			break;
		}

		case DIGITAL_READ_POLLING_START:{
			// TODO - MAKE RE-ENRANT
			digitalReadPin[digitalReadPollingPinCount] = ioCmd[1]; // put on polling read list
			++digitalReadPollingPinCount;
			break;
		}

		case DIGITAL_READ_POLLING_STOP:{
			// TODO - MAKE RE-ENRANT
			removeAndShift(digitalReadPin, digitalReadPollingPinCount, ioCmd[1]);
			break;
		}

		case SET_ANALOG_TRIGGER:{
			// TODO - if POLLING ALREADY DON'T RE-ADD - MAKE RE-ENTRANT
			analogReadPin[analogReadPollingPinCount] = ioCmd[1]; // put on polling read list
			++analogReadPollingPinCount;
			break;
		}

		case DIGITAL_DEBOUNCE_ON:{
			// debounceDelay = 50;
			debounceDelay = ((ioCmd[1]<<8) + ioCmd[2]);
			break;
		}

		case DIGITAL_DEBOUNCE_OFF:{
			debounceDelay = 0;
			break;
		}

		case DIGITAL_TRIGGER_ONLY_ON:{
			digitalTriggerOnly = true;
			break;

		case DIGITAL_TRIGGER_ONLY_OFF:
			digitalTriggerOnly = false;
			break;
		}

		case SET_SERIAL_RATE:
		{
			Serial.end();
			delay(500);
			Serial.begin(ioCmd[1]);
			break;
		}

		case GET_MRLCOMM_VERSION:{
			Serial.write(MAGIC_NUMBER);
			Serial.write(2); // size
			Serial.write(GET_MRLCOMM_VERSION);
			Serial.write((byte)MRLCOMM_VERSION);
			break;
			}

		case PULSE_IN: {
		    // might need to hack the pulseIn lib - but would
		    // like to do it without delay
			// http://arduino.cc/en/Tutorial/BlinkWithoutDelay
			int trigPin = ioCmd[1];
			int echoPin = ioCmd[2];
			// TODO - implement HI/LOW value & timeout & variable delay for trigger

			pinMode(trigPin, OUTPUT);
			pinMode(echoPin, INPUT);

			digitalWrite(trigPin, LOW);
			delayMicroseconds(2);

			digitalWrite(trigPin, HIGH);
			delayMicroseconds(10);

			digitalWrite(trigPin, LOW);
			unsigned long duration = pulseIn(echoPin, HIGH);

			//Calculate the distance (in cm) based on the speed of sound.
			// distance = duration/58.2;

			//sendMsg(4, ANALOG_VALUE, analogReadPin[i], readValue >> 8, readValue & 0xFF);
 			//sendMsg(5, PULSE_IN, duration >> 24, duration >> 16, duration >> 8, duration & 0xFF);
 			//sendMsg(6, SENSOR_DATA, 47, duration >> 24, duration >> 16, duration >> 8, duration & 0xFF);

			Serial.write(MAGIC_NUMBER);
			Serial.write(5); // size 1 FN + 4 bytes of unsigned long
			Serial.write(PULSE_IN);
            // write the long value out
			Serial.write((byte)(duration >> 24));
			Serial.write((byte)(duration >> 16));
			Serial.write((byte)(duration >> 8));
			Serial.write((byte)duration & 0xFF);

			break;
		}

		case SET_SAMPLE_RATE:{
			// 2 byte int - valid range 1-65,535
			sampleRate = (ioCmd[1]<<8) + ioCmd[2];
			if (sampleRate == 0)
				{ sampleRate = 1; } // avoid /0 error - FIXME - time estimate param
			break;
		}

		case SOFT_RESET:{
			softReset();
			break;
		}

		case STEPPER_ATTACH:{
			stepper_type& stepper = steppers[ioCmd[1]];
			stepper.index = ioCmd[1];
			stepper.type = ioCmd[2];
			stepper.isRunning = false;
			stepper.currentPos = 0;
			stepper.targetPos = 0;
			stepper.dir = 0;
			stepper.speed = 100;

			if (stepper.type == STEPPER_TYPE_POLOLU) {
				stepper.step0 = ioCmd[3]; // dir pin
				stepper.step1 = ioCmd[4]; // step pin
			} else {
				sendError(ERROR_UNKOWN_CMD);
			}
			break;
		}

		case STEPPER_RESET:{
			stepper_type& stepper = steppers[ioCmd[1]];
			stepper.isRunning = false;
			stepper.currentPos = 0;
			stepper.targetPos = 0;
			stepper.dir = 0;
			stepper.speed = 100;
			break;
		}

		case STEPPER_MOVE:{
			stepper_type& stepper = steppers[ioCmd[1]];
			if (stepper.type == STEPPER_TYPE_POLOLU) {
				stepper.isRunning = true;

				stepper.targetPos = stepper.currentPos + (ioCmd[2]<<8) + ioCmd[3];
				// relative position & direction
				if (stepper.targetPos < 0) {
					// direction
					digitalWrite(stepper.step0, 1);
				} else {
					digitalWrite(stepper.step0, 0);
				}
			} else {
				sendError(ERROR_UNKOWN_CMD);
			}
			break;
		}

		case STEPPER_STOP:{
			stepper_type& stepper = steppers[ioCmd[1]];
			if (stepper.type == STEPPER_TYPE_POLOLU) {
				stepper.isRunning = false;
				stepper.targetPos = stepper.currentPos;

				Serial.write(MAGIC_NUMBER);
				Serial.write(5); // size = 1 FN + 1 eventType + 1 index + 1 curPos
				Serial.write(STEPPER_EVENT);
				Serial.write(STEPPER_EVENT_STOP);
				Serial.write(stepper.index); // send my index
				Serial.write(stepper.currentPos >> 8);   // MSB
				Serial.write(stepper.currentPos & 0xFF);	// LSB
			} else {
				sendError(ERROR_UNKOWN_CMD);
			}
			break;
		}

			// --VENDOR CODE BEGIN--
			// --VENDOR CODE END--

		case PINGDAR_ATTACH:{
			int pingdarIndex = ioCmd[1];
			pingdar_type& pingdar = pingdars[pingdarIndex];
			pingdar.servoIndex = ioCmd[2];
			pingdar.sensorIndex = ioCmd[3];
			pingdar.step = 1;
			break;
		}

		case SENSOR_ATTACH:{
			int sensorIndex = ioCmd[1];
			sensor_type& sensor = sensors[sensorIndex];
			sensor.type = ioCmd[2];

			// initialize based on sensor type
			if (sensor.type == SENSOR_ULTRASONIC){
				sensor.trigPin = ioCmd[3];
				sensor.echoPin = ioCmd[4];
				pinMode(sensor.trigPin, OUTPUT);
				pinMode(sensor.echoPin, INPUT);
				//sensor.ping = new NewPing(sensor.trigPin, sensor.echoPin, 100);
			}

			break;
		}

		case SENSOR_POLLING_START:{
			int sensorIndex = ioCmd[1];
			sensor_type& sensor = sensors[sensorIndex];
			sensor.isRunning = true;

			// I'm used to ms - and would need to change some
			// interfaces if i was to support inbound longs
			//sensor.timeoutUS = ioCmd[2] * 1000;
			sensor.timeoutUS = 20000; // 20 ms
			sensor.state = ECHO_STATE_START;

			break;
		}

		case SENSOR_POLLING_STOP:{
			int sensorIndex = ioCmd[1];
			sensor_type& sensor = sensors[sensorIndex];
			sensor.isRunning = false;
			break;
		}

		case NOP:{
			// No Operation
			break;
		}

		default:{
		    sendError(ERROR_UNKOWN_CMD);
			break;
		}
		} // end switch

		// reset buffer
		memset(ioCmd,0,sizeof(ioCmd));
		byteCount = 0;

	} // if getCommand()

	// all reads are affected by sample rate
	if (loopCount%sampleRate == 0) {
		// digital polling read - send data for pins which are currently in INPUT mode only AND whose state has changed
		for (int i  = 0; i < digitalReadPollingPinCount; ++i)
		{
			if (debounceDelay)
			{
			  if (millis() - lastDebounceTime[digitalReadPin[i]] < debounceDelay)
			  {
			    continue;
			  }
			}

			// read the pin
			readValue = digitalRead(digitalReadPin[i]);

			// if my value is different from last time  && config - send it
			if (lastDigitalInputValue[digitalReadPin[i]] != readValue  || !digitalTriggerOnly)
			{
				Serial.write(MAGIC_NUMBER);
				Serial.write(3); // size
				Serial.write(DIGITAL_VALUE);
				Serial.write(digitalReadPin[i]);// Pin#
				Serial.write(readValue); 	// LSB

			    lastDebounceTime[digitalReadPin[i]] = millis();
			}

			// set the last input value of this pin
			lastDigitalInputValue[digitalReadPin[i]] = readValue;
		}

		// analog polling read - send data for pins which are currently in INPUT mode only AND whose state has changed
		for (int i  = 0; i < analogReadPollingPinCount; ++i)
		{
			// read the pin
			readValue = analogRead(analogReadPin[i]);

			// if my value is different from last time - send it
			if (lastAnalogInputValue[analogReadPin[i]] != readValue   || !analogTriggerOnly) //TODO - SEND_DELTA_MIN_DIFF
			{
				//sendMsg(4, ANALOG_VALUE, analogReadPin[i], readValue >> 8, readValue & 0xFF);

				Serial.write(MAGIC_NUMBER);
				Serial.write(4); //size
				Serial.write(ANALOG_VALUE);
				Serial.write(analogReadPin[i]);
				Serial.write(readValue >> 8);   // MSB
				Serial.write(readValue & 0xFF);	// LSB

	        }
			// set the last input value of this pin
			lastAnalogInputValue[analogReadPin[i]] = readValue;
		}
	}

	// update moving servos - send events if required
	for (int i = 0; i < MAX_SERVOS; ++i)
	{
		servo_type& s = servos[i];
		if (s.isMoving && s.servo != 0){
			if (s.currentPos != s.targetPos)
			{
				// caclulate the appropriate modulus to drive
				// the servo to the next position
				// TODO - check for speed > 0 && speed < 100 - send ERROR back?
				int speedModulus = (100 - s.speed) * 10;
				if (loopCount % speedModulus == 0)
				{
					int increment = s.step * ((s.currentPos < s.targetPos)?1:-1);
					// move the servo an increment
					s.currentPos = s.currentPos + increment;
					s.servo->write(s.currentPos);
					if (s.eventsEnabled) sendServoEvent(s, SERVO_EVENT_POSITION_UPDATE);
				}
			} else {
				if (s.isSweeping) {
					if (s.targetPos == s.min){
						s.targetPos = s.max;
					} else {
						s.targetPos = s.min;
					}
				} else {
					if (s.eventsEnabled) sendServoEvent(s, SERVO_EVENT_STOPPED);
					s.isMoving = false;
				}
			}
		}
	}

	unsigned long ts;

	for (int i = 0; i < SENSORS_MAX; ++i) {
		sensor_type& sensor = sensors[i];
		if (sensor.isRunning == true){
			if (sensor.type == SENSOR_ULTRASONIC){

				// we are running & have an ultrasonic (ping) sensor
				// check to see what state we  are in

				if (sensor.state == ECHO_STATE_START){
					// trigPin prepare - start low for an
					// upcoming high pulse
					pinMode(sensor.trigPin, OUTPUT);
					digitalWrite(sensor.trigPin, LOW);

					// put the echopin into a high state
					// is this necessary ???
					pinMode(sensor.echoPin, OUTPUT);
					digitalWrite(sensor.echoPin, HIGH);

					ts = micros();
					if (ts - sensor.ts > 2){
						sensor.ts = ts;
						sensor.state = ECHO_STATE_TRIG_PULSE_BEGIN;
					}
				} else if (sensor.state == ECHO_STATE_TRIG_PULSE_BEGIN){

					// begin high pulse for at least 10 us
					pinMode(sensor.trigPin, OUTPUT);
					digitalWrite(sensor.trigPin, HIGH);

					ts = micros();
					if (ts - sensor.ts > 10){
						sensor.ts = ts;
						sensor.state = ECHO_STATE_TRIG_PULSE_END;
					}
				} else if (sensor.state == ECHO_STATE_TRIG_PULSE_END){
					// end of pulse
					pinMode(sensor.trigPin, OUTPUT);
					digitalWrite(sensor.trigPin, LOW);

					sensor.state = ECHO_STATE_MIN_PAUSE_PRE_LISTENING;
					sensor.ts = micros();
				} else if (sensor.state == ECHO_STATE_MIN_PAUSE_PRE_LISTENING){

					ts = micros();
					if (ts - sensor.ts > 1500){
						sensor.ts = ts;

						// putting echo pin into listen mode
						pinMode(sensor.echoPin, OUTPUT);
						digitalWrite(sensor.echoPin, HIGH);
						pinMode(sensor.echoPin, INPUT);

						sensor.state = ECHO_STATE_LISTENING;
					}

				} else if (sensor.state == ECHO_STATE_LISTENING) {
					// timeout or change states..
					int value = digitalRead(sensor.echoPin);
					ts = micros();

					if (value == LOW) {
						sensor.lastValue = ts - sensor.ts;
						sensor.ts = ts;
						sensor.state = ECHO_STATE_GOOD_RANGE;
					} else if (ts - sensor.ts > sensor.timeoutUS) {
						sensor.state = ECHO_STATE_TIMEOUT;
						sensor.ts = ts;
						sensor.lastValue = 0;
					}

				} else if (sensor.state == ECHO_STATE_GOOD_RANGE || sensor.state == ECHO_STATE_TIMEOUT) {
					Serial.write(MAGIC_NUMBER);
					Serial.write(6); // size 1 FN + 4 bytes of unsigned long
					Serial.write(SENSOR_DATA);
					Serial.write(i);
		            // write the long value out
					Serial.write((byte)(sensor.lastValue >> 24));
					Serial.write((byte)(sensor.lastValue >> 16));
					Serial.write((byte)(sensor.lastValue >> 8));
					Serial.write((byte) sensor.lastValue & 0xFF);
					sensor.state = ECHO_STATE_START;
				} // end else if

			} // if (sensor.type == SENSOR_ULTRASONIC)

		} // end isRunning

	} // end for each sensor

	// TODO - brake - speed - fractional stepping - other stepper types
	for (int i = 0; i < STEPPERS_MAX; ++i) {
		stepper_type& stepper = steppers[i];
		if (stepper.isRunning == true){
			if (stepper.type == STEPPER_TYPE_POLOLU){

				// direction is already set in initial STEPPER_MOVE

				if (stepper.currentPos < stepper.targetPos) {

				    // step - POLOLU has single step pin (dir is on step0)
					digitalWrite(stepper.step1, 1);
					delayMicroseconds(1); // :P should require another state? loop is ~106us min ?
					digitalWrite(stepper.step1, 0);

					stepper.currentPos++;
				} else if (stepper.currentPos > stepper.targetPos) {

				    // step - POLOLU has single step pin (dir is on step0)
					digitalWrite(stepper.step1, 1);
					delayMicroseconds(1); // :P should require another state? loop is ~106us min ?
					digitalWrite(stepper.step1, 0);

					stepper.currentPos--;

				} else {
					stepper.isRunning = false;
					stepper.currentPos = stepper.targetPos; // forcing ? :P
					Serial.write(MAGIC_NUMBER);
					Serial.write(5); // size = 1 FN + 1 eventType + 1 index + 1 curPos
					Serial.write(STEPPER_EVENT);
					Serial.write(STEPPER_EVENT_STOP);
					Serial.write(stepper.index); // send my index
					Serial.write(stepper.currentPos >> 8);   // MSB
					Serial.write(stepper.currentPos & 0xFF);	// LSB
				}

			}
		}
	}

	unsigned long now = micros();
	loadTime = now - lastMicros; // avg outside
 	lastMicros = now;

	// report load time
	if (loadTimingEnabled && (loopCount%loadTimingModulus == 0)) {

 		// send it
		Serial.write(MAGIC_NUMBER);
		Serial.write(5); // size 1 FN + 4 bytes of unsigned long
		Serial.write(LOAD_TIMING_EVENT);
        // write the long value out
		Serial.write((byte)(loadTime >> 24));
		Serial.write((byte)(loadTime >> 16));
		Serial.write((byte)(loadTime >> 8));
		Serial.write((byte) loadTime & 0xFF);
	}

} // end of big loop

unsigned long getUltrasonicRange(sensor_type& sensor){

		// added for sensors which have single pin !
		pinMode(sensor.trigPin, OUTPUT);
		digitalWrite(sensor.trigPin, LOW);
		delayMicroseconds(2);

		digitalWrite(sensor.trigPin, HIGH);
		delayMicroseconds(10);

		digitalWrite(sensor.trigPin, LOW);

		// added for sensors which have single pin !
		pinMode(sensor.echoPin, INPUT);
		// CHECKING return pulseIn(sensor.echoPin, HIGH, sensor.timeoutUS);
		// TODO - adaptive timeout ? - start big - pull in until valid value - push out if range is coming close
		return pulseIn(sensor.echoPin, HIGH);
}

void sendServoEvent(servo_type& s, int eventType){
  	// check type of event - STOP vs CURRENT POS

	Serial.write(MAGIC_NUMBER);
	Serial.write(5); // size = 1 FN + 1 INDEX + 1 eventType + 1 curPos
	Serial.write(SERVO_EVENT);
	Serial.write(s.index); // send my index
	// write the long value out
	Serial.write(eventType);
	Serial.write(s.currentPos);
	Serial.write(s.targetPos);
}

void sendError(int type){
	Serial.write(MAGIC_NUMBER);
	Serial.write(2); // size = 1 FN + 1 TYPE
	Serial.write(MRLCOMM_ERROR);
	Serial.write(type);
}

/* SEEMED LIKE A GOOD IDEA NOT !!!!
void sendMsg ( int num, ... )
{
	va_list arguments;
	// Initializing arguments to store all values after num
	va_start ( arguments, num );

	// write header
	msgBuf[0] = MAGIC_NUMBER;
	msgBuf[1] = num;

	// copies msg payload to buffer after header
	for ( int x = 2; x < num+2; x++ )
	{
		msgBuf[x] = (byte) va_arg ( arguments, int );
	}
	va_end ( arguments );                  // Cleans up the list
	Serial.write(msgBuf, num + 2);
	return;
}
*/

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


Lab2 660 Hz Detect

Lab2 660 Hz Detect

error: pathspec 'code' did not match any file(s) known to git
error: pathspec 'dump/lab2/Lab2_660HzDetect.ino' did not match any file(s) known to git


Added Display

Added Display

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/markwatneyy/ttt_arduino.git/'


erasing repeated example

erasing repeated example

// This example is to get the last value of variable from the Ubidots API

// This example is to save multiple variables to the Ubidots API with TCP method

/****************************************
 * Include Libraries
 ****************************************/

#include "Ubidots.h"

/****************************************
 * Define Constants
 ****************************************/

#ifndef TOKEN
#define TOKEN "Your_Token"  // Put here your Ubidots TOKEN
#endif

Ubidots ubidots(TOKEN, UBI_HTTP);

/****************************************
 * Auxiliar Functions
 ****************************************/

//Put here your auxiliar functions

/****************************************
 * Main Functions
 ****************************************/

void setup() {
  Serial.begin(115200);
  //ubidots.setDebug(true);  // Uncomment this line for printing debug messages
}

void loop() {
  float value1 = analogRead(A0);
  float value2 = analogRead(A1);
  float value3 = analogRead(A2);
  ubidots.add("Variable_Name_One", value1);  // Change for your variable name
  ubidots.add("Variable_Name_Two", value2);
  ubidots.add("Variable_Name_Three", value3);

  bool bufferSent = false;
  bufferSent = ubidots.send();  // Will send data to a device label that matches the device Id

  if(bufferSent){
    // Do something if values were sent properly
    Serial.println("Values sent by the device");
  }

  delay(5000);
}

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


Starting project

Starting project

void setup() {
  // put your setup code here, to run once:

}

void loop() {
  // put your main code here, to run repeatedly:

}


all timer test done (missing calcCharge test)

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/janiversen/SolarPower.git/'


Add DFRobot examples

Add DFRobot examples

/**************************************************************
 * Blynk is a platform with iOS and Android apps to control
 * Arduino, Raspberry Pi and the likes over the Internet.
 * You can easily build graphic interfaces for all your
 * projects by simply dragging and dropping widgets.
 *
 *   Downloads, docs, tutorials: http://www.blynk.cc
 *   Blynk community:            http://community.blynk.cc
 *   Social networks:            http://www.fb.com/blynkapp
 *                               http://twitter.com/blynk_app
 *
 * Blynk library is licensed under MIT license
 * This example code is in public domain.
 *
 **************************************************************
 *
 * This example shows how to use DFRobot Bluno or BLE Link module
 * to connect your project to Blynk.
 *
 * NOTE: BLE support is in beta!
 *
 **************************************************************/

// You could use a spare Hardware Serial on boards that have it (like Mega)
#include <SoftwareSerial.h>
SoftwareSerial DebugSerial(2, 3); // RX, TX

#define BLYNK_PRINT DebugSerial
#define BLYNK_USE_DIRECT_CONNECT
#include <BlynkSimpleSerialBLE.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";

void setup()
{
  // Debug console
  DebugSerial.begin(9600);

  // Blynk will work through Serial
  Serial.begin(115200);
  Blynk.begin(auth, Serial);
}

void loop()
{
  Blynk.run();
}

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


Added ack for PWM set

Added ack for PWM set

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/snowdenator/EarlHomeAutomation.git/'


added change of http header

added change of http header


Blink the Philips Hue lights

Blink the Philips Hue lights

replace SSID, PASSWORD, BRIDGE_IP, USERNAME

#include <ESP8266WiFi.h>
#include <ESPHue.h>

const char* ssid = "SSID";    // your network SSID (name)
const char* pass = "PASSWORD";    // your network password

//                 bridge ip    username
ESPHue h = ESPHue("BRIDGE_IP", "USERNAME");

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

void loop() {
  h.HSB(2000, 255, 255); //configure hsb
  h.set(1); //apply set hsb to lamp 1
  h.set(2); //apply set hsb to lamp 2

  delay(1000);

  h.off(); //configure off
  h.set(1); //apply set off to lamp 1
  h.set(2); //apply set off to lamp 2

  delay(1000);
}

void connectToWifi() {
  Serial.println();
  Serial.println();
  Serial.print(F("Attempting to connect to network: "));
  Serial.println( ssid );

  uint8_t timeout = 0;
  WiFi.begin( ssid, pass );
  while( WiFi.status() != WL_CONNECTED && timeout < 250) {
    delay(250);
    Serial.print('.');
    timeout++;
  }
  Serial.println();
  if( timeout >= 250 ) Serial.println(F("Failed to connect to Wifi!"));
  else Serial.println(F("Connected to wifi"));
}

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


Example Program for Displaying Chinese Characters (#115)

* Example Program for Displaying Chinese Characters

* Fix Geometry.h not found

#include <Arduino.h>
#include <U8g2lib.h>

#define BtnPin 35
#define BuzzerPin 26

U8G2_SH1107_64X128_F_4W_HW_SPI u8g(U8G2_R0,14, /* dc=*/ 27, /* reset=*/ 33);

int btnClicked;
int oledState;
unsigned long initTime;

void setup() {
  u8g.begin();
  u8g.setFont(u8g2_font_wqy12_t_gb2312);
  u8g.enableUTF8Print();

  pinMode(BtnPin, INPUT_PULLUP);
  attachInterrupt(BtnPin,pressed,FALLING);

  pinMode(BuzzerPin, OUTPUT);
  digitalWrite(BuzzerPin, LOW);

  btnClicked=0;
  oledState=0;

  delay(500);
  initTime=millis();
}

void pressed()
{
  btnClicked=1;
}

void draw(void)
{
  u8g.firstPage();
  do {
    u8g.drawUTF8(2,14*1+4,"    道忽思");
    u8g.drawUTF8(2,14*2+4,"    ，已君");
    u8g.drawUTF8(2,14*3+4,"古  努晚令");
    u8g.drawUTF8(2,14*4+4,"诗  力。人");
    u8g.drawUTF8(2,14*5+4,"十  加弃老");
    u8g.drawUTF8(2,14*6+4,"九  餐捐，");
    u8g.drawUTF8(2,14*7+4,"首  饭勿岁");
    u8g.drawUTF8(2,14*8+4,"    。复月");

    u8g.drawLine(10+2,14*2+4,12+2,14*2+4);
    u8g.drawLine(12+2,14*2-1,12+2,14*2+4);
    u8g.drawLine(12+2,14*2-1,0+2,14*2-1);
    u8g.drawLine(0+2,14*2+1,0+2,14*2-1);
    u8g.drawLine(0+2,14*2+1,10+2,14*2+1);
    u8g.drawLine(10+2,14*2+1,10+2,14*2+3);

    u8g.drawLine(1+2,14*8-4,-1+2,14*8-4);
    u8g.drawLine(-1+2,14*8+1,-1+2,14*8-4);
    u8g.drawLine(-1+2,14*8+1,11+2,14*8+1);
    u8g.drawLine(11+2,14*8-1,11+2,14*8+1);
    u8g.drawLine(11+2,14*8-1,1+2,14*8-1);
    u8g.drawLine(1+2,14*8-1,1+2,14*8-3);
  } while( u8g.nextPage() );
}
void loop() {
  if(btnClicked==1)
  {
    oledState=(oledState+1)%2;
    if(oledState==1)u8g.noDisplay();
    else u8g.display();
    initTime=millis();
    btnClicked=0;
  }
  if (millis()-initTime>60000)esp_deep_sleep_start();
  draw();
  delay(1);
}

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


Note to self - test. Got it? Good!

Note to self - test. Got it? Good!

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/'


[feat] Add esp32 mqtt example (#4)

[feat] Add esp32 mqtt example (#4)

* [feat] Add esp32 mqtt example
* [refactor] Apply Google cpp code style and change to String class

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


Bargraph example

Bargraph example

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

void setup()
{
  Serial.begin(1000000);
  GD.begin(~GD_STORAGE);
  printf("ok\n");

  GD.BitmapHandle(0);
  GD.cmd_setbitmap(0, BARGRAPH, 1280, 256);
  for (int i = 0; i < 1280; i++)
    GD.wr(i, random(256));
}

void loop()
{
  GD.VertexFormat(0);

  GD.ClearColorRGB(0x000050);
  GD.Clear();

  GD.Begin(BITMAPS);
  GD.BitmapHandle(0);

  // First, draw the bargraph with no scaling
  GD.Vertex2f(0, 50);

  // Now scale in y by 0.5
  GD.cmd_loadidentity();
  GD.cmd_scale(F16(1), F16(0.5));
  GD.cmd_setmatrix();

  GD.Vertex2f(0, 500);
  GD.swap();
}

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


Create nRF24L01PLUS.ino

Create nRF24L01PLUS.ino

#include <SPI.h>

int CSNpin = 10;
int CEpin = 9;
int IRQpin = 3;

int function; //1 is RX, 0 is TX
bool packet = false;

void setup() {
  RFsetup("RX",33); //initialize nRF24L01+ as RX with the address ending with "33"
  pinMode(13, OUTPUT);
  //Serial.begin(57600);
}

void loop() {
  if (function == 0) { //TX
    delay(1000);
    RFwrite(100);
    delay(100);
    if (packet == true) {
      int data;
      SPIsetup();
      digitalWrite(CSNpin, LOW);
      SPI.transfer(0x61); //R_RX_PAYLOAD read
      data = SPI.transfer(0xff); //read payload
      digitalWrite(CSNpin, HIGH);
      SPI.end();
      delayMicroseconds(20);
      clearSTATUS();
      delayMicroseconds(20);
      packet = false;
      // Do something with STATUS (data)
      //Serial.print("Ack Received: ");
      //Serial.println(data);
    }
    clearSTATUS();
    delayMicroseconds(20);
    clearTX();
  }
  if (function == 1) { //RX
    RFlisten();

    if (packet == true) {
      digitalWrite(CEpin, LOW);

      if (digitalRead(13) == HIGH) {
          SPIsetup();
          SPIcommand2(0xa8,0x64); //W_ACK_PAYLOAD write (100)
          SPI.end();
      }
      if (digitalRead(13) == LOW) {
        SPIsetup();
        SPIcommand2(0xa8,0x00); //W_ACK_PAYLOAD write (0)
        SPI.end();
      }

      int data;
      delayMicroseconds(20);
      SPIsetup();
      digitalWrite(CSNpin, LOW);
      SPI.transfer(0x61); //R_RX_PAYLOAD read
      data = SPI.transfer(0xff); //read payload
      digitalWrite(CSNpin, HIGH);
      SPI.end();
      delayMicroseconds(20);
      clearSTATUS();
      delayMicroseconds(20);
      digitalWrite(CEpin, HIGH);
      packet = false;
      Serial.println(data);
      if (data == 0) {
        digitalWrite(13, LOW);
      }
      if (data == 100) {
        digitalWrite(13, HIGH);
      }
    }
  }
}

void SPIsetup() {
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setClockDivider(SPI_CLOCK_DIV16);
}

void RFsetup(String mode, byte address) {
  pinMode(CSNpin, OUTPUT);
  pinMode(CEpin, OUTPUT);
  pinMode(IRQpin, INPUT);
  detachInterrupt(1);

  digitalWrite(CSNpin, HIGH); //CSN is active low
  digitalWrite(CEpin, LOW); //No RX or TX at this time

  SPIsetup();
  SPIcommand2(0x20,0x08); //CONFIG write (power down)
  delayMicroseconds(200);

  if (mode == "RX") {
    function = 1;
    attachInterrupt(1, packet_received, FALLING); //Interrupt for received packets
    SPIcommand2(0x20,0x3f); //CONFIG write (power up & RX)
    delayMicroseconds(50);
    SPIcommand6(0x30,address,0xb6,0xb5,0xb4,0xb3); //TX_ADDR write (0xB3B4B5B6__)
    delayMicroseconds(50);
    SPIcommand6(0x2a,address,0xb6,0xb5,0xb4,0xb3); //RX_ADDR_P0 write (0xB3B4B5B6__)
  }
  if (mode == "TX") {
    function = 0;
    attachInterrupt(1, packet_received, FALLING); //Interrupt for received ack packets
    SPIcommand2(0x20,0x3e); //CONFIG write (power up & TX with payload IRQ)
    delayMicroseconds(50);
    SPIcommand2(0x21,0x01); //EN_AA write (enable P0)
    delayMicroseconds(50);
    SPIcommand2(0x24,0x23); //SETUP_RETR write (enable 750us delay)
    delayMicroseconds(50);
    SPIcommand6(0x30,address,0xb6,0xb5,0xb4,0xb3); //TX_ADDR write (0xB3B4B5B6__)
    delayMicroseconds(50);
    SPIcommand6(0x2a,address,0xb6,0xb5,0xb4,0xb3); //RX_ADDR_P0 write (0xB3B4B5B6__)
  }

  delayMicroseconds(50);
  SPIcommand2(0x22,0x01); //EN_RXADDR write (enable P0)
  delayMicroseconds(50);
  SPIcommand2(0x3d,0x06); //FEATURE write (enable EN_ACK_PAYLOAD and EN_DPL) //
  delayMicroseconds(50);
  SPIcommand2(0x3c,0x01); //DYNPD write (enable DPL_P0) //
  delayMicroseconds(50);
  SPIcommand2(0x31,0x01); //RX_PW_P0 write (1 byte RX width)
  delayMicroseconds(50);
  SPIcommand2(0x25,0x32); //RF_CH write (channel 50)
  delayMicroseconds(50);
  SPIcommand2(0x26,0x22); //RFSETUP write (250kbps & -12dBm)
  delayMicroseconds(50);
  SPIcommand2(0x27,0x7e); //STATUS write (Interrupts Clear)
  SPI.end();
}

void RFwrite(byte command) {
  SPIsetup();
  SPIcommand2(0xa0,command); //W_TX_PAYLOAD write (Payload)
  SPI.end();
  digitalWrite(CEpin, HIGH);
  delayMicroseconds(15);
  digitalWrite(CEpin, LOW);
}

void RFlisten() {
  digitalWrite(CEpin, HIGH);
}

void packet_received() {
  packet = true;
}

void readSTATUS() {
  SPIsetup();
  SPIcommand2(0x07,0xff); //STATUS read
  SPI.end();
}

void clearSTATUS() {
  SPIsetup();
  SPIcommand2(0x27,0x7e);
  SPI.end();
}

void clearRX() {
  SPIsetup();
  SPIcommand(0xe2);
  SPI.end();
}

void clearTX() {
  SPIsetup();
  SPIcommand(0xe1);
  SPI.end();
}

void SPIcommand(byte command) {
  digitalWrite(CSNpin, LOW);
  SPI.transfer(command); //command
  digitalWrite(CSNpin, HIGH);
}

void SPIcommand2(byte command, byte value) {
  digitalWrite(CSNpin, LOW);
  SPI.transfer(command); //register write command
  SPI.transfer(value); //register value
  digitalWrite(CSNpin, HIGH);
}

void SPIcommand6(byte command, byte value1, byte value2, byte value3, byte value4, byte value5) {
  digitalWrite(CSNpin, LOW);
  SPI.transfer(command); //register write command
  SPI.transfer(value1); //register value 1
  SPI.transfer(value2); //register value 2
  SPI.transfer(value3); //register value 3
  SPI.transfer(value4); //register value 4
  SPI.transfer(value5); //register value 5
  digitalWrite(CSNpin, HIGH);
}

error: pathspec 'nRF24L01-Interface/nRF24L01PLUS.ino' did not match any file(s) known to git


Manufacturer specifications on HC-SR04

Manufacturer specifications on HC-SR04

The manufacturer recommends at least a 10 microsecond High value on the trigger pin of the HC-SR04 in order to inititate the ultrasonic chirp used for range finding (distance sensing).

error: pathspec 'Testing' did not match any file(s) known to git
error: pathspec 'the' did not match any file(s) known to git
error: pathspec 'Board/Test_Ultrasound/Test_Ultrasound.ino' did not match any file(s) known to git


Create repeating_block_pattern.ino

Create repeating_block_pattern.ino

//***************************************************************
//  Repeting block pattern example
//
//    There is a check to make sure we don't try to write data to
//    pixels that don't exist because the causes bad things to
//    happen.
//
//  Marc Miller, July 2017
//***************************************************************

#include "FastLED.h"
#define DATA_PIN    11
#define CLOCK_PIN   13
#define LED_TYPE    LPD8806
#define COLOR_ORDER GRB
#define NUM_LEDS    32
#define BRIGHTNESS  50
CRGB leds[NUM_LEDS];

uint8_t blockSize = 5;  // number of pixels to light up in a block
uint16_t wait = 200;  // delay time

uint8_t count;  // used to keep track of what block to light up.
uint16_t loopStart = 0;
uint16_t loopEnd = blockSize;

//---------------------------------------------------------------
void setup() {
  Serial.begin(115200);  // Allows serial monitor output (check baud rate)
  delay(1500); // startup delay for recovery
  //FastLED.addLeds<LED_TYPE,DATA_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
  FastLED.addLeds<LED_TYPE,DATA_PIN,CLOCK_PIN,COLOR_ORDER>(leds, NUM_LEDS).setCorrection(TypicalLEDStrip);
  FastLED.setBrightness(BRIGHTNESS);
  FastLED.clear();  // clear strip data
}

//---------------------------------------------------------------
void loop() {

  loopStart = count * blockSize;
  loopEnd = blockSize + count*blockSize;

  // Trying to write data to pixels that don't exit is bad.
  // Check to make sure we are still within our NUM_LEDS range
  // and clamp to NUM_LEDS if needed.
  if (loopEnd > NUM_LEDS) { loopEnd = NUM_LEDS; }  // limit maximum to NUM_LEDS

  uint8_t hue = random8();  // for fun, pick a new color for each block
  for(uint16_t i=loopStart; i < loopEnd; i++) {
    leds[i] =  CHSV( hue, 255, 255 );
  }
  FastLED.delay(wait);

  for(uint16_t i=loopStart; i < loopEnd; i++) {
    leds[i] =  CRGB::Black;
  }

  count++;  // increase count by one
  // reset count if we have come to the end of the strip
  if ((count * blockSize) >= NUM_LEDS) { count = 0; }

  EVERY_N_SECONDS(5){
    blockSize = random8(2,9);  // for fun, pick a new random block size
  }

}//end_main_loop

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


Create Blink.ino

Create Blink.ino

/*
  Blink
  Turns on an LED on for one second, then off for one second, repeatedly.
  This example code is in the public domain.
 */

void setup() {
  // initialize the digital pin as an output.
  // Pin 13 has an LED connected on most Arduino boards:
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13, HIGH);   // set the LED on
  delay(1000);              // wait for a second
  digitalWrite(13, LOW);    // set the LED off
  delay(1000);              // wait for a second
}

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