comment on WireS

comment on WireS

// MewPro
//
// The following small-factor micro processor boards are known to work with MewPro at least core functionalities and fit within the GoPro housing.
// Not all the sensors, however, are supported by each of them.
//
//   Arduino Pro Mini 328 3.3V 8MHz
//          w/ Arduino IDE 1.5.7+
//          if you have troubles in compiling unused or nonexistent libraries, simply comment out #include line as //#include (see Note* below)
//
//   Arduino Pro Micro - 3.3V 8MHz
//          w/ Arduino IDE 1.5.7+
//          if you have troubles in compiling unused or nonexistent libraries, simply comment out #include line as //#include (see Note* below)
//
//   Teensy 3.x / Teensy LC
//          [POWER SUPPLY: The VIN-VUSB pad connection on the bottom side of Teensy 3.x/LC needs to be cut.]
//          To compile the code with Teensy 3.x/LC:
//          1. use Arduino IDE 1.0.6+ and Teensyduino 1.20+
//          2. comment out all unused #include as //#include (see Note* below)
//
//   (Note*: There is an infamous Arduino IDE's preprocessor bug (or something) that causes to ignore #ifdef/#else/#endif directives and forces
//    to compile unnecessary libraries.)
//
//   Intel Edison
//          Since Intel Edison can not work as I2C slave, it requires an I2C proxy.
//
//   GR-KURUMI
//          [POWER SUPPLY: The dummy resistor soldered on JP1 of the MewPro board needs replacement w/ a general purpose diode of >100mA w/ dropoff voltage 1V
//           (eg. Bourns S0180); Anode should be located on the Herobus side and Cathode on the Arduino side.]
//          To compile the code with GR-KURUMI using Renesas web compiler http://www.renesas.com/products/promotion/gr/index.jsp#cloud :
//          1. open a new project with the template GR-KURUMI_Sketch_V1.04.zip.
//          2. create a folder named MewPro and upload all the files there.
//          3. at project's home directory, replace all the lines of gr_scketch.cpp by the following code (BEGIN / END lines should be excluded).
/* BEGIN copy
#include <RLduino78.h>
#include "MewPro/MewPro.ino"
#include "MewPro/a_Queue.ino"
#include "MewPro/b_TimeAlarms.ino"
#include "MewPro/c_I2C.ino"
#include "MewPro/d_BacpacCommands.ino"
#include "MewPro/e_Shutter.ino"
#include "MewPro/f_Switch.ino"
#include "MewPro/g_IRremote.ino"
#include "MewPro/h_LightSensor.ino"
#include "MewPro/i_PIRsensor.ino"
#include "MewPro/j_VideoMotionDetect.ino"
#include "MewPro/k_Genlock.ino"
END copy */
//

//   Copyright (c) 2014-2015 orangkucing
//
// MewPro firmware version string for maintenance
#define MEWPRO_FIRMWARE_VERSION "2015051800"

//
#include <Arduino.h>
#include <EEPROM.h>
#include "MewPro.h"

// enable console output
// set false if this is MewPro #0 of dual dongle configuration
boolean debug = true;

//////////////////////////////////////////////////////////
// Options:
//   Choose either "#define" to use or "#undef" not to use.
//   if #define then don't forget to remove // before //#include

//********************************************************
// a_TimeAlarms: MewPro driven timelapse
#undef  USE_TIME_ALARMS
// Time and TimeAlarms libraries are downloadable from
//   http://www.pjrc.com/teensy/td_libs_Time.html
//   and http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
// In order to compile the code on Pro Mini 328, find the following and edit the first line of them
//   #if defined(__AVR__)
//   #include <avr/pgmspace.h>
//   #else
// to
//   #if defined(__AVR__) && !defined(__AVR_ATmega328P__)
//   #include <avr/pgmspace.h>
//   #else
// appeared in Documents/Arduino/libraries/Time/DateStrings.cpp
//#include <Time.h> // *** please comment out this line if USE_TIME_ALARMS is not defined ***
//#include <TimeAlarms.h> // *** please comment out this line if USE_TIME_ALARMS is not defined ***

//********************************************************
// c_I2C: I2C interface (THIS PART CAN'T BE OPTED OUT)
//
// Note: in order to use MewPro reliably, THE FOLLOWING MODIFICATIONS TO STANDARD ARDUINO LIBRARY SOURCE IS
// STRONGLY RECOMMENDED:
//
// Arduino Pro Mini / Arduino Pro Micro
//     1. hardware/arduino/avr/libraries/Wire/Wire.h
//            old: #define BUFFER_LENGTH 32                        -->   new: #define BUFFER_LENGTH 64
//     2. hardware/arduino/avr/libraries/Wire/utility/twi.h
//            old: #define TWI_BUFFER_LENGTH 32                    -->   new: #define TWI_BUFFER_LENGTH 64
// Arduino Due
//     hardware/arduino/sam/libraries/Wire/Wire.h
//            old: #define BUFFER_LENGTH 32                        -->   new: #define BUFFER_LENGTH 64
#include <Wire.h> // *** please comment out this line if __MK20DX256__ or __MK20DX128__ or __MKL26Z64__ or __AVR_ATtiny1634__ is defined ***
#if BUFFER_LENGTH < 64
#error Please modify Arduino Wire library source code to increase the I2C buffer size
#endif
//
// Teensy 3.0 or 3.1 or LC
//#include <i2c_t3.h> // *** please comment out this line if __MK20DX256__ and __MK20DX128__ and __MKL26Z64__ are not defined ***
//
// ATtiny1634 core https://github.com/SpenceKonde/arduino-tiny-841
//    WireS library is downloadable from https://github.com/orangkucing/WireS
//    - In order to use F(" ") macro, hardware/arduino-tiny-841/avr/cores/tiny/{Print|WString}.{cpp|h} must
//      be replaced by hardware/arduino/avr/cores/arduino/{Print|WString}.{cpp|h}
//    - And hardware/arduino/avr/cores/arduino/Printable.h must be copied to
//      hardware/arduino-tiny-841/avr/cores/tiny/Printable.h
//    - Please also refer this commit: https://github.com/orangkucing/WireS/commit/e5d0a80ebd1f0797fc750a10208918a6392a488a
//#include <WireS.h> // *** please comment out this line if __AVR_ATtiny1634__ is not defined ***

#undef  USE_I2C_PROXY // define if using I2C proxy and this CPU acts as I2C master

//********************************************************
// e_Shutters: A remote shutters without contact bounce or chatter
#undef  USE_SHUTTER

//********************************************************
// f_Switches: One or two mechanical switches
#undef  USE_SWITCHES

//********************************************************
// g_IRremote: IR remote controller
#undef  USE_IR_REMOTE
// IRremote2 is downloadable from https://github.com/enternoescape/Arduino-IRremote-Due
// (this works not only on Due but also on Pro Mini etc.)
//#include <IRremote2.h> // *** please comment out this line if USE_IR_REMOTE is not defined ***

//********************************************************
// h_LightSensor: Ambient light sensor
#undef  USE_LIGHT_SENSOR

//********************************************************
// i_PIRsensor: Passive InfraRed motion sensor
#undef  USE_PIR_SENSOR

//********************************************************
// j_VideoMotionDetect: Video Motion Detector
//   Video motion detect consumes almost all the dynamic memory. So if you want to use this then #undef all options above.
#undef  USE_VIDEOMOTION
// The part of code utilizes the following library except GR-KURUMI. Please download and install:
//   https://github.com/orangkucing/analogComp
//#include "analogComp.h" // *** please comment out this line if USE_VIDEOMOTION is not defined or GR-KURUMI ***

//********************************************************
// k_Genlock: Generator Lock
//   Note: MewPro #0 in dual dongle configuration should always boolean debug = false;
#undef  USE_GENLOCK

// end of Options
//////////////////////////////////////////////////////////

// if __AVR_ATmega32U4__ (Leonardo or Pro Micro) then use Serial1 (TTL) instead of Serial (USB) to communicate with genlock dongle
#if defined(USE_GENLOCK) && defined(__AVR_ATmega32U4__)
#define Serial Serial1
#endif

boolean lastHerobusState = LOW;  // Will be HIGH when camera attached.
int eepromId = 0;

void userSettings()
{
  // This function is called once after camera boot.
  // you can set put any camera commands here. For example:
  // queueIn("AI1");
  // queueIn("TI5");
}

void setup()
{
  // Remark. Arduino Pro Mini 328 3.3V 8MHz is too slow to catch up with the highest 115200 baud.
  //     cf. http://forum.arduino.cc/index.php?topic=54623.0
  // Set 57600 baud or slower.
  Serial.begin(57600);

  setupShutter();
  setupSwitch();
  setupIRremote();
  setupLightSensor();
  setupPIRSensor();
  setupGenlock();

  setupLED(); // onboard LED setup
  pinMode(BPRDY, OUTPUT); digitalWrite(BPRDY, LOW);    // Show camera MewPro attach.

  // don't forget to switch pin configurations to INPUT.
  pinMode(I2CINT, INPUT);  // Teensy: default disabled
  pinMode(HBUSRDY, INPUT); // default: analog input
  pinMode(PWRBTN, INPUT);  // default: analog input
}

void loop()
{
  // Attach or detach bacpac
  if (digitalRead(HBUSRDY) == HIGH) {
    if (lastHerobusState != HIGH) {
#if !defined(USE_I2C_PROXY)
      pinMode(I2CINT, OUTPUT); digitalWrite(I2CINT, HIGH);
#endif
      lastHerobusState = HIGH;
      if (eepromId == 0) {
        isMaster(); // determine master/slave and resetI2C()
      } else {
        resetI2C();
      }
    }
  } else {
    if (lastHerobusState != LOW) {
      pinMode(I2CINT, INPUT);
      lastHerobusState = LOW;
    }
  }
  checkTimeAlarms();
  checkBacpacCommands();
  checkCameraCommands();
  checkSwitch();
  checkIRremote();
  checkLightSensor();
  checkPIRSensor();
  checkVMD();
  checkGenlock();
}

// MewPro
//
// The following small-factor micro processor boards are known to work with MewPro at least core functionalities and fit within the GoPro housing.
// Not all the sensors, however, are supported by each of them.
//
//   Arduino Pro Mini 328 3.3V 8MHz
//          w/ Arduino IDE 1.5.7+
//          if you have troubles in compiling unused or nonexistent libraries, simply comment out #include line as //#include (see Note* below)
//
//   Arduino Pro Micro - 3.3V 8MHz
//          w/ Arduino IDE 1.5.7+
//          if you have troubles in compiling unused or nonexistent libraries, simply comment out #include line as //#include (see Note* below)
//
//   Teensy 3.x / Teensy LC
//          [POWER SUPPLY: The VIN-VUSB pad connection on the bottom side of Teensy 3.x/LC needs to be cut.]
//          To compile the code with Teensy 3.x/LC:
//          1. use Arduino IDE 1.0.6+ and Teensyduino 1.20+
//          2. comment out all unused #include as //#include (see Note* below)
//
//   (Note*: There is an infamous Arduino IDE's preprocessor bug (or something) that causes to ignore #ifdef/#else/#endif directives and forces
//    to compile unnecessary libraries.)
//
//   Intel Edison
//          Since Intel Edison can not work as I2C slave, it requires an I2C proxy.
//
//   GR-KURUMI
//          [POWER SUPPLY: The dummy resistor soldered on JP1 of the MewPro board needs replacement w/ a general purpose diode of >100mA w/ dropoff voltage 1V
//           (eg. Bourns S0180); Anode should be located on the Herobus side and Cathode on the Arduino side.]
//          To compile the code with GR-KURUMI using Renesas web compiler http://www.renesas.com/products/promotion/gr/index.jsp#cloud :
//          1. open a new project with the template GR-KURUMI_Sketch_V1.04.zip.
//          2. create a folder named MewPro and upload all the files there.
//          3. at project's home directory, replace all the lines of gr_scketch.cpp by the following code (BEGIN / END lines should be excluded).
/* BEGIN copy
#include <RLduino78.h>
#include "MewPro/MewPro.ino"
#include "MewPro/a_Queue.ino"
#include "MewPro/b_TimeAlarms.ino"
#include "MewPro/c_I2C.ino"
#include "MewPro/d_BacpacCommands.ino"
#include "MewPro/e_Shutter.ino"
#include "MewPro/f_Switch.ino"
#include "MewPro/g_IRremote.ino"
#include "MewPro/h_LightSensor.ino"
#include "MewPro/i_PIRsensor.ino"
#include "MewPro/j_VideoMotionDetect.ino"
#include "MewPro/k_Genlock.ino"
END copy */
//

//   Copyright (c) 2014-2015 orangkucing
//
// MewPro firmware version string for maintenance
#define MEWPRO_FIRMWARE_VERSION "2015051800"

//
#include <Arduino.h>
#include <EEPROM.h>
#include "MewPro.h"

// enable console output
// set false if this is MewPro #0 of dual dongle configuration
boolean debug = true;

//////////////////////////////////////////////////////////
// Options:
//   Choose either "#define" to use or "#undef" not to use.
//   if #define then don't forget to remove // before //#include

//********************************************************
// a_TimeAlarms: MewPro driven timelapse
#undef  USE_TIME_ALARMS
// Time and TimeAlarms libraries are downloadable from
//   http://www.pjrc.com/teensy/td_libs_Time.html
//   and http://www.pjrc.com/teensy/td_libs_TimeAlarms.html
// In order to compile the code on Pro Mini 328, find the following and edit the first line of them
//   #if defined(__AVR__)
//   #include <avr/pgmspace.h>
//   #else
// to
//   #if defined(__AVR__) && !defined(__AVR_ATmega328P__)
//   #include <avr/pgmspace.h>
//   #else
// appeared in Documents/Arduino/libraries/Time/DateStrings.cpp
//#include <Time.h> // *** please comment out this line if USE_TIME_ALARMS is not defined ***
//#include <TimeAlarms.h> // *** please comment out this line if USE_TIME_ALARMS is not defined ***

//********************************************************
// c_I2C: I2C interface (THIS PART CAN'T BE OPTED OUT)
//
// Note: in order to use MewPro reliably, THE FOLLOWING MODIFICATIONS TO STANDARD ARDUINO LIBRARY SOURCE IS
// STRONGLY RECOMMENDED:
//
// Arduino Pro Mini / Arduino Pro Micro
//     1. hardware/arduino/avr/libraries/Wire/Wire.h
//            old: #define BUFFER_LENGTH 32                        -->   new: #define BUFFER_LENGTH 64
//     2. hardware/arduino/avr/libraries/Wire/utility/twi.h
//            old: #define TWI_BUFFER_LENGTH 32                    -->   new: #define TWI_BUFFER_LENGTH 64
// Arduino Due
//     hardware/arduino/sam/libraries/Wire/Wire.h
//            old: #define BUFFER_LENGTH 32                        -->   new: #define BUFFER_LENGTH 64
#include <Wire.h> // *** please comment out this line if __MK20DX256__ or __MK20DX128__ or __MKL26Z64__ or __AVR_ATtiny1634__ is defined ***
#if BUFFER_LENGTH < 64
#error Please modify Arduino Wire library source code to increase the I2C buffer size
#endif
//
// Teensy 3.0 or 3.1 or LC
//#include <i2c_t3.h> // *** please comment out this line if __MK20DX256__ and __MK20DX128__ and __MKL26Z64__ are not defined ***
//
// ATtiny1634 core https://github.com/SpenceKonde/arduino-tiny-841
//    WireS library is downloadable from https://github.com/orangkucing/WireS
//    - In order to use F(" ") macro, hardware/arduino-tiny-841/avr/cores/tiny/{Print|WString}.{cpp|h} must
//      be replaced by hardware/arduino/avr/cores/arduino/{Print|WString}.{cpp|h}
//    - And hardware/arduino/avr/cores/arduino/Printable.h must be copied to
//      hardware/arduino-tiny-841/avr/cores/tiny/Printable.h
//#include <WireS.h> // *** please comment out this line if __AVR_ATtiny1634__ is not defined ***

#undef  USE_I2C_PROXY // define if using I2C proxy and this CPU acts as I2C master

//********************************************************
// e_Shutters: A remote shutters without contact bounce or chatter
#undef  USE_SHUTTER

//********************************************************
// f_Switches: One or two mechanical switches
#undef  USE_SWITCHES

//********************************************************
// g_IRremote: IR remote controller
#undef  USE_IR_REMOTE
// IRremote2 is downloadable from https://github.com/enternoescape/Arduino-IRremote-Due
// (this works not only on Due but also on Pro Mini etc.)
//#include <IRremote2.h> // *** please comment out this line if USE_IR_REMOTE is not defined ***

//********************************************************
// h_LightSensor: Ambient light sensor
#undef  USE_LIGHT_SENSOR

//********************************************************
// i_PIRsensor: Passive InfraRed motion sensor
#undef  USE_PIR_SENSOR

//********************************************************
// j_VideoMotionDetect: Video Motion Detector
//   Video motion detect consumes almost all the dynamic memory. So if you want to use this then #undef all options above.
#undef  USE_VIDEOMOTION
// The part of code utilizes the following library except GR-KURUMI. Please download and install:
//   https://github.com/orangkucing/analogComp
//#include "analogComp.h" // *** please comment out this line if USE_VIDEOMOTION is not defined or GR-KURUMI ***

//********************************************************
// k_Genlock: Generator Lock
//   Note: MewPro #0 in dual dongle configuration should always boolean debug = false;
#undef  USE_GENLOCK

// end of Options
//////////////////////////////////////////////////////////

// if __AVR_ATmega32U4__ (Leonardo or Pro Micro) then use Serial1 (TTL) instead of Serial (USB) to communicate with genlock dongle
#if defined(USE_GENLOCK) && defined(__AVR_ATmega32U4__)
#define Serial Serial1
#endif

boolean lastHerobusState = LOW;  // Will be HIGH when camera attached.
int eepromId = 0;

void userSettings()
{
  // This function is called once after camera boot.
  // you can set put any camera commands here. For example:
  // queueIn("AI1");
  // queueIn("TI5");
}

void setup()
{
  // Remark. Arduino Pro Mini 328 3.3V 8MHz is too slow to catch up with the highest 115200 baud.
  //     cf. http://forum.arduino.cc/index.php?topic=54623.0
  // Set 57600 baud or slower.
  Serial.begin(57600);

  setupShutter();
  setupSwitch();
  setupIRremote();
  setupLightSensor();
  setupPIRSensor();
  setupGenlock();

  setupLED(); // onboard LED setup
  pinMode(BPRDY, OUTPUT); digitalWrite(BPRDY, LOW);    // Show camera MewPro attach.

  // don't forget to switch pin configurations to INPUT.
  pinMode(I2CINT, INPUT);  // Teensy: default disabled
  pinMode(HBUSRDY, INPUT); // default: analog input
  pinMode(PWRBTN, INPUT);  // default: analog input
}

void loop()
{
  // Attach or detach bacpac
  if (digitalRead(HBUSRDY) == HIGH) {
    if (lastHerobusState != HIGH) {
#if !defined(USE_I2C_PROXY)
      pinMode(I2CINT, OUTPUT); digitalWrite(I2CINT, HIGH);
#endif
      lastHerobusState = HIGH;
      if (eepromId == 0) {
        isMaster(); // determine master/slave and resetI2C()
      } else {
        resetI2C();
      }
    }
  } else {
    if (lastHerobusState != LOW) {
      pinMode(I2CINT, INPUT);
      lastHerobusState = LOW;
    }
  }
  checkTimeAlarms();
  checkBacpacCommands();
  checkCameraCommands();
  checkSwitch();
  checkIRremote();
  checkLightSensor();
  checkPIRSensor();
  checkVMD();
  checkGenlock();
}


Added sensors and actuators implementation for arduino

Jira issue: WP-595

#include <aJSON.h>
#include <SPI.h>
#include <Ethernet.h>

#define NUM_ELEMENTS   2

#define BOARD_ID         "00001"
//#define BOARD_LANGUAGE "webinos"
//#define BOARD_PROTOCOL "HTTP"
//#define BOARD_NAME     "ARDUINO_UNO"
#define BOARD_IP         192,168,1,120
#define BOARD_PORT       80

#define PZP_IP           192,168,1,130
#define PZP_PORT         1984

//NB sa -> 0=sensor, 1=actuator
//NB ad -> 0=analog, 1=digital
#define ELEMENTS_RES "{\"bid\":\"00001\",\"cmd\":\"ele\",\"elements\":[{\"id\":\"00001_000\", \"element\": {\"sa\":\"0\",\"maximumRange\":\"0.1\",\"minDelay\":\"500\",\"power\":\"0.02\",\"resolution\":\"0.001\",\"type\":\"temperature\",\"vendor\":\"apple_temp\",\"version\":\"1\"}},{\"id\":\"00001_001\", \"element\":{\"sa\":\"0\",\"maximumRange\":\"0.1\",\"minDelay\":\"500\",\"power\":\"0.02\",\"resolution\":\"0.001\",\"type\":\"proximity\",\"vendor\":\"apple_prox\",\"version\":\"1\"}}]}"
#define HELLO_REQ "GET /newboard?jsondata={\"id\":\"00001\",\"protocol\":\"HTTP\",\"name\":\"ARDUINO_UNO\",\"ip\":\"192.168.1.120\",\"port\":\"80\"} HTTP/1.0"

typedef struct {
  char* id;
  bool sa;
  bool ad;
  int pin;
  bool active;
  long rate;
  long lastConnectionTime;
  } IOElement;

IOElement * elements[NUM_ELEMENTS];

//Ethernet stuff
byte mac[] = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress pzp_ip(PZP_IP);
IPAddress arduino_ip(BOARD_IP);
EthernetClient client;
EthernetServer server(BOARD_PORT);

boolean boardconnected = false;

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

  elements[0] = new IOElement();
  elements[0]->id = "00001_000";
  elements[0]->sa = 0;
  elements[0]->ad = 0;
  elements[0]->pin = 0;
  elements[0]->active = 0;
  elements[0]->rate = 1000;

  elements[1] = new IOElement();
  elements[1]->id = "00001_001";
  elements[1]->sa = 0;
  elements[1]->ad = 1;
  elements[1]->pin = 1;
  elements[1]->active = 0;
  elements[1]->rate = 3500;

  //start Ethernet
  Ethernet.begin(mac, arduino_ip);
}

//hell function
String getValueFromSensor(bool ad, int pin){
  int value = -1;
  if(ad == 0){ //analog sensor
    value = analogRead(pin);
  }
  else{ //digital sensor
    value = digitalRead(pin);
  }
  return String(value);
}

void sendDataToAPI(int id_ele){
//  Serial.print("Send data id : ");
//  Serial.println(id_ele);
  if (client.connect(pzp_ip, PZP_PORT)) {
    client.print("POST /sensor?id=");
    client.print(elements[id_ele]->id);
    client.print("&data=");
    client.print(getValueFromSensor(elements[id_ele]->ad, elements[id_ele]->pin));
    client.println("\0 HTTP/1.0");
    client.println();
    client.stop();
    elements[id_ele]->lastConnectionTime = millis();
  }
}

void loop(){
  if(!boardconnected){
    Serial.println("Try connecting to PZP");
    if (client.connect(pzp_ip, PZP_PORT)) {
      client.println(HELLO_REQ);
      client.println();

      String s;
      bool nextisbody = false;
      delay(1000);

      char vet[19];
      int i=0;
      int num_spaces=0;
      while(client.available() > 0){
        char c = client.read();

//      // Not work! test it!
//        if(num_spaces==2){
//          vet[i++] = c;
//          if(i==19){
//            vet[i] = '/0';
//            if(strcmp(vet, "{\"ack\":\"newboard\"}") == 0)
//              Serial.println("new board");
//            else
//              Serial.println("error");
//
//            boardconnected=true;
//            break;
//          }
//          else
//            Serial.print(c);
//        }
//        else{
//          if(c == '\n')
//            num_spaces++;
//          else
//            num_spaces=0;
//        }

        s += c;
        if(c == '\n'){
          if(nextisbody){
            Serial.println(s);
            char json_char[s.length()];
            s.toCharArray(json_char, s.length());
            aJsonObject* jsonObject = aJson.parse(json_char);
            aJsonObject* ack = aJson.getObjectItem(jsonObject, "ack");
            if(strcmp(ack->valuestring,"newboard")==0){
//            if(s.equals("{\"ack\":\"newboard\"}")){
              delete jsonObject;
              delete ack;
              free(&json_char);
              free(&s);
              boardconnected=true;
              server.begin();
            }
//            else
//              Serial.println("PZP refused my req");
            break;

          }
          if(s.equals("\r\n")){
            nextisbody = true;
          }
          s = "";
        }

      }
      client.stop();
    }
    else {
     // Serial.println("PZP unavailable");
      delay(2000);
    }
  }
  else{ // boardisconnected == true
    EthernetClient client = server.available();
    if (client) {
      // an http request ends with a blank line
      boolean currentLineIsBlank = true;
      char cmd[4];
      char pin[4];
      char dat[30];
      int counter=1;
      int i=0,j=0,z=0;
      bool finish = false;

      while (client.connected()) {
        if (client.available()) {
          char c = client.read();
          // GET /?cmd=get&pin=012&dat=.....\n
          if(counter>10 && counter<14)
            cmd[i++] = c;
          if(counter>18 && counter<22)
            pin[j++] = c;
          if(counter > 26){
            dat[z++] = c;
            if(c == '\ ')
              finish=true;
          }
          if(finish){
            cmd[i] = '\0';
            pin[j] = '\0';
            dat[z-1] = '\0';

            Serial.println(cmd);
            Serial.println(pin);
            Serial.println(dat);
            client.println("HTTP/1.1 200 OK");
            client.println("Content-Type: application/json");
            client.println("Connnection: keep-alive");
            client.println();

            if(strcmp(cmd,"ele")==0){
              client.println(ELEMENTS_RES);
            }
            else if(strcmp(cmd,"get")==0){
              int ipin = atoi(pin);
              int value = analogRead(ipin);
              client.print("{\"cmd\":\"get\",\"eid\":\"");
              client.print(BOARD_ID);
              client.print("_");
              client.print(ipin);
              client.print("\",\"dat\":\"");
              client.print(value);
              client.println("\"}");
            }
            else if(strcmp(cmd,"str")==0 || strcmp(cmd,"stp")==0){

              Serial.print(pin);
              Serial.print(" mode : ");
              Serial.println(dat);

              int len = strlen(BOARD_ID) + 1 + strlen(pin);  // BOARD_ID + _ + pin
              Serial.println(len);

              char eid[len+1];
              strcpy(eid,BOARD_ID);
              strcat(eid,"_");
              strcat(eid,pin);
              strcat(eid,'\0');
//              Serial.println(eid);

              if(strcmp(cmd,"str")==0){
                client.print("{\"cmd\":\"str\",");
                client.print("\"id\":\"");
                client.print(eid);
                client.println("\"}");
                Serial.print("starting sensor ");
                Serial.println(eid);

                for(int i=0; i<NUM_ELEMENTS; i++){
                  if(strcmp(elements[i]->id, eid) == 0)
                    elements[i]->active = true;
                }
              }
              else{ //if(strcmp(cmd,"stp")==0){
                client.println("{\"cmd\":\"stp\"}");
                Serial.println("stopping sensor ");
                for(int i=0; i<NUM_ELEMENTS; i++){
                  if(strcmp(elements[i]->id, eid) == 0)
                    elements[i]->active = false;
                }
              }
            }
            break;
          }
          counter++;
        }
      }
      // give the web browser time to receive the data
      delay(1);
      client.stop();
    }

    for(int i=0; i<NUM_ELEMENTS; i++){
      if(elements[i]->active && (millis() - elements[i]->lastConnectionTime > elements[i]->rate)){
        sendDataToAPI(i);
      }
    }

//    for(int i=0; i<NUM_ELEMENTS; i++){
//      if(elements[i]->active && ( time*mindelay % elements[i]->rate == 0) ){
//        Serial.print("Read from sensor ");
//        Serial.println(elements[i]->id);
//        if (client.connect(pzp_ip, PZP_PORT)) {
//          client.print("POST /sensor?id=");
//          client.print(elements[i]->id);
//          client.print("&data=");
//          client.print(getValueFromSensor(elements[i]->ad, elements[i]->pin));
//          client.println("\0 HTTP/1.0");
//          client.println();
//          client.stop();
//        }
//      }
//    }
//    time++;
//    delay(mindelay);

  }
}

error: pathspec 'webinos/platform/arduino/api/sensors_actuators_driver/sensors_actuators_driver.ino' did not match any file(s) known to git


Add bluetooth

Add bluetooth

/bin/sh: 1: Syntax error: "(" unexpected


Added failure tone and matched timing of opening tone to original game.

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/tonyczeh/arduino-repeat.git/'


Some stray calls to ipToString.

Some stray calls to ipToString.

/*
 * 2016-11-26 dvb
 * Work on OmServer, so that its messages tend to
 * help a new user bootstrap to it.
 */
#include "Arduino.h"
#include "OmBlinker.h"
#include "OmWebServer.h"
#include <OmEspHelpers.h>

// These includes arent used in this file, but tells Arduino IDE that this project uses them.
#include <ESP8266WebServer.h>
#include <ESP8266WiFi.h>

OmBlinker ob(-1);
OmWebServer w;
OmWebPages p;

void setup()
{
  Serial.begin(115200);
  Serial.printf("\n\n\nWelcome to the Sketch\n\n");

  ob.addNumber(1234);

  w.addWifi("noope", "haha");
  w.addWifi("omino warp", "0123456789");

  w.setHandler(p);
}

int ticks = 0;
void loop()
{
  delay(10);
  ob.tick();
  w.tick();

  ticks++;
  if(ticks % 1000 == 0)
  {
    ob.addInterjection(10, 2);
  }
}

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


Improved Style

Improved Style

Improved Code Layout impending a rewrite.

/*
 *   Copyright (c) 2014 Matthias Frick, All rights reserved.
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *   See the GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *   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.
 */

#include <BLE_API.h>
#include <pins_arduino.h>
#include <SPI.h>
#include <Usb.h>
#include <usbh_midi.h>
#define __CORE_CM0_H_GENERIC
#define BLE_UUID_TXRX_SERVICE            0x0000 /**< The UUID of the Nordic UART Service. */
#define BLE_UUID_TX_CHARACTERISTIC       0x0001 /**< The UUID of the TX Characteristic. */
#define BLE_UUID_RX_CHARACTERISTIC      0x0002 /**< The UUID of the RX Characteristic. */

#define TXRX_BUF_LEN                     100
#define UART_RX_TIME                     APP_TIMER_TICKS(10, 0)

#define STATUS_CHECK_TIME                APP_TIMER_TICKS(20, 0)

// Activate to debug
// this increases delay significantly due to increased I/Os
#define DEBUG 1

#ifdef DEBUG
#define DEBUG_PRINT(x)     Serial.print (x)
#define DEBUG_PRINTDEC(x)     Serial.print (x, DEC)
#define DEBUG_PRINTHEX(x)     Serial.print (x, HEX)
#define DEBUG_PRINTLN(x)  Serial.println (x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTDEC(x)
#define DEBUG_PRINTHEX(x)
#define DEBUG_PRINTLN(x)
#endif

BLEDevice  ble;

static app_timer_id_t                    m_uart_rx_id;
static app_timer_id_t                    m_status_check_id;
static uint8_t rx_buf[TXRX_BUF_LEN];
static int rx_buf_num, rx_state = 0;
static uint8_t rx_temp_buf[20];

// TXRX Service & UDIDs
static const uint8_t uart_base_uuid[] = {0x03, 0xB8, 0x0E, 0x5A, 0xED, 0xE8, 0x4B, 0x33, 0xA7, 0x51, 0x6C, 0xE3, 0x4E, 0xC4, 0xC7, 0};
static const uint8_t uart_tx_uuid[]   = {0x77, 0x72, 0xE5, 0xDB, 0x38, 0x68, 0x41, 0x12, 0xA1, 0xA9, 0xF2, 0x66, 0x9D, 0x10, 0x6B, 0xF3};
static const uint8_t uart_rx_uuid[]   = {0x77, 0x72, 0xE5, 0xDB, 0x38, 0x68, 0x41, 0x12, 0xA1, 0xA9, 0xF2, 0x66, 0x9D, 0x10, 0x6B, 0xF3};
static const uint8_t uart_base_uuid_rev[] = {0, 0xC7, 0xC4, 0x4E, 0xE3, 0x6C, 0x51, 0xA7, 0x33, 0x4B, 0xE8, 0xED, 0x5A, 0x0E, 0xB8, 0x03};

uint8_t txPayload[TXRX_BUF_LEN] = {0,};
uint8_t rxPayload[TXRX_BUF_LEN] = {0,};

GattCharacteristic  txCharacteristic (uart_tx_uuid, txPayload, 1, 20,
                                     GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ);

GattCharacteristic *uartChars[] = {&txCharacteristic};
GattService         uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));

/*******************************************************************************
 * INITIALIZE USB MIDI Variables
 *******************************************************************************/
USB  Usb;
USBH_MIDI  Midi(&Usb);
uint8_t usbstate;
uint8_t laststate;
uint8_t rcode;
USB_DEVICE_DESCRIPTOR buf;

void MIDI_poll();
void doDelay(unsigned long t1, unsigned long t2, unsigned long delayTime);

boolean bFirst;
boolean isConnected;
uint16_t pid, vid;

/*******************************************************************************
* INITIALIZE Internal BLE Buffer
*******************************************************************************/
#define MAX_TX_BUFF 64
static uint8_t midiOut_buff[MAX_TX_BUFF];
static uint8_t midiOut_buff_len = 0;

/*******************************************************************************
* Send MIDI data to BLE Stack
*
* BLE Packet is capped to 17 bytes (2 bytes prefix + 3 bytes MIDI + 3 * 4 bytes)
*
* Right now this is periodically called by the app_timer, to make sure the buffer clears
* out fast enough as calling this through MIDI_poll() caused more delay.
* TO DO: Use MIDI Structs instead of byte array
*
*******************************************************************************/
void m_uart_rx_handle(void * p_context)
{
if(rx_buf_num > 0 && isConnected)
{
	 int bufInc = 0;

	 // with every ticker-call to this function we take 17 bytes off the buffer and send it out to BLE
	 if (rx_buf_num < 17)
	 {
	    bufInc = rx_buf_num % 17;
	 }
	 else
	 {
		 bufInc = 17;
	 }
	  ble.updateCharacteristicValue(txCharacteristic.getHandle(), rx_buf, bufInc);
	  memmove(rx_buf, rx_buf+bufInc, rx_buf_num-bufInc); // probably not best practice, needs to be fixed
	  rx_buf_num -= bufInc;
	  rx_state = 0;
}
}

/*******************************************************************************
* Connection callback
*
*  TO DO:
* - Probably doesnt need Serial.Read() here since we dont do any reading
*
/******************************************************************************/
void uartCallBack(void)
{
  uint32_t err_code = NRF_SUCCESS;

  if (rx_state == 0)
  {
    rx_state = 1;
    err_code = app_timer_start(m_uart_rx_id, UART_RX_TIME, NULL);
    APP_ERROR_CHECK(err_code);
    rx_buf_num = 0;
  }
  while ( Serial.available() )
  {
    rx_buf[rx_buf_num] = Serial.read();
    rx_buf_num++;
  }
}

void m_status_check_handle(void * p_context)
{

  Usb.Task();
  usbstate = Usb.getUsbTaskState();

  if (usbstate != laststate)
	{
    laststate = usbstate;

    switch (usbstate) {
      case ( USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE):
        E_Notify(PSTR("\r\nWaiting for device..."), 0x80);
        break;
      case ( USB_ATTACHED_SUBSTATE_RESET_DEVICE):
        E_Notify(PSTR("\r\nDevice connected. Resetting..."), 0x80);
        break;
      case ( USB_ATTACHED_SUBSTATE_WAIT_SOF):
        E_Notify(PSTR("\r\nReset complete. Waiting for the first SOF..."), 0x80);
        break;
      case ( USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE):
        E_Notify(PSTR("\r\nSOF generation started. Enumerating device..."), 0x80);
        break;
      case ( USB_STATE_ADDRESSING):
        E_Notify(PSTR("\r\nSetting device address..."), 0x80);
        break;
      case ( USB_STATE_RUNNING):
        E_Notify(PSTR("\r\nGetting device descriptor"), 0x80);
        rcode = Usb.getDevDescr(1, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*) & buf);

        if (rcode)
				{
          E_Notify(PSTR("\r\nError reading device descriptor. Error code "), 0x80);
        }
        else
				{
          E_Notify(PSTR("\r\nDescriptor Length:\t"), 0x80);
          print_hex(buf.bLength, 8);
          E_Notify(PSTR("\r\nDescriptor type:\t"), 0x80);
          print_hex(buf.bDescriptorType, 8);
          E_Notify(PSTR("\r\nUSB version:\t\t"), 0x80);
          print_hex(buf.bcdUSB, 16);
          E_Notify(PSTR("\r\nDevice class:\t\t"), 0x80);
          print_hex(buf.bDeviceClass, 8);
          E_Notify(PSTR("\r\nDevice Subclass:\t"), 0x80);
          print_hex(buf.bDeviceSubClass, 8);
          E_Notify(PSTR("\r\nDevice Protocol:\t"), 0x80);
          print_hex(buf.bDeviceProtocol, 8);
          E_Notify(PSTR("\r\nMax.packet size:\t"), 0x80);
          print_hex(buf.bMaxPacketSize0, 8);
          E_Notify(PSTR("\r\nVendor  ID:\t\t"), 0x80);
          print_hex(buf.idVendor, 16);
          E_Notify(PSTR("\r\nProduct ID:\t\t"), 0x80);
          print_hex(buf.idProduct, 16);
          E_Notify(PSTR("\r\nRevision ID:\t\t"), 0x80);
          print_hex(buf.bcdDevice, 16);
          E_Notify(PSTR("\r\nMfg.string index:\t"), 0x80);
          print_hex(buf.iManufacturer, 8);
          E_Notify(PSTR("\r\nProd.string index:\t"), 0x80);
          print_hex(buf.iProduct, 8);
          E_Notify(PSTR("\r\nSerial number index:\t"), 0x80);
          print_hex(buf.iSerialNumber, 8);
          E_Notify(PSTR("\r\nNumber of conf.:\t"), 0x80);
          print_hex(buf.bNumConfigurations, 8);

        }
        break;
      case ( USB_STATE_ERROR):
        E_Notify(PSTR("\r\nUSB state machine reached error state"), 0x80);
        break;

      default:
        break;
    }//switch( usbstate...
  }

  if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
  {
		MIDI_poll();
  }

}

// Disconnect Callback
void disconnectionCallback(void)
{
  Serial.println("Disconnected! \r\n");
  Serial.println("Restarting the advertising process \r\n");
  isConnected = false;
  ble.startAdvertising();
}

void connectionCallback(void)
{
 	isConnected = true;
 	uint32_t err_code = NRF_SUCCESS;
  err_code = app_timer_create(&m_uart_rx_id, APP_TIMER_MODE_REPEATED, m_uart_rx_handle);
  APP_ERROR_CHECK(err_code);

  err_code = app_timer_start(m_uart_rx_id, STATUS_CHECK_TIME, NULL);
  APP_ERROR_CHECK(err_code);
}

/*******************************************************************************
* Callback for INCOMING MIDI BLE Data
*
*
*******************************************************************************/

void onDataWritten(uint16_t charHandle)
{
  uint8_t buf[TXRX_BUF_LEN];
  uint16_t bytesRead;
	Serial.println("Something");
  if ( charHandle == txCharacteristic.getHandle() )
  {
    ble.readCharacteristicValue(txCharacteristic.getHandle(), buf, &bytesRead);
    parseBLEtoMIDI(buf, bytesRead);
  }
}

void setup(void)
{
  bFirst = true;
  vid = pid = 0;
  isConnected = false;
  uint32_t err_code = NRF_SUCCESS;
  uart_callback_t uart_cb;
  Serial.begin(9600);

  //Workaround for non UHS2.0 Shield
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  DEBUG_PRINTLN("BLE Arduino Slave");
  Usb.Init();
  delay(500);
  Serial.begin(9600);

  ble.init();
  ble.onDisconnection(disconnectionCallback);
  ble.onConnection(connectionCallback);
  ble.onDataWritten(onDataWritten);

  /* setup advertising */
  ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
  ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
  ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *)"BLIDIno", sizeof("BLIDIno") - 1);
  ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid));

  /* 100ms; in multiples of 0.625ms. */
  ble.setAdvertisingInterval(160);

  ble.addService(uartService);
  SPI.begin();
  //Set Dev_Name
  err_code = RBL_SetDevName("BLIDino");
  APP_ERROR_CHECK(err_code);

  ble.startAdvertising();
 // err_code = app_timer_create(&m_uart_rx_id, APP_TIMER_MODE_SINGLE_SHOT, m_uart_rx_handle);

  err_code = app_timer_create(&m_status_check_id, APP_TIMER_MODE_REPEATED, m_status_check_handle);
  APP_ERROR_CHECK(err_code);

  err_code = app_timer_start(m_status_check_id, STATUS_CHECK_TIME, NULL);
  APP_ERROR_CHECK(err_code);

}

void loop(void)
{
  ble.waitForEvent();
}

/*******************************************************************************
 * Poll MIDI DATA from USB Port
 *******************************************************************************/
void MIDI_poll()
{

  uint8_t bufMidi[64];
  uint16_t  rcvd;
  uint8_t size;
  byte outBuf[ 3 ];
  char buf[20];

  if (Midi.vid != vid || Midi.pid != pid) {
    vid = Midi.vid;
    pid = Midi.pid;
  }

  do {
    if ( (size = Midi.RecvData(outBuf)) > 0 ) {
      // Send data to parser
     parseMIDItoAppleBle(size, outBuf);

    }
  } while (size > 0);

 uint32_t err_code = NRF_SUCCESS;

}

/*******************************************************************************
 * Convert MIDI BLE to MIDI USB
 *
 * Pleas check the experimental branch for MIDI BLE to MIDI USB
 *
 *******************************************************************************/
void parseBLEtoMIDI(uint8_t *dataptr, uint16_t bytesRead)
{
  // stubbed out

}

/*******************************************************************************
 * Convert MIDI Data to MIDI-BLE Packets
 *
 * TO DO:
 * - Jitter / Time Coding is not yet implemented
 * - 1 Byte between MIDI Packet is time-offset currently ignored
 * - Move this to proper MIDI Parsing (e.g. SysEx)
 *
 *******************************************************************************/
void parseMIDItoAppleBle(int size, byte outBuf[3]) {
  char time[2];
  char buf[20];

  unsigned long timer = 0;
  int lastPos;
  timer = millis();

  uint16_t blueMidiTime = 0;
  blueMidiTime = 32768 + (timer % 16383);

  uint32_t err_code = NRF_SUCCESS;
  int localBufNum = rx_buf_num;

  if(rx_buf_num <= 100) // buffer up to 100 bytes
  {
      if (rx_buf_num % 17 == 0) // End of packet, start a new one
      {
        rx_buf[rx_buf_num] = blueMidiTime >> 8;
        rx_buf_num++;
        rx_buf[rx_buf_num] = 0x80;
        rx_buf_num++;
      }
      else
      {
        rx_buf[rx_buf_num] = 0x80;
        rx_buf_num++;
      }

      for (int i = 0; i < size; i++)
      {
        rx_buf[rx_buf_num] = outBuf[i];
        rx_buf_num++;
      }
  }
}

/*******************************************************************************
 * Convert USB Host debug info to Hex
 *
 *******************************************************************************/
void print_hex(int v, int num_places) {
  int mask = 0, n, num_nibbles, digit;

  for (n = 1; n <= num_places; n++) {
    mask = (mask << 1) | 0x0001;
  }
  v = v & mask; // truncate v to specified number of places

  num_nibbles = num_places / 4;
  if ((num_places % 4) != 0) {
    ++num_nibbles;
  }
  do {
    digit = ((v >> (num_nibbles - 1) * 4)) & 0x0f;
    DEBUG_PRINTHEX(digit);
  }
  while (--num_nibbles);
}

/*
 *   Copyright (c) 2014 Matthias Frick, All rights reserved.
 *
 *   This library is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU Lesser General Public
 *   License as published by the Free Software Foundation; either
 *   version 2.1 of the License, or (at your option) any later version.
 *
 *   This library is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 *   See the GNU Lesser General Public License for more details.
 *
 *   You should have received a copy of the GNU Lesser General Public
 *   License along with this library; if not, write to the Free Software
 *   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *   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.
 */

#include <BLE_API.h>
#include <pins_arduino.h>
#include <SPI.h>
#include <Usb.h>
#include <usbh_midi.h>
#define __CORE_CM0_H_GENERIC
#define BLE_UUID_TXRX_SERVICE            0x0000 /**< The UUID of the Nordic UART Service. */
#define BLE_UUID_TX_CHARACTERISTIC       0x0001 /**< The UUID of the TX Characteristic. */
#define BLE_UUID_RX_CHARACTERISTIC      0x0002 /**< The UUID of the RX Characteristic. */

#define TXRX_BUF_LEN                     100
#define UART_RX_TIME                     APP_TIMER_TICKS(10, 0)

#define STATUS_CHECK_TIME                APP_TIMER_TICKS(20, 0)

// Activate to debug
// this increases delay significantly due to increased I/Os
#define DEBUG 1

#ifdef DEBUG
#define DEBUG_PRINT(x)     Serial.print (x)
#define DEBUG_PRINTDEC(x)     Serial.print (x, DEC)
#define DEBUG_PRINTHEX(x)     Serial.print (x, HEX)
#define DEBUG_PRINTLN(x)  Serial.println (x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTDEC(x)
#define DEBUG_PRINTHEX(x)
#define DEBUG_PRINTLN(x)
#endif

BLEDevice  ble;

static app_timer_id_t                    m_uart_rx_id;
static app_timer_id_t                    m_status_check_id;
static uint8_t rx_buf[TXRX_BUF_LEN];
static int rx_buf_num, rx_state = 0;
static uint8_t rx_temp_buf[20];

// TXRX Service & UDIDs
static const uint8_t uart_base_uuid[] = {0x03, 0xB8, 0x0E, 0x5A, 0xED, 0xE8, 0x4B, 0x33, 0xA7, 0x51, 0x6C, 0xE3, 0x4E, 0xC4, 0xC7, 0};
static const uint8_t uart_tx_uuid[]   = {0x77, 0x72, 0xE5, 0xDB, 0x38, 0x68, 0x41, 0x12, 0xA1, 0xA9, 0xF2, 0x66, 0x9D, 0x10, 0x6B, 0xF3};
static const uint8_t uart_rx_uuid[]   = {0x77, 0x72, 0xE5, 0xDB, 0x38, 0x68, 0x41, 0x12, 0xA1, 0xA9, 0xF2, 0x66, 0x9D, 0x10, 0x6B, 0xF3};
static const uint8_t uart_base_uuid_rev[] = {0, 0xC7, 0xC4, 0x4E, 0xE3, 0x6C, 0x51, 0xA7, 0x33, 0x4B, 0xE8, 0xED, 0x5A, 0x0E, 0xB8, 0x03};

uint8_t txPayload[TXRX_BUF_LEN] = {0,};
uint8_t rxPayload[TXRX_BUF_LEN] = {0,};

GattCharacteristic  txCharacteristic (uart_tx_uuid, txPayload, 1, 20,
                                     GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ);

GattCharacteristic *uartChars[] = {&txCharacteristic};
GattService         uartService(uart_base_uuid, uartChars, sizeof(uartChars) / sizeof(GattCharacteristic *));

/*******************************************************************************
 * INITIALIZE USB MIDI Variables
 *******************************************************************************/
USB  Usb;
USBH_MIDI  Midi(&Usb);
uint8_t usbstate;
uint8_t laststate;
uint8_t rcode;
//uint8_t buf[sizeof(USB_DEVICE_DESCRIPTOR)];
USB_DEVICE_DESCRIPTOR buf;

void MIDI_poll();
void doDelay(unsigned long t1, unsigned long t2, unsigned long delayTime);

boolean bFirst;
boolean isConnected;
uint16_t pid, vid;

/*******************************************************************************
* INITIALIZE Internal BLE Buffer
*******************************************************************************/
#define MAX_TX_BUFF 64
static uint8_t midiOut_buff[MAX_TX_BUFF];
static uint8_t midiOut_buff_len = 0;

/*******************************************************************************
* Send MIDI data to BLE Stack
*
* BLE Packet is capped to 17 bytes (2 bytes prefix + 3 bytes MIDI + 3 * 4 bytes)
*
* Right now this is periodically called by the app_timer, to make sure the buffer clears
* out fast enough as calling this through MIDI_poll() caused more delay.
* TO DO: Use MIDI Structs instead of byte array
*
*******************************************************************************/
void m_uart_rx_handle(void * p_context)
{
  if(rx_buf_num > 0 && isConnected) {
 int bufInc = 0;

 // with every ticker-call to this function we take 17 bytes off the buffer and send it out to BLE
 if (rx_buf_num < 17) {
    bufInc = rx_buf_num % 17;
  }
 else {
    bufInc = 17;
 }
  ble.updateCharacteristicValue(txCharacteristic.getHandle(), rx_buf, bufInc);
  memmove(rx_buf, rx_buf+bufInc, rx_buf_num-bufInc); // probably not best practice, needs to be fixed
  rx_buf_num -= bufInc;
  rx_state = 0;
  }
}

/*******************************************************************************
* Connection callback
*
*  TO DO:
* - Probably doesnt need Serial.Read() here since we dont do any reading
*
/******************************************************************************/
void uartCallBack(void)
{
  uint32_t err_code = NRF_SUCCESS;

  if (rx_state == 0)
  {
    rx_state = 1;
    err_code = app_timer_start(m_uart_rx_id, UART_RX_TIME, NULL);
    APP_ERROR_CHECK(err_code);
    rx_buf_num = 0;
  }
  while ( Serial.available() )
  {
    rx_buf[rx_buf_num] = Serial.read();
    rx_buf_num++;
  }
}

void m_status_check_handle(void * p_context)
{

  Usb.Task();
  usbstate = Usb.getUsbTaskState();

  if (usbstate != laststate) {
    laststate = usbstate;

    switch (usbstate) {
      case ( USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE):
        E_Notify(PSTR("\r\nWaiting for device..."), 0x80);
        break;
      case ( USB_ATTACHED_SUBSTATE_RESET_DEVICE):
        E_Notify(PSTR("\r\nDevice connected. Resetting..."), 0x80);
        break;
      case ( USB_ATTACHED_SUBSTATE_WAIT_SOF):
        E_Notify(PSTR("\r\nReset complete. Waiting for the first SOF..."), 0x80);
        break;
      case ( USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE):
        E_Notify(PSTR("\r\nSOF generation started. Enumerating device..."), 0x80);
        break;
      case ( USB_STATE_ADDRESSING):
        E_Notify(PSTR("\r\nSetting device address..."), 0x80);
        break;
      case ( USB_STATE_RUNNING):
        E_Notify(PSTR("\r\nGetting device descriptor"), 0x80);
        rcode = Usb.getDevDescr(1, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*) & buf);

        if (rcode) {
          E_Notify(PSTR("\r\nError reading device descriptor. Error code "), 0x80);
          // print_hex(rcode, 8);
        }
        else {

          E_Notify(PSTR("\r\nDescriptor Length:\t"), 0x80);
          print_hex(buf.bLength, 8);
          E_Notify(PSTR("\r\nDescriptor type:\t"), 0x80);
          print_hex(buf.bDescriptorType, 8);
          E_Notify(PSTR("\r\nUSB version:\t\t"), 0x80);
          print_hex(buf.bcdUSB, 16);
          E_Notify(PSTR("\r\nDevice class:\t\t"), 0x80);
          print_hex(buf.bDeviceClass, 8);
          E_Notify(PSTR("\r\nDevice Subclass:\t"), 0x80);
          print_hex(buf.bDeviceSubClass, 8);
          E_Notify(PSTR("\r\nDevice Protocol:\t"), 0x80);
          print_hex(buf.bDeviceProtocol, 8);
          E_Notify(PSTR("\r\nMax.packet size:\t"), 0x80);
          print_hex(buf.bMaxPacketSize0, 8);
          E_Notify(PSTR("\r\nVendor  ID:\t\t"), 0x80);
          print_hex(buf.idVendor, 16);
          E_Notify(PSTR("\r\nProduct ID:\t\t"), 0x80);
          print_hex(buf.idProduct, 16);
          E_Notify(PSTR("\r\nRevision ID:\t\t"), 0x80);
          print_hex(buf.bcdDevice, 16);
          E_Notify(PSTR("\r\nMfg.string index:\t"), 0x80);
          print_hex(buf.iManufacturer, 8);
          E_Notify(PSTR("\r\nProd.string index:\t"), 0x80);
          print_hex(buf.iProduct, 8);
          E_Notify(PSTR("\r\nSerial number index:\t"), 0x80);
          print_hex(buf.iSerialNumber, 8);
          E_Notify(PSTR("\r\nNumber of conf.:\t"), 0x80);
          print_hex(buf.bNumConfigurations, 8);

        }
        break;
      case ( USB_STATE_ERROR):
        E_Notify(PSTR("\r\nUSB state machine reached error state"), 0x80);
        break;

      default:
        break;
    }//switch( usbstate...
  }

  if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
  {

    MIDI_poll();
  }

}

// Disconnect Callback
void disconnectionCallback(void)
{
  Serial.println("Disconnected! \r\n");
  Serial.println("Restarting the advertising process \r\n");
  isConnected = false;
  ble.startAdvertising();
}

void connectionCallback(void) {
 isConnected = true;
 uint32_t err_code = NRF_SUCCESS;
  err_code = app_timer_create(&m_uart_rx_id, APP_TIMER_MODE_REPEATED, m_uart_rx_handle);
  APP_ERROR_CHECK(err_code);

  err_code = app_timer_start(m_uart_rx_id, STATUS_CHECK_TIME, NULL);
  APP_ERROR_CHECK(err_code);

}

/*******************************************************************************
* Callback for INCOMING MIDI BLE Data
*
*
*******************************************************************************/

void onDataWritten(uint16_t charHandle)
{
  uint8_t buf[TXRX_BUF_LEN];
  uint16_t bytesRead;
 Serial.println("Something");

  if ( charHandle == txCharacteristic.getHandle() )
  {
    ble.readCharacteristicValue(txCharacteristic.getHandle(), buf, &bytesRead);
    parseBLEtoMIDI(buf, bytesRead);
  }
}

void setup(void)
{
  bFirst = true;
  vid = pid = 0;
  isConnected = false;
  uint32_t err_code = NRF_SUCCESS;
  uart_callback_t uart_cb;
  Serial.begin(9600);
  // while (!Serial); // activate to wait for attached serial

  //Workaround for non UHS2.0 Shield
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);

  DEBUG_PRINTLN("BLE Arduino Slave");
  Usb.Init();
  delay(500);
  Serial.begin(9600);

  ble.init();
  ble.onDisconnection(disconnectionCallback);
  ble.onConnection(connectionCallback);
  ble.onDataWritten(onDataWritten);

  /* setup advertising */
  ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED);
  ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
  ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *)"BLIDIno", sizeof("BLIDIno") - 1);
  ble.accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (const uint8_t *)uart_base_uuid_rev, sizeof(uart_base_uuid));

  /* 100ms; in multiples of 0.625ms. */
  ble.setAdvertisingInterval(160);

  ble.addService(uartService);
  SPI.begin();
  //Set Dev_Name
  err_code = RBL_SetDevName("BLIDino");
  APP_ERROR_CHECK(err_code);

  ble.startAdvertising();
 // err_code = app_timer_create(&m_uart_rx_id, APP_TIMER_MODE_SINGLE_SHOT, m_uart_rx_handle);

  err_code = app_timer_create(&m_status_check_id, APP_TIMER_MODE_REPEATED, m_status_check_handle);
  APP_ERROR_CHECK(err_code);

  err_code = app_timer_start(m_status_check_id, STATUS_CHECK_TIME, NULL);
  APP_ERROR_CHECK(err_code);

}

void loop(void)
{
  ble.waitForEvent();
}

/*******************************************************************************
 * Poll MIDI DATA from USB Port
 *******************************************************************************/
void MIDI_poll()
{

  uint8_t bufMidi[64];
  uint16_t  rcvd;
  uint8_t size;
  byte outBuf[ 3 ];
  char buf[20];

  if (Midi.vid != vid || Midi.pid != pid) {
    vid = Midi.vid;
    pid = Midi.pid;
  }

  do {
    if ( (size = Midi.RecvData(outBuf)) > 0 ) {
      // Send data to parser
     parseMIDItoAppleBle(size, outBuf);

    }
  } while (size > 0);

 uint32_t err_code = NRF_SUCCESS;

}

/*******************************************************************************
 * Convert MIDI BLE to MIDI USB
 *
 * Pleas check the experimental branch for MIDI BLE to MIDI USB
 *
 *******************************************************************************/
void parseBLEtoMIDI(uint8_t *dataptr, uint16_t bytesRead)
{
  // stubbed out

}

/*******************************************************************************
 * Convert MIDI Data to MIDI-BLE Packets
 *
 * TO DO:
 * - Jitter / Time Coding is not yet implemented
 * - 1 Byte between MIDI Packet is time-offset currently ignored
 * - Move this to proper MIDI Parsing (e.g. SysEx)
 *
 *******************************************************************************/
void parseMIDItoAppleBle(int size, byte outBuf[3]) {
  char time[2];
  char buf[20];

  unsigned long timer = 0;
  int lastPos;
  timer = millis();

  uint16_t blueMidiTime = 0;
  blueMidiTime = 32768 + (timer % 16383);

  uint32_t err_code = NRF_SUCCESS;
  int localBufNum = rx_buf_num;

  if(rx_buf_num <= 100) // buffer up to 100 bytes
  {
      if (rx_buf_num % 17 == 0) // End of packet, start a new one
      {
        rx_buf[rx_buf_num] = blueMidiTime >> 8;
        rx_buf_num++;
        rx_buf[rx_buf_num] = 0x80;
        rx_buf_num++;
      }
      else
      {
        rx_buf[rx_buf_num] = 0x80;
        rx_buf_num++;
      }

      for (int i = 0; i < size; i++)
      {
        rx_buf[rx_buf_num] = outBuf[i];
        rx_buf_num++;
      }
  }
}

/*******************************************************************************
 * Convert USB Host debug info to Hex
 *
 *******************************************************************************/
void print_hex(int v, int num_places) {
  int mask = 0, n, num_nibbles, digit;

  for (n = 1; n <= num_places; n++) {
    mask = (mask << 1) | 0x0001;
  }
  v = v & mask; // truncate v to specified number of places

  num_nibbles = num_places / 4;
  if ((num_places % 4) != 0) {
    ++num_nibbles;
  }
  do {
    digit = ((v >> (num_nibbles - 1) * 4)) & 0x0f;
    DEBUG_PRINTHEX(digit);
  }
  while (--num_nibbles);
}


Fixed credentials  : UNDO RESET: on sample

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/TheBeachMaster/AfricasTalkingIOT.git/'


add PushButtonNode as SerialApi example

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/electronicplayground/ep-arduino.git/'


hmm letting the queue run dry is not htat hard …

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/trinamic/T-Bone.git/'


Added encoders support

Added encoders support

#include <Servo.h>
#include <AStar32U4.h>
#include <PololuRPiSlave.h>
#include <FastGPIO.h>

/* This example program shows how to make the A-Star 32U4 Robot
 * Controller into a Raspberry Pi I2C slave.  The RPi and A-Star can
 * exchange data bidirectionally, allowing each device to do what it
 * does best: high-level programming can be handled in a language such
 * as Python on the RPi, while the A-Star takes charge of motor
 * control, analog inputs, and other low-level I/O.
 *
 * The example and libraries are available for download at:
 *
 * https://github.com/pololu/pololu-rpi-slave-arduino-library
 *
 * You will need the corresponding Raspberry Pi code, which is
 * available in that repository under the pi/ subfolder.  The Pi code
 * sets up a simple Python-based web application as a control panel
 * for your Raspberry Pi robot.
 */

// Custom data structure that we will use for interpreting the buffer.
// We recommend keeping this under 64 bytes total.  If you change the
// data format, make sure to update the corresponding code in
// a_star.py on the Raspberry Pi.

struct Data
{
  bool yellow, green, red;
  bool buttonA, buttonB, buttonC;

  int16_t leftMotor, rightMotor;
  uint16_t batteryMillivolts;
  uint16_t analog[6];

  bool resetEncoders;

  int16_t encoderLCount, encoderRCount;

  bool playNotes;
  char notes[14];
};

PololuRPiSlave<struct Data,0> slave;
PololuBuzzer buzzer;
AStar32U4Motors motors;
AStar32U4ButtonA buttonA;
AStar32U4ButtonB buttonB;
AStar32U4ButtonC buttonC;

// Encoders variables
const byte encoderLeftPin = 8;
const byte encoderRightPin = 7;
volatile uint16_t encoderLeftCount;
volatile uint16_t encoderRightCount;

// ISRs
// ISR for left encoder (PCINT)
ISR(PCINT0_vect)
{
  encoderLeftCount++;
}

// ISR for right encoder (INT)
static void rightISR()
{
  encoderRightCount++;
}

void setup()
{
  // Set up the slave at I2C address 20.
  slave.init(20);

  // Play startup sound.
  buzzer.play("v10>>g16>>>c16");

  // Setup encoders pins and attach ISRs
  FastGPIO::Pin<encoderLeftPin>::setInputPulledUp();
  FastGPIO::Pin<encoderRightPin>::setInputPulledUp();
  PCICR = (1 << PCIE0);
  PCMSK0 = (1 << PCINT4);
  PCIFR = (1 << PCIF0);
  attachInterrupt(digitalPinToInterrupt(encoderRightPin), rightISR, CHANGE);
}

void loop()
{
  // Call updateBuffer() before using the buffer, to get the latest
  // data including recent master writes.
  slave.updateBuffer();

  // Write various values into the data structure.
  slave.buffer.buttonA = buttonA.isPressed();
  slave.buffer.buttonB = buttonB.isPressed();
  slave.buffer.buttonC = buttonC.isPressed();

  // Change this to readBatteryMillivoltsLV() for the LV model.
  slave.buffer.batteryMillivolts = readBatteryMillivoltsSV();

  for(uint8_t i=0; i<6; i++)
  {
    slave.buffer.analog[i] = analogRead(i);
  }

  // Read encoders
  slave.buffer.encoderLCount = encoderLeftCount;
  slave.buffer.encoderRCount = encoderRightCount;
  if (slave.buffer.resetEncoders)
  {
    slave.buffer.resetEncoders = 0;
    encoderLeftCount = 0;
    encoderRightCount = 0;
  }

  // READING the buffer is allowed before or after finishWrites().
  ledYellow(slave.buffer.yellow);
  ledGreen(slave.buffer.green);
  ledRed(slave.buffer.red);
  motors.setSpeeds(slave.buffer.leftMotor, slave.buffer.rightMotor);

  // Playing music involves both reading and writing, since we only
  // want to do it once.
  if(slave.buffer.playNotes)
  {
    buzzer.play(slave.buffer.notes);
    while(buzzer.isPlaying());
    slave.buffer.playNotes = false;
  }

  // When you are done WRITING, call finalizeWrites() to make modified
  // data available to I2C master.
  slave.finalizeWrites();
}

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


uploading arduino code from last semester

/*
 David Spruill, 2014

 This code is designed to control the Bblr Bubble Display made as a capstone final project
 in Duke's ECE 459 Embedded Systems course taught by Dr. John Board.

 This code currently deals with both time keeping, bluetooth phone connections for picture
 reception, and bubble (pixel) compensation planning.
 */

#include <TimerOne.h>
#include <Time.h>

//Image
#define rails 24 // number of rails
#define height 5 // maximum number of bubbles that can fit in the board
#define charHeight 5
#define charWidth 3
#define allowedHeight 100//max allowed height of a schedule

//Timing
#define pixelPitch 330 // distance between the pixels
#define blockPitch 1000 // distance between letters/blocks
#define compensation 10 // compensation time
#define pixelDuration 8
#define initialDelay 3000
#define calibrationBubbleSize 40

boolean PixelDelay[rails] = {
  10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10};

int counterOffset = 0;
byte mode = 0;
boolean currTime = 0;
boolean phoneSetTime = false;

int currRails = 24;
int currRowLimit = 5;

boolean setSchedule = false;
boolean startPrint = false;

boolean schedule[rails][allowedHeight];

unsigned long lastWrite = 0;
int currRow = 0;

// Alphanumeric lib
boolean alphabet[26][3][5] = {
    {{1, 1, 1, 1, 1},{1, 0, 1, 0, 0},{1, 1, 1, 1, 1}},  //A
    {{1, 1, 1, 1, 1},{1, 0, 1, 0, 1},{0, 1, 0, 1, 0}},  //B
    {{0, 1, 1, 1, 0},{1, 0, 0, 0, 1},{1, 0, 0, 0, 1}},  //C
    {{1, 1, 1, 1, 1},{1, 0, 0, 0, 1},{0, 1, 1, 1, 0}},  //D
    {{1, 1, 1, 1, 1},{1, 0, 1, 0, 1},{1, 0, 0, 0, 1}},  //E
    {{1, 1, 1, 1, 1},{1, 0, 1, 0, 0},{1, 0, 0, 0, 0}},  //F
    {{0, 1, 1, 1, 0},{1, 0, 1, 0, 1},{1, 0, 0, 1, 0}},  //G ~ looks funny
    {{1, 1, 1, 1, 1},{0, 0, 1, 0, 0},{1, 1, 1, 1, 1}},  //H
    {{1, 0, 0, 0, 1},{1, 1, 1, 1, 1},{1, 0, 0, 0, 1}},  //I
    {{0, 0, 0, 1, 0},{1, 0, 0, 0, 1},{1, 1, 1, 1, 0}},  //J
    {{1, 1, 1, 1, 1},{0, 1, 0, 1, 0},{1, 0, 0, 0, 1}},  //K
    {{1, 1, 1, 1, 1},{0, 0, 0, 0, 1},{0, 0, 0, 0, 1}},  //L
    {{1, 1, 1, 1, 1},{0, 1, 1, 0, 0},{1, 1, 1, 1, 1}},  //M
    {{1, 1, 1, 1, 1},{0, 1, 1, 1, 0},{1, 1, 1, 1, 1}},  //N
    {{0, 1, 1, 1, 0},{1, 0, 0, 0, 1},{0, 1, 1, 1, 0}},  //O
    {{1, 1, 1, 1, 1},{1, 0, 1, 0, 0},{0, 1, 0, 0, 0}},  //P
    {{0, 1, 1, 1, 0},{1, 0, 0, 1, 1},{0, 1, 1, 1, 1}},  //Q ~ good be better
    {{1, 1, 1, 1, 1},{1, 0, 1, 1, 0},{0, 1, 0, 0, 1}},  //R
    {{0, 1, 0, 0, 1},{1, 0, 1, 0, 1},{1, 0, 0, 1, 0}},  //S
    {{1, 0, 0, 0, 0},{1, 1, 1, 1, 1},{1, 0, 0, 0, 0}},  //T
    {{1, 1, 1, 1, 0},{0, 0, 0, 0, 1},{1, 1, 1, 1, 0}},  //U
    {{1, 1, 1, 0, 0},{0, 0, 0, 1, 1},{1, 1, 1, 0, 0}},  //V
    {{1, 1, 1, 1, 1},{0, 0, 0, 1, 0},{1, 1, 1, 1, 1}},  //W
    {{1, 1, 0, 1, 1},{0, 0, 1, 0, 0},{1, 1, 0, 1, 1}},  //X
    {{1, 1, 0, 0, 0},{0, 0, 1, 1, 1},{1, 1, 0, 0, 0}},  //Y
    {{1, 0, 0, 1, 1},{1, 0, 1, 0, 1},{1, 1, 0, 0, 1}}}; //Z

boolean numbers[10][3][5] =  {
    {{0, 1, 1, 1, 0},{1, 0, 0, 0, 1},{0, 1, 1, 1, 0}},  //0
    {{0, 1, 0, 0, 1},{1, 1, 1, 1, 1},{0, 0, 0, 0, 1}},  //1
    {{1, 0, 1, 1, 1},{1, 0, 1, 0, 1},{1, 1, 1, 0, 1}},  //2
    {{1, 0, 0, 0, 1},{1, 0, 1, 0, 1},{1, 1, 1, 1, 1}},  //3
    {{1, 1, 1, 0, 0},{0, 0, 1, 0, 0},{1, 1, 1, 1, 1}},  //4
    {{1, 1, 1, 0, 0},{1, 0, 1, 0, 1},{1, 0, 1, 1, 1}},  //5
    {{1, 1, 1, 1, 1},{1, 0, 1, 0, 1},{1, 0, 1, 1, 1}},  //6
    {{1, 0, 0, 1, 1},{1, 0, 1, 0, 0},{1, 1, 0, 0, 0}},  //7
    {{1, 1, 1, 1, 1},{1, 0, 1, 0, 1},{1, 1, 1, 1, 1}},  //8
    {{1, 1, 1, 0, 0},{1, 0, 1, 0, 0},{1, 1, 1, 1, 1}}}; //9    These last several could use some straightening out

void setup()
{
  pinMode(13,OUTPUT);
  Serial.begin(9600);  // Begin the serial monitor at 9600bps

  Serial1.begin(115200);  // The Bluetooth Mate defaults to 115200bps
  Serial1.print("$");  // Print three times individually
  Serial1.print("$");
  Serial1.print("$");  // Enter command mode
  delay(100);  // Short delay, wait for the Mate to send back CMD

  Serial.println("configuring");
  Serial1.println("U,9600,E");  // Change the baudrate to 9600, even parity
  Serial1.println("---");
  Serial1.end();
  Serial1.begin(9600);  // Start bluetooth serial at 9600

  Timer1.initialize(1000000); // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
  Timer1.attachInterrupt( timerInt ); // attach the service routine here
  setTime(0);
}

void loop()
{
  if(Serial1.available())  // If the bluetooth sent any characters
  {
    // Send any characters the bluetooth prints to the serial monitor
    char currByte = Serial1.read();
    switch(currByte){
    case 0xFE:
      updateTime();
      break;
    case 0xFD:
      getImage();
      break;
    case 0xFC:
      stopDisplay();
      break;
    case 0xFB:
      startClock();
      break;
    case 0xFA:
      getText();
      break;
    }
  }
  if(startPrint){
    //begin printing
    if(millis() - lastWrite > pixelPitch){
      for(int i = 0; i < rails; i++){
        Serial.print(String(schedule[i][currRow],DEC));
         //here we would turn on the solenoids
      }
      Serial.print("\n");
      delay(pixelDuration);
      for(int i =0; i < rails; i++){
         //here we would turn off the solenoids
      }
      lastWrite = millis();
      currRow++;
      if(currRow >= currRowLimit) {
        stopDisplay(); // appropriately stop printing & clear schedule
        currRow = 0;
        Serial.print("\n");
      }
    }
    else {
      for(int i = 0; i < rails; i++){
        //Serial.print("0"); //this else isn't actually needed, just for testing
      }

    }
  }
}

void getText(){

}

void getImage() {
  digitalWrite(13,HIGH);
  char received[10] = {
    0,0,0,0,0,0,0,0,0,0          };
  int receivedCount = Serial1.readBytesUntil(0xA0,received,10);
  if(receivedCount < 2) return;

  int imageRails = received[0];
  if(imageRails > rails) return;

  currRowLimit = received[1];
  Serial.println("rails: "+String(imageRails) + " rows: "+String(currRowLimit));
  char *image = new char[imageRails*currRowLimit+10];
  int pixelsReceived = Serial1.readBytesUntil(0xFF,image,imageRails*currRowLimit);
  Serial.print("Data: ");
  for(int i = 0; i < imageRails*currRowLimit+10; i++){Serial.print(String(image[i],DEC) + " "); if(i%(imageRails)==0)Serial.print("\n");}
  Serial.println();

  int leftSide = (rails - imageRails) / 2;  if(leftSide < 0) leftSide = 0;

  for(int i = 0; i < rails; i++){
    for(int j = 0; j < currRowLimit; j++){
     if(i>=leftSide&&i<(leftSide+imageRails)){
      schedule[i][j] = image[(i-leftSide)+j*(imageRails)-8] == 0x01;
     }
     else schedule[i][j] = 0;
    }
  }
  startPrint = true;
  setSchedule = true;
}

void stopDisplay() { //stop printing and clear the schedule
  startPrint = false;
  for(int i = 0; i < rails; i++){
   for(int j = 0; j < allowedHeight; j++){
    schedule[i][j] = 0;
   }
  }
}

void startClock() {

}

void updateTime(){
  while(Serial1.available() < 5) {
  }
  char received[10] = {
    0,0,0,0,0,0,0,0,0,0          };
  int receivedCount = Serial1.readBytesUntil(0xFF,received,10);
  Serial.println();
  setTime((unsigned char)received[0],(unsigned char)received[1],(unsigned char)received[2],
  (unsigned char)received[3],(unsigned char)received[4],(word)(((unsigned) received[5])<<8) + (word)((unsigned)received[6]));
  phoneSetTime = true;
}

void timerInt()
{
  if(++counterOffset == 30 & !startPrint){
    counterOffset = 0;
    if(phoneSetTime){
      digitalWrite(13,digitalRead(13)^1);
      if(mode == 0){
        if(currTime)  WriteCurrTime();
        if(!currTime) WriteCurrDate();
        currTime = !currTime;
      }
    }
  }
}

void WriteCurrTime(){
  currRowLimit = 5;
  if(rails < 24) return;
  for(int i = 0; i < currRowLimit; i++){
     int currHour = hour();
     char AorP = 'A';
     if(currHour > 12) {currHour-=12; AorP = 'P';}
     schedule[0][i]  = numbers[currHour/10][0][i];
     schedule[1][i]  = numbers[currHour/10][1][i];
     schedule[2][i]  = numbers[currHour/10][2][i];

     schedule[3][i]  = false;

     schedule[4][i]  = numbers[currHour%10][0][i];
     schedule[5][i]  = numbers[currHour%10][1][i];
     schedule[6][i]  = numbers[currHour%10][2][i];

     schedule[7][i]  = (i%2)-1==0 && i>0; //colons

     schedule[8][i]  = numbers[minute()/10][0][i];
     schedule[9][i]  = numbers[minute()/10][1][i];
     schedule[10][i] = numbers[minute()/10][2][i];

     schedule[11][i] = false;

     schedule[12][i] = numbers[minute()%10][0][i];
     schedule[13][i] = numbers[minute()%10][1][i];
     schedule[14][i] = numbers[minute()%10][2][i];

     schedule[15][i] = false;

     schedule[16][i] = alphabet[AorP-65][0][i];
     schedule[17][i] = alphabet[AorP-65][1][i];
     schedule[18][i] = alphabet[AorP-65][2][i];

     schedule[19][i] = false;

     schedule[20][i] = alphabet['M'-65][0][i];
     schedule[21][i] = alphabet['M'-65][1][i];
     schedule[22][i] = alphabet['M'-65][2][i];

     schedule[23][i] = false;
  }
  startPrint = true;
  setSchedule = true;
}
void WriteCurrDate(){
  currRowLimit = 5;
  if(rails < 24) return;
  for(int i = 0; i < currRowLimit; i++){
     schedule[0][i]  = numbers[month()/10][0][i];
     schedule[1][i]  = numbers[month()/10][1][i];
     schedule[2][i]  = numbers[month()/10][2][i];

     schedule[3][i]  = false;

     schedule[4][i]  = numbers[month()%10][0][i];
     schedule[5][i]  = numbers[month()%10][1][i];
     schedule[6][i]  = numbers[month()%10][2][i];

     schedule[7][i]  = false;

     schedule[8][i]  = numbers[day()/10][0][i];
     schedule[9][i]  = numbers[day()/10][1][i];
     schedule[10][i] = numbers[day()/10][2][i];

     schedule[11][i] = false;

     schedule[12][i] = numbers[day()%10][0][i];
     schedule[13][i] = numbers[day()%10][1][i];
     schedule[14][i] = numbers[day()%10][2][i];

     schedule[15][i] = false;

     schedule[16][i] = numbers[(year()%100)/10][0][i];
     schedule[17][i] = numbers[(year()%100)/10][1][i];
     schedule[18][i] = numbers[(year()%100)/10][2][i];

     schedule[19][i] = false;

     schedule[20][i] = numbers[(year()%100)%10][0][i];
     schedule[21][i] = numbers[(year()%100)%10][1][i];
     schedule[22][i] = numbers[(year()%100)%10][2][i];

     schedule[23][i] = false;
  }
  startPrint = true;
  setSchedule = true;
}

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


Optimise data types

Optimise data types

fatal: remote error: upload-pack: not our ref 3b0409b09357730b4c54a4b6dac30ede0f3141bc
fatal: the remote end hung up unexpectedly


Update ProbeCube_pp_099b0224.ino

Update ProbeCube_pp_099b0224.ino

Arduino with cc3000wifi based/Code/ProbeCube_pp_099b0224.ino

error: pathspec 'Arduino' did not match any file(s) known to git
error: pathspec 'with' did not match any file(s) known to git
error: pathspec 'cc3000wifi' did not match any file(s) known to git
error: pathspec 'based/Code/ProbeCube_pp_099b0224.ino' did not match any file(s) known to git


create Thunder Watcher sketch.

create Thunder Watcher sketch.

//AS3935 SCL = A5
//AS3935 SDA = A4
//AS3935 IRQ = D5
//AQM1602 SCL = A5
//AQM1602 SDA = A4
//USE 5V PWR

#include <ST7032.h> // LCD library
#include <Wire.h>
#include <FreqCounter.h>

#define AS3935_ADRS 0x00
#define LCD_ADRS 0x3E

#define AFE_GB  0x1F  // ANALOG FRONT END GAIN BOOST = 12(Indoor) 0x00 to 0x1F
#define NF_LEV  0x02  // NOIS FLOOR LEVEL 0x00 to 0x07
#define WDTH    0x02  // WATCH DOG THRESHOLD 0x00 to 0x0F

ST7032 lcd;

String LCD_STRING;
byte reg0,reg1,reg2,reg3,reg4,reg5,reg6,reg7,reg8,reg3A,reg3B,reg3C,reg3D,regDUMMY;
unsigned long enargy;
unsigned int distance;
long int freq;
long int OLD_BUFFER = 10000;
long int NOW_BUFFER = 0;
int C;
long int F;
byte CAP_RESULT;

// Thunder mark character
byte Lightning[8] = {
	0b00010,
	0b00100,
	0b01100,
	0b11111,
	0b00110,
	0b00100,
	0b01000,
	0b10000
};

void ByteWrite(byte reg, byte data)
{
  Wire.beginTransmission(AS3935_ADRS);
  Wire.write(reg);
  Wire.write(data);
  Wire.endTransmission();
  delay(50);
}

byte ByteRead(byte reg)
{
  byte data = 0;
  Wire.beginTransmission(AS3935_ADRS);
  Wire.write(reg);
  Wire.endTransmission(false);
  Wire.requestFrom(AS3935_ADRS,1);
  data = Wire.read();      // Receive 1 byte
  return data;
}

void resistorRead(void)
{
  Wire.beginTransmission(AS3935_ADRS);
  Wire.write(0);
  Wire.endTransmission(false);
  Wire.requestFrom(AS3935_ADRS,9);
  reg0 = Wire.read();
  reg1 = Wire.read();
  reg2 = Wire.read();
  reg3 = Wire.read();
  reg4 = Wire.read();
  reg5 = Wire.read();
  reg6 = Wire.read();
  reg7 = Wire.read();
  reg8 = Wire.read();
  Wire.beginTransmission(AS3935_ADRS);
  Wire.write(0x3A);
  Wire.endTransmission(false);
  Wire.requestFrom(AS3935_ADRS,4);
  reg3A = Wire.read();
  reg3B = Wire.read();
  reg3C = Wire.read();
  reg3D = Wire.read();

}

void setup()
{
  pinMode(2,INPUT);

  Wire.begin();
  Serial.begin(9600);          // start serial communication at 9600bps
  Serial.println("READY");   // print the reading
  // create a new character
  lcd.createChar(5, Lightning);

  INIT_LCD();
  DISP_OPENNING();
  INIT_AS3935();
}

void loop()
{
  writeCommand(0x01); // Clear Display
  while(1)
  {
  if (digitalRead(5)== HIGH) INT_DETECTS();
  }
}

void INT_DETECTS(void)
{
  digitalWrite(4, HIGH);  // LED ON
  byte reg3buffer;
  delay(4);
  resistorRead();
  reg3buffer = reg3 & 0x0F;
  if (reg3buffer == 0x01) INT_NH();
  if (reg3buffer == 0x04) INT_D();
  if (reg3buffer == 0x08) INT_L();
  digitalWrite(4, LOW);  // LED OFF
}

void INT_NH(void)  //noise level too high
{
  writeCommand(0x01); // Clear Display
  LCD_STRING = "Nois Level High ";
  LCD_DISP_16_1();
  LCD_STRING = "el High ";
  LCD_DISP_16_2();
  delay(700);
  writeCommand(0x01); // Clear Display
  LCD_STRING = "Watching........ ";
  LCD_DISP_16_1();
}

void INT_D(void)  //disturber detected
{
  writeCommand(0x01); // Clear Display
  LCD_STRING = "Disturbe";
  LCD_DISP_16_1();
  LCD_STRING = "r DETect";
  LCD_DISP_16_2();
  delay(1500);
  writeCommand(0x01); // Clear Display
  LCD_STRING = "Watching........";
  LCD_DISP_16_1();
}

void INT_L(void)  //lightning interrupt
{
  writeCommand(0x01); // Clear Display
  enargy = (((reg6 & 0x0F) * 65536)+ (reg5 * 256)+ (reg4)) & 0x0FFFFF;
  distance = (reg7 );
  lcd.setCursor(0, 0);
  lcd.write(5);
  LCD_STRING = "E=" + String(enargy) ;
  lcd.setCursor(1, 0);
  LCD_DISP_16_1();
  LCD_STRING = "D=" + String(distance) + "km";

  if(reg7 == 0x01)  LCD_STRING = "E=" + String(enargy) + " OvrHed";
  if(reg7 == 0x3F)  LCD_STRING = "E=" + String(enargy) + " OutRng";
  LCD_DISP_16_2();
  serialDisplay();
  delay(5000);
  writeCommand(0x01); // Clear Display
  LCD_STRING = "Watching........";
  LCD_DISP_16_1();
}

void INIT_AS3935(void)
{
  ByteWrite(0x3C,0x96);
  ByteWrite(0x3D,0x96);
  ByteWrite(0x00,(AFE_GB << 1));  // SET ANALOG FRONT END GAIN BOOST
  ByteWrite(0x01,((NF_LEV << 4) | WDTH));
  ByteWrite(0x03,0x00);           // FRQ DIV RATIO = 1/16
  CALIB_LCO();
}

void CALIB_LCO(void)
{
  writeCommand(0x01); // Clear Display
  delay(20);
  LCD_STRING = "NOW CALIBRATION ";
  LCD_DISP_16_1();
  LCD_STRING = "C=000pF F=500000";
  LCD_DISP_16_2();
  FREQ_COUNT();    //DUMMY
  for ( byte b = 0; b < 0x10 ; b++)
  {
    ByteWrite(0x08,(0x80 | b));
    delay(50);
    FREQ_COUNT();
    NOW_BUFFER = abs(freq - 3125);
    if(OLD_BUFFER > NOW_BUFFER) CAP_RESULT = b;
    OLD_BUFFER = NOW_BUFFER;
    Serial.print("CAP = ");
    Serial.print(b,DEC);
    Serial.print(" freq = ");
    Serial.println((freq * 16 * 10 ),DEC );
    LCD_STRING = String(b * 8);
    writeCommand(0x40+0x82);
    for(int i = 0; i < 3; i++)
    {
      writeData(LCD_STRING[i]);
    }
    LCD_STRING = String(freq * 16 * 10);
    writeCommand(0x40+0x8A);
    for(int i = 0; i < 7 ; i++)
    {
      writeData(LCD_STRING[i]);
    }
    delay(300);
  }
  writeCommand(0x01); // Clear Display
  Serial.print("CAP_RESULT=");
  Serial.print(CAP_RESULT);
  Serial.print("   ");
  Serial.print(CAP_RESULT * 8);
  Serial.println("pF");
  ByteWrite(0x08,(0x80 | CAP_RESULT));
  delay(100);
  FREQ_COUNT();
  LCD_STRING = "CALIBRATION DONE";
  LCD_DISP_16_1();
  LCD_STRING = "pF 5000000Hz    ";
  LCD_DISP_16_2();
  LCD_STRING = String(CAP_RESULT * 8);
  writeCommand(0x40+0x80);
  for (int i = 0; i < 3; i++)
  {
    writeData(LCD_STRING[i]);
  }
  LCD_STRING = String(freq * 16 * 10);
  writeCommand(0x40+0x87);
  for (int i = 0; i < 7; i++)
  {
    writeData(LCD_STRING[i]);
  }
  ByteWrite(0x08,CAP_RESULT);
  delay(3000);
}

void  FREQ_COUNT(void)
{
    FreqCounter::f_comp = 10;
    FreqCounter::start(100);
    while (FreqCounter::f_ready == 0);
    freq = FreqCounter::f_freq;
}

void DISP_OPENNING(void)
{
  LCD_STRING = "Lightning Sensor";
  LCD_DISP_16_1();
  writeCommand(0x40+0x80);
  LCD_STRING = "   AS3935 DEMO  ";
  LCD_DISP_16_2();
  delay(2000);
}

//Write Data
void writeData(byte t_data)
{
  Wire.beginTransmission(LCD_ADRS);
  Wire.write(0x40);
  Wire.write(t_data);
  Wire.endTransmission();
delay(1);
}
//Write Command
void writeCommand(byte t_command)
{
  Wire.beginTransmission(LCD_ADRS);
  Wire.write(0x00);
  Wire.write(t_command);
  Wire.endTransmission();
delay(10);
}

//Initialize LCD
void INIT_LCD()
{
    lcd.begin(8, 2);      // LCD range
    lcd.setContrast(30);  // Contrast setting
    lcd.setCursor(0, 0);  // Cursor position
}

void LCD_DISP_16_1(void)
{
  for(int i = 0; i < 16; i++)
  {
    writeData(LCD_STRING[i]);
  }
}

void LCD_DISP_16_2(void)
{
  writeCommand(0x40+0x80);
  for(int i = 0; i < 16; i++)
  {
    writeData(LCD_STRING[i]);
  }
}

void serialDisplay(void)
{
  Serial.print(LCD_STRING);
  Serial.print(" reg0=");
  Serial.print(reg0,HEX);
  Serial.print(" reg1=");
  Serial.print(reg1,HEX);
  Serial.print(" reg2=");
  Serial.print(reg2,HEX);
  Serial.print(" reg3=");
  Serial.print(reg3,HEX);
  Serial.print(" reg4=");
  Serial.print(reg4,HEX);
  Serial.print(" reg5=");
  Serial.print(reg5,HEX);
  Serial.print(" reg6=");
  Serial.print(reg6,HEX);
  Serial.print(" reg7=");
  Serial.print(reg7,HEX);
  Serial.print(" reg8=");
  Serial.println(reg8,HEX);
}

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


Bluetooth control of 2 LEDs

Bluetooth control of 2 LEDs

int ledPin = 13;
int state = 0;
int flag = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0)
  {
    state = Serial.read();
    Serial.print("State: ");
    Serial.println(state);
    flag = 0;
  }

  if (state == '0')
  {
    digitalWrite(ledPin, LOW);
    if (flag == 0)
    {
      Serial.println("LED: off");
      flag = 1;
    }
  }

  if (state == '1')
  {
    digitalWrite(ledPin, HIGH);
    if (flag == 0)
    {
      Serial.println("LED: on");
      flag = 1;
    }
  }
}

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


implementado botão um-clique com debounce

/*
 EMP-B Due
 V0.1 © 03/08/2014 William Koch

 Controlador de Empacotadeira com Arduino Due.
*/

// Constantes de Entradas
const byte botao_geral = 22;
int estado_botao_geral;
int estado_botao_geral_anterior = HIGH;
long atraso_geral_anterior = 0;

const byte indicador_geral = 25;
int estado_indicador_geral = LOW;

const byte botao_dosador = 26;
int estado_botao_dosador;
int estado_botao_dosador_anterior = HIGH;
long atraso_dosador_anterior = 0;

const byte indicador_dosador = 29;
int estado_indicador_dosador = LOW;

long atraso = 50;

void setup() {
  pinMode(botao_geral, INPUT_PULLUP);
  pinMode(botao_dosador, INPUT_PULLUP);

  pinMode(indicador_geral, OUTPUT);
  pinMode(indicador_dosador, OUTPUT);

  // set initial LED state
  digitalWrite(indicador_geral, estado_indicador_geral);
  digitalWrite(indicador_dosador, estado_indicador_dosador);
}

void loop() {
  botao_um_clique(botao_geral, &estado_botao_geral, &estado_botao_geral_anterior, &atraso_geral_anterior, indicador_geral, &estado_indicador_geral);
  botao_um_clique(botao_dosador, &estado_botao_dosador, &estado_botao_dosador_anterior, &atraso_dosador_anterior, indicador_dosador, &estado_indicador_dosador);
}

void botao_um_clique(byte botao, int *estado, int *estado_anterior, long *atraso_anterior, byte saida, int *estado_saida ){
  int reading = digitalRead(botao);
  if (reading != *estado_anterior) {
    *atraso_anterior = millis();
  }

  if ((millis() - *atraso_anterior) > atraso) {
    if (reading != *estado) {
      *estado = reading;
      if (*estado == LOW) {
        *estado_saida = !*estado_saida;
      }
    }
  }
  digitalWrite(saida, *estado_saida);
  *estado_anterior = reading;
}

// void botao_maquina(){
//   // read the state of the switch into a local variable:
//   int reading = digitalRead(buttonPin);

//   // check to see if you just pressed the button
//   // (i.e. the input went from LOW to HIGH),  and you've waited
//   // long enough since the last press to ignore any noise:

//   // If the switch changed, due to noise or pressing:
//   if (reading != lastButtonState) {
//     // reset the debouncing timer
//     lastDebounceTime = millis();
//   }

//   if ((millis() - lastDebounceTime) > debounceDelay) {
//     // whatever the reading is at, it's been there for longer
//     // than the debounce delay, so take it as the actual current state:

//     // if the button state has changed:
//     if (reading != buttonState) {
//       buttonState = reading;

//       // only toggle the LED if the new button state is HIGH
//       if (buttonState == LOW) {
//         ledState = !ledState;
//       }
//     }
//   }

//   // set the LED:
//   digitalWrite(ledPin, ledState);

//   // save the reading.  Next time through the loop,
//   // it'll be the lastButtonState:
//   lastButtonState = reading;
// }

error: pathspec 'EMP-B-Due.ino' did not match any file(s) known to git


Altitude Control Servo code

Altitude Control Servo code

Servo servo;
int t = 0;
int timeStop = 0;
bool valveClosed = true;
bool isCrusing = false;
bool manueverDone = false;
int altDiff = 0; //avg difference between last 5 readings of alt
int tCruise = 0;
void setup() {
  servo.attach(0);

}

void loop() {
  if (alt >= 50000 && valveClosed) {
    t = millis() + 9000;
    servo.write(180);
    valveClosed = false;
  }
  if (55000 <= alt && !valveClosed) {
    t = millis() + 9000;
    servo.write(0);
    valveClosed = true;
    manueverDone = true;
  }
  if (millis() > t) {
    servo.write(90);
  }
  if (altDiff < 100 && manueverDone) {
    isCruising = true;
    tCruise = millis() + 300000;
  }
  if (millis() > tCruise && isCruising) {
    t = millis() + 216_000_000;
    servo.write(180);
    valveClosed = false;
    isCruising = false;
  }
  if (millis() > (t + 60000) && !isCruising && manueverDone) {
    t = millis() + 216_000_000;
    servo.write(180);
    valveClosed = false;
    isCruising = false;
  }

}

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


Depuracion de archivos antiguos, actualizacion del sensor de energia

/**
  * Description: This code has been only tested in Intel Galileo Gen 1 and gets the readings of the next sensors:
        * SCT-013-000 - Electric current sensor
    Then it calls the python scripts to send the data to the server via MQTT. All readings are writen to a file
    located in the SD card, located by default in '/media/mmcblk0p1/'. The SD functions were taken from:
    https://gist.github.com/carlynorama/9316252, we only override writing methods so it could support multiple
    data types.

  * Author:       Gustavo Adrián Jiménez González (Ruxaxup)
  * Date:         03 - 27 - 2017
  * Version:      1.0.0
  * Contact:      gustavo.jim.gonz@gmail.com
**/

#include <Wire.h>
#include <SD.h>
#include "EmonLib.h"

#define POTENCIA1 0X20
#define POTENCIA 0X40

#define ALL_CONNECTED 48
#define DEBUG 0

//FRECUENCIA DE MUESTREO
#define SECOND         			1000
#define CONNECTION_DELAY        SECOND *1 		// 1 second
#define TIME_POTENCIA 			1              	//min
#define TIME_DISC       		SECOND * 2     	//Time for connecting sensors
//LEDS
#define LED_ERROR 13
#define LED_WARNING 12
#define LED_OK 11

//SENSOR LEYENDO
#define LED_SENS_1 10
#define LED_SENS_2 9
#define LED_SENS_3 8

//CANTIDAD DE SENSORES DE ENERGIA
#define ENERGY_COUNT  3

//VALOR DE CALIBRACION DE SENSORES DE ENERGIA
#define ENERGY_CAL    116 //504

byte readingFlag = 0x0;

byte warningFlag = 0x0;

byte estatus_sensores, estatus_anterior;

typedef struct {  /*S2*/
  double power[ENERGY_COUNT];   /*S2*/
} Mediciones;

enum states {
  start,
  idle,
  readSensors,
  sendMetadata,
  sendDataMQTT,
  error,
  checkRanges,
  connectSensors,
  idleIterator
};

states state = start;

//Energy sensors
EnergyMonitor energySensors[ENERGY_COUNT];  /*S2*/
//Energy IN array
int energyPINS[] = {A1, A2, A3};
Mediciones m;

/////////////   MQTT    ///////////////

void blinkERRORLed(int times)
{
  for (int i = 0; i < times; i++) {
    digitalWrite(LED_ERROR, HIGH);
    delay(250);
    digitalWrite(LED_ERROR, LOW);
    delay(250);
  }
}

void blinkConnectionLEDS(int times)
{
  for (int i = 0; i < times; i++) {
    digitalWrite (LED_SENS_1, HIGH);
    digitalWrite (LED_SENS_2, HIGH);
    digitalWrite (LED_SENS_3, HIGH);
    delay(100);
    digitalWrite (LED_SENS_1, LOW);
    digitalWrite (LED_SENS_2, LOW);
    digitalWrite (LED_SENS_3, LOW);
    delay(100);
    digitalWrite (LED_ERROR,  HIGH);
    digitalWrite (LED_WARNING, HIGH);
    digitalWrite (LED_OK, HIGH);
    delay(100);
    digitalWrite (LED_ERROR, LOW);
    digitalWrite (LED_WARNING, LOW);
    digitalWrite (LED_OK, LOW);
    delay(100);
  }
}

void _sendMetaData(String status) {
  char data[30];

  String path = String("python /home/root/PythonMQTT/sendMetadata.py " + status + " " + estatus_sensores);
  char command [path.length() + 1  ];
  path.toCharArray(command, sizeof(command));
  if (DEBUG == 1) Serial.println(command);
  system(command);
}

void _sendDataMQTT(String tipoLectura, String status, int energyIndex) {
  char data[25];
  String path = String("python /home/root/PythonMQTT/sendDataMQTTEnergy.py " + tipoLectura + energyIndex + " " + status);
  galileoCreateFile("values.txt");
  if (DEBUG == 1) Serial.println(tipoLectura);
  if (tipoLectura.equals("power")) {
    addValueToFile("values.txt", m.power[energyIndex]*127); // VALOR MODIFICADO - CALIBRACIÓN NUEVA
  }                                                                                /*S2*/
  char command [path.length() + 1  ];
  path.toCharArray(command, sizeof(command));
  if (DEBUG == 1) Serial.println(command);
  system(command);
  blinkERRORLed(5);
}

////////////    MQTT    ///////////////

void clearData()
{
  for(int i = 0; i < ENERGY_COUNT; i++)
  {
    m.power[i] = 0.0;
  }

}

////////////////////////////////////
boolean getCurrent(EnergyMonitor em, int index)
{
  //Calcula a corrente
  //I = 0.28, P = 25 kW
  double Irms = em.calcIrms(1480);
  m.power[index] = Irms;
  return true;

}
//////////// Rangos ////////////////

void turnOnStatusLeds(byte sensor)
{
  switch (sensor) {
    case POTENCIA:
      if ((warningFlag & POTENCIA) == POTENCIA) {
        digitalWrite (LED_WARNING, HIGH);
        digitalWrite (LED_OK, LOW);
        digitalWrite (LED_ERROR, LOW);
      }
      else {
        digitalWrite(LED_WARNING, LOW);
        digitalWrite (LED_ERROR, LOW);
        digitalWrite(LED_OK, HIGH);

      }
      break;
      case POTENCIA1:
      if ((warningFlag & POTENCIA1) == POTENCIA1) {
        digitalWrite (LED_WARNING, HIGH);
        digitalWrite (LED_OK, LOW);
        digitalWrite (LED_ERROR, LOW);
      }
      else {
        digitalWrite(LED_WARNING, LOW);
        digitalWrite (LED_ERROR, LOW);
        digitalWrite(LED_OK, HIGH);

      }
      break;
  }
}

void turnOnSensorLeds(byte sensor)
{
  switch (sensor) {
    case POTENCIA:
      digitalWrite (LED_SENS_1, HIGH);
      digitalWrite (LED_SENS_2, HIGH);
      digitalWrite (LED_SENS_3, HIGH);

      break;
      case POTENCIA1:
      digitalWrite (LED_SENS_1, HIGH);
      digitalWrite (LED_SENS_2, HIGH);
      digitalWrite (LED_SENS_3, HIGH);

      break;
  }

}

void resetLeds()
{
  delay(SECOND);
  digitalWrite (LED_SENS_1, LOW);
  digitalWrite (LED_SENS_2, LOW);
  digitalWrite (LED_SENS_3, LOW);
  digitalWrite(LED_WARNING, LOW);
  digitalWrite (LED_ERROR, LOW);
  digitalWrite(LED_OK, LOW);

}

void check_ranges()
{
  warningFlag = 0;
  if ( (estatus_sensores & POTENCIA) == POTENCIA ) {

  }
}

void check_sensors()

{
  estatus_anterior = estatus_sensores;
  estatus_sensores = 0;
  if (getCurrent(energySensors[0], 0)) {
    estatus_sensores = estatus_sensores | POTENCIA;
  }
  else {
    if (DEBUG == 1)Serial.println("Sensor de potencia1 desconectado");
  }
}

void calibrateCurrentSensor(EnergyMonitor *em)
{
  em->calcIrms(5860);
  em->calcIrms(5860);
  em->calcIrms(5860);
  em->calcIrms(5860);
  em->calcIrms(5860);
}

void setup(void)
{

  Serial.begin(9600);
  //Current
  //Pino, calibracao - Cur Const= Ratio/BurdenR. 1800/62 = 29.
  for(int i = 0; i < ENERGY_COUNT; i++)
  {
    energySensors[i].current(energyPINS[i], ENERGY_CAL);
    calibrateCurrentSensor(&energySensors[i]);
  }

  pinMode(LED_ERROR, OUTPUT);
  digitalWrite(LED_ERROR, LOW);
  pinMode(LED_WARNING, OUTPUT);
  digitalWrite(LED_WARNING, LOW);
  pinMode(LED_OK, OUTPUT);
  digitalWrite(LED_OK, LOW);
  pinMode(LED_SENS_1, OUTPUT);
  digitalWrite(LED_SENS_1, LOW);
  pinMode(LED_SENS_2, OUTPUT);
  digitalWrite(LED_SENS_2, LOW);
  pinMode(LED_SENS_3, OUTPUT);
  digitalWrite(LED_SENS_3, LOW);

  //Indicador de arranque
  turnOnSensorLeds(POTENCIA);
  resetLeds();
  turnOnSensorLeds(POTENCIA);
  resetLeds();

  turnOnSensorLeds(POTENCIA1);
  resetLeds();
  turnOnSensorLeds(POTENCIA1);
  resetLeds();

  estatus_sensores = 0;
}

/******************************** SD **********************************/
//SD.open retrieves the file in append more.
void addValueToFile(String fileName, float content) {
  char charFileName[fileName.length() + 1];
  fileName.toCharArray(charFileName, sizeof(charFileName));

  if (SD.exists(charFileName)) {
    File targetFile = SD.open(charFileName, FILE_WRITE);
    targetFile.print(content);
    targetFile.print("\n");
    targetFile.close();
  }
}

void addValueToFile(String fileName, double content) {
  char charFileName[fileName.length() + 1];
  fileName.toCharArray(charFileName, sizeof(charFileName));

  if (SD.exists(charFileName)) {
    File targetFile = SD.open(charFileName, FILE_WRITE);
    targetFile.print(content);
    targetFile.print("\n");
    targetFile.close();
  }
}

void addValueToFile(String fileName, uint32_t content) {
  char charFileName[fileName.length() + 1];
  fileName.toCharArray(charFileName, sizeof(charFileName));

  if (SD.exists(charFileName)) {
    File targetFile = SD.open(charFileName, FILE_WRITE);
    targetFile.print(content);
  }
}

void galileoCreateFile(String fileName) {
  String status_message = String();
  status_message = fileName;
  char charFileName[fileName.length() + 1];
  fileName.toCharArray(charFileName, sizeof(charFileName));

  if (SD.exists(charFileName)) {
    status_message += " exists already.";
    if (DEBUG == 1) Serial.println("existe");
  }
  else {
    if (DEBUG == 1) Serial.println("no existe");
    char system_message[256];
    char directory[] = "/media/realroot";
    sprintf(system_message, "touch %s/%s", directory, charFileName);
    SD.open(charFileName,FILE_WRITE);
    system(system_message);
    if (SD.exists(charFileName)) {
      status_message += " created.";
    }
    else {
      status_message += " creation tried and failed.";
    }
  }
}

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

int cont_current = 0;
int cont_disconnected = 0;

void loop(void)
{
  String tipoLectura = String();

  switch (state) {

    case start:
      check_sensors();
      if (estatus_sensores == 0) {
        state = error;
      } else {
        if (estatus_sensores != estatus_anterior) {
          if (DEBUG == 1) Serial.println("Hubo cambios");
          state = sendMetadata;
        } else {
          if (DEBUG == 1) Serial.println("No hubo cambios");
          state = idle;
        }
      }

      break;

    case idle:
      if (DEBUG == 1) Serial.println("state:Duermo 1 min");
      delay(SECOND * 60);
      if ( (estatus_sensores & POTENCIA) == POTENCIA ) {
        cont_current++;
      } else {
        cont_current = 0;
      }

      if (DEBUG == 1) {
        Serial.print("cont_current = ");
        Serial.println(cont_current);
      }
      if (DEBUG == 1) Serial.println("state:Idle");

      if (cont_current >= TIME_POTENCIA) {
        readingFlag = readingFlag | POTENCIA;
      }

      if (readingFlag != 0x00) {
        state = readSensors;
      }

      break;

    case sendMetadata:
      if (DEBUG == 1) Serial.println("state:sendMetadata");
      _sendMetaData("S");
      state = idle;
      break;

    case sendDataMQTT:
      if (DEBUG == 1) Serial.println("state:sendDataMQTT");

      if ( (readingFlag & POTENCIA) == POTENCIA) {
        for(int i = 0; i < ENERGY_COUNT; i++)
        {
          if(DEBUG == 1)
          {
            Serial.print("Enviando POTENCIA ");
            Serial.print(i);
            Serial.print(":");
            Serial.print(m.power[i] * 127);
            Serial.println(" W");
            Serial.print("***CORRIENTE electrica: ");
            Serial.print(m.power[i]);
            Serial.println(" A");
          }
          _sendDataMQTT("power", ((warningFlag & POTENCIA) == POTENCIA) ? "W" : "K", i);
        }

        cont_current = 0;
        turnOnSensorLeds(POTENCIA);
        turnOnStatusLeds(POTENCIA);
        resetLeds();
        readingFlag = readingFlag ^ POTENCIA;
      }

      clearData();
      if (DEBUG == 1)Serial.print("SENSORS STATUS: ");
      if (DEBUG == 1)Serial.println(estatus_sensores);
      if (false) {
        if (DEBUG == 1)Serial.println("CONNECT SENSOR");
        state = connectSensors;
      } else {
        state = start;
      }

      break;

    case readSensors:
      if (DEBUG == 1) Serial.println("state:readSensors");
      if( (readingFlag & POTENCIA) == POTENCIA)
      {

          if(DEBUG == 1) Serial.println("ENERGY SENSORS");
          for(int i = 0; i < ENERGY_COUNT; i++)
          {
            getCurrent(energySensors[i],i);
            if(DEBUG == 1)
            {
              Serial.print(i+1);
              Serial.print(" Sensor: ");
              Serial.println(m.power[i]);
            }
          }

      }
      state = checkRanges;
      break;

    case checkRanges:
      check_ranges();
      state = sendDataMQTT;
      break;

    case error:
      if (DEBUG == 1) Serial.println("state:Error");
      blinkERRORLed(10);
      cont_disconnected++;
      if (cont_disconnected == TIME_DISC) {
        cont_disconnected = 0;
        state = start;
      } else {
        delay(CONNECTION_DELAY);
      }

      break;

    case connectSensors:
      blinkConnectionLEDS(5);
      cont_disconnected++;
      if (cont_disconnected == TIME_DISC) {
        cont_disconnected = 0;
        state = start;
      } else {
        delay(CONNECTION_DELAY);
      }
      break;

    case idleIterator:

      break;

    default:
      if (DEBUG == 1) Serial.println("state:Default");
      break;
  }

}

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


Add first Arduino example - blinky with delay function.

/**
 * Copyright (c) 2019, Łukasz Marcin Podkalicki <lpodkalicki@gmail.com>
 * ArduinoUno/001
 * Blinky with delay function.
 */

#define LED_PIN (13)

void setup() {
  pinMode(LED_PIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_PIN, !digitalRead(LED_PIN)); // Toggle LED pin
  delay(500); // wait 0.5s
}

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