added apparent power readings

added apparent power readings

/*

  emonTxV3.4 Discrete Sampling

  If AC-AC adapter is detected assume emonTx is also powered from adapter (jumper shorted) and take Real Power Readings and disable sleep mode to keep load on power supply constant
  If AC-AC addapter is not detected assume powering from battereis / USB 5V AC sample is not present so take Apparent Power Readings and enable sleep mode

  Transmitt values via RFM69CW radio

   -----------------------------------------
  Part of the openenergymonitor.org project

  Authors: Glyn Hudson & Trystan Lea
  Builds upon JCW JeeLabs RF12 library and Arduino

  Licence: GNU GPL V3

*/

/*Recommended node ID allocation
------------------------------------------------------------------------------------------------------------
-ID-	-Node Type-
0	- Special allocation in JeeLib RFM12 driver - reserved for OOK use
1-4     - Control nodes
5-10	- Energy monitoring nodes
11-14	--Un-assigned --
15-16	- Base Station & logging nodes
17-30	- Environmental sensing nodes (temperature humidity etc.)
31	- Special allocation in JeeLib RFM12 driver - Node31 can communicate with nodes on any network group
-------------------------------------------------------------------------------------------------------------

Change Log:
v2.3   16/11/15 Change to unsigned long for pulse count and make default node ID 8 to avoid emonHub node decoder conflict & fix counting pulses faster than 110ms, strobed meter LED http://openenergymonitor.org/emon/node/11490
v2.2   12/11/15 Remove debug timming serial print code
v2.1   24/10/15 Improved timing so that packets are sent just under 10s, reducing resulting data gaps in feeds + default status code for no temp sensors of 3000 which reduces corrupt packets improving data reliability
V2.0   30/09/15 Update number of samples 1480 > 1662 to improve sampling accurancy: 1662 samples take 300 mS, which equates to 15 cycles @ 50 Hz or 18 cycles @ 60 Hz.
V1.9   25/08/15 Fix spurious pulse readings from RJ45 port when DS18B20 but no pulse counter is connected (enable internal pull-up)
V1.8 - 18/06/15 Increase max pulse width to 110ms
V1.7 - 12/06/15 Fix pulse count debounce issue & enable pulse count pulse temperature
V1.6 - Add support for multiple DS18B20 temperature sensors
V1.5 - Add interrupt pulse counting - simplify serial print debug
V1.4.1 - Remove filter settle routine as latest emonLib 19/01/15 does not require
V1.4 - Support for RFM69CW, DIP switches and battery voltage reading on emonTx V3.4
V1.3 - fix filter settle time to eliminate large inital reading
V1.2 - fix bug which caused Vrms to be returned as zero if CT1 was not connected
V1.1 - fix bug in startup Vrms calculation, startup Vrms startup calculation is now more accuratre
*/

#define emonTxV3                                                                          // Tell emonLib this is the emonTx V3 - don't read Vcc assume Vcc = 3.3V as is always the case on emonTx V3 eliminates bandgap error and need for calibration http://harizanov.com/2013/09/thoughts-on-avr-adc-accuracy/
#define RF69_COMPAT 1                                                              // Set to 1 if using RFM69CW or 0 is using RFM12B
#include <JeeLib.h>                                                                      //https://github.com/jcw/jeelib - Tested with JeeLib 3/11/14
ISR(WDT_vect) { Sleepy::watchdogEvent(); }                            // Attached JeeLib sleep function to Atmega328 watchdog -enables MCU to be put into sleep mode inbetween readings to reduce power consumption

#include "EmonLib.h"                                                                    // Include EmonLib energy monitoring library https://github.com/openenergymonitor/EmonLib
EnergyMonitor ct1, ct2, ct3, ct4;

#include <OneWire.h>                                                  //http://www.pjrc.com/teensy/td_libs_OneWire.html
#include <DallasTemperature.h>                                        //http://download.milesburton.com/Arduino/MaximTemperature/DallasTemperature_LATEST.zip

const byte version = 23;         // firmware version divided by 10 e,g 16 = V1.6

//----------------------------emonTx V3 Settings---------------------------------------------------------------------------------------------------------------
const byte Vrms=                  230;                               // Vrms for apparent power readings (when no AC-AC voltage sample is present)
const byte TIME_BETWEEN_READINGS = 10;            //Time between readings

//http://openenergymonitor.org/emon/buildingblocks/calibration

const float Ical1=                90.9;                                 // (2000 turns / 22 Ohm burden) = 90.9
const float Ical2=                90.9;                                 // (2000 turns / 22 Ohm burden) = 90.9
const float Ical3=                90.9;                                 // (2000 turns / 22 Ohm burden) = 90.9
const float Ical4=                16.67;                               // (2000 turns / 120 Ohm burden) = 16.67

float Vcal=                       268.97;                             // (230V x 13) / (9V x 1.2) = 276.9 Calibration for UK AC-AC adapter 77DB-06-09
//float Vcal=276.9;
//const float Vcal=               260;                             //  Calibration for EU AC-AC adapter 77DE-06-09
const float Vcal_USA=             130.0;                             //Calibration for US AC-AC adapter 77DA-10-09
boolean USA=FALSE;

const float phase_shift=          1.7;
const int no_of_samples=          1662;
const int no_of_half_wavelengths= 30;
const int timeout=                2000;                               //emonLib timeout
const int ACAC_DETECTION_LEVEL=   3000;
const byte min_pulsewidth= 110;                                // minimum width of interrupt pulse (default pulse output meters = 100ms)
const int TEMPERATURE_PRECISION=  11;                          //9 (93.8ms),10 (187.5ms) ,11 (375ms) or 12 (750ms) bits equal to resplution of 0.5C, 0.25C, 0.125C and 0.0625C
const byte MaxOnewire=             6;
#define ASYNC_DELAY 375                                          // DS18B20 conversion delay - 9bit requres 95ms, 10bit 187ms, 11bit 375ms and 12bit resolution takes 750ms
//-------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------

//----------------------------emonTx V3 hard-wired connections---------------------------------------------------------------------------------------------------------------
const byte LEDpin=                 6;                              // emonTx V3 LED
const byte DS18B20_PWR=            19;                             // DS18B20 Power
const byte DIP_switch1=            8;                              // Voltage selection 230 / 110 V AC (default switch off 230V)  - switch off D8 is HIGH from internal pullup
const byte DIP_switch2=            9;                              // RF node ID (default no chance in node ID, switch on for nodeID -1) switch off D9 is HIGH from internal pullup
const byte battery_voltage_pin=    7;                              // Battery Voltage sample from 3 x AA
const byte pulse_countINT=         1;                              // INT 1 / Dig 3 Terminal Block / RJ45 Pulse counting pin(emonTx V3.4) - (INT0 / Dig2 emonTx V3.2)
const byte pulse_count_pin=        3;                              // INT 1 / Dig 3 Terminal Block / RJ45 Pulse counting pin(emonTx V3.4) - (INT0 / Dig2 emonTx V3.2)
#define ONE_WIRE_BUS               5                               // DS18B20 Data
//-------------------------------------------------------------------------------------------------------------------------------------------

//Setup DS128B20
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
byte allAddress [MaxOnewire][8];  // 8 bytes per address
byte numSensors;
//-------------------------------------------------------------------------------------------------------------------------------------------

//-----------------------RFM12B / RFM69CW SETTINGS----------------------------------------------------------------------------------------------------
#define RF_freq RF12_433MHZ                                              // Frequency of RF69CW module can be RF12_433MHZ, RF12_868MHZ or RF12_915MHZ. You should use the one matching the module you have.
byte nodeID = 8;                                                        // emonTx RFM12B node ID
const int networkGroup = 210;

typedef struct {
  int power1, aPower1, power2, aPower2, power3, aPower3, power4, aPower4, Vrms, temp[MaxOnewire];  //ADDED aPower for apparent power readings
  unsigned long pulseCount;
} PayloadTX;     // create structure - a neat way of packaging data for RF comms

PayloadTX emontx;

//-------------------------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------------------------

//Random Variables
//boolean settled = false;
boolean CT1, CT2, CT3, CT4, ACAC, debug, DS18B20_STATUS;
byte CT_count=0;
volatile byte pulseCount = 0;
unsigned long pulsetime=0;                                    // Record time of interrupt pulse
void setup()
{
  pinMode(LEDpin, OUTPUT);
  pinMode(DS18B20_PWR, OUTPUT);

  pinMode(pulse_count_pin, INPUT_PULLUP);                     // Set emonTx V3.4 interrupt pulse counting pin as input (Dig 3 / INT1)
  emontx.pulseCount=0;                                        // Make sure pulse count starts at zero

  digitalWrite(LEDpin,HIGH);

  Serial.begin(9600);

  Serial.print("emonTx V3.4 Discrete Sampling V"); Serial.print(version*0.1);
  #if (RF69_COMPAT)
    Serial.println(" RFM69CW");
  #else
    Serial.println(" RFM12B");
  #endif
  Serial.println("OpenEnergyMonitor.org");
  Serial.println("POST.....wait 10s");

  //READ DIP SWITCH POSITIONS
  pinMode(DIP_switch1, INPUT_PULLUP);
  pinMode(DIP_switch2, INPUT_PULLUP);
  if (digitalRead(DIP_switch1)==LOW) nodeID--;                            // IF DIP switch 1 is switched on then subtract 1 from nodeID
  if (digitalRead(DIP_switch2)==LOW) USA=TRUE;                            // IF DIP switch 2 is switched on then activate USA mode

  if (USA==TRUE){                                                         // if USA mode is true
    Vcal=Vcal_USA;                                                        // Assume USA AC/AC adatper is being used, set calibration accordingly
  }

  delay(10);
  rf12_initialize(nodeID, RF_freq, networkGroup);                         // initialize RFM12B/rfm69CW
  for (int i=10; i>=0; i--)                                               // Send RF test sequence (for factory testing)
  {
    emontx.power1=i;
    rf12_sendNow(0, &emontx, sizeof emontx);
    delay(100);
  }
  rf12_sendWait(2);
  emontx.power1=0;

  if (analogRead(1) > 0) {CT1 = 1; CT_count++;} else CT1=0;              // check to see if CT is connected to CT1 input, if so enable that channel
  if (analogRead(2) > 0) {CT2 = 1; CT_count++;} else CT2=0;              // check to see if CT is connected to CT2 input, if so enable that channel
  if (analogRead(3) > 0) {CT3 = 1; CT_count++;} else CT3=0;              // check to see if CT is connected to CT3 input, if so enable that channel
  if (analogRead(4) > 0) {CT4 = 1; CT_count++;} else CT4=0;              // check to see if CT is connected to CT4 input, if so enable that channel

  if ( CT_count == 0) CT1=1;                                             // If no CT's are connected CT1-4 then by default read from CT1

  // Quick check to see if there is a voltage waveform present on the ACAC Voltage input
  // Check consists of calculating the RMS from 100 samples of the voltage input.
  Sleepy::loseSomeTime(10000);            //wait for settle
  digitalWrite(LEDpin,LOW);

  // Calculate if there is an ACAC adapter on analog input 0
  //double vrms = calc_rms(0,1780) * (Vcal * (3.3/1024) );
  double vrms = calc_rms(0,1780) * 0.87;
  if (vrms>90) ACAC = 1; else ACAC=0;

  if (ACAC)
  {
    for (int i=0; i<10; i++)                                              // indicate AC has been detected by flashing LED 10 times
    {
      digitalWrite(LEDpin, HIGH); delay(200);
      digitalWrite(LEDpin, LOW); delay(300);
    }
  }
  else
  {
    delay(1000);
    digitalWrite(LEDpin, HIGH); delay(2000); digitalWrite(LEDpin, LOW);   // indicate DC power has been detected by turing LED on then off
  }

  //################################################################################################################################
  //Setup and for presence of DS18B20
  //################################################################################################################################
  digitalWrite(DS18B20_PWR, HIGH); delay(100);
  sensors.begin();
  sensors.setWaitForConversion(false);             // disable automatic temperature conversion to reduce time spent awake, conversion will be implemented manually in sleeping
                                                   // http://harizanov.com/2013/07/optimizing-ds18b20-code-for-low-power-applications/
  numSensors=(sensors.getDeviceCount());
  if (numSensors > MaxOnewire) numSensors=MaxOnewire;   //Limit number of sensors to max number of sensors

  byte j=0;                                        // search for one wire devices and
                                                   // copy to device address arrays.
  while ((j < numSensors) && (oneWire.search(allAddress[j])))  j++;

  delay(500);
  digitalWrite(DS18B20_PWR, LOW);

  if (numSensors==0) DS18B20_STATUS=0;
    else DS18B20_STATUS=1;

  //################################################################################################################################

  if (Serial) debug = 1; else debug=0;          // if serial UART to USB is connected show debug O/P. If not then disable serial
  if (debug==1)
  {
    Serial.print("CT 1 Cal "); Serial.println(Ical1);
    Serial.print("CT 2 Cal "); Serial.println(Ical2);
    Serial.print("CT 3 Cal "); Serial.println(Ical3);
    Serial.print("CT 4 Cal "); Serial.println(Ical4);
    delay(1000);

    Serial.print("RMS Voltage on AC-AC  is: ~");
    Serial.print(vrms,0); Serial.println("V");

    if (ACAC) {
      Serial.println("AC-AC detected - Real Power measure enabled");
      Serial.println("assuming pwr from AC-AC (jumper closed)");
      if (USA==TRUE) Serial.println("USA mode active");
      Serial.print("Vcal: "); Serial.println(Vcal);
      Serial.print("Phase Shift: "); Serial.println(phase_shift);
    } else {
      Serial.println("AC-AC NOT detected - Apparent Pwr measure enabled");
      Serial.print("Assuming VRMS: "); Serial.print(Vrms); Serial.println("V");
      Serial.println("Assuming power from batt / 5V USB - power save enabled");
    }

    if (CT_count==0) {
      Serial.println("NO CT's detected");
    } else {
      if (CT1) Serial.println("CT 1 detected");
      if (CT2) Serial.println("CT 2 detected");
      if (CT3) Serial.println("CT 3 detected");
      if (CT4) Serial.println("CT 4 detected");
    }

    if (DS18B20_STATUS==1) {
      Serial.print("Detected Temp Sensors:  ");
      Serial.println(numSensors);
    } else {
      Serial.println("No temperature sensor");
    }

    #if (RF69_COMPAT)
       Serial.println("RFM69CW");
    #else
      Serial.println("RFM12B");
    #endif

    Serial.print("Node: "); Serial.print(nodeID);
    Serial.print(" Freq: ");
    if (RF_freq == RF12_433MHZ) Serial.print("433Mhz");
    if (RF_freq == RF12_868MHZ) Serial.print("868Mhz");
    if (RF_freq == RF12_915MHZ) Serial.print("915Mhz");
    Serial.print(" Network: "); Serial.println(networkGroup);

    Serial.print("CT1 CT2 CT3 CT4 VRMS/BATT PULSE");
    if (DS18B20_STATUS==1){Serial.print(" Temperature 1-"); Serial.print(numSensors);}
    Serial.println(" ");
    delay(500);

  }
  else
  {
    Serial.end();
  }

  if (CT1) ct1.current(1, Ical1);             // CT ADC channel 1, calibration.  calibration (2000 turns / 22 Ohm burden resistor = 90.909)
  if (CT2) ct2.current(2, Ical2);             // CT ADC channel 2, calibration.
  if (CT3) ct3.current(3, Ical3);             // CT ADC channel 3, calibration.
  if (CT4) ct4.current(4, Ical4);             // CT ADC channel 4, calibration.  calibration (2000 turns / 120 Ohm burden resistor = 16.66) high accuracy @ low power -  4.5kW Max @ 240V

  if (ACAC)
  {
    if (CT1) ct1.voltage(0, Vcal, phase_shift);          // ADC pin, Calibration, phase_shift
    if (CT2) ct2.voltage(0, Vcal, phase_shift);          // ADC pin, Calibration, phase_shift
    if (CT3) ct3.voltage(0, Vcal, phase_shift);          // ADC pin, Calibration, phase_shift
    if (CT4) ct4.voltage(0, Vcal, phase_shift);          // ADC pin, Calibration, phase_shift
  }

  attachInterrupt(pulse_countINT, onPulse, FALLING);     // Attach pulse counting interrupt pulse counting

  for(byte j=0;j<MaxOnewire;j++)
      emontx.temp[j] = 3000;                             // If no temp sensors connected default to status code 3000
                                                         // will appear as 300 once multipled by 0.1 in emonhub
} //end SETUP

void loop()
{
  unsigned long start = millis();

  if (ACAC) {
    delay(200);                         //if powering from AC-AC allow time for power supply to settle
    emontx.Vrms=0;                      //Set Vrms to zero, this will be overwirtten by CT 1-4
  }

  // emontx.power1 = 1;
  // emontx.power2 = 1;
  // emontx.power3 = 1;
  // emontx.power4 = 1;

  if (CT1) {
    if (ACAC) {
      ct1.calcVI(no_of_half_wavelengths,timeout);
      emontx.power1=ct1.realPower;
      emontx.aPower1=ct1.apparentPower;                                               //ADDED aparent power reading por CT1
      emontx.Vrms=ct1.Vrms*100;
    } else {
      emontx.power1 = ct1.calcIrms(no_of_samples)*Vrms;                               // Calculate Apparent Power 1  1480 is  number of sample
    }
  }

  if (CT2) {
    if (ACAC) {
      ct2.calcVI(no_of_half_wavelengths,timeout);
      emontx.power2=ct2.realPower;                                                    //ADDED aparent power reading por CT2
      emontx.aPower2=ct2.apparentPower;
      emontx.Vrms=ct2.Vrms*100;
    } else {
      emontx.power2 = ct2.calcIrms(no_of_samples)*Vrms;                               // Calculate Apparent Power 1  1480 is  number of samples
    }
  }

  if (CT3) {
    if (ACAC) {
      ct3.calcVI(no_of_half_wavelengths,timeout);
      emontx.power3=ct3.realPower;                                                    //ADDED aparent power reading por CT3
      emontx.aPower3=ct3.apparentPower;
      emontx.Vrms=ct3.Vrms*100;
    } else {
      emontx.power3 = ct3.calcIrms(no_of_samples)*Vrms;                               // Calculate Apparent Power 1  1480 is  number of samples
    }
  }

  if (CT4) {
    if (ACAC) {
      ct4.calcVI(no_of_half_wavelengths,timeout);
      emontx.power4=ct4.realPower;                                                    //ADDED aparent power reading por CT4
      emontx.aPower4=ct4.apparentPower;
      emontx.Vrms=ct4.Vrms*100;
    } else {
      emontx.power4 = ct4.calcIrms(no_of_samples)*Vrms;                               // Calculate Apparent Power 1  1480 is  number of samples
    }
  }

  if (!ACAC){                                                                         // read battery voltage if powered by DC
    int battery_voltage=analogRead(battery_voltage_pin) * 0.681322727;                // 6.6V battery = 3.3V input = 1024 ADC
    emontx.Vrms= battery_voltage;
  }

  if (DS18B20_STATUS==1)
  {
    digitalWrite(DS18B20_PWR, HIGH);
    Sleepy::loseSomeTime(50);
    for(int j=0;j<numSensors;j++)
      sensors.setResolution(allAddress[j], TEMPERATURE_PRECISION);                    // and set the a to d conversion resolution of each.
    sensors.requestTemperatures();
    Sleepy::loseSomeTime(ASYNC_DELAY);                                                // Must wait for conversion, since we use ASYNC mode
    for(byte j=0;j<numSensors;j++)
      emontx.temp[j]=get_temperature(j);
    digitalWrite(DS18B20_PWR, LOW);
  }

  if (pulseCount)                                                                     // if the ISR has counted some pulses, update the total count
  {
    cli();                                                                            // Disable interrupt just in case pulse comes in while we are updating the count
    emontx.pulseCount += pulseCount;
    pulseCount = 0;
    sei();                                                                            // Re-enable interrupts
  }

  if (debug==1) {
    Serial.print(emontx.power1); Serial.print(" ");
    Serial.print(emontx.power2); Serial.print(" ");
    Serial.print(emontx.power3); Serial.print(" ");
    Serial.print(emontx.power4); Serial.print(" ");
    Serial.print(emontx.Vrms); Serial.print(" ");
    Serial.print(emontx.pulseCount); Serial.print(" ");
    if (DS18B20_STATUS==1){
      for(byte j=0;j<numSensors;j++){
        Serial.print(emontx.temp[j]);
       Serial.print(" ");
      }
    }
    Serial.println("");
    delay(50);
  }

  if (ACAC) {digitalWrite(LEDpin, HIGH); delay(200); digitalWrite(LEDpin, LOW);}    // flash LED if powered by AC

  send_rf_data();                                                           // *SEND RF DATA* - see emontx_lib

  unsigned long runtime = millis() - start;
  unsigned long sleeptime = (TIME_BETWEEN_READINGS*1000) - runtime - 100;

  if (ACAC) {                                                               // If powered by AC-AC adaper (mains power) then delay instead of sleep
    delay(sleeptime);
  } else {                                                                  // if powered by battery then sleep rather than dealy and disable LED to lower energy consumption
                                   // lose an additional 500ms here (measured timing)
    Sleepy::loseSomeTime(sleeptime-500);                                    // sleep or delay in seconds
  }
}

void send_rf_data()
{
  rf12_sleep(RF12_WAKEUP);
  rf12_sendNow(0, &emontx, sizeof emontx);                           //send temperature data via RFM12B using new rf12_sendNow wrapper
  rf12_sendWait(2);
  if (!ACAC) rf12_sleep(RF12_SLEEP);                             //if powred by battery then put the RF module into sleep inbetween readings
}

double calc_rms(int pin, int samples)
{
  unsigned long sum = 0;
  for (int i=0; i<samples; i++) // 178 samples takes about 20ms
  {
    int raw = (analogRead(0)-512);
    sum += (unsigned long)raw * raw;
  }
  double rms = sqrt((double)sum / samples);
  return rms;
}

// The interrupt routine - runs each time a falling edge of a pulse is detected
void onPulse()
{
  if ( (millis() - pulsetime) > min_pulsewidth) {
    pulseCount++;					//calculate wh elapsed from time between pulses
  }
  pulsetime=millis();
}

int get_temperature(byte sensor)
{
  float temp=(sensors.getTempC(allAddress[sensor]));
  if ((temp<125.0) && (temp>-55.0)) return(temp*10);            //if reading is within range for the sensor convert float to int ready to send via RF
}

error: pathspec 'utils/emontxv3_firmware/raspimon_firmware/DiscreteSampling/DiscreteSampling.ino' did not match any file(s) known to git


Adicionando WildSnakeLDR, que ajusta a velocidade da cobrinha a partir da leitura do LDR

/*

Autor: Pitanga <pitanga@members.fsf.org> com base em sketches preexistentes

Este sketch é uma variante do WildSnakeGS que usa o LDR para a velocidade!

A ideia é simples: a cobra é um répti, portanto um animal pecilotermo...

Na presença da luz do sol, a temperatura e o metabolismo dos pecilotermos aumentam,
portanto eles ficam mais ágeis. Na ausência da luz do sol, ficam mais frios e
lentos, ou até dormindo!

Para o usuário final, o circuito funciona assim:

- Após o reset, o segmento inferior do display pisca por 3 segundos. Neste
  momento o usuário deve reduzir a incidência de luz no LDR para calibrar
  o nível inferior de luminosidade.

- Em seguida o segmento central acende por 1 segundo para indicar que a
  calibragem do nível inferior encerrou e o usuário deve se preparar para
  a calibragem do nível superior.

- O segmento superior do display pisca por 3 segundos para que o usuário
  aumente a incidência de luz no LDR e assim calibre o nível superior de
  luminosidade.

- Após as duas calibragens, o circuito passa a ajustar continuamente a
  velocidade da cobrinha conforme a luz incidente no LDR.

Sobre como funciona a parte da cobrinha:

A two-segment snake slithers aimlessly over the display. On intersections,
the next step is chosen at random.

Most of the logic is encoded in the `moves` array which lists possible next
steps for each current position and direction. Snake head position and
direction is coded like pictured below, i.e. when the snake head is at the
middle segment going right, the code is 6, going left in the same place is
code 13.

       >:0
       <:7
      -----
^:5  |     | v:1
v:12 | >:6 | ^:8
      -----
^:4  | <:13| v:2
v:11 |     | ^:9
      -----
       <:3
       >:10

To understand this diagram, read:

> as a right arrow
< as a left arrow
v as a down arrow
^ as an up arrow

*/

// {first_choice, second_choice*}
// * -1 means there is no second_choice
int moves[][2] = {
  {1, -1},  // 0
  {13, 2},  // 1
  {3, -1},  // 2
  {4, -1},  // 3
  {6, 5},   // 4
  {0, -1},  // 5
  {2, 8},   // 6
  {12, -1}, // 7
  {7, -1},  // 8
  {13, 8},  // 9
  {9, -1},  // 10
  {10, -1}, // 11
  {6, 11},  // 12
  {5, 11}   // 13
};

/*     A
     -----
  F |     | B
    |  G  |
     -----
  E |     | C
    |  D  |
     -----
*/

//                A   B  C  D  E   F   G
int display[] = {8, 9, 10, 11, 12, 13, 7}; // Garoa Dojo Shield
const int SEGMENTS = 7;

int head = 1; // segment B
int tail = 0; // segment A

// variáveis para calibração
int seg_alto = 8;
int seg_meio = 7;
int seg_baixo = 11;
int ldr = A1;
int ldr_min = 0;
int ldr_max = 0;
int delay_min = 10;
int delay_max = 500;
//para permitir colocar luz forçada além do maximo calibrado (ex. lanterna)
float extra_factor = 0.1;

int const QT_AMOSTRA = 100;
int const TEMPO_AMOSTRAGEM = 3000;

void setup() {
  Serial.begin(9600);
  for (int i=0; i<SEGMENTS; i++) {
    pinMode(display[i], OUTPUT);
  }

  //calibração
  ldr_min = amostragem(ldr, seg_baixo);
  digitalWrite(seg_meio, HIGH);
  delay(1000);
  digitalWrite(seg_meio, LOW);
  ldr_max = amostragem(ldr, seg_alto);

  digitalWrite(display[tail % 7], HIGH);
}

void loop() {
  digitalWrite(display[head % 7], HIGH);
  int valor_delay = leitura_ldr();
  Serial.println(valor_delay);
  delay(valor_delay);
  digitalWrite(display[tail % 7], LOW);
  tail = head;
  int* choices = moves[head];
  if (choices[1] == -1) {
    head = choices[0];  // no second choice
  } else {
    head = choices[random(2)];  // random move
  }
}

int cmp(const void *x, const void *y) {
  return (*(int *)x - *(int *)y);
}

int mediana(int amostra[], int qt_amostra) {
  qsort(amostra, qt_amostra, sizeof(int), cmp);
  return amostra[qt_amostra/2];
}

int amostragem(int pino_leitura, int pino_sinal) {
  int amostra [QT_AMOSTRA];
  for (int i=0; i<QT_AMOSTRA; i++){
    if (i % 6 == 0) digitalWrite(pino_sinal, HIGH);
    amostra[i] = analogRead(pino_leitura);
    delay(TEMPO_AMOSTRAGEM/QT_AMOSTRA);
    if (i % 6 == 3) digitalWrite(pino_sinal, LOW);
  }
  digitalWrite(pino_sinal, LOW);
  return mediana(amostra, QT_AMOSTRA);
}

int leitura_ldr() {
  return (int)map(constrain(analogRead(ldr), ldr_min , ldr_max*(1+extra_factor)), ldr_min, ldr_max*(1+extra_factor), delay_max, delay_min);
}

/* Como funciona

- Para calibrar o limite inferior do LDR, a função `setup` chama `amostragem`
  informando um `pino_leitura` e um `pino_sinal`. O `pino_leitura` é `A1`
  (onde está o LDR no Garoa Dojo Shield). Na primeira chamada o `pino_sinal`
  é 11 (segmento inferior do display no Garoa Dojo Shield).

- A função `amostragem` pisca por 3 segundos o `pino_sinal` (segmento
  inferior) para informar o usuário de que está sendo feita a leitura do
  limite inferior. Neste momento o usuário deve reduzir a incidência de luz
  no LDR. Enquanto pisca `pino_sinal`, são colhidas 100 amostras
  de valores no LDR. Uma vez colhidas as amostras, a `pino_sinal` é desligado
  e é calculada a mediana (valor central do array de amostras, ordenado pela
  função `qsort` da biblioteca padrão do AVR - pesquise AVR stdlib.h).

- A função `setup` armazena o resultado da `amostragem` em `ldr_min`, e
  acende o segmento central do display para indicar ao usuário que a
  calabração do valor inferior terminou e vai começar a calibração do valor
  superior. Após 3 segundos, a função `amostragem` é chamada novamente, desta
  vez com o `pino_sinal` ligado ao segmento superior do display.

- O `pino_sinal` (segmento superior) pisca por 3 segundos, é feita a coleta
  de 100 amostras e devolvida a mediana.

- `setup` armazena o novo resultado em `ldr_max`.

- Durante o `loop`, os valores lidos do LDR são limitados por `constrain` à
  faixa de `ldr_min` até `ldr_max`, e convertidos por `map` a um valor
  proporcional entre 0 e 255 (mínimo e máximo do PWM). O valor convertido
  é usado para controlar o led do segmento inferior.

*/

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


Upload initial Arduino sketch

Upload initial Arduino sketch

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


Bluetooth example code, fixed to work with Uno

// iWRAP external host controller library generic demo
// 2014-05-25 by Jeff Rowberg <jeff@rowberg.net>
//
// Changelog:
//  2014-05-25 - Initial release

/* ============================================
iWRAP host controller library code is placed under the MIT license
Copyright (c) 2014 Jeff Rowberg

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
===============================================
*/

// iWRAP firmware should be v5.0.2 (build 861 or higher)
// Config settings may vary, but ideally you will at least enable a few
// special config bits and MUX mode with the following commands:
//
//      SET CONTROL CONFIG 3400 0040 70A1
//      SET CONTROL MUX 1
//
// See the iWRAP User Guide from Bluegiga for more detail. The following
// pre-built MUX frames can be handy for changing various settings, e.g.
// using an app like Realterm with the "Send" tab and "Send Numbers"
// button to send a hex string while the module is configured with MUX
// mode enabled:
//
// MUX frame for "SET CONTROL MUX 0" (disable MUX mode):
//      $bf $ff $00 $17 $53 $45 $54 $20 $43 $4f $4e $54 $52 $4f $4c $20 $4d $55 $58 $20 $30 $00
// MUX frame for "SET CONTROL BAUD 38400":
//      $bf $ff $00 $16 $53 $45 $54 $20 $43 $4f $4e $54 $52 $4f $4c $20 $42 $41 $55 $44 $20 $33 $38 $34 $30 $30 $00
// MUX frame for "SET CONTROL BAUD 115200":
//      $bf $ff $00 $17 $53 $45 $54 $20 $43 $4f $4e $54 $52 $4f $4c $20 $42 $41 $55 $44 $20 $31 $31 $35 $32 $30 $30 $00

#include <Arduino.h>
//#include <avr/pgmspace.h>

#define PLATFORM_ARDUINO_UNO    // also Pro Mini and other ATMega328-based boards
//#define PLATFORM_TEENSY2        // both Teensy 2.0 and Teensy++ 2.0

#ifdef PLATFORM_ARDUINO_UNO
    #include <AltSoftSerial.h>
    AltSoftSerial mySerial; // RX=8, TX=9
#endif

#define HOST_BAUD                   38400   // works with 8MHz CPU clock
#define IWRAP_BAUD                  38400   // works with 8MHz CPU clock (REQUIRES iWRAP RECONFIGURATION, DEFAULT IS 115200)
#define MODULE_RESET_PIN            12      // optional connection for MCU-based module reset

// -------- iWRAP configuration definitions --------
// COPY TO TOP OF "iWRAP.h" TO APPLY TO THIS PROGRAM
// OR ELSE ALL FEATURES ENABLED DUE TO BUILD SYSTEM
// -------------------------------------------------
#define IWRAP_DEBUG
#define IWRAP_INCLUDE_RSP_CALL
#define IWRAP_INCLUDE_RSP_LIST_COUNT
#define IWRAP_INCLUDE_RSP_LIST_RESULT
#define IWRAP_INCLUDE_RSP_SET
#define IWRAP_INCLUDE_EVT_CONNECT
#define IWRAP_INCLUDE_EVT_NO_CARRIER
#define IWRAP_INCLUDE_EVT_PAIR
#define IWRAP_INCLUDE_EVT_READY
#define IWRAP_INCLUDE_EVT_RING
#define IWRAP_CONFIGURED
// -------------------------------------------------

#include <iWRAP.h>

#define IWRAP_STATE_IDLE            0
#define IWRAP_STATE_UNKNOWN         1
#define IWRAP_STATE_PENDING_AT      2
#define IWRAP_STATE_PENDING_SET     3
#define IWRAP_STATE_PENDING_LIST    4
#define IWRAP_STATE_PENDING_CALL    5
#define IWRAP_STATE_COMM_FAILED     255

#define IWRAP_MAX_PAIRINGS          16

// connection map structure
typedef struct {
    iwrap_address_t mac;
    uint8_t active_links;
    uint8_t link_a2dp1;
    uint8_t link_a2dp2;
    uint8_t link_avrcp;
    uint8_t link_hfp;
    uint8_t link_hfpag;
    uint8_t link_hid_control;
    uint8_t link_hid_interrupt;
    uint8_t link_hsp;
    uint8_t link_hspag;
    uint8_t link_iap;
    uint8_t link_sco;
    uint8_t link_spp;
    // other profile-specific link IDs may be added here
} iwrap_connection_t;
iwrap_connection_t *iwrap_connection_map[IWRAP_MAX_PAIRINGS];

// iwrap state tracking info
uint8_t iwrap_mode = IWRAP_MODE_MUX;
uint8_t iwrap_state = IWRAP_STATE_UNKNOWN;
uint8_t iwrap_initialized = 0;
uint32_t iwrap_time_ref = 0;
uint8_t iwrap_pairings = 0;
uint8_t iwrap_pending_calls = 0;
uint8_t iwrap_pending_call_link_id = 0xFF;
uint8_t iwrap_connected_devices = 0;
uint8_t iwrap_active_connections = 0;
uint8_t iwrap_autocall_target = 0;
uint16_t iwrap_autocall_delay_ms = 10000;
uint32_t iwrap_autocall_last_time = 0;
uint8_t iwrap_autocall_index = 0;

// iWRAP callbacks necessary for application
void my_iwrap_rsp_call(uint8_t link_id);
void my_iwrap_rsp_list_count(uint8_t num_of_connections);
void my_iwrap_rsp_list_result(uint8_t link_id, const char *mode, uint16_t blocksize, uint32_t elapsed_time, uint16_t local_msc, uint16_t remote_msc, const iwrap_address_t *addr, uint16_t channel, uint8_t direction, uint8_t powermode, uint8_t role, uint8_t crypt, uint16_t buffer, uint8_t eretx);
void my_iwrap_rsp_set(uint8_t category, const char *option, const char *value);
void my_iwrap_evt_connect(uint8_t link_id, const char *type, uint16_t target, const iwrap_address_t *address);
void my_iwrap_evt_no_carrier(uint8_t link_id, uint16_t error_code, const char *message);
void my_iwrap_evt_pair(const iwrap_address_t *address, uint8_t key_type, const uint8_t *link_key);
void my_iwrap_evt_ready();
void my_iwrap_evt_ring(uint8_t link_id, const iwrap_address_t *address, uint16_t channel, const char *profile);

// general helper functions
uint8_t find_pairing_from_mac(const iwrap_address_t *mac);
uint8_t find_pairing_from_link_id(uint8_t link_id);
void add_mapped_connection(uint8_t link_id, const iwrap_address_t *addr, const char *mode, uint16_t channel);
uint8_t remove_mapped_connection(uint8_t link_id);
void print_connection_map();
void print_demo_menu();
void process_demo_choice(char b);

// platform-specific helper functions
int serial_out(const char *str);
int serial_out(const __FlashStringHelper *str);
int iwrap_out(int len, unsigned char *data);

void setup() {
    #if defined(PLATFORM_ARDUINO_UNO)
        // open the hardware serial port for debug/status output and software serial for iWRAP
        Serial.begin(HOST_BAUD);
        mySerial.begin(IWRAP_BAUD);
    #elif defined(PLATFORM_TEENSY2)
        // open the USB serial port for debug/status output and Serial1 for iWRAP
        Serial.begin(HOST_BAUD);
        Serial1.begin(IWRAP_BAUD);
    #else
        #error Select a supported platform, or add support for your own
    #endif

    // setup optional hardware reset pin connection (digital pin 9)
    digitalWrite(MODULE_RESET_PIN, LOW);
    pinMode(MODULE_RESET_PIN, OUTPUT);

    // assign transport/debug output
    iwrap_output = iwrap_out;
    #ifdef IWRAP_DEBUG
        iwrap_debug = serial_out;
    #endif /* IWRAP_DEBUG */

    // assign event callbacks
    iwrap_rsp_call = my_iwrap_rsp_call;
    iwrap_rsp_list_count = my_iwrap_rsp_list_count;
    iwrap_rsp_list_result = my_iwrap_rsp_list_result;
    iwrap_rsp_set = my_iwrap_rsp_set;
    iwrap_evt_connect = my_iwrap_evt_connect;
    iwrap_evt_no_carrier = my_iwrap_evt_no_carrier;
    iwrap_evt_pair = my_iwrap_evt_pair;
    iwrap_evt_ready = my_iwrap_evt_ready;
    iwrap_evt_ring = my_iwrap_evt_ring;

    // boot message to host
    serial_out(F("iWRAP host library generic demo started\n"));
}

void loop() {
    uint16_t result;

    // manage iWRAP state machine
    if (!iwrap_pending_commands) {
        // no pending commands, some state transition occurring
        if (iwrap_state) {
            // not idle, in the middle of some process
            if (iwrap_state == IWRAP_STATE_UNKNOWN) {
                // reset all detailed state trackers
                iwrap_initialized = 0;
                iwrap_pairings = 0;
                iwrap_pending_calls = 0;
                iwrap_pending_call_link_id = 0xFF;
                iwrap_connected_devices = 0;
                iwrap_active_connections = 0;

                // send command to test module connectivity
                serial_out(F("Testing iWRAP communication...\n"));
                iwrap_send_command("AT", iwrap_mode);
                iwrap_state = IWRAP_STATE_PENDING_AT;

                // initialize time reference for connectivity test timeout
                iwrap_time_ref = millis();
            } else if (iwrap_state == IWRAP_STATE_PENDING_AT) {
                // send command to dump all module settings and pairings
                serial_out(F("Getting iWRAP settings...\n"));
                iwrap_send_command("SET", iwrap_mode);
                iwrap_state = IWRAP_STATE_PENDING_SET;
            } else if (iwrap_state == IWRAP_STATE_PENDING_SET) {
                // send command to show all current connections
                serial_out(F("Getting active connection list...\n"));
                iwrap_send_command("LIST", iwrap_mode);
                iwrap_state = IWRAP_STATE_PENDING_LIST;
            } else if (iwrap_state == IWRAP_STATE_PENDING_LIST) {
                // all done!
                if (!iwrap_initialized) {
                    iwrap_initialized = 1;
                    serial_out(F("iWRAP initialization complete\n"));
                }
                print_connection_map();
                print_demo_menu();
                iwrap_state = IWRAP_STATE_IDLE;
            } else if (iwrap_state == IWRAP_STATE_PENDING_CALL && !iwrap_pending_calls) {
                // all done!
                serial_out(F("Pending call processed\n"));
                iwrap_state = IWRAP_STATE_IDLE;
            }
        } else if (iwrap_initialized) {
            // idle
            if (iwrap_pairings && iwrap_autocall_target > iwrap_connected_devices && !iwrap_pending_calls
                               && (!iwrap_autocall_last_time || (millis() - iwrap_autocall_last_time) >= iwrap_autocall_delay_ms)) {
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF 19 A2DP";      // A2DP
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF 17 AVRCP";     // AVRCP
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF 111F HFP";     // HFP
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF 111E HFP-AG";  // HFP-AG
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF 11 HID";       // HID
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF 1112 HSP";     // HSP
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF 1108 HSP-AG";  // HSP-AG
                //char cmd[] = "CALL AA:BB:CC:DD:EE:FF * IAP";        // IAP
                char cmd[] = "CALL AA:BB:CC:DD:EE:FF 1101 RFCOMM";  // SPP
                char *cptr = cmd + 5;

                // find first unconnected device
                for (; iwrap_connection_map[iwrap_autocall_index] -> active_links; iwrap_autocall_index++);

                // write MAC string into call command buffer and send it
                iwrap_bintohexstr((uint8_t *)(iwrap_connection_map[iwrap_autocall_index] -> mac.address), 6, &cptr, ':', 0);
                char s[21];
                sprintf(s, "Calling device #%d\r\n", iwrap_autocall_index);
                serial_out(s);
                iwrap_send_command(cmd, iwrap_mode);
                iwrap_autocall_last_time = millis();
            }
        }
    }

    // check for incoming iWRAP data
    #if defined(PLATFORM_ARDUINO_UNO)
        if ((result = mySerial.read()) < 256) iwrap_parse(result & 0xFF, iwrap_mode);
    #elif defined(PLATFORM_TEENSY2)
        if ((result = Serial1.read()) < 256) iwrap_parse(result & 0xFF, iwrap_mode);
    #endif

    // check for timeout if still testing communication
    if (!iwrap_initialized && iwrap_state == IWRAP_STATE_PENDING_AT) {
        if (millis() - iwrap_time_ref > 5000) {
            serial_out(F("ERROR: Could not communicate with iWRAP module\n"));
            iwrap_state = IWRAP_STATE_COMM_FAILED;
            iwrap_pending_commands = 0; // normally handled by the parser, but comms failed
        }
    }

    // check for incoming host data
    #if defined(PLATFORM_ARDUINO_UNO)
        if ((result = Serial.read()) < 256)
    #elif defined(PLATFORM_TEENSY2)
        if ((result = Serial.read()) < 256)
    #endif
    {
        process_demo_choice(result & 0xFF);
    }
}

/* ============================================================================
 * IWRAP RESPONSE AND EVENT HANDLER IMPLEMENTATIONS
 * ========================================================================= */

void my_iwrap_rsp_call(uint8_t link_id) {
    iwrap_pending_calls++;
    iwrap_pending_call_link_id = link_id;
    iwrap_autocall_index = (iwrap_autocall_index + 1) % iwrap_pairings;
    iwrap_state = IWRAP_STATE_PENDING_CALL;
}

void my_iwrap_rsp_list_count(uint8_t num_of_connections) {
    iwrap_active_connections = num_of_connections;
}

void my_iwrap_rsp_list_result(uint8_t link_id, const char *mode, uint16_t blocksize, uint32_t elapsed_time, uint16_t local_msc, uint16_t remote_msc, const iwrap_address_t *addr, uint16_t channel, uint8_t direction, uint8_t powermode, uint8_t role, uint8_t crypt, uint16_t buffer, uint8_t eretx) {
    add_mapped_connection(link_id, addr, mode, channel);
}

void my_iwrap_rsp_set(uint8_t category, const char *option, const char *value) {
    if (category == IWRAP_SET_CATEGORY_BT) {
        if (strncmp((char *)option, "BDADDR", 6) == 0) {
            iwrap_address_t local_mac;
            iwrap_hexstrtobin((char *)value, 0, local_mac.address, 0);
            char *local_mac_str = (char *)malloc(18);
            if (local_mac_str) {
                iwrap_bintohexstr(local_mac.address, 6, &local_mac_str, ':', 1);
                serial_out(F(":: Module MAC is "));
                serial_out(local_mac_str);
                serial_out(F("\n"));
                free(local_mac_str);
            }
        } else if (strncmp((char *)option, "NAME", 4) == 0) {
            serial_out(F(":: Friendly name is "));
            serial_out(value);
            serial_out(F("\n"));
        } else if (strncmp((char *)option, "PAIR", 4) == 0) {
            iwrap_address_t remote_mac;
            iwrap_hexstrtobin((char *)value, 0, remote_mac.address, 0);

            // make sure we allocate memory for the connection map entry
            if (iwrap_connection_map[iwrap_pairings] == 0) {
                iwrap_connection_map[iwrap_pairings] = (iwrap_connection_t *)malloc(sizeof(iwrap_connection_t));
            }
            memset(iwrap_connection_map[iwrap_pairings], 0xFF, sizeof(iwrap_connection_t)); // 0xFF is "no link ID"
            memcpy(&(iwrap_connection_map[iwrap_pairings] -> mac), &remote_mac, sizeof(iwrap_address_t));
            iwrap_connection_map[iwrap_pairings] -> active_links = 0;
            iwrap_pairings++;

            char *remote_mac_str = (char *)malloc(18);
            if (remote_mac_str) {
                iwrap_bintohexstr(remote_mac.address, 6, &remote_mac_str, ':', 1);
                serial_out(F(":: Pairing (MAC="));
                serial_out(remote_mac_str);
                serial_out(F(", key="));
                serial_out(value + 18);
                serial_out(F(")\n"));
                free(remote_mac_str);
            }
        }
    }
}

void my_iwrap_evt_connect(uint8_t link_id, const char *type, uint16_t target, const iwrap_address_t *address) {
    if (iwrap_pending_call_link_id == link_id) {
        if (iwrap_pending_calls) iwrap_pending_calls--;
        if (iwrap_state == IWRAP_STATE_PENDING_CALL) iwrap_state = IWRAP_STATE_IDLE;
        iwrap_pending_call_link_id = 0xFF;
    }
    iwrap_active_connections++;
    add_mapped_connection(link_id, address, type, target);
    print_connection_map();
}

void my_iwrap_evt_no_carrier(uint8_t link_id, uint16_t error_code, const char *message) {
    if (iwrap_pending_call_link_id == link_id) {
        if (iwrap_pending_calls) iwrap_pending_calls--;
        if (iwrap_state == IWRAP_STATE_PENDING_CALL) iwrap_state = IWRAP_STATE_IDLE;
        iwrap_pending_call_link_id = 0xFF;
    }
    if (remove_mapped_connection(link_id) != 0xFF) {
        // only update and reprint if the connection was already mapped
        // (i.e. not already closed or a failed outgoing connection attempt)
        if (iwrap_active_connections) iwrap_active_connections--;
        print_connection_map();
    }
}

void my_iwrap_evt_pair(const iwrap_address_t *address, uint8_t key_type, const uint8_t *link_key) {
    // request pair list again (could be a new pair, or updated pair, or new + overwritten pair)
    iwrap_send_command("SET BT PAIR", iwrap_mode);
    iwrap_state = IWRAP_STATE_PENDING_SET;
}

void my_iwrap_evt_ready() {
    iwrap_state = IWRAP_STATE_UNKNOWN;
}

void my_iwrap_evt_ring(uint8_t link_id, const iwrap_address_t *address, uint16_t channel, const char *profile) {
    add_mapped_connection(link_id, address, profile, channel);
    print_connection_map();
}

/* ============================================================================
 * GENERAL HELPER FUNCTIONS
 * ========================================================================= */

uint8_t find_pairing_from_mac(const iwrap_address_t *mac) {
    uint8_t i;
    for (i = 0; i < iwrap_pairings; i++) {
        if (memcmp(&(iwrap_connection_map[i] -> mac), mac, sizeof(iwrap_address_t)) == 0) return i;
    }
    return i >= iwrap_pairings ? 0xFF : i;
}

uint8_t find_pairing_from_link_id(uint8_t link_id) {
    // NOTE: This implementation walks through the iwrap_connection_t struct memory
    // starting at the first link ID (A2DP #1) and going all the way to the end (if
    // necessary). This means it is contingent on the structure keeping this memory
    // arrangement, where the last set of whatever is contained there is always the
    // set of link IDs.

    uint8_t i, j, *idptr;
    for (i = 0; i < iwrap_pairings; i++) {
        idptr = &(iwrap_connection_map[i] -> link_a2dp1);
        for (j = 6; j < sizeof(iwrap_connection_t); j++, idptr++) if (idptr[0] == link_id) return i;
    }
    return 0xFF;
}

void add_mapped_connection(uint8_t link_id, const iwrap_address_t *addr, const char *mode, uint16_t channel) {
    uint8_t pairing_index = find_pairing_from_mac(addr);

    // make sure we found a match (we SHOULD always match something, if we properly parsed the pairing data first)
    if (pairing_index == 0xFF) return; // uh oh

    // updated connected device count and overall active link count for this device
    if (!iwrap_connection_map[pairing_index] -> active_links) iwrap_connected_devices++;
    iwrap_connection_map[pairing_index] -> active_links++;

    // add link ID to connection map
    if (strcmp(mode, "A2DP") == 0) {
        if (iwrap_connection_map[pairing_index] -> link_a2dp1 == 0xFF) {
            iwrap_connection_map[pairing_index] -> link_a2dp1 = link_id;
        } else {
            iwrap_connection_map[pairing_index] -> link_a2dp2 = link_id;
        }
    } else if (strcmp(mode, "AVRCP") == 0) {
        iwrap_connection_map[pairing_index] -> link_avrcp = link_id;
    } else if (strcmp(mode, "HFP") == 0) {
        iwrap_connection_map[pairing_index] -> link_hfp = link_id;
    } else if (strcmp(mode, "HFPAG") == 0) {
        iwrap_connection_map[pairing_index] -> link_hfpag = link_id;
    } else if (strcmp(mode, "HID") == 0) {
        if (channel == 0x11) {
            iwrap_connection_map[pairing_index] -> link_hid_control = link_id;
        } else {
            iwrap_connection_map[pairing_index] -> link_hid_interrupt = link_id;
        }
    } else if (strcmp(mode, "HSP") == 0) {
        iwrap_connection_map[pairing_index] -> link_hsp = link_id;
    } else if (strcmp(mode, "HSPAG") == 0) {
        iwrap_connection_map[pairing_index] -> link_hspag = link_id;
    } else if (strcmp(mode, "IAP") == 0) {
        iwrap_connection_map[pairing_index] -> link_iap = link_id;
    } else if (strcmp(mode, "RFCOMM") == 0) {
        // probably SPP, possibly other RFCOMM-based connections
        if (channel == 1) {
            iwrap_connection_map[pairing_index] -> link_spp = link_id;
        //} else {
            //printf("RFCOMM link on channel %d, profile unknown\n", channel);
        }
    }
}

uint8_t remove_mapped_connection(uint8_t link_id) {
    uint8_t i;
    for (i = 0; i < iwrap_pairings; i++) {
        if (iwrap_connection_map[i] -> link_a2dp1 == link_id) { iwrap_connection_map[i] -> link_a2dp1 = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_a2dp2 == link_id) { iwrap_connection_map[i] -> link_a2dp2 = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_avrcp == link_id) { iwrap_connection_map[i] -> link_avrcp = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_hfp == link_id) { iwrap_connection_map[i] -> link_hfp = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_hfpag == link_id) { iwrap_connection_map[i] -> link_hfpag = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_hid_control == link_id) { iwrap_connection_map[i] -> link_hid_control = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_hid_interrupt == link_id) { iwrap_connection_map[i] -> link_hid_interrupt = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_hsp == link_id) { iwrap_connection_map[i] -> link_hsp = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_hspag == link_id) { iwrap_connection_map[i] -> link_hspag = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_iap == link_id) { iwrap_connection_map[i] -> link_iap = 0xFF; break; }
        if (iwrap_connection_map[i] -> link_spp == link_id) { iwrap_connection_map[i] -> link_spp = 0xFF; break; }
    }

    // check to make sure we found the link ID in the map
    if (i < iwrap_pairings) {
        // updated connected device count and overall active link count for this device
        if (iwrap_connection_map[i] -> active_links) {
            iwrap_connection_map[i] -> active_links--;
            if (!iwrap_connection_map[i] -> active_links) iwrap_connected_devices--;
        }
        return i;
    }

    // not found, return 0xFF
    return 0xFF;
}

/* ============================================================================
 * PLATFORM-SPECIFIC HELPER FUNCTIONS
 * ========================================================================= */

#if defined(PLATFORM_ARDUINO_UNO)
    int serial_out(const char *str) {
        // debug output to host goes through hardware serial
        return Serial.print(str);
    }
    int serial_out(const __FlashStringHelper *str) {
        // debug output to host goes through hardware serial
        return Serial.print(str);
    }
    int iwrap_out(int len, unsigned char *data) {
        // iWRAP output to module goes through software serial
        return mySerial.write(data, len);
    }
#elif defined(PLATFORM_TEENSY2)
    int serial_out(const char *str) {
        // debug output to host goes through Serial (USB)
        return Serial.print(str);
    }
    int serial_out(const __FlashStringHelper *str) {
        // debug output to host goes through Serial (USB)
        return Serial.print(str);
    }
    int iwrap_out(int len, unsigned char *data) {
        // iWRAP output to module goes through Serial1 (hardware UART)
        return Serial1.write(data, len);
    }
#endif

void print_connection_map() {
    char s[100];
    serial_out(F("==============================================================================\n"));
    sprintf(s, "Connection map (%d pairings, %d connected devices, %d total connections)\n", iwrap_pairings, iwrap_connected_devices, iwrap_active_connections);
    serial_out(s);
    serial_out(F("--------+-------+-------+-----+-------+-------+-----+-------+-----+-----+-----\n"));
    serial_out(F("Device\t|  A2DP | AVRCP | HFP | HFPAG |  HID  | HSP | HSPAG | IAP | SCO | SPP\n"));
    serial_out(F("--------+-------+-------+-----+-------+-------+-----+-------+-----+-----+-----\n"));
    uint8_t i;
    for (i = 0; i < iwrap_pairings; i++) {
        sprintf(s, "#%d (%d)\t| %2d/%2d |  %2d   |  %2d |   %2d  | %2d/%2d |  %2d |   %2d  |  %2d |  %2d |  %2d\n", i, iwrap_connection_map[i] -> active_links,
            (int8_t)iwrap_connection_map[i] -> link_a2dp1,
            (int8_t)iwrap_connection_map[i] -> link_a2dp2,
            (int8_t)iwrap_connection_map[i] -> link_avrcp,
            (int8_t)iwrap_connection_map[i] -> link_hfp,
            (int8_t)iwrap_connection_map[i] -> link_hfpag,
            (int8_t)iwrap_connection_map[i] -> link_hid_control,
            (int8_t)iwrap_connection_map[i] -> link_hid_interrupt,
            (int8_t)iwrap_connection_map[i] -> link_hsp,
            (int8_t)iwrap_connection_map[i] -> link_hspag,
            (int8_t)iwrap_connection_map[i] -> link_iap,
            (int8_t)iwrap_connection_map[i] -> link_sco,
            (int8_t)iwrap_connection_map[i] -> link_spp
            );
        serial_out(s);
    }
    serial_out(F("--------+-------+-------+-----+-------+-------+-----+-------+-----+-----+-----\n"));
}

void print_demo_menu() {
    serial_out(F("iWRAP generic demo menu\n"));
    serial_out(F("============================================================\n"));
    serial_out(F("0: Reset module (pulses iWRAP module RESET pin high for 5ms)\n"));
    serial_out(F("1: Toggle round-robin autocall algorithm on or off\n"));
    serial_out(F("2: Make module discoverable and connectable (SET BT PAGE 3)\n"));
    serial_out(F("3: Make module undiscoverable, but connectable (SET BT PAGE 2)\n"));
    serial_out(F("4: Make module undiscoverable and unconnectable (SET BT PAGE 0)\n"));
}

void process_demo_choice(char b) {
    // check for RESET command ("0")
    if (b == '0') {
        serial_out("=> (0) Performing hardware reset on iWRAP module\n\n");
        digitalWrite(MODULE_RESET_PIN, HIGH);
        delay(5);
        digitalWrite(MODULE_RESET_PIN, LOW);
        iwrap_pending_commands = 0; // normally handled by the parser, but this is a hard reset
    } else if (b == '1') {
        if (iwrap_autocall_target) {
            serial_out("=> (1) Disabling round-robin autocall algorithm\n\n");
            iwrap_autocall_target = 0;
        } else {
            serial_out("=> (1) Enabling round-robin autocall algorithm\n\n");
            iwrap_autocall_target = 1;
        }
    } else if (b == '2') {
        serial_out("=> (2) Setting page mode to 3 (discoverable and connectable)\n\n");
        iwrap_send_command("SET BT PAGEMODE 3", iwrap_mode);
    } else if (b == '3') {
        serial_out("=> (3) Setting page mode to 2 (undiscoverable, but connectable)\n\n");
        iwrap_send_command("SET BT PAGEMODE 2", iwrap_mode);
    } else if (b == '4') {
        serial_out("=> (4) Setting page mode to 0 (undiscoverable and unconnectable)\n\n");
        iwrap_send_command("SET BT PAGEMODE 0", iwrap_mode);
    }
}

error: pathspec 'src/arduino-bluetooth/iWRAP_demo_uno/iWRAP_demo_uno.ino' did not match any file(s) known to git


add announcer sketch

add announcer sketch

/// @dir announcer
/// Test sketch to send out "announcer" type management packets.
/// @see http://jeelabs.org/2013/01/16/remote-node-discovery-code/
// 2013-01-15 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#include <JeeLib.h>

#define MINUTES 1   // send out new announcement packets this often, cyclic
#define DEBUG 1     // send quickly, and to serial port instead of wireless

#define SKETCH_roomNode   11
#define SKETCH_ookRelay2  12
#define SKETCH_smaRelay   13
#define SKETCH_otRelay    14
#define SKETCH_p1scanner  15
#define SKETCH_homePower  16
#define SKETCH_radioBlip  17

typedef struct {
  byte nodeId;
  word sketchId;
  byte *items, size;
} NodeInfo;

MilliTimer minuteTimer;
byte nextSend, seqNum;
byte sendBuf[RF12_MAXDATA];

byte items_roomNode_v2[] = {
  0x01-1, 2, // version 2
  0x25-1, 8, 1, 7, -10, 1, // fields are 5 packed bit groups
};

byte items_homePower_v1[] = {
  0x01-1, 1, // version 1
  0x26-1, 16, 16, 16, 16, 16, 16, // fields are 6x 16-bit ints
};

byte items_radioBlip_v1[] = {
  0x01-1, 1, // version 1
  0x21-1, 32, // field is one 32-bit int
};

byte items_otRelay_v1[] = {
  0x01-1, 1, // version 1
  0x22-1, 8, 16, // fields are 2 ints
};

byte items_smaRelay_v1[] = {
  0x01-1, 1, // version 1
  0x27-1, 16, 16, 16, 16, 16, 16, 16, // fields are 7x 16-bit ints
};

#define NUM_NODES (sizeof nodeInfo / sizeof (NodeInfo))

NodeInfo nodeInfo[] = {
  { 2,  SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 3,  SKETCH_radioBlip, items_radioBlip_v1, sizeof items_radioBlip_v1 },
  { 4,  SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 5,  SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 6,  SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 9,  SKETCH_homePower, items_homePower_v1, sizeof items_homePower_v1 },
  { 10, SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 11, SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 12, SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 13, SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 14, SKETCH_otRelay,   items_otRelay_v1,   sizeof items_otRelay_v1   },
  { 15, SKETCH_smaRelay,  items_smaRelay_v1,  sizeof items_smaRelay_v1  },
  { 23, SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
  { 24, SKETCH_roomNode,  items_roomNode_v2,  sizeof items_roomNode_v2  },
};

static void sendAnnouncement (byte index) {
  NodeInfo *nip = &nodeInfo[index];
  // construct header according to the "standard" management packet format
  // see http://jeelabs.org/2013/01/15/remote-node-discovery-part-2/
  sendBuf[0] = (1 << 5) | nip->nodeId;
  sendBuf[1] = ++seqNum;
  sendBuf[2] = nip->sketchId;
  sendBuf[3] = nip->sketchId >> 8;
  // append item data with specific node packet details
  memcpy(sendBuf + 4, nip->items, nip->size);
  byte bytes = 4 + nip->size;

#if !DEBUG
  while (!rf12_canSend())
    rf12_recvDone();
  // special management packet, sent as special "packet to node 0"
  rf12_sendStart(RF12_HDR_DST, sendBuf, bytes);
#endif

  Serial.print(index);
  Serial.print(':');
  for (byte i = 0; i < 4 + nip->size; ++i) {
    Serial.print(' ');
    Serial.print(sendBuf[i] >> 4, HEX);
    Serial.print(sendBuf[i] & 0x0F, HEX);
  }
  Serial.println();
}

void setup () {
  Serial.begin(57600);
  Serial.println("\n[announcer]");
#if !DEBUG
  rf12_initialize(1, RF12_868MHZ, 5);
#endif
}

void loop () {
  if (minuteTimer.poll(DEBUG ? 3000 : 60000)) {
    sendAnnouncement(nextSend);
    if (++nextSend >= NUM_NODES)
      nextSend = 0;
  }
}

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


Storing last brighntess so we can optimize it's update.

///
///  Created for personal use, use it at your own risk and benefit.
///

#include "PinDefinitions.h"
#include "LedDefinitions.h"

#include "FastColour.h"
#include "LedSection.h"
#include "RPMWS2812.h"
//#include <NeoSerial.h>
//#include <SoftwareSerial.h>

#define SERIAL_BAUD_RATE 115200
#define STARTING_BRIGHTNESS 150 //Out of 255

#define ANIMATION_STEPS 6000
#define DEMO_RPM_RANGE 19000

#define ANIMATION_DURATION 12000
#define ANIMATION_UPDATE_INTERVAL 5
#define DEMO_RPM_UPDATE_INTERVAL  5
#define DEMO_LED_UPDATE_INTERVAL 100
#define DEMO_RPM_LOG_UPDATE_INTERVAL 400

#define BRIGHTNESS_UPDATE_INTERVAL 30
#define SERIAL_POLL_INTERVAL 20

#define POWER_AVERAGE_SAMPLES 10

//Sections data
#define MEDIUM_RPM 9000
#define HIGH_RPM 13000
#define MAX_RPM 15000

#define ALERT_PULSE_MILLIS 110
#define ALERT_PULSE_DUTY_CYCLE 160
#define ALERT_MIN_BRIGHTNESS 60

#define LOW_COLOUR cHSV(240, 255, 255)
#define MEDIUM_COLOUR cHSV(100, 255, 255)
#define HIGH_COLOUR cHSV(120, 255, 255)
#define BACKGROUND_COLOUR cHSV(240, 255, 5)
#define LED_MIN_BRIGHTNESS_VALUE 20

//NeoSerial Serial(0, 1);
//SoftwareSerial Serial(4, 3);
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

RPMWS2812 RPMDriver;

uint8_t GlobalBrightness = STARTING_BRIGHTNESS;
uint8_t LastGlobalBrightness = 0;

//Mostly demo stuff
uint16_t DemoRPM = 0;
uint16_t AnimationStep = 0;
uint32_t StartTime, RPMStart, RPMEnd;
uint32_t Now;
uint32_t AnimationStart;
uint32_t LastRPMUpdate, LastLEDUpdate, LastAnimationUpdate, LastRPMLogUpdate,
LastPowerUpdate, LastPowerLogUpdate, LastBrightnessUpdate, LastSerialUpdate;

uint64_t LastPowerSum = 0;
uint32_t LastAveragePower = 0;
uint16_t PowerSumCounter = 0;

void SetupDemo()
{
	AnimationStep = 0;

	StartTime = millis();

	LastLEDUpdate = StartTime;
	LastRPMUpdate = StartTime;
	LastLEDUpdate = StartTime;
	LastAnimationUpdate = StartTime;
	AnimationStart = StartTime;
	LastPowerUpdate = StartTime;
	LastPowerLogUpdate = StartTime;
	LastRPMLogUpdate = StartTime;
	LastBrightnessUpdate = StartTime;
	LastSerialUpdate = StartTime;
}
void Demo(uint32_t now)
{
	if (now - LastAnimationUpdate > ANIMATION_UPDATE_INTERVAL - 1)
	{
		LastAnimationUpdate += ANIMATION_UPDATE_INTERVAL;

		AnimationStep = ((ANIMATION_STEPS*(now - AnimationStart)) / ANIMATION_DURATION);

		if (now - AnimationStart > ANIMATION_DURATION - 1)
		{
			AnimationStep = 0;
			Serial.print(F("Animation end, took "));
			Serial.print((int32_t)(now - AnimationStart), DEC);
			Serial.println(F(" ms"));
			AnimationStart = now;
		}
	}
}

void serialEvent() {
	while (Serial.available()) {
		// get the new byte:
		char inChar = (char)Serial.read();
		// add it to the inputString:
		inputString += inChar;
		// if the incoming character is a newline, set a flag
		// so the main loop can do something about it:
		if (inChar == '\n') {
			stringComplete = true;
		}
	}
}

void UpdateSerial()
{
	int NewBrightness = inputString.toInt();

	GlobalBrightness = constrain(NewBrightness, 0, 255);

	inputString = "";
	stringComplete = false;

}

void UpdateBrightness()
{
	if (GlobalBrightness != LastGlobalBrightness)
	{
		RPMDriver.SetBrightness(GlobalBrightness);
		//RPMDriver.SetExtendedOverflowRange(constrain(GlobalBrightness + 5, 0, 255));
		//Serial.print("GlobalBrightness: ");
		//Serial.println(GlobalBrightness);

		LastGlobalBrightness = GlobalBrightness;
	}

}

void setup()
{

	Serial.begin(SERIAL_BAUD_RATE);
	inputString.reserve(200);// reserve bytes for the inputString:
	delay(500);

	Serial.println();
	Serial.println();
	Serial.println(F("RPM setup..."));
	SetupRPMDriver();
	Serial.println(F(" complete"));

	SetupDemo();
}

cHSV GetAlertBrightness()
{
	return { HIGH_COLOUR.h, HIGH_COLOUR.s, max(GlobalBrightness, ALERT_MIN_BRIGHTNESS) };
}

bool SetupRPMDriver()
{

	//RPMDriver.AddLogger(&Serial);
	RPMDriver.Begin();
	RPMDriver.SetDesignModel(SUB_PIXEL_ENABLED);// | SUB_PIXEL_HIGH_RANGE_ENABLED | BACKGROUND_ENABLED);
	RPMDriver.SetBrightness(GlobalBrightness);
	RPMDriver.SetRangeRPM(600, 15000);
	RPMDriver.ClearSections();

	RPMDriver.SetAlertBlink(HIGH_COLOUR, ALERT_PULSE_MILLIS, ALERT_PULSE_DUTY_CYCLE);

	//RPMDriver.SetExtendedOverflowRange(constrain(GlobalBrightness + 50, 0, 255));

	RPMDriver.SetSection(0, MEDIUM_RPM / 2, LOW_COLOUR, BACKGROUND_COLOUR);
	RPMDriver.SetSection(MEDIUM_RPM / 2, MEDIUM_RPM, cHSV(300, 254, 254), BACKGROUND_COLOUR);
	RPMDriver.SetSection(MEDIUM_RPM, HIGH_RPM, MEDIUM_COLOUR, BACKGROUND_COLOUR);
	RPMDriver.SetSection(HIGH_RPM, MAX_RPM, HIGH_COLOUR, BACKGROUND_COLOUR);//, { 120,255,1 }
	RPMDriver.BootAnimation(LOW_COLOUR);

}

void loop()
{
	Now = millis();

	if (Now - LastBrightnessUpdate > BRIGHTNESS_UPDATE_INTERVAL - 1)
	{

		LastBrightnessUpdate += BRIGHTNESS_UPDATE_INTERVAL;

		UpdateBrightness();
		/*Serial.print("GlobalBrightness: ");
		Serial.println(GlobalBrightness);*/
	}

	if (Now - LastLEDUpdate > DEMO_LED_UPDATE_INTERVAL - 1)
	{
		LastLEDUpdate += DEMO_LED_UPDATE_INTERVAL;
	}

	if (Now - LastRPMLogUpdate > DEMO_RPM_LOG_UPDATE_INTERVAL - 1)
	{
		LastRPMLogUpdate += DEMO_RPM_LOG_UPDATE_INTERVAL;
		Serial.print("RPM: ");
		Serial.println(DemoRPM);
	}

	if (Now - LastRPMUpdate > DEMO_RPM_UPDATE_INTERVAL - 1)
	{
		LastRPMUpdate += DEMO_RPM_UPDATE_INTERVAL;

		if (AnimationStep < ANIMATION_STEPS / 2)
		{
			DemoRPM = AnimationStep * 2 * ((uint32_t)DEMO_RPM_RANGE / (uint32_t)ANIMATION_STEPS);
		}
		else
		{
			DemoRPM = (ANIMATION_STEPS - AnimationStep) * 2 * ((uint32_t)DEMO_RPM_RANGE / ANIMATION_STEPS);
		}

		//RPMStart = micros();
		RPMDriver.UpdateRPM(DemoRPM, Now, true);
		//Serial.println(RPMDriver.Debug());
		//RPMEnd = micros();
		//Serial.print("Update RPM took: ");
		//Serial.print((RPMEnd - RPMStart));
		//Serial.println(" us");
	}

	Demo(Now);

	if (Now - LastSerialUpdate > SERIAL_POLL_INTERVAL - 1)
	{
		if (stringComplete)
		{
			UpdateSerial();
		}
		LastSerialUpdate += SERIAL_POLL_INTERVAL;

		//Serial.print("GlobalBrightness: ");
		//Serial.println(GlobalBrightness);
	}
}

///
///  Created for personal use, use it at your own risk and benefit.
///

#include "PinDefinitions.h"
#include "LedDefinitions.h"

#include "FastColour.h"
#include "LedSection.h"
#include "RPMWS2812.h"
//#include <NeoSerial.h>
//#include <SoftwareSerial.h>

#define SERIAL_BAUD_RATE 115200
#define STARTING_BRIGHTNESS 150 //Out of 255

#define ANIMATION_STEPS 6000
#define DEMO_RPM_RANGE 19000

#define ANIMATION_DURATION 12000
#define ANIMATION_UPDATE_INTERVAL 5
#define DEMO_RPM_UPDATE_INTERVAL  5
#define DEMO_LED_UPDATE_INTERVAL 100
#define DEMO_RPM_LOG_UPDATE_INTERVAL 400

#define BRIGHTNESS_UPDATE_INTERVAL 30
#define SERIAL_POLL_INTERVAL 20

#define POWER_AVERAGE_SAMPLES 10

//Sections data
#define MEDIUM_RPM 9000
#define HIGH_RPM 13000
#define MAX_RPM 15000

#define ALERT_PULSE_MILLIS 110
#define ALERT_PULSE_DUTY_CYCLE 160
#define ALERT_MIN_BRIGHTNESS 60

#define LOW_COLOUR cHSV(240, 255, 255)
#define MEDIUM_COLOUR cHSV(100, 255, 255)
#define HIGH_COLOUR cHSV(120, 255, 255)
#define BACKGROUND_COLOUR cHSV(240, 255, 5)
#define LED_MIN_BRIGHTNESS_VALUE 20

//NeoSerial Serial(0, 1);
//SoftwareSerial Serial(4, 3);
String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

RPMWS2812 RPMDriver;

uint8_t GlobalBrightness = STARTING_BRIGHTNESS;

//Mostly demo stuff
uint16_t DemoRPM = 0;
uint16_t AnimationStep = 0;
uint32_t StartTime, RPMStart, RPMEnd;
uint32_t Now;
uint32_t AnimationStart;
uint32_t LastRPMUpdate, LastLEDUpdate, LastAnimationUpdate, LastRPMLogUpdate,
LastPowerUpdate, LastPowerLogUpdate, LastBrightnessUpdate, LastSerialUpdate;
uint64_t LastPowerSum = 0;
uint32_t LastAveragePower = 0;
uint16_t PowerSumCounter = 0;

void SetupDemo()
{
	AnimationStep = 0;

	StartTime = millis();

	LastLEDUpdate = StartTime;
	LastRPMUpdate = StartTime;
	LastLEDUpdate = StartTime;
	LastAnimationUpdate = StartTime;
	AnimationStart = StartTime;
	LastPowerUpdate = StartTime;
	LastPowerLogUpdate = StartTime;
	LastRPMLogUpdate = StartTime;
	LastBrightnessUpdate = StartTime;
	LastSerialUpdate = StartTime;
}
void Demo(uint32_t now)
{
	if (now - LastAnimationUpdate > ANIMATION_UPDATE_INTERVAL - 1)
	{
		LastAnimationUpdate += ANIMATION_UPDATE_INTERVAL;

		AnimationStep = ((ANIMATION_STEPS*(now - AnimationStart)) / ANIMATION_DURATION);

		if (now - AnimationStart > ANIMATION_DURATION - 1)
		{
			AnimationStep = 0;
			Serial.print(F("Animation end, took "));
			Serial.print((int32_t)(now - AnimationStart), DEC);
			Serial.println(F(" ms"));
			AnimationStart = now;
		}
	}
}

void serialEvent() {
	while (Serial.available()) {
		// get the new byte:
		char inChar = (char)Serial.read();
		// add it to the inputString:
		inputString += inChar;
		// if the incoming character is a newline, set a flag
		// so the main loop can do something about it:
		if (inChar == '\n') {
			stringComplete = true;
		}
	}
}

void UpdateSerial()
{
	int NewBrightness = inputString.toInt();

	GlobalBrightness = constrain(NewBrightness, 0, 255);

	inputString = "";
	stringComplete = false;

}

void UpdateBrightness()
{
	RPMDriver.SetBrightness(GlobalBrightness);
	//RPMDriver.SetExtendedOverflowRange(constrain(GlobalBrightness + 5, 0, 255));
	RPMDriver.SetAlertBlink(GetAlertBrightness());
	//Serial.print("GlobalBrightness: ");
	//Serial.println(GlobalBrightness);
}

void setup()
{

	Serial.begin(SERIAL_BAUD_RATE);
	inputString.reserve(200);// reserve bytes for the inputString:
	delay(500);

	Serial.println();
	Serial.println();
	Serial.println(F("RPM setup..."));
	SetupRPMDriver();
	Serial.println(F(" complete"));

	SetupDemo();
}

cHSV GetAlertBrightness()
{
	return { HIGH_COLOUR.h, HIGH_COLOUR.s, max(GlobalBrightness, ALERT_MIN_BRIGHTNESS) };
}

bool SetupRPMDriver()
{

	//RPMDriver.AddLogger(&Serial);
	RPMDriver.Begin();
	RPMDriver.SetDesignModel(SUB_PIXEL_ENABLED);// | SUB_PIXEL_HIGH_RANGE_ENABLED | BACKGROUND_ENABLED);
	RPMDriver.SetBrightness(GlobalBrightness);
	RPMDriver.SetRangeRPM(600, 15000);
	RPMDriver.ClearSections();

	RPMDriver.SetAlertBlink(GetAlertBrightness(), ALERT_PULSE_MILLIS, ALERT_PULSE_DUTY_CYCLE);

	//RPMDriver.SetExtendedOverflowRange(constrain(GlobalBrightness + 50, 0, 255));

	RPMDriver.SetSection(0, MEDIUM_RPM / 2, LOW_COLOUR, BACKGROUND_COLOUR);
	RPMDriver.SetSection(MEDIUM_RPM / 2, MEDIUM_RPM, cHSV(300, 254, 254), BACKGROUND_COLOUR);
	RPMDriver.SetSection(MEDIUM_RPM, HIGH_RPM, MEDIUM_COLOUR, BACKGROUND_COLOUR);
	RPMDriver.SetSection(HIGH_RPM, MAX_RPM, HIGH_COLOUR, BACKGROUND_COLOUR);//, { 120,255,1 }
	RPMDriver.BootAnimation(LOW_COLOUR);

}

void loop()
{
	Now = millis();

	if (Now - LastBrightnessUpdate > BRIGHTNESS_UPDATE_INTERVAL - 1)
	{

		LastBrightnessUpdate += BRIGHTNESS_UPDATE_INTERVAL;

		UpdateBrightness();
		/*Serial.print("GlobalBrightness: ");
		Serial.println(GlobalBrightness);*/
	}

	if (Now - LastLEDUpdate > DEMO_LED_UPDATE_INTERVAL - 1)
	{
		LastLEDUpdate += DEMO_LED_UPDATE_INTERVAL;
	}

	if (Now - LastRPMLogUpdate > DEMO_RPM_LOG_UPDATE_INTERVAL - 1)
	{
		LastRPMLogUpdate += DEMO_RPM_LOG_UPDATE_INTERVAL;
		Serial.print("RPM: ");
		Serial.println(DemoRPM);
	}

	if (Now - LastRPMUpdate > DEMO_RPM_UPDATE_INTERVAL - 1)
	{
		LastRPMUpdate += DEMO_RPM_UPDATE_INTERVAL;

		if (AnimationStep < ANIMATION_STEPS / 2)
		{
			DemoRPM = AnimationStep * 2 * ((uint32_t)DEMO_RPM_RANGE / (uint32_t)ANIMATION_STEPS);
		}
		else
		{
			DemoRPM = (ANIMATION_STEPS - AnimationStep) * 2 * ((uint32_t)DEMO_RPM_RANGE / ANIMATION_STEPS);
		}

		//RPMStart = micros();
		RPMDriver.UpdateRPM(DemoRPM, Now, true);
		//Serial.println(RPMDriver.Debug());
		//RPMEnd = micros();
		//Serial.print("Update RPM took: ");
		//Serial.print((RPMEnd - RPMStart));
		//Serial.println(" us");
	}

	Demo(Now);

	if (Now - LastSerialUpdate > SERIAL_POLL_INTERVAL - 1)
	{
		if (stringComplete)
		{
			UpdateSerial();
		}
		LastSerialUpdate += SERIAL_POLL_INTERVAL;

		//Serial.print("GlobalBrightness: ");
		//Serial.println(GlobalBrightness);
	}
}


jk communications fully online 2

jk communications fully online 2

#include <ax12.h>
#include <BioloidController.h>
#include "poses.h"

#define BASE_MIN    0
#define BASE_MAX    1023

#define SHOULDER_MIN  205
#define SHOULDER_MAX  810

#define ELBOW_MIN    210
#define ELBOW_MAX    900

#define WRIST_MIN    200
#define WRIST_MAX    830

#define WROT_MIN     0
#define WROT_MAX     1023

#define GRIP_MIN     0
#define GRIP_MAX     512

int GetServoNo();
int GetAngle(int no);
void doPose(int Base, int Shoulder, int Elbow, int Wrist, int Wrot, int grip);
int SetAngle(int no, int angle);
void setNextPose(int no, int angle);
void ScanServo();
void readAngles();
void Move();
void MoveTest();
void RelaxServos();
void parseMove(int counter, int* path);

char incomingChar;
String message,SOPHeader,EOPTail,endChars;
String Eof,Startseq,Endseq,getangles;

BioloidController bioloid = BioloidController(1000000);

const int SERVOCOUNT = 8;
prog_uint16_t currPose[SERVOCOUNT+1];
int id;
int pos;
int pos2;
int conn;
boolean IDCheck;
boolean RunCheck;

void setup() {

   delay (100);
   Serial.begin(9600);
   /*   Serial.println("###########################\n");
   Serial.println("Serial Communication Established.\n");
   Serial.println("###########################"); */
   SOPHeader = "Start:";
   EOPTail = ":End";
   Eof = "ARRDONE";
   Startseq = "STARTSEQ";
   getangles = "GETANG";
   Endseq = "ENDSEQ";
   pinMode(0,OUTPUT);
   bioloid.setup(8);
   currPose[0] = 8;
   //initialize variables
   id = 1;
   pos = 0;
   conn = 0;
   IDCheck = 1;
   RunCheck = 0;
  //open serial port

  //Check Lipo Battery Voltage
/*  CheckVoltage();

  MoveCenter();
*/
//
  delay(10);

//Scan Servos, return position.
/*  ScanServo();

  MoveTest();

  MoveHome();*/

  RelaxServos();
  doPose(512, 512, 512, 512, 512, 512);
  RunCheck = 1;

}

void loop(){
  // read the sensor:
    //int inByte = Serial.read();
    char c = 0;
    char in = 'X';
    while (!conn) {
      if ((c = Serial.read()) == 'X') {
          Serial.print("X");
          conn = 1;
      }
    }
    int no;
    int angle;
    /*
    switch (inByte) {

      case '0':
        Serial.println("Got byte from program");
        break;
      case '1':
        ScanServo();
        break;

      case '2':
        no = GetServoNo();
        if (no == -1) {
          break;
        }
        GetAngle(no);
        Move();
        break;
      case '3':
        doPose(512, 512, 512, 512, 512, 512);
        break;
      case '4':
        RelaxServos();
        break;

      case '5':
        Move();
        MoveTest();
        break;
    } */

    readAngles();
}

int GetServoNo() {
  Serial.println("Waiting for servo #:");
    delay(3000);
    int inByte = -1;
    String angle = "";
    if (Serial.available() > 0) { //if data is available
        inByte = Serial.read() - 48; //get the servo number
        Serial.print("Servo ID: ");
        Serial.println(inByte);
        return inByte;
    }
    else {
        return -1; //if no servo given, continue
    }
}

int GetAngle(int no) {
  for (int i = 1; i <= SERVOCOUNT; i++) {
      currPose[i] = ax12GetRegister(i, 36, 2);
      bioloid.setNextPose(i, currPose[i]);

      Serial.println(bioloid.getId(i));
  }
  setNextPose(no, 300);
}

void doPose(int Base, int Shoulder, int Elbow, int Wrist, int Wrot, int grip) {
  unsigned long starttime, stoptime;
  starttime = millis();
  setNextPose(Base, Shoulder, Elbow, Wrist, Wrot, grip);
  stoptime = millis();
  //Serial.println("time setNextPose = ");
  //Serial.println(stoptime - starttime);
  starttime = millis();
  Move();
  stoptime = millis();
  //Serial.println("time Move = ");
  //Serial.println(stoptime - starttime);
  //Serial.println("Hello:End");
}

int SetAngle(int no, int angle) {
  for (int i = 1; i <= SERVOCOUNT; i++) {
      currPose[i] = ax12GetRegister(i, 36, 2);
      bioloid.setNextPose(i, currPose[i]);

      Serial.println(bioloid.getId(i));
  }
  setNextPose(no, angle);
}

void setNextPose(int Base, int Shoulder, int Elbow, int Wrist, int Wrot, int grip) {
  int thatsTheRightNumber = 300;
      thatsTheRightNumber = max(min(Base, BASE_MAX), BASE_MIN);
      bioloid.setNextPose(1, thatsTheRightNumber);

      thatsTheRightNumber = max(min(Shoulder, SHOULDER_MAX), SHOULDER_MIN);
      bioloid.setNextPose(2, thatsTheRightNumber);
      bioloid.setNextPose(3, 1024-thatsTheRightNumber);

      thatsTheRightNumber = max(min(Elbow, ELBOW_MAX), ELBOW_MIN);
      bioloid.setNextPose(4, thatsTheRightNumber);
      bioloid.setNextPose(5, 1024-thatsTheRightNumber);

      thatsTheRightNumber = max(min(Wrist, WRIST_MAX), WRIST_MIN);
      bioloid.setNextPose(6, thatsTheRightNumber);

      thatsTheRightNumber = max(min(Wrot, WROT_MAX), WROT_MIN);
      bioloid.setNextPose(7, thatsTheRightNumber);

      thatsTheRightNumber = max(min(grip, GRIP_MAX), GRIP_MIN);
      bioloid.setNextPose(8, thatsTheRightNumber);

}

void ScanServo(){
  id = 1;
  Serial.println("###########################");
  Serial.println("Starting Servo Scanning Test.");
  Serial.println("###########################");

  while (id <= SERVOCOUNT){
  pos =  ax12GetRegister(id, 36, 2);
  Serial.print("Servo ID: ");
  Serial.println(id);
  Serial.print("Servo Position: ");
  Serial.println(pos);

  if (pos <= 0){
  Serial.println("###########################");
  Serial.print("ERROR! Servo ID: ");
  Serial.print(id);
  Serial.println(" not found. Please check connection and verify correct ID is set.");
  Serial.println("###########################");
  IDCheck = 0;
  }

  id = (id++)%SERVOCOUNT;
  delay(10);
  }
  if (IDCheck == 0){
    Serial.println("###########################");
    Serial.println("ERROR! Servo ID(s) are missing from Scan. Please check connection and verify correct ID is set.");
    Serial.println("###########################");
  }
  else{
  Serial.println("All servo IDs present.");
  }
}

void readAngles() {
  /*unsigned long starttime, stoptime;
  starttime = millis();*/
  int i = 0;
  int *path;
  //message = "";
  while(1) {
    if (Serial.available()) {
      //Start reading the stream
      //Serial.println("before read");
      incomingChar = Serial.read();
      message.concat(incomingChar); //Concatanate the received characters to the string message
      if(message.endsWith(Startseq)) {
        message = String("");
        while(1) {
          if (Serial.available()) {
            incomingChar=Serial.read();
            message.concat(incomingChar);
          }
          if (message.endsWith(Endseq)) {
            break;
          }
        }
        message = message.substring(0,message.length()-Endseq.length());
        int s = message.toInt();
        int *path = (int*)malloc(sizeof(int) * s * 6);
        Serial.println(s);
        while(1) {
          if (Serial.available()) {
            incomingChar = Serial.read();
            message.concat(incomingChar);
            if (message.endsWith(SOPHeader)) {
              message = "";
              Serial.println("Got here\n");
              while(1) { //Start receiving once data is available on the serial link
                if (Serial.available()) {
                  incomingChar=Serial.read();
                  message.concat(incomingChar);
                  if(message.endsWith(EOPTail)) {
                    Serial.println("Got here2\n");
                    //message = message.substring(0,message.length()-EOPTail.length());
                    //Serial.println(message);
                    parseMove(i, path);
                    i++;
                    break;
                  }
                }
              }
            }
          }
          if (message.endsWith(Eof)) {
            for (int j = 0; j < i; j++) {
              doPose(path[j*6], path[j*6+1], path[j*6+2], path[j*6+3], path[j*6+4], path[j*6+5]);
            }
            free(path);
            conn = 0;
            return;
          }
        }
      }
      //Serial.print("Q");
      if (message.endsWith(getangles)) {
        message = "";
        int id = 1;
        Serial.print(",");
        while (id <= SERVOCOUNT) {
          pos =  ax12GetRegister(id, 36, 2);
          Serial.print(pos);
          Serial.print(",");
          id++;
        }
        Serial.print("Q");
        conn = 0;
        return;
      }
    }
  }/*
  for (int j = 0; j < i; j++) {
    doPose(path[j*6], path[j*6+1], path[j*6+2], path[j*6+3], path[j*6+4], path[j*6+5]);
  }*/
  return;

  /*while(Serial.available()) { //Start receiving once data is available on the serial link
        int i = 0;
        //Start reading the stream
        incomingChar=Serial.read();
        message.concat(incomingChar); //Concatanate the received characters to the string message

        if(message.endsWith(SOPHeader)){ //If the last characters correspond to the SOP Heade strip it off and start considering this a valid message
          message="";
        }
        //Check for EOP trailer and strip it off
        if(message.endsWith(EOPTail)){ // If in the debug state signal that the EOP has been detected
          message=message.substring(0,message.length()-EOPTail.length());
          parseMove(message, path, i);
          i++;
        }
        if(message.endsWith(EOF)) {
          break;
        }
  }
  stoptime = millis();
  Serial.println("Time = ");
  Serial.println(stoptime - starttime);*/
}

void parseMove(int counter, int *path) {

  int Base, Shoulder, Shoulder1, Elbow, Elbow1, Wrist, Wrot, grip;
  char *str;
  char* delim = ",";
  char* delim2 = ":";
  char temp[message.length()+1];
  Serial.println("Hello\n");
  message.toCharArray(temp, message.length());
  Base = atoi(strtok_r(temp, delim, &str));
  Shoulder = atoi(strtok_r(NULL, delim, &str));
  Shoulder1 = atoi(strtok_r(NULL, delim, &str));
  Elbow = atoi(strtok_r(NULL, delim, &str));
  Elbow1 = atoi(strtok_r(NULL, delim, &str));
  Wrist = atoi(strtok_r(NULL, delim, &str));
  Wrot = atoi(strtok_r(NULL, delim, &str));
  grip = atoi(strtok_r(NULL, delim2, &str));

  path[counter * 6] = Base;
  path[counter * 6 + 1] = Shoulder;
  path[counter * 6 + 2] = Elbow;
  path[counter * 6 + 3] = Wrist;
  path[counter * 6 + 4] = Wrot;
  path[counter * 6 + 5] = grip;
  //doPose(Base, Shoulder, Elbow, Wrist, Wrot, grip);
  /*Serial.println(Base);
  Serial.println(Shoulder);
  Serial.println(Elbow);
  Serial.println(Wrist);
  Serial.println(Wrot);
  Serial.println(grip);*/

}

void Move(){
    delay(10);                    // recommended pause

    //bioloid.loadPose(Center);   // load the pose from FLASH, into the nextPose buffer
    bioloid.readPose();            // read in current servo positions to the curPose buffer
    //Serial.println("Moving servos to centered position");
    for (int i = 1; i <= SERVOCOUNT; i++) {
        //Serial.println(bioloid.getCurPose(i));
        //Serial.println(bioloid.getNextPose(i));
    }
    bioloid.interpolateSetup(50); // setup for interpolation from current->next over 1/2 a second
    while(bioloid.interpolating > 0){  // do this while we have not reached our new pose
        bioloid.interpolateStep();     // move servos, if necessary.
        delay(3);
    }
}

void MoveTest(){
  //Serial.println("###########################");
  //Serial.println("Initializing Movement Sign Test");
  //Serial.println("###########################");
  delay(10);
  id = 1;
  pos = pos2 = 512;

// Base Servo Test

  //Serial.println("Moving Servo ID: 1");

  while(pos >= 312){
  SetPosition(1, pos);
  pos = pos--;
  delay(10);
  }

  while(pos <= 512){
  SetPosition(1, pos);
  pos = pos++;
  delay(10);
  }

  delay(500);

// Shoulder Servos Test

  Serial.println("Moving Servo IDs: 2 & 3 (Shoulder)");
  while(pos >= 312){
  SetPosition(2, pos);
  SetPosition(3, pos2);
  pos = pos--;
  pos2 = pos2++;
  delay(10);
  }

  while(pos <= 512){
  SetPosition(2, pos);
  SetPosition(3, pos2);
  pos = pos++;
  pos2 = pos2--;
  delay(10);
  }

  delay(500);

// Elbow Servo Test

  Serial.println("Moving Servo IDs: 4 & 5 (Elbow)");
  while(pos <= 712){
  SetPosition(4, pos);
  SetPosition(5, pos2);
  pos = pos++;
  pos2 = pos2--;
  delay(10);
  }

  while(pos >= 512){
  SetPosition(4, pos);
  SetPosition(5, pos2);
  pos = pos--;
  pos2 = pos2++;
  delay(10);
  }

  delay(500);

  //Wrist Servo Test

  Serial.println("Moving Servo ID: 6");

  while(pos <= 712){
  SetPosition(6, pos);
  pos = pos++;
  delay(10);
  }

  while(pos >= 512){
  SetPosition(6, pos);
  pos = pos--;
  delay(10);
  }

  delay(500);

  //Wrist Rotate Servo Test

  Serial.println("Moving Servo ID: 7");

  while(pos >= 312){
  SetPosition(7, pos);
  pos = pos--;
  delay(10);
  }

  while(pos <= 512){
  SetPosition(7, pos);
  pos = pos++;
  delay(10);
  }

  delay(500);

  //Gripper Servo Test

    Serial.println("Moving Servo ID: 8");

  while(pos >= 312){
  SetPosition(8, pos);
  pos = pos--;
  delay(10);
  }

  while(pos <= 512){
  SetPosition(8, pos);
  pos = pos++;
  delay(10);
  }

  delay(500);

}

void RelaxServos(){
  id = 1;
  /*Serial.println("###########################");
  Serial.println("Relaxing Servos.");
  Serial.println("###########################");
  */while(id <= SERVOCOUNT){
    Relax(id);
    id = (id++)%SERVOCOUNT;
    delay(50);
  }
}

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


added test for all the leds and the cny70s

#include <Shiftduino.h>

Shiftduino sd(22, 24 , 23, 3);
boolean testRed[] = {0, 1, 0, 1, 0, 1, 0, 1,
                    0, 1, 0, 1, 0, 1, 0, 1,
                    0, 1, 0, 1, 0, 1, 0, 1};

boolean testGreen[] = {1, 0, 1, 0, 1, 0, 1, 0,
                      1, 0, 1, 0, 1, 0, 1, 0,
                      1, 0, 1, 0, 1, 0, 1, 0};

boolean leds = true;

void setup() {
  Serial.begin(9600);
  sd.clear();
  sd.setPins(testGreen);
  delay(1000);
  sd.clear();
}

void loop() {
  if (leds){
    testLeds();
  } else{
    testCNY70();
  }

}

void testCNY70(){
  // Used analog pins for CNY70: [A8, A0]
  sd.clear();
  // Change the analog ping to test each one
  int color = analogRead(A0);
  Serial.println(color);
  delay(300);
}

void testLeds(){
  sd.clear();
  sd.setPins(testRed);
  delay(300);
  sd.clear();
  sd.setPins(testGreen);
  delay(300);
}

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


add serial

add serial

error: pathspec 'arduino/opencr_arduino/opencr/libraries/ROS/examples/02.' did not match any file(s) known to git
error: pathspec 'Sensors/b_cliff/b_cliff.ino' did not match any file(s) known to git


Example added

Example added

/*
   Copyright (c) 2017 Kikkei Labs UG
   Author: Moises Martinez <moises@kikkei.com>
*/

#include <MotionDetector.h>
#include <SetupAP.h>

kikkei::iot::TimeCounter timer;
kikkei::iot::MotionDetector motion_detector(&timer);
kikkei::iot::SetupAP setup_ap;

void setup()
{
  Serial.begin(115200);
  Serial.println("Starting....");

  if (true) //device setup
  {
    motion_detector.activate();
  }
  else
  {
    setup_ap.activate();
  }
}

void loop()
{
  timer.update();

  if (true)
    motion_detector.tick();
  else
    setup_ap.tick();
}

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


Adding example sketch for connecting an Autonomy with LoRaBee to TTN over ABP or OTAA

/*
 *    Basic sketch for connecting
 *    a Sodaq Autonomo equiped with a
 *    LoRaBee to The Things Network
 *
 *
 */

#include <rn2483.h>

// Autonomo Serial port definitions.
#define debugSerial SerialUSB
#define loraSerial Serial1

// create an instance of the Library.
rn2483 myLora(loraSerial);

void setup()
{
  // Put power on the BeeSocket.
  digitalWrite(BEE_VCC, HIGH);

  // built_in led
  pinMode(LED_BUILTIN, OUTPUT);
  led_on();

  // make sure usb serial connection is available,
  // or after 10s go on anyway for 'headless' use of the
  // node.
  while ((!debugSerial) && (millis() < 10000));

  // beginning serial connections.
  debugSerial.begin(57600);
  loraSerial.begin(9600);

  //
  debugSerial.println(F("--------------------------------"));
  debugSerial.println(F("Basic sketch for connecting "));
  debugSerial.println(F("to The ThingsNetwork"));
  debugSerial.println(F("--------------------------------"));
  led_off();

  initialize_radio();

}

void initialize_radio()
{

  myLora.autobaud();

  debugSerial.println("DevEUI? ");debugSerial.print(F("> "));
  debugSerial.println(myLora.hweui());
  debugSerial.println("Version?");debugSerial.print(F("> "));
  debugSerial.println(myLora.sysver());
  debugSerial.println(F("--------------------------------"));

  debugSerial.println(F("Trying to join TTN"));
  bool join_result = false;

  //ABP: initABP(String addr, String AppSKey, String NwkSKey);
  join_result = myLora.initABP("02017201", "8D7FFEF938589D95AAD928C2E2E7E48F", "AE17E567AECC8787F749A62F5541D522");

  //OTAA: initOTAA(String AppEUI, String AppKey);
  //join_result = myLora.initOTAA("70B3D57ED00001A6", "A23C96EE13804963F8C2BD6285448198");

  while(!join_result)
  {
    debugSerial.println("\u2A2F Unable to join. Are your keys correct, and do you have TTN coverage?");
    delay(30000); //delay 30s before retry
    join_result = myLora.init();
  }
  debugSerial.println("\u2713 Successfully joined TTN");

}

void loop()
{
    led_on();
    debugSerial.println(F("> TXing"));
    myLora.tx("!"); //one byte, blocking function
    led_off();

    // delay it a little bit
    // but the library manages the real dutycycle check.
    delay(200);
}

void led_on()
{
  digitalWrite(LED_BUILTIN, 1);
}

void led_off()
{
  digitalWrite(LED_BUILTIN, 0);
}

error: pathspec 'examples/TTN-Autonomo-basic-connect/TTN-autonomo-basic.ino' did not match any file(s) known to git


test ADC library

test ADC library

/* Test suite for the ADC library
*/

#include <ADC.h>

ADC *adc = new ADC(); // adc object

#if defined(ADC_TEENSY_LC) // teensy LC
#define PINS 13
#define DIG_PINS 13
#define PINS_DIFF 2
uint8_t adc_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9,A10,A11, A12};
uint8_t adc_pins_dig[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9,A10,A11, A12};
uint8_t adc_pins_diff[] = {A10, A11};

#elif defined(ADC_TEENSY_3_0)  // teensy 3.0
#define PINS 14
#define DIG_PINS 10
#define PINS_DIFF 4
uint8_t adc_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13};
uint8_t adc_pins_dig[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9};
uint8_t adc_pins_diff[] = {A10, A11, A12, A13};

#elif defined(ADC_TEENSY_3_1) || defined(ADC_TEENSY_3_2)  // teensy 3.1/3.2
#define PINS 21
#define DIG_PINS 16
#define PINS_DIFF 4
uint8_t adc_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9,A10,A11,A12,A13,
                      A14, A15,A16,A17,A18,A19,A20 };
uint8_t adc_pins_dig[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8,A9, A15,A16,A17,A18,A19,A20 };
uint8_t adc_pins_diff[] = {A10, A11, A12, A13};

#elif defined(ADC_TEENSY_3_5)  // Teensy 3.5
#define PINS 27
#define DIG_PINS 21
#define PINS_DIFF 2
uint8_t adc_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9, A10,
                      A11,A12,A13,A14,A15,A16,A17,A18,A19,A20,A21,A22,A23,A24, A25, A26};
uint8_t adc_pins_dig[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9, A12,A13,A14,A15,A16,A17,A18,A19,A20,A23,A24};
uint8_t adc_pins_diff[] = {A10, A11};

#elif defined(ADC_TEENSY_3_6)  // Teensy 3.6
#define PINS 25
#define DIG_PINS 21
#define PINS_DIFF 2
uint8_t adc_pins[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9, A10,
                      A11,A12,A13,A14,A15,A16,A17,A18,A19,A20,A21,A22,A23,A24};
uint8_t adc_pins_dig[] = {A0,A1,A2,A3,A4,A5,A6,A7,A8, A9, A12,A13,A14,A15,A16,A17,A18,A19,A20,A23,A24};
uint8_t adc_pins_diff[] = {A10, A11};
#endif // defined

void setup() {

    pinMode(LED_BUILTIN, OUTPUT);

    for (int i=0;i<PINS;i++) {
        pinMode(adc_pins[i], INPUT);
    }

    Serial.begin(9600);

    ///// ADC0 ////
    // reference can be ADC_REFERENCE::REF_3V3, ADC_REFERENCE::REF_1V2 (not for Teensy LC) or ADC_REFERENCE::REF_EXT.
    //adc->setReference(ADC_REFERENCE::REF_1V2, ADC_NUM::ADC_0); // change all 3.3 to 1.2 if you change the reference to 1V2

    adc->setAveraging(16); // set number of averages
    adc->setResolution(16); // set bits of resolution

    // it can be any of the ADC_CONVERSION_SPEED enum: VERY_LOW_SPEED, LOW_SPEED, MED_SPEED, HIGH_SPEED_16BITS, HIGH_SPEED or VERY_HIGH_SPEED
    // see the documentation for more information
    // additionally the conversion speed can also be ADACK_2_4, ADACK_4_0, ADACK_5_2 and ADACK_6_2,
    // where the numbers are the frequency of the ADC clock in MHz and are independent on the bus speed.
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::VERY_LOW_SPEED); // change the conversion speed
    // it can be any of the ADC_MED_SPEED enum: VERY_LOW_SPEED, LOW_SPEED, MED_SPEED, HIGH_SPEED or VERY_HIGH_SPEED
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_LOW_SPEED); // change the sampling speed

    // always call the compare functions after changing the resolution!
    //adc->enableCompare(1.0/3.3*adc->getMaxValue(ADC_NUM::ADC_0), 0, ADC_NUM::ADC_0); // measurement will be ready if value < 1.0V
    //adc->enableCompareRange(1.0*adc->getMaxValue(ADC_NUM::ADC_0)/3.3, 2.0*adc->getMaxValue(ADC_NUM::ADC_0)/3.3, 0, 1, ADC_NUM::ADC_0); // ready if value lies out of [1.0,2.0] V

    // If you enable interrupts, notice that the isr will read the result, so that isComplete() will return false (most of the time)
    //adc->enableInterrupts(ADC_NUM::ADC_0);

    ////// ADC1 /////
    #if ADC_NUM_ADCS>1
    adc->setAveraging(16, ADC_NUM::ADC_1); // set number of averages
    adc->setResolution(16, ADC_NUM::ADC_1); // set bits of resolution
    adc->setConversionSpeed(ADC_CONVERSION_SPEED::VERY_LOW_SPEED, ADC_NUM::ADC_1); // change the conversion speed
    adc->setSamplingSpeed(ADC_SAMPLING_SPEED::VERY_LOW_SPEED, ADC_NUM::ADC_1); // change the sampling speed

    //adc->setReference(ADC_REFERENCE::REF_1V2, ADC_NUM::ADC_1);

    // always call the compare functions after changing the resolution!
    //adc->enableCompare(1.0/3.3*adc->getMaxValue(ADC_NUM::ADC_1), 0, ADC_NUM::ADC_1); // measurement will be ready if value < 1.0V
    //adc->enableCompareRange(1.0*adc->getMaxValue(ADC_NUM::ADC_1)/3.3, 2.0*adc->getMaxValue(ADC_NUM::ADC_1)/3.3, 0, 1, ADC_NUM::ADC_1); // ready if value lies out of [1.0,2.0] V

    // If you enable interrupts, note that the isr will read the result, so that isComplete() will return false (most of the time)
    //adc->enableInterrupts(ADC_NUM::ADC_1);

    #endif

    delay(500);
}

int value = 0;
int pin=0;

void test_pull(bool pullup) {
    uint8_t mode = pullup ? INPUT_PULLUP : INPUT_PULLDOWN;

    for (int i=0;i<DIG_PINS;i++) {
        pinMode(adc_pins[i], mode);
        value = adc->analogRead(adc_pins_dig[i]);
        if (value < 3.2) {
            Serial.print("A"); Serial.print(i); Serial.print(": ");
            Serial.print("FAILED "); Serial.print(pullup ? "INPUT_PULLUP" : "INPUT_PULLDOWN"); Serial.println(". ");
        }
    }
}

void loop() {

    test_pull(true);
    test_pull(false);

    // Print errors, if any.
    adc->printError();
    adc->resetError();

    //digitalWriteFast(LED_BUILTIN, !digitalReadFast(LED_BUILTIN));

    delay(500);

}

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


Added OTA

Added OTA

esp8266/projects/Blynk Light Switch v1/blynk_light_switch_01/blynk_light_switch_01.ino

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


change debug

change debug