_05_kidSerie_sketch_05.Adafruit_First_Try.ino  05#kidSerie

_05_kidSerie_sketch_05.Adafruit_First_Try.ino  05#kidSerie

/*
  Project name:
     05 #kidSerie - Adafruit-IO Meets ESP8266, Arduino & MIT App Inventor 2
     (Awesome Smart Phone App!)
     Flavour V -
     Hex File: _05_kidSerie_sketch_05.Adafruit_First_Try.ino
   Revision History:
     20161029:
       - from github adafruit/Adafruit_MQTT_Library
  https://github.com/adafruit/Adafruit_MQTT_Library/blob/master/examples/mqtt_esp8266/mqtt_esp8266.ino
  https://learn.adafruit.com/mqtt-adafruit-io-and-you/intro-to-adafruit-mqtt

   Description:
     Simple code to intro Adafruit-io technology using MQTT broker, ESP8266, DHTXX sensor & arduino.
     We will publish two topics: temp and humidity and subscribe them also.
     We will access the our dashboard by phone using MIT App Inventor 2.
     Awesome project!!!

   MCU:                  Arduino 1.6.12 - @16MHz       http://www.arduino.cc/
   ESP8266:              ESP-01                        https://goo.gl/E0Eq4l
   DHT11:                PRODUCT ID: 386               https://www.adafruit.com/product/386

   Connections:
      See Official youtube channel vids:
   Based on:   Tony DiCola for Adafruit Industries - see below!

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License v3 as published by
   the Free Software Foundation
*/
/***************************************************
  Adafruit MQTT Library ESP8266 Example
  Must use ESP8266 Arduino from:
    https://github.com/esp8266/Arduino
  Works great with Adafruit's Huzzah ESP board & Feather
  ----> https://www.adafruit.com/product/2471
  ----> https://www.adafruit.com/products/2821
  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!
  Written by Tony DiCola for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 ****************************************************/
/******************************* Adafruit MQTT *******************************/
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"

/******************************* Esp8266**************************************/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
/******************************* DHT Config **********************************/
#include <DHT.h>
#define DHTTYPE DHT11
#define DHTPIN  2

/************************* WiFi Access Point *********************************/

#define WLAN_SSID       "...your SSID..."
#define WLAN_PASS       "...your password..."

/************************* Adafruit.io Setup *********************************/

#define AIO_SERVER      "io.adafruit.com"
#define AIO_SERVERPORT  1883      // use 8883 for SSL
#define AIO_USERNAME    "...your AIO username (see https://accounts.adafruit.com)..."
#define AIO_KEY         "...your AIO key..."

/************ Global State (you don't need to change this!) ******************/

// Create an ESP8266 WiFiClient class to connect to the MQTT server.
WiFiClient client;
// or... use WiFiFlientSecure for SSL
//WiFiClientSecure client;

// Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);

/****************************** Feeds ****************************************/
/****************************** Topics ***************************************/
// Setup a feed called 'temp_topic' and 'humid_topic' for publishing.
// Notice MQTT paths for AIO follow the form: <username>/feeds/<feedname>
Adafruit_MQTT_Publish temp_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/temp");
Adafruit_MQTT_Publish humid_topic = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/humid");
/****************************** Subscriptions*********************************/
// Setup a feed for subscribing
Adafruit_MQTT_Subscribe temp_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/temp");
Adafruit_MQTT_Subscribe humid_subscription = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME "/feeds/humid");

/*************************** MQTT Conn ***************************************/

// Bug workaround for Arduino 1.6.6, it seems to need a function declaration
// for some reason (only affects ESP8266, likely an arduino-builder bug).
void MQTT_connect();

/*************************** DHT Init   **************************************/
// Initialize DHT sensor
// NOTE: For working with a faster than ATmega328p 16 MHz Arduino chip, like an ESP8266,
// you need to increase the threshold for cycle counts considered a 1 or 0.
// You can do this by passing a 3rd parameter for this threshold.  It's a bit
// of fiddling to find the right value, but in general the faster the CPU the
// higher the value.  The default for a 16mhz AVR is a value of 6.  For an
// Arduino Due that runs at 84mhz a value of 30 works.
// This is for the ESP8266 processor on ESP-01
DHT dht(DHTPIN, DHTTYPE, 11); // 11 works fine for ESP8266
/*************************** DHT Data   **************************************/
//float humidity, temp_f;   // Values read from sensor as Fahrenheit
float humidity, temp_c;    // Values read from sensor as Celsius
String tempString = "";    // String to display
/*************************** DHT Timing   ************************************/
// Generally, you should use "unsigned long" for variables that hold time
unsigned long previousMillis = 0;        // will store last temp was read
const long interval = 2000;              // interval at which to read sensor

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

  Serial.println(F("Adafruit MQTT demo"));

  // Connect to WiFi access point.
  Serial.println(); Serial.println();
  Serial.print("Connecting to ");
  Serial.println(WLAN_SSID);

  WiFi.begin(WLAN_SSID, WLAN_PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.println("WiFi connected");
  Serial.println("IP address: "); Serial.println(WiFi.localIP());

  // Setup MQTT subscription for onoff feed.
  mqtt.subscribe(&temp_subscription);
  delay(1000);
  mqtt.subscribe(&humid_subscription);
}

//uint32_t x = 0;   // Mock data

/****************************** Loop  ***************************************/
void loop() {
  gettemperature() ;
  // Ensure the connection to the MQTT server is alive (this will make the first
  // connection and automatically reconnect when disconnected).  See the MQTT_connect
  // function definition further below.
  MQTT_connect();

  // this is our 'wait for incoming subscription packets' busy subloop
  // try to spend your time here

  /****************************** Subscript  ***********************************/
  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(10000))) {
    if (subscription == &humid_subscription) {
      Serial.print(F("Got humid: "));
      Serial.println((char *)humid_subscription.lastread);
    }
    else {
      Serial.print(F("Got temp: "));
      Serial.println((char *)temp_subscription.lastread);
    }
  }

  /****************************** Publish  **********************************/
  // Now we can publish stuff!
  Serial.print(F("\nSending temp val "));
  Serial.print(temp_c);
  Serial.print("...");
  if (! temp_topic.publish(temp_c)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

  Serial.print(F("\nSending humid val "));
  Serial.print(humidity);
  Serial.print("...");
  if (! humid_topic.publish(humidity)) {
    Serial.println(F("Failed"));
  } else {
    Serial.println(F("OK!"));
  }

  /****************************** Ping  ***************************************/

  // ping the server to keep the mqtt connection alive
  // NOT required if you are publishing once every KEEPALIVE seconds
  /*
    if(! mqtt.ping()) {
    mqtt.disconnect();
    }
  */
}
/********************************* MQTT Conn  ********************************/
// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

  // Stop if already connected.
  if (mqtt.connected()) {
    return;
  }

  Serial.print("Connecting to MQTT... ");

  uint8_t retries = 3;
  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
    Serial.println(mqtt.connectErrorString(ret));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);  // wait 5 seconds
    retries--;
    if (retries == 0) {
      // basically die and wait for WDT to reset me
      while (1);
    }
  }
  Serial.println("MQTT Connected!");
}
/****************************** Get Data From DHTxx  ************************/
void gettemperature() {
  // Wait at least 2 seconds seconds between measurements.
  // if the difference between the current time and last time you read
  // the sensor is bigger than the interval you set, read the sensor
  // Works better than delay for things happening elsewhere also
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you read the sensor
    previousMillis = currentMillis;

    // Reading temperature for humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (it's a very slow sensor)
    humidity = dht.readHumidity();          // Read humidity (percent)
    //temp_f = dht.readTemperature(true);     // Read temperature as Fahrenheit
    temp_c = dht.readTemperature();    // Read temperature as Celsius
    // Check if any reads failed and exit early (to try again).
    if (isnan(temp_c) || isnan(humidity) || temp_c != 0 || humidity != 0 ) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    }
  }
}

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


Arduino code for voltmeter and relay controller

// http://startingelectronics.com/articles/arduino/measuring-voltage-with-arduino/

/*--------------------------------------------------------------
  Program:      volt_measure

  Description:  Reads value on analog input A2 and calculates
                the voltage assuming that a voltage divider
                network on the pin divides by 11.

  Hardware:     Arduino Uno with voltage divider on A2.

  Software:     Developed using Arduino 1.0.5 software
                Should be compatible with Arduino 1.0 +

  Date:         22 May 2013

  Author:       W.A. Smith, http://startingelectronics.com
--------------------------------------------------------------*/

// number of analog samples to take per reading
#define NUM_SAMPLES 20

int sum = 0;                    // sum of samples taken
unsigned char sample_count = 0; // current sample number
float voltage = 0.0;            // calculated voltage

int inverter    = 0;            // is the inverter remote on?
int mains_power = 0;            // is mains power on?

#define REF_VOLTAGE  4.97       // Arduino 5V voltage

#define INV_REMOTE  8           // Output pin for inverter remote control
#define INV_LIVE    9           // Output pin for inverter live power
#define INV_NEUTRAL 10          // Output

// Voltage divider A0: 12.59 / 2.11

void setup()
{
    Serial.begin(9600);
    pinMode(A0, INPUT);  // Doesn't seem to work
    pinMode(A1, INPUT);  // Input from voltage divider

    pinMode(12, INPUT);  // mains_power voltage sensor (relay contact, 0V/5V)
    // Relay http://www.farnell.com/datasheets/296895.pdf wiring 5V (digital 1)=no power

    pinMode(INV_REMOTE, OUTPUT);   // Relay board channel 1: Inverter remote
    pinMode(INV_LIVE, OUTPUT);   // Relay board channel 3: Inverter/mains_power live
    pinMode(INV_NEUTRAL, OUTPUT);   // Relay board channel 4: Inverter/mains_power neutral

    digitalWrite(INV_REMOTE, LOW);
    digitalWrite(INV_LIVE, LOW);
    digitalWrite(INV_NEUTRAL, LOW);

}

void loop()
{
    // take a number of analog samples and add them up
    while (sample_count < NUM_SAMPLES) {
        float sample = analogRead(A1);
        sum += sample;
        sample_count++;
        // Serial.print("Actual: ");
        // Serial.println(sample);
        delay(20);
    }
    // calculate the voltage
    // use 5.0 for a 5.0V ADC reference voltage
    // 5.015V is the calibrated reference voltage
    voltage = (((float)sum / (float)NUM_SAMPLES * REF_VOLTAGE) / 1024.0) * 5.99;

    // send voltage for display on Serial Monitor
    // voltage multiplied by 11 when using voltage divider that
    // divides by 11. 11.132 is the calibrated voltage divide
    // value

    Serial.print("voltage=");
    Serial.print(voltage);

    // mains_power sensor
    mains_power = !digitalRead(12);

    Serial.print(" mains_power=");
    Serial.print(mains_power);

    if (!mains_power) {
        // Always use inverter: low-voltage cutoff will cause it to power off eventually
        if (!inverter) {
            inverterOn();
        }
    } else {

      // Battery getting low
      if ((voltage < 12.1) && inverter) {
          inverterOff();
      }

      // Battery charged and/or solar power available
      if ((voltage > 12.5) && !inverter) {
        inverterOn();
      }

    }

    Serial.print(" inverter=");
    Serial.print(inverter);

    Serial.println();

    sample_count = 0;
    sum = 0;

    delay(4600);
}

void inverterOn() {
  digitalWrite(INV_REMOTE, HIGH);
  delay(1000);
  digitalWrite(INV_LIVE, HIGH);
  digitalWrite(INV_NEUTRAL, HIGH);
  inverter = 1;
}

void inverterOff() {
  digitalWrite(INV_LIVE, LOW);
  digitalWrite(INV_NEUTRAL, LOW);
  delay(500);
  digitalWrite(INV_REMOTE, LOW);
  inverter = 0;
}

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


special animation for the Vermillion exhibit that incorporates a range finder to shift between a blue-green stasis pattern and go more red-orange as someone gets closer.  with sparkle motion!

#include <Adafruit_WS2801.h>

// Choose which 2 pins you will use for output.
// Can be any valid output pins.
const int DATA_PIN = 2;       // 'yellow' wire
const int CLOCK_PIN = 3;      // 'green' wire

const int SENSOR_PIN = A0;

// highest component color value we want to push. could be as high as 31
const int MAX_COLOR = 31;
const int MIN_COLOR = 2;
const int NUM_PIXELS = 50;

const int INACTIVE_MAX_BLUE = MAX_COLOR / 2;
const int INACTIVE_MIN_BLUE = MIN_COLOR;
const int INACTIVE_MAX_GREEN = MAX_COLOR;
const int INACTIVE_MIN_GREEN = MAX_COLOR + 10;
const int INACTIVE_MAX_RED = 0;
const int INACTIVE_MIN_RED = 0;

const int ACTIVE_MAX_BLUE = 0;
const int ACTIVE_MIN_BLUE = 0;
const int ACTIVE_MAX_GREEN = 20;
const int ACTIVE_MIN_GREEN = 8;
const int ACTIVE_MAX_RED = MAX_COLOR;
const int ACTIVE_MIN_RED = MAX_COLOR;

const int LOOP_DELAY = 50;
// odds of any one pixel being full white for 1 loop delay
const int SPARKLE_DEMONINATOR = 100;

Adafruit_WS2801 strip = Adafruit_WS2801(NUM_PIXELS, DATA_PIN, CLOCK_PIN);

void setup() {
  // put your setup code here, to run once:
  strip.begin();
  strip.show();

  pinMode(SENSOR_PIN, INPUT);

  Serial.begin(9600);
  Serial.println("Starting Up Vermillion animation...");
}

void loop() {
  // put your main code here, to run repeatedly:
  int i;
  int component;
  int step;
  int red;
  int green;
  int blue;
  int sensorValue;

  // sensor values between 20 - 200 cause an equal percentage of the first and last
  // 20 pixels to go to red scale
  sensorValue = analogRead(SENSOR_PIN);

  for (int i = 0; i < NUM_PIXELS; i++){
    if (random(SPARKLE_DEMONINATOR) == 1){
      red = MAX_COLOR;
      green = MAX_COLOR;
      blue = MAX_COLOR;
    } else if( shouldGoRed(i, sensorValue) ){
      red = random(ACTIVE_MIN_RED, ACTIVE_MAX_RED);
      green = random(ACTIVE_MIN_GREEN, ACTIVE_MAX_GREEN);
      blue = random(ACTIVE_MIN_BLUE, ACTIVE_MAX_BLUE);
    } else {
      red = random(INACTIVE_MIN_RED, INACTIVE_MAX_RED);
      green = random(INACTIVE_MIN_GREEN, INACTIVE_MAX_GREEN);
      blue = random(INACTIVE_MIN_BLUE, INACTIVE_MAX_BLUE);
    }
    strip.setPixelColor(i, red, green, blue);
  }
  strip.show();
  delay(LOOP_DELAY);
}

bool shouldGoRed(int pixelIndex, int sensorValue){
  char outputBuffer[64];
  int degree = (sensorValue / 9);

  if( pixelIndex > 20 && pixelIndex < 30 || sensorValue > 200)
    return false;

  // Serial.print(itoa(pixelIndex, outputBuffer, 10));
  // Serial.print("- SENSOR_PIN: ");
  // Serial.print(", degree: ");
  // Serial.print(itoa(degree, outputBuffer, 10));
  // Serial.print("\n");

  return pixelIndex < 20 - degree || pixelIndex > 30 && pixelIndex < 50 - degree;
}

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


calibration code for IR sensor for reference

/*
  Calibration

 Demonstrates one technique for calibrating sensor input.  The
 sensor readings during the first five seconds of the sketch
 execution define the minimum and maximum of expected values
 attached to the sensor pin.

 The sensor minimum and maximum initial values may seem backwards.
 Initially, you set the minimum high and listen for anything
 lower, saving it as the new minimum. Likewise, you set the
 maximum low and listen for anything higher as the new maximum.

 The circuit:
 * Analog sensor (potentiometer will do) attached to analog input 0
 * LED attached from digital pin 9 to ground

 created 29 Oct 2008
 By David A Mellis
 modified 30 Aug 2011
 By Tom Igoe

 http://arduino.cc/en/Tutorial/Calibration

 This example code is in the public domain.

 */

// These constants won't change:
const int sensorPin = A0;    // pin that the sensor is attached to
const int ledPin = 9;        // pin that the LED is attached to

// variables:
int sensorValue = 0;         // the sensor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value

void setup() {
  // turn on LED to signal the start of the calibration period:
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);//pin 13?

  // calibrate during the first five seconds
  while (millis() < 5000) {
    sensorValue = analogRead(sensorPin);

    // record the maximum sensor value
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }

    // record the minimum sensor value
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }

  // signal the end of the calibration period
  digitalWrite(13, LOW);
}

void loop() {
  // read the sensor:
  sensorValue = analogRead(sensorPin);

  // apply the calibration to the sensor reading
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

  // in case the sensor value is outside the range seen during calibration
  sensorValue = constrain(sensorValue, 0, 255);

  // fade the LED using the calibrated value:
  analogWrite(ledPin, sensorValue);
}

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


Create Heltec_LoRa32_ttn-abp.ino

Create Heltec_LoRa32_ttn-abp.ino

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


dang, wasn't that the error anyway??

dang, wasn't that the error anyway??

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


copy galaxytopper.ino to "tick_demos.ino"

I'm going to be reducing the number and diversity of modes in my topper,
but want to preserve this functionality for demonstration purposes.

/*
 * Fimware for the Galaxy Topper
 * Galaxy Topper is a top hat inspired by Chris Knight's build at:
 *   http://www.instructables.com/id/My-hat-its-full-of-stars/
 *
 * It uses 6 ShiftBrite pixels to drive a "galaxy" of points of light poking
 * through the felt of a simple, felt top hat. The hat has several different
 * modes and more can be added fairly easily. There is a momentary pushbutton
 * hidden under the bow on the band to cycle through the modes. To keep things
 * fresh and interesting the pushbutton seeds the pRNG with the current value
 * of millis() when pushed.
 *
 * MODES:
 *  - Stealth: All pixels are off, leaving the hat dark.
 *  - Sparkle: each pixel picks a random color, waits a short time, and picks a
 *      new one
 *  - Rainbow: Each pixel fades around the color wheel. Pixels are offset from
 *      one another to give a more active pattern
 *  - Nebula: each pixel fades randomly through blue/white/purple colors
 *      creating a rippling, twinkling pattern in the colors of the night sky
 *  - Christmas Lights: Pixels cycle through the soft colors of old strings of
 *      Christmas lights. Colors are nominally red, yellow, green, and blue,
 *      TODO: but in practice are washed out and warmed over
 *  - Christmas: Pixels alternate between red and green.
 *
 * TODO:
 * I'd really like to add a couple more pixels tied directly into certain
 * patterns (alchemical symbols?) that I can have illuminate at random or on
 * command, but I'm not sure if that'll work out.
 */

#include "shiftbrite.h"
#include "ticker.h"
#include "math.h"     // only used to get pow(...) for our skew(...) function

/* Constants */
#define LATCH_PIN    9  // replace with pin you use for the ShiftBrite latch
#define BUTTON_PIN   3  // pin used for the button to cycle modes
#define NUM_LEDS     6  // Number of LEDs in your chain
#define NUM_MODES    6  // Number of light modes the topper supports
#define FPS        100  // number of times per second to update shiftbrites
#define TPS        100  // ticks per second

/* Predeclarations */
// Necessary to avoid confusing particle's preprocessor
// see https://docs.particle.io/reference/firmware/core/#preprocessor
void colorwheel_tick(Ticker *t, unsigned long tick);
void cycling_tick(Ticker *t, unsigned long tick);
void fading_cycling_tick(Ticker *t, unsigned long tick);
void targeted_tick(Ticker *t, unsigned long tick);
void dark_tick(Ticker *t, unsigned long tick);
TickerRgb hsv2rgb(double hue, double sat, double value);

/* Define Objects */
ShiftBrite sb(NUM_LEDS, LATCH_PIN);
Ticker Tickers[NUM_LEDS] = {
	Ticker(&dark_tick, 0, 0,  0),
	Ticker(&dark_tick, 0, 0,  0),
	Ticker(&dark_tick, 0, 0,  0),
	Ticker(&dark_tick, 0, 0,  0),
	Ticker(&dark_tick, 0, 0,  0),
	Ticker(&dark_tick, 0, 0,  0),
};

/* Timing */
unsigned long frame_delay = 1000 / FPS;
unsigned long tick_delay  = 1000 / TPS;
unsigned long tick, last_tick, last_frame = 0;

/* Button to switch modes */
int current_mode = 0;
volatile int           mode_change_requested = 0;
volatile unsigned long button_last_triggered = 0;

void setup()
{
	// Initialize shiftbrite
	sb.begin();
	sb.show();

	// Set up mode-change button
	pinMode(BUTTON_PIN, INPUT_PULLUP);
	attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), trigger_change, FALLING);

	// Initialize tickers
	mode_stealth();
}

void loop()
{
	if (mode_change_requested) {
		change_mode();
		mode_change_requested = 0;
	}

	unsigned long now = millis();

	// Is it time to do another tick?
	if (now - last_tick > tick_delay) {
		last_tick = millis();
		for(int i = 0; i < NUM_LEDS; ++i) {
			Tickers[i].Tick(tick);
			TickerRgb c = Tickers[i].current;
			sb.setPixelRGB(i, c.red, c.green, c.blue);
		}
		++tick;
	}

	// Is it time to refresh our shiftbrites?
	if (millis() - last_frame > frame_delay) {
		last_frame = millis();
		sb.show();
	}
}

/*********************
 * MODE SETUP FUNCTIONS *
 ************************/
void trigger_change() {
	if (millis() - button_last_triggered > 600) {
		button_last_triggered = millis();
		mode_change_requested = 1;
	}
}

void change_mode() {
	randomSeed(millis());

	++current_mode;
	current_mode %= NUM_MODES;
	switch(current_mode) {
		case 0:
			mode_stealth();
			break;
		case 1:
			mode_sparkle();
			break;
		case 2:
			mode_rainbow();
			break;
		case 3:
			mode_nebula();
			break;
		case 4:
			mode_christmas_lights();
			break;
		case 5:
			mode_christmas();
			break;
		default:
			mode_stealth();
			break;
	}

}

void mode_stealth()
{
	for (int i = 0; i < NUM_LEDS; ++i) {
		Tickers[i] = Ticker(&dark_tick, 0, 0, 0);
	}
}

void mode_nebula()
{
	// Use targeting tickers constrained to be colors with strong blue channels
	// to make a flickering "nebula" effect.
	for (int i = 0; i < NUM_LEDS; ++i) {
		Tickers[i] = Ticker(&targeted_tick, 3, 0, i * 5 + 1);

		Tickers[i].targets[0] = {red: random(0,1023), green: random(0,1023), blue: random(0,1023)};
		Tickers[i].targets[1] = {red: 0, green: 0, blue: 511};
		Tickers[i].targets[2] = {red: 1023, green: 1023, blue: 1023};
	}
}

void mode_sparkle()
{
	for (int i = 0; i < NUM_LEDS; ++i) {
		Tickers[i] = Ticker(&random_tick, 0, 2, i);
	}
}

void mode_christmas_lights()
{
	for (int i = 0; i < NUM_LEDS; ++i) {
		// Slow by 2^6
		Tickers[i] = Ticker(&cycling_tick, 4, 6, i);

		//TODO: Adjust these values to taste to simulate christmas lights
		Tickers[i].targets[0] = {red: 1023, green:    0, blue:    0}; // Red
		Tickers[i].targets[1] = {red: 1023, green: 1023, blue:    0}; // Yellow
		Tickers[i].targets[2] = {red:    0, green: 1023, blue:    0}; // Green
		Tickers[i].targets[3] = {red:    0, green:    0, blue: 1023}; // Blue
	}
}

void mode_christmas()
{
	for (int i = 0; i < NUM_LEDS; ++i) {
		// Slow by 2^6
		Tickers[i] = Ticker(&cycling_tick, 2, 6, i);

		Tickers[i].targets[0] = {red: 1023, green:    0, blue:    0}; // Red
		Tickers[i].targets[1] = {red:    0, green: 1023, blue:    0}; // Green
	}
}

void mode_rainbow()
{
	for (int i = 0; i < NUM_LEDS; ++i) {
		Tickers[i] = Ticker(&colorwheel_tick, 0, 0, i * 15);
	}
}

/*********************
 *  TICKER FUNCTIONS *
 *********************/

/* Do nothing */
void dark_tick(Ticker *t, unsigned long tick)
{
	t->current = {red: 0, green: 0, blue: 0};
}

/*
 * Cycles around the color wheel by using tick to compute the hue (value and
 * saturation are held constant at 1).
 *
 * Ticker's speed_adjust is used to slow the cycle by powers of 2
 *
 * Ticker's offset is used to set the color *ahead* of the tick's base hue.
 * This can be used to sync multiple colorwheel_tick Tickers into a ribbon.
 *
 * This tick function does not use any target colors.
 */
void colorwheel_tick(Ticker *t, unsigned long tick)
{
	int16_t hue = ((tick >> t->speed_adjust) + t->offset) % 360;
	t->current = hsv2rgb((double)hue, 1.0, 1.0);
}

/*
 * Picks a random color and switches to it.
 *
 * By default it switches every tick. Slow this by 2^n by setting Ticker's
 * speed_adjust to n.
 *
 * This tick function does not use any targets
 */
void random_tick(Ticker *t, unsigned long tick)
{
	if (tick % (1 << t->speed_adjust)) {return;}
	t->current = {red: random(0,1023), green: random(0,1023), blue: random(0,1023)};
}

/*
 * Cycles through a fixed list of target colors.
 *
 * By default moves to the next color in the cycle every tick. Slow this
 * by 2^n by setting Ticker's speed_adjust to n.
 *
 * Advance the position in the cycle with Ticker's offset. This can be used to
 * sync multiple cycling_tick tickers into a string.
 *
 * This tick function uses as many targets as you choose to give the Ticker.
 */
void cycling_tick(Ticker *t, unsigned long tick)
{
	int current_index = ((tick >> t->speed_adjust) + t->offset) % t->num_targets;
	t->current = t->targets[current_index];
}

/*
 * Cycles through a fixed list of target colors, fading between them.
 *
 * Fading from one color to the next takes about a second. TODO: make this
 * dynamic via Ticker's speed_adjust.
 *
 * Advance the position in the cycle with Ticker's offset. This can be used to
 * sync multiple cycling_tick tickers into a string.
 *
 * This tick function uses as many targets as you choose to give the Ticker.
 */
void fading_cycling_tick(Ticker *t, unsigned long tick)
{
	int previous_index = ((tick / TPS) + t->offset) % t->num_targets; // Update target once per second.
	TickerRgb previous_color = t->targets[previous_index];
	TickerRgb next_color     = t->targets[(previous_index + 1) % t->num_targets];

	int16_t red_delta     = next_color.red       - previous_color.red;
	int16_t current_red   = previous_color.red   + ((red_delta * (tick % TPS)) / TPS);
	int16_t green_delta   = next_color.green     - previous_color.green;
	int16_t current_green = previous_color.green + ((green_delta * (tick % TPS)) / TPS);
	int16_t blue_delta    = next_color.blue      - previous_color.blue;
	int16_t current_blue  = previous_color.blue  + ((blue_delta * (tick % TPS)) / TPS);

	t->current = {red: current_red, green: current_green, blue: current_blue};
}

/*
 * Fades to a target color. Once target color is reached, the target and fade
 * speed are randomized. Target randomization is controllable within min and
 * max values on each color channel.
 *
 * Ticker's offset is used as the step size to control how quickly the color
 * moves towards the target.
 *
 * Ticker's speed_adjust is used to skip cycles by powers of 2:
 * 0 executes every cycle
 * 1 executes every other cycle
 * 2 executes every fourth cycle...
 *
 * This tick function uses three "target" colors:
 *   0: The color to fade towards
 *   1: The minimum value for each color channel when randomizing
 *   2: The maximum value for each color channel when randomizing
 */
void targeted_tick(Ticker *t, unsigned long tick)
{
	// speed_adjust keeps us from ticking on certain cycles
	if (tick % (1 << t->speed_adjust)) {return;}

	TickerRgb* current = &t->current;
	TickerRgb* target  = &t->targets[0];
	TickerRgb  minima  = t->targets[1];
	TickerRgb  maxima  = t->targets[2];
	int step_size = t->offset;

	if (   current->red   == target->red
		&& current->green == target->green
		&& current->blue  == target->blue)
	{
		// We've reached the target! Pick a new one.
		target->red   = random(minima.red,   maxima.red);
		target->green = random(minima.green, maxima.green);
		target->blue  = random(minima.blue,  maxima.blue);
		// And just for fun let's also randomize the fade speed!
		t->offset       = skew(random(1, 100), 5, 50, 100);
		t->speed_adjust = random(0, 1);
	}
	// Still working towards the target. Take a step in the right direction
	// TODO: Should we adjust the step sizes so that each channel reaches
	//       its target at the same time?
	current->red   += stepToward(target->red,   current->red,   step_size);
	current->green += stepToward(target->green, current->green, step_size);
	current->blue  += stepToward(target->blue,  current->blue,  step_size);
}

/*** HELPER FUNCTIONS ***/

/*
 * Given a target value, current value, and step size, calculate the value to
 * add to the current value to move it towards its target by the step size
 * without going past the target.
 */
int16_t stepToward(int16_t target, int16_t current, int step_size)
{
	int16_t delta = target - current;
	delta = abs(delta);

	int direction = 0;
	if (target > current) {direction =  1;}
	if (target < current) {direction = -1;}

	return (delta > step_size ? step_size : delta) * direction;
}

/*
 * This is the gamma correction function that I included a lookup table for in
 * shiftbrite.h. It's used here to map a uniform distribution to something skewed
 * heavily towards the low end.
 *
 * Basically I want my targeting Tickers to fade slowly most of the time but do a
 * really quick flicker every once in a while.
 */
int16_t skew(int16_t x, int16_t exponent, int16_t max_out, int16_t range)
{
	return (int16_t)(pow((float)x / (float)range, exponent) * max_out + 1);
}

/*
 * This function converts an HSV value into an RGB value.
 * Code taken from StackOverflow user DavidH:
 *   http://stackoverflow.com/questions/3018313/algorithm-to-convert-rgb-to-hsv-and-hsv-to-rgb-in-range-0-255-for-both
 */
TickerRgb hsv2rgb(double hue, double sat, double value)
{
	double sextant, chroma, q, t, ff;
	double red, blue, green;
	long  i;
	TickerRgb   out;

	if(sat <= 0.0) {
		red   = value;
		green = value;
		blue  = value;
		return out;
	}

	sextant = hue;
	if(sextant >= 360.0) sextant = 0.0;
	sextant /= 60.0;
	i = (long)sextant;
	ff = sextant - i;
	chroma = value * (1.0 - sat);
	q = value * (1.0 - (sat * ff));
	t = value * (1.0 - (sat * (1.0 - ff)));

	switch(i) {
		case 0:
			red   = value;
			green = t;
			blue  = chroma;
			break;
		case 1:
			red   = q;
			green = value;
			blue = chroma;
			break;
		case 2:
			red   = chroma;
			green = value;
			blue  = t;
			break;
		case 3:
			red   = chroma;
			green = q;
			blue  = value;
			break;
		case 4:
			red   = t;
			green = chroma;
			blue  = value;
			break;
		case 5:
		default:
			red   = value;
			green = chroma;
			blue  = q;
			break;
	}
	out.red   = (int16_t)(red   * 1023);
	out.green = (int16_t)(green * 1023);
	out.blue  = (int16_t)(blue  * 1023);
	return out;
}

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


Nonce pool should be post-incremented instead of pre-incremented

Signed-off-by: Edi Permadi <163b49ac0c44ca5b49677bf42f3f8680b3bd9867@gmail.com>

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/edipermadi/teensy-hsm.git/'


improved error handling for nduino comm

improved error handling for nduino comm

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


fixed TX_REPEAT typo in nduino

fixed TX_REPEAT typo in nduino


Basic one-wire temperature sensor sketch

#include <OneWire.h>
#include <DallasTemperature.h>

// Data wire is plugged into port 2 on the Arduino
#define ONE_WIRE_BUS 2

// State variables
bool enabled = false;
byte targetTempF = 0;

// Setup a oneWire instance to communicate with OneWire devices
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to the Dallas Temperature library
DallasTemperature sensors(&oneWire);
DeviceAddress thermometer;

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

    sensors.begin();
    if (!sensors.getAddress(thermometer, 0)) {
        Serial.println("Unable to find address for Device 0");
    }

    sensors.setResolution(thermometer, 9);
}

float temperature()
{
    return DallasTemperature::toFahrenheit(sensors.getTempC(thermometer));
}

void loop()
{
    // Wait for serial data
    while (!Serial.available());
    byte cmd = Serial.read();
    if (cmd == '0') {
        // 0: Get status
        // Send the command to get temperatures
        sensors.requestTemperatures();
        // Print the received temperature
        Serial.print("Enabled: ");
        Serial.print(enabled);
        Serial.print(", temp F: ");
        Serial.print(temperature());
        Serial.print(", target F: ");
        Serial.println(targetTempF);
    } else if (cmd == '1') {
        // 1: Turn on heater
        enabled = true;
        Serial.println("Heater on");
    } else if (cmd == '2') {
        // 2: Turn off heater
        enabled = false;
        Serial.println("Heater off");
    } else if (cmd == '3') {
        // 3: Set target temperature
        while (!Serial.available());
        targetTempF = Serial.read();
        Serial.print("Set temp to ");
        Serial.println(targetTempF);
    } else {
        while (Serial.available()) {
            Serial.read();
        }
    }
}

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


Issue #2 Debugging for every action and state of the device

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/franciscoalario/GoldenAnt.git/'


added example files

added example files

#include <Servo.h>
#include <RobotArm.h>

RobotArm arm(1,2,3,4,5);

void setup() {
}

void loop() {
  arm.updateJoint(RobotArm::BASE,125);
}

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


Kill interrupts during reading an math period.

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/spoollord/MyOurWeather.git/'


Add updated sketch with range detection average

#include "Arduino.h"
#include "Adafruit_NeoPixel.h"
#include "Servo.h"

// Base Date
const uint8_t initialDelay = 2500;

// Ranges and Data
const uint8_t rangeLimit_Warning1 = 50;
const uint8_t rangeLimit_Warning2 = 40;
const uint8_t rangeLimit_Warning3 = 25;
const uint8_t rangeLimit_Stop = 15;

const uint16_t rangeLimit_RotateFor = 500;
unsigned long rangeLimit_Timestamp = 0;
bool wheelSpinCompleted = true;

// Ultrasonic Sensor
const uint8_t trigPin = 9;
const uint8_t echoPin = 10;

long rangeData_Left[15];
long average_Left;
long rangeData_Center[10];
long average_Center;
long rangeData_Right[15];
long average_Right;
uint8_t rangeDataIndex = 0;

// LED
const uint8_t ledPin = 11;
const bool ledBatterySaving = true;
Adafruit_NeoPixel LEDStrip = Adafruit_NeoPixel(26, ledPin, NEO_GRB + NEO_KHZ800);

// Motor / Wheels
const uint8_t motorPin1_1 = 4;
const uint8_t motorPin1_2 = 5;

const uint8_t motorPin2_1 = 7;
const uint8_t motorPin2_2 = 8;

const uint8_t motorEnablePin = 3;

// Ultrasonic Servo
Servo ServoMotor;
const uint8_t servoPin = 6;
const uint8_t servoRotationAngel = 10;

enum direction {
  left,
  center,
  right
};

uint8_t servoPos = 90;
direction servoMovement = right;
direction servoLocation = center;

void setup()
{
    // Scanner
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input

    rangeLimit_Timestamp = millis();

    pinMode(motorEnablePin, OUTPUT);
    analogWrite(motorEnablePin, 255);

    // Motor
    pinMode(motorPin1_1, OUTPUT);
    pinMode(motorPin1_2, OUTPUT);

    pinMode(motorPin2_1, OUTPUT);
    pinMode(motorPin2_2, OUTPUT);

    Serial.begin(9600); // Starts the serial communication

    LEDStrip.begin();
    LEDStrip.show(); // Initialize all pixels to 'off'

    // attach servo pin and set to initial direction
    ServoMotor.attach(servoPin);
    ServoMotor.write(servoPos);
}

long MicrosecondsToCentimeters(long microseconds)
{
    return microseconds / 29 / 2;
}

// Use library to minimize delay
long GetUltrasoundRange()
{
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

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

    long duration = pulseIn(echoPin, HIGH);

    // convert the time into a distance
    return MicrosecondsToCentimeters(duration);
}

void CalculateAverageRange()
{
    long range = GetUltrasoundRange();
    long **rangeData_Current;

    // get current meassurement and add to array
    if(servoLocation == left)
    {
        rangeData_Left[rangeDataIndex++] = range;
        rangeData_Current = rangeData_Left;
    }

    if(servoLocation == center)
    {
        rangeData_Center[rangeDataIndex++] = range;
        rangeData_Current = rangeData_Center;
    }

    if(servoLocation == right)
    {
        rangeData_Right[rangeDataIndex++] = range;
        rangeData_Current = rangeData_Right;
    }

    direction servoLocationLast = servoLocation;
    direction servoMovementLast = servoMovement;

    // Get the next Angle and Move the Servo
    ServoMotor.write(GetNextServoAngle());

    // if the new servo location is different from the one before calculate an anverage
    if(servoLocation != servoLocationLast || servoMovement != servoMovementLast)
    {
        long summedUp = 0;
        for (int i = 0; i < rangeDataIndex; i++)
        {
            summedUp += rangeData_Current[i];
            rangeData_Current[i] = 0;
        }

        long average = summedUp/rangeDataIndex;
        if(servoLocationLast == left) { average_Left = average; }
        if(servoLocationLast == center) { average_Center = average; }
        if(servoLocationLast == right) { average_Right = average; }

        rangeDataIndex = 0;
    }
}

void SetMotor(int pin1, int pin2, int speed)
{
    if (speed < 0)
    {
        analogWrite(pin1, 0);
        analogWrite(pin2, 255);
    }
    else
    {
        analogWrite(pin1, 255);
        analogWrite(pin2, 0);
    }

    if (speed == 0)
    {
        analogWrite(pin1, 0);
        analogWrite(pin2, 0);
    }
}

void ColorSet(uint32_t c)
{
    for(uint16_t i=0; i < LEDStrip.numPixels(); i++)
    {
        if(ledBatterySaving && i%4 == 0 || !ledBatterySaving)
        {
            LEDStrip.setPixelColor(i, c);
        }
    }
    LEDStrip.show();
}

uint8_t GetNextServoAngle()
{
    // 0 - 80 / 80 - 100 / 100 - 180
    if(servoPos <= 0)
    {
        servoMovement = right;
        servoPos = 0;
    }

    if(servoPos >= 180)
    {
        servoMovement = left;
        servoPos = 180;
    }

    if(servoMovement == right)
    {
        servoPos += servoRotationAngel;
    }
    else
    {
        servoPos -= servoRotationAngel;
    }

    if(servoPos < 80)
    {
        servoLocation = left;
    }

    if(servoPos >= 80 && servoPos <= 100)
    {
        servoLocation = center;
    }

    if(servoPos > 100)
    {
        servoLocation = right;
    }

    return servoPos;
}

void SetLightByRange(long range)
{
    uint32_t color = LEDStrip.Color(0, 255, 0);
    if(range < rangeLimit_Warning1) { color = LEDStrip.Color(127, 255, 0);}
    if(range < rangeLimit_Warning2) { color = LEDStrip.Color(255, 255, 0); }
    if(range < rangeLimit_Warning3) { color = LEDStrip.Color(255, 127, 0); }
    if(range < rangeLimit_Stop) { color = LEDStrip.Color(255, 0, 0); }

    ColorSet(color);
}

void ErrorState()
{
    ColorSet(LEDStrip.Color(0, 0, 255));

    SetMotor(motorPin1_1, motorPin1_2, 0);
    SetMotor(motorPin2_1, motorPin2_2, 0);
}

void loop()
{

    CalculateAverageRange();

    /*
    average_Left
    average_Center
    average_Right
    */

    long range = average_Center;

    SetLightByRange(range);

    if(millis() < initialDelay)
    {
        return;
    }

    // maybe wait for x seconds before starting so a full
    // left center right scan can be performed first

    // obstacle is further away than X cm
    if(wheelSpinCompleted && range > rangeLimit_Stop)
    {
        // drive
        SetMotor(motorPin1_1, motorPin1_2, 255);
        SetMotor(motorPin2_1, motorPin2_2, 255);

        rangeLimit_Timestamp = millis();
    }
    else
    {

        // TODO

        // rotate
        SetMotor(motorPin1_1, motorPin1_2, -255);
        SetMotor(motorPin2_1, motorPin2_2, 255);

        wheelSpinCompleted = false;

        if(range > rangeLimit_Warning3 && (rangeLimit_Timestamp + rangeLimit_RotateFor) <= millis())
        {
            wheelSpinCompleted = true;
        }
    }
}

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


Pressure Mat code for MOAD

Pressure Mat code for MOAD

#include <Dhcp.h>
#include <Dns.h>
#include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp.h>
#include <util.h>

#include <SPI.h>

int requestID = 1;

// The MAC address of your Ethernet board (or Ethernet Shield) is located on the back of the curcuit board.
byte mac[] = { 0x0, 0xA2, 0xDA, 0x0D, 0x90, 0xE2 };  // Arduino Ethernet

char packetBuffer[512];

PROGMEM prog_char *loopPacket1 = "{\"path\":\"/api/v1/thing/reporting\",\"requestID\":\"";
PROGMEM prog_char *loopPacket2 = "\",\"things\":{\"/device/sensor/arduino/mat\":{\"prototype\":{\"device\":{\"name\":\"60# pressure mat (902PR)\",\"maker\":\"United Security Products\"},\"name\":\"true\",\"status\":[\"present\",\"absent\",\"recent\"],\"properties\":{\"pressure\":[\"on\",\"off\"]}},\"instances\":[{\"name\":\"Pressure Mat\",\"status\":\"present\",\"unit\":{\"serial\":\"";
PROGMEM prog_char *loopPacket3 = "\",\"udn\":\"195a42b0-ef6b-11e2-99d0-";
PROGMEM prog_char *loopPacket4 = "-mat\"},\"info\":{\"pressure\":\"";
PROGMEM prog_char *loopPacket5 = "\"},\"uptime\":\"";
PROGMEM prog_char *loopPacket6 = "\"}]}}}";

// All TSRP transmissions are via UDP to port 22601 on multicast address '224.192.32.19'.
EthernetUDP udp;
IPAddress ip(224,192,32,19);
unsigned int port = 22601;

const int buttonPin = 7;
int buttonState;
int lastButtonState = LOW;
int sentPacket = 0;

long lastDebounceTime = 0;
long debounceDelay = 50;

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

  Serial.begin(9600);
  Serial.println("Starting...");
  while(!Serial) { }

  Serial.println("Waiting for DHCP address.");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Error: Failed to configure Ethernet using DHCP");
    while(1) {  }
  }

  Serial.print("MAC address: ");
  for (byte thisByte = 0; thisByte < 6; thisByte++) {
    Serial.print(mac[thisByte], HEX);
    Serial.print(":");
  }
  Serial.println();

  Serial.print("IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();

  udp.beginMulti(ip,port);

}

void loop() {
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState) {
    lastDebounceTime = millis();
  }
  if ((millis() - lastDebounceTime) > debounceDelay) {
    buttonState = reading;
    //Serial.print( "Button state = " );
    //Serial.println( buttonState );
    if ( buttonState && !sentPacket ) {
       Serial.println("Sending pressure = on");
       sentPacket = 1;
       requestID = requestID + 1;

       char buffer[12];
       strcpy(packetBuffer,(char*)pgm_read_word(&loopPacket1) );
       strcat(packetBuffer, itoa( requestID, buffer, 10) );
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket2) );
       for (byte thisByte = 0; thisByte < 6; thisByte++) {
         sprintf(buffer, "%x", mac[thisByte] );
         strcat(packetBuffer, buffer);
       }
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket3) );
       for (byte thisByte = 0; thisByte < 6; thisByte++) {
         sprintf(buffer, "%x", mac[thisByte] );
         strcat(packetBuffer, buffer);
       }
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket4) );
       strcat(packetBuffer, "on");
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket5) );
       strcat(packetBuffer, itoa( millis()/1000, buffer, 10) );
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket6) );

       Serial.println(packetBuffer);
       udp.beginPacket(udp.remoteIP(), udp.remotePort());
       udp.write(packetBuffer);
       udp.endPacket();

    } else if ( !buttonState && !sentPacket ) {
       Serial.println("Sending pressure = off");
       sentPacket = 1;
       requestID = requestID + 1;

       char buffer[12];
       strcpy(packetBuffer,(char*)pgm_read_word(&loopPacket1) );
       strcat(packetBuffer, itoa( requestID, buffer, 10) );
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket2) );
       for (byte thisByte = 0; thisByte < 6; thisByte++) {
         sprintf(buffer, "%x", mac[thisByte] );
         strcat(packetBuffer, buffer);
       }
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket3) );
       for (byte thisByte = 0; thisByte < 6; thisByte++) {
         sprintf(buffer, "%x", mac[thisByte] );
         strcat(packetBuffer, buffer);
       }
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket4) );
       strcat(packetBuffer, "off");
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket5) );
       strcat(packetBuffer, itoa( millis()/1000, buffer, 10) );
       strcat(packetBuffer,(char*)pgm_read_word(&loopPacket6) );

       Serial.println(packetBuffer);
       udp.beginPacket(udp.remoteIP(), udp.remotePort());
       udp.write(packetBuffer);
       udp.endPacket();

   }

  }

  if ( lastButtonState != reading ) {
     sentPacket = 0;
  }
  lastButtonState = reading;

    /*

    char buffer[12];

    strcpy(packetBuffer,(char*)pgm_read_word(&loopPacket1) );
    strcat(packetBuffer, itoa( requestID, buffer, 10) );
    strcat(packetBuffer,(char*)pgm_read_word(&loopPacket2) );
    for (byte thisByte = 0; thisByte < 6; thisByte++) {
      sprintf(buffer, "%x", mac[thisByte] );
      strcat(packetBuffer, buffer);
    }
    strcat(packetBuffer,(char*)pgm_read_word(&loopPacket3) );
    for (byte thisByte = 0; thisByte < 6; thisByte++) {
      sprintf(buffer, "%x", mac[thisByte] );
      strcat(packetBuffer, buffer);
    }
    strcat(packetBuffer,(char*)pgm_read_word(&loopPacket4) );
    strcat(packetBuffer, dtostrf(t,4,2,buffer));
    strcat(packetBuffer,(char*)pgm_read_word(&loopPacket5) );
    strcat(packetBuffer, dtostrf(h,4,2,buffer));
    strcat(packetBuffer,(char*)pgm_read_word(&loopPacket6) );
    strcat(packetBuffer, itoa( millis()/1000, buffer, 10) );
    strcat(packetBuffer,(char*)pgm_read_word(&loopPacket7) );

    Serial.println(packetBuffer);
    udp.beginPacket(udp.remoteIP(), udp.remotePort());
    udp.write(packetBuffer);
    udp.endPacket();

    */

}

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


add new Arilux example

add new Arilux example

#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>
#include <PubSubClient.h>   // https://github.com/knolleary/pubsubclient
#include <ArduinoJson.h>    // https://github.com/bblanchon/ArduinoJson
#include <WS2812FX.h>       // https://github.com/kitesurfer1404/WS2812FX

#include "config.h"

struct RGBW {
  uint8_t red;
  uint8_t green;
  uint8_t blue;
  uint8_t white;
  bool    isWhiteSelected;
  uint8_t brightness;
};

WiFiClient    wifiClient;
PubSubClient  mqttClient(wifiClient);
WS2812FX      ws2812fx = WS2812FX(1, NULL, NEO_RGBW);
RGBW          rgbw = {PWM_MIN,PWM_MIN,PWM_MIN,PWM_MIN,false,PWM_MAX};

long lastReconnectAttempt = 0;
bool newStateToPublish = false;

///////////////////////////////////////////////////////////////////////////////////////////////
// LIGHT
///////////////////////////////////////////////////////////////////////////////////////////////
uint8_t getRedValueFromRGB(uint32_t p_color) {return p_color >> 16;}
uint8_t getGreenValueFromRGB(uint32_t p_color) {return p_color >> 8;}
uint8_t getBlueValueFromRGB(uint32_t p_color) {return p_color;}

void customShow(void) {
  // get the current color
  uint32 rgb = ws2812fx.getPixelColor(0);

  // retrieve the value for each channel
  rgbw.red =    getRedValueFromRGB(rgb);
  rgbw.green =  getGreenValueFromRGB(rgb);
  rgbw.blue =   getBlueValueFromRGB(rgb);

  // set each channel with the new value
  analogWrite(RED_PIN,    map(rgbw.red,   PWM_MIN, PWM_MAX, PWM_MIN, rgbw.brightness));
  analogWrite(GREEN_PIN,  map(rgbw.green, PWM_MIN, PWM_MAX, PWM_MIN, rgbw.brightness));
  analogWrite(BLUE_PIN,   map(rgbw.blue,  PWM_MIN, PWM_MAX, PWM_MIN, rgbw.brightness));
  analogWrite(WHITE_PIN,  map(rgbw.white, PWM_MIN, PWM_MAX, PWM_MIN, rgbw.brightness));
}

void setupLight(void) {
  // set the pins as output
  pinMode(RED_PIN,    OUTPUT);
  pinMode(GREEN_PIN,  OUTPUT);
  pinMode(BLUE_PIN,   OUTPUT);
  pinMode(WHITE_PIN,  OUTPUT);

  analogWriteFreq(PWM_FREQUENCY);
  analogWriteRange(PWM_MAX);

  ws2812fx.init();
  ws2812fx.setColor(GREEN);
  ws2812fx.stop();
  ws2812fx.setCustomShow(customShow);
}

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

void callback(char* p_topic, byte* p_payload, unsigned int p_length) {
  String topic(p_topic);

  if (topic.equals(MQTT_CMD_TOPIC)) {
    DynamicJsonBuffer dynamicJsonBuffer;
    JsonObject& root = dynamicJsonBuffer.parseObject(p_payload);

    // check if the payload contains a new state
    if (root.containsKey("state")) {
      if (strcmp(root["state"], MQTT_STATE_ON_PAYLOAD) == 0) {
        if (ws2812fx.isRunning() == false) {
          if (rgbw.isWhiteSelected == true) {
            rgbw.white = PWM_MAX;
          }

          ws2812fx.start();
          newStateToPublish = true;
        }
      } else if (strcmp(root["state"], MQTT_STATE_OFF_PAYLOAD) == 0) {
        if (ws2812fx.isRunning() == true) {
          if (rgbw.isWhiteSelected == true) {
            rgbw.white = PWM_MIN;
          }

          ws2812fx.stop();
          newStateToPublish = true;
        }
      }
    }

    // check if the payload contains a new color value
    if (root.containsKey("color")) {
      uint8_t red = root["color"]["r"];
      uint8_t green = root["color"]["g"];
      uint8_t blue = root["color"]["b"];

      if ((red >= PWM_MIN || red <= PWM_MAX) && (green >= PWM_MIN || green <= PWM_MAX) && (blue >= PWM_MIN || blue <= PWM_MAX)) {
        rgbw.white = PWM_MIN;
        rgbw.isWhiteSelected = false;
        ws2812fx.setColor(red, green, blue);
        newStateToPublish = true;
      }
    }

    // check if the payload contains a new brightness value
    if (root.containsKey("brightness")) {
      uint8_t brightness = root["brightness"];

      if (brightness >= PWM_MIN || brightness <= PWM_MAX) {
        rgbw.brightness = brightness;
        newStateToPublish = true;
      }
    }

    // check if the payload contains a new white value
    if (root.containsKey("white_value")) {
      uint8_t white_value = root["white_value"];

      if (white_value >= PWM_MIN || white_value <= PWM_MAX) {
        rgbw.white = PWM_MAX;
        rgbw.brightness = white_value;
        rgbw.isWhiteSelected = true;
        ws2812fx.setColor(0, 0, 0);
        newStateToPublish = true;
      }
    }
  }
}

void sendState(void) {
  DynamicJsonBuffer dynamicJsonBuffer;
  JsonObject& root = dynamicJsonBuffer.createObject();
  root["state"] = ws2812fx.isRunning() ? MQTT_STATE_ON_PAYLOAD : MQTT_STATE_OFF_PAYLOAD;
  root["brightness"] = rgbw.brightness;
  JsonObject& color = root.createNestedObject("color");
  color["r"] = rgbw.red;
  color["g"] = rgbw.green;
  color["b"] = rgbw.blue;
  root["white_value"] = rgbw.white == 0 ? 0 : rgbw.brightness;

  char tmp[128] = {0};
  root.printTo(tmp);
  mqttClient.publish(MQTT_STATE_TOPIC, tmp);
}

bool reconnect() {
  if (mqttClient.connect(DEVICE_NAME, MQTT_USERNAME, MQTT_PASSWORD, MQTT_AVAILABILITY_TOPIC, 0, 1, "offline")) {
    mqttClient.subscribe(MQTT_CMD_TOPIC);
    mqttClient.publish(MQTT_AVAILABILITY_TOPIC, "online");

    sendState();
  }
  return mqttClient.connected();
}

void setupMQTT(void) {
  mqttClient.setServer(MQTT_SERVER, MQTT_SERVER_PORT);
  mqttClient.setCallback(callback);
}

///////////////////////////////////////////////////////////////////////////////////////////////
// WIFI
///////////////////////////////////////////////////////////////////////////////////////////////

void setupWiFi(void) {
  Serial.print("Connecting to ");
  Serial.println(WIFI_SSID);

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

///////////////////////////////////////////////////////////////////////////////////////////////
// SETUP and LOOP
///////////////////////////////////////////////////////////////////////////////////////////////

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

  setupWiFi();

  setupMQTT();

  setupLight();

  ArduinoOTA.begin();
}

void loop() {
  if (!mqttClient.connected()) {
    long now = millis();
    if (now - lastReconnectAttempt > 5000) {
      lastReconnectAttempt = now;
      if (reconnect())
        lastReconnectAttempt = 0;
    }
  } else {
    mqttClient.loop();
  }

  ws2812fx.service();

  yield();

  if (newStateToPublish) {
    newStateToPublish = false;
    sendState();
  }

  yield();

  ArduinoOTA.handle();
}

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


Add media keys

Add media keys

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/mvines/futboard.git/'


just another git test

just another git test

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


Adding an example for DC Motor Driver

Adding an example for DC Motor Driver

/*
 * This example uses HC-SR04 distance sensor to detect obstacles and change course.
 *
 * Dependencies:
 *    Wire
 *    Adafruit_Motor_Shield_V2_Library
 *    BackSeatDriver
 *    BackSeatDriver_DCMotorAdapter
 *    NewPing
 *
 * Created on: Jul 17, 2014
 *
 * Author: Konstantin Gredeskoul
 *
 * © 2014 All rights reserved.  Please see LICENSE.
 *
 */

#include <NewPing.h>

#define TRIGGER_PIN  13   // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN     12   // Arduino pin tied to echo pin on the ultrasonic sensor.
#define MAX_DISTANCE 100  // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

#include <BackSeatDriver_DCMotorAdapter.h>
#include <BackSeatDriver.h>

signed short motorLayout[] = { 1, -2, -3, 4};
uint8_t ledPin1 = 4, ledPin2 = 11, ledPin3 = 8;

#define OBSTACLE_DISTANCE_TURN 40
#define OBSTACLE_DISTANCE_SLOWDOWN 70

BackSeatDriver_DCMotorAdapter *adapter;
BackSeatDriver *bot;

bool running = true, led1 = false, led2 = false, led3 = false;

static uint8_t speed = 100;
static unsigned int spaceAfterTurn;
static unsigned int lastSpaceAhead = 0, x = 0, maneuverSpaceAhead;
static const uint8_t sonarCheckPeriodMs = 30; // don't check more often than that
static unsigned short lastSonarAtMs = 0;

// speed can go up to 255
static uint32_t startMs = 0;
static const bool debug = true;

char buffer[128];

// blinky shit

void light1(bool on) {
	led1 = on;
	led1 ? digitalWrite(ledPin1, HIGH) : digitalWrite(ledPin1, LOW);
}
void light2(bool on) {
	led2 = on;
	led2 ? digitalWrite(ledPin2, HIGH) : digitalWrite(ledPin2, LOW);
}
void light3(bool on) {
	led3 = on;
	led3 ? digitalWrite(ledPin3, HIGH) : digitalWrite(ledPin3, LOW);
}

void blink1() {
	light1(!led1);
}

void blink2() {
	light2(!led2);
}

void blink3() {
	light3(!led3);
}

//_______________________________________________________________________
//
// Sonar Navigation

unsigned int spaceAhead() {
	if (millis() > sonarCheckPeriodMs + lastSonarAtMs) {
		lastSonarAtMs = millis();
		unsigned int value = sonar.ping() / US_ROUNDTRIP_CM;
		if (debug && value > 0 && value < OBSTACLE_DISTANCE_SLOWDOWN) {
			sprintf(buffer, "spaceAhead is %d", value);
			bot->log(buffer);
		}
		lastSpaceAhead = (value == 0) ? MAX_DISTANCE : value;
	}
	return lastSpaceAhead;
}

bool navigateWithSonar() {
	int distance = spaceAhead();
	maneuverSpaceAhead = 0;
	if (distance <= OBSTACLE_DISTANCE_TURN) {
		turnAndCheck();
		maneuverSpaceAhead = distance;
		light1(true);
		light2(true);
		light3(false);
		return true;
	} else if (distance > OBSTACLE_DISTANCE_TURN
			&& distance < OBSTACLE_DISTANCE_SLOWDOWN) {
		// reduce speed
		speed = 100 - (OBSTACLE_DISTANCE_SLOWDOWN - distance) / 2;
		light1(true);
		light2(false);
		light3(false);
	} else if (distance >= OBSTACLE_DISTANCE_SLOWDOWN) {
		speed = 100;
		light1(false);
		light2(false);
	}
	return false;
}

void turnAndCheck() {
	signed short angle = (rand() % 2 == 1) ? 45 : -45;
	bot->turn(angle, &checkOnce);
}

void checkOnce(uint8_t type, signed short parameter) {
	signed short angle = (parameter == -45) ? 90 : -90;
	spaceAfterTurn = spaceAhead();
	if (spaceAfterTurn < maneuverSpaceAhead)
		bot->turn(angle, &checkTwice);
}

void checkTwice(uint8_t type, signed short parameter) {
	signed short angle = (parameter == -90) ? -135 : 135;
	spaceAfterTurn = spaceAhead();
	if (spaceAfterTurn < maneuverSpaceAhead)
		bot->turn(angle, NULL);
}

void leftTurn90(uint8_t type, signed short parameter) 	{
	delay(1000); bot->turn(-90,  &rightTurn90);
}
void rightTurn90(uint8_t type, signed short parameter)	{
	delay(1000); bot->turn( 90, &leftTurn90);
}
void goBack() {
	bot->goBackward(70, 600, &turnAround);
}
void turnAround(uint8_t type, signed short parameter) {
	bot->turn(180, NULL);
}

//______________________________________________________________

void setup() {
	Serial.begin(9600);
	Serial.println("Racer Starting...");
	srand(millis());

	pinMode(ledPin1, OUTPUT);
	pinMode(ledPin2, OUTPUT);
	pinMode(ledPin3, OUTPUT);

	adapter = new BackSeatDriver_DCMotorAdapter(4, motorLayout);

	bot = new BackSeatDriver(adapter);
	bot->attach();
	bot->debug(true);
	bot->setMovingSpeedPercent(70);
	bot->setTurningDelayCoefficient(6);
	bot->setTurningSpeedPercent(70);

	startMs = millis();

}

void loop() {
	if (!bot->isManeuvering() && running) {
		light3(true);
		bot->goForward(speed);
		navigateWithSonar();
	}

}

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


reverted to original arduino controller

reverted to original arduino controller


DateTime tests

DateTime tests

/**
 * Modified version of jcw "datecalc" example sketch in the RTClib directory.
 * Used to test various date calculations.
 *
 * Original sketch:
 * 2010-02-04 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php
 * Modifications
 * 2015-08-15 <bill@jamimi.com> http://opensource.org/licenses/mit-license.php
 */

#include <Wire.h>
#include <RTClib.h>

void showDate(const char* txt, const DateTime& dt) {
    Serial.print(txt);
    Serial.print(' ');
    Serial.print(dt.year(), DEC);
    Serial.print('/');
    Serial.print(dt.month(), DEC);
    Serial.print('/');
    Serial.print(dt.day(), DEC);
    Serial.print(' ');
    Serial.print(dt.hour(), DEC);
    Serial.print(':');
    Serial.print(dt.minute(), DEC);
    Serial.print(':');
    Serial.print(dt.second(), DEC);

    Serial.print(" = ");
    Serial.print(dt.get());
    Serial.print("s / ");
    Serial.print(dt.get() / 86400L);
    Serial.print("d since 2000");

    Serial.println();
}

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

    DateTime dtn (__DATE__, __TIME__);
    showDate("dtn", dtn);

    DateTime dtn1 (dtn.year(), dtn.month(), dtn.day(), dtn.hour(), dtn.minute() + 1, 0);
    showDate("dtn1", dtn1);

    DateTime dtn2 (dtn.get() + 30);
    showDate("dtn2", dtn2);

    DateTime dt0 (0, 1, 1);
    showDate("dt0", dt0);

    DateTime dt1 (1, 1, 1);
    showDate("dt1", dt1);

    DateTime dt2 (2009, 1, 1, 0, 0, 0);
    showDate("dt2", dt2);

    DateTime dt3 (2009, 1, 2, 0, 0, 0);
    showDate("dt3", dt3);

    DateTime dt4 (2009, 1, 27, 0, 0, 0);
    showDate("dt4", dt4);

    DateTime dt5 (2009, 2, 27, 0, 0, 0);
    showDate("dt5", dt5);

    DateTime dt6 (2009, 12, 27, 0, 0, 0);
    showDate("dt6", dt6);

    DateTime dt7 = dt6.get() + 3600; // one hour later
    showDate("dt7", dt7);

    DateTime dt8 = dt6.get() + 86400L; // one day later
    showDate("dt8", dt8);

    DateTime dt9 = dt6.get() + 7 * 86400L; // one week later
    showDate("dt9", dt9);
}

void loop () {
}

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


first commit

first commit

#include <DHT.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>

#define DHTPIN 2
#define DHTTYPE DHT11
#define DHTALIM 3
#define TRANSCEIVERALIM 4

DHT dht(DHTPIN, DHTTYPE);

int f_wdt=1;
int sleep_count=0;
int ack=0;

void setup() {
  Serial.begin(9600);
  dht.begin();
  pinMode(DHTALIM, OUTPUT);
  pinMode(TRANSCEIVERALIM, OUTPUT);

  /* Clear the reset flag. */
  MCUSR &= ~(1<<WDRF);

  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   */
  WDTCSR |= (1<<WDCE) | (1<<WDE);

  /* set new watchdog timeout prescaler value */
  WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */

  /* Enable the WD interrupt (note no reset). */
  WDTCSR |= _BV(WDIE);
}

void loop() {
  if((f_wdt == 1) && (sleep_count >= 0))
  {

    Serial.println("UP!");

    digitalWrite(DHTALIM, HIGH);
    digitalWrite(TRANSCEIVERALIM, HIGH);
    delay(3000);

    float h = dht.readHumidity();
    float t = dht.readTemperature();
    byte h_b;
    byte t_b;
    h_b = (byte) h;
    t_b = (byte) t;

    digitalWrite(DHTALIM, LOW);

    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
    }
    else {
      while (sendData(t_b, h_b) != 69)
      {
        delay(50);
      }
    }
    digitalWrite(TRANSCEIVERALIM, LOW);

    /* Don't forget to clear the flag. */
    f_wdt = 0;

    sleep_count = 0;

    /* Re-enter sleep mode. */
    Serial.println("go back to sleep");
    delay(50);
    enterSleep();
  }
  else if(f_wdt == 1)
  {
    sleep_count++;
    f_wdt = 0;
    enterSleep();
  }
  else
  {
    /* Do nothing. */
  }
}

ISR(WDT_vect)
{
  if(f_wdt == 0)
  {
    f_wdt=1;
  }
  else
  {
    Serial.println("WDT Overrun!!!");
  }
}

void enterSleep(void)
{
  Serial.println("zzzzzz");
  delay(50);
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);   /* EDIT: could also use SLEEP_MODE_PWR_DOWN for lowest power consumption. */
  sleep_enable();

  /* Now enter sleep mode. */
  sleep_mode();

  /* The program will continue from here after the WDT timeout*/
  sleep_disable(); /* First thing to do is disable sleep. */

  /* Re-enable the peripherals. */
  power_all_enable();
}

int sendData(int temp, int hum)
{
  ack = 0;
  //dummy bytes
  Serial.write(169);
  Serial.write(244);
  Serial.write(190);
  //humidity
  Serial.write(hum);
  //255 - humidity
  Serial.write(255-hum);
  //temperature + 25
  //(temperature can be negative)
  Serial.write(temp+25);
  //230 - temperature
  Serial.write(255-temp);
  //for redunduncy, temperature + humidity
  Serial.write(hum+temp);
  //temperature + humidity - 255
  Serial.write(hum+temp);
  //dummy bytes
  Serial.write(190);
  Serial.write(244);
  Serial.write(169);
  delay(200);
  if (Serial.available() > 0) {
    ack=Serial.read();
  }
  else {
    ack=0;
  }
  return ack;
}


Initial commit: basic Arduino firmware with identification command

/*
  MAX1464 library for Arduino
  Copyright (C) 2016 Giacomo Mazzamuto <gmazzamuto@gmail.com>

  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, see <http://www.gnu.org/licenses/>.
*/

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete

void printIden() {
    Serial.println("Arduino MAX1464 Serial Terminal");
}

void setup() {
  // initialize serial:
  Serial.begin(115200);
  printIden();
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

/*
  SerialEvent occurs whenever a new data comes in the
 hardware serial RX.  This routine is run between each
 time loop() runs, so using delay inside loop can delay
 response.  Multiple bytes of data may be available.
 */
void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
    else {
      // add it to the inputString:
      inputString += inChar;
    }
  }
}

void loop() {
  if (stringComplete) {
    inputString.toUpperCase();
    if(String("IDEN").startsWith(inputString)) {
      printIden();
    }
    else {
      Serial.print("Unknown input string: ");
      Serial.println(inputString);
    }

 // clear the string:
    inputString = "";
    stringComplete = false;
  }
}


Arduino code. Run before the Python file.

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
   // initialize the LED pins:
      for (int thisPin = 2; thisPin < 6; thisPin++) {
        pinMode(thisPin, OUTPUT);
      }

      for (int thisPin = 2; thisPin < 6; thisPin++) {
        digitalWrite(thisPin, HIGH);
      }

}

void loop() {
  // read the sensor:
  if (Serial.available() > 0) {
    int inByte = Serial.read();
    // do something different depending on the character received.
    // The switch statement expects single number values for each case;
    // in this exmaple, though, you're using single quotes to tell
    // the controller to get the ASCII value for the character.  For
    // example 'a' = 97, 'b' = 98, and so forth:

   // car controls
   // 2 = forward
   // 3 = backward
   // 4 = left
   // 5 = right

    switch (inByte) {

    case 'a':    //forward
      // turn all the LEDs off:
//      for (int thisPin = 2; thisPin < 6; thisPin++) {
//        digitalWrite(thisPin, HIGH);
//      }
      for (int thisPin = 4; thisPin < 6; thisPin++) {
        digitalWrite(thisPin, HIGH);
      }
      digitalWrite(2, LOW);
      break;

    case 'b':    //backward
//      for (int thisPin = 2; thisPin < 6; thisPin++) {
//        digitalWrite(thisPin, HIGH);
//      }
      for (int thisPin = 4; thisPin < 6; thisPin++) {
        digitalWrite(thisPin, HIGH);
      }
      digitalWrite(3, LOW);
      break;

    case 'c':    //forward left
//      for (int thisPin = 2; thisPin < 6; thisPin++) {
//        digitalWrite(thisPin, HIGH);
//      }
      digitalWrite(5, HIGH);
//      delay(50);
      digitalWrite(4, LOW);
      delay(100);
      digitalWrite(2, LOW);
      break;

    case 'd':    //forward right
//      for (int thisPin = 2; thisPin < 6; thisPin++) {
//        digitalWrite(thisPin, HIGH);
//      }
      digitalWrite(4, HIGH);
//      delay(50);
      digitalWrite(5, LOW);
      delay(100);
      digitalWrite(2, LOW);
      break;
    case 'e':    //backward left
//      for (int thisPin = 2; thisPin < 6; thisPin++) {
//        digitalWrite(thisPin, HIGH);
//      }
      digitalWrite(5, HIGH);
      digitalWrite(4, LOW);
      delay(100);
      digitalWrite(3, LOW);
      break;

    case 'f':    //backward right
//      for (int thisPin = 2; thisPin < 6; thisPin++) {
//        digitalWrite(thisPin, HIGH);
//      }
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      delay(100);
      digitalWrite(3, LOW);
      break;
    default:
      // turn all the LEDs off:
      for (int thisPin = 2; thisPin < 6; thisPin++) {
        digitalWrite(thisPin, HIGH);
      }
     }
     delay(400);
     for (int thisPin = 2; thisPin < 4; thisPin++) {
       digitalWrite(thisPin, HIGH);
//     for (int thisPin = 2; thisPin < 6; thisPin++) {
//       digitalWrite(thisPin, HIGH);
     //delay(100);
    }
  }
}

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


Correção de bugs Gateway

Correção de bugs Gateway

Gateway deveria jogar na saída serial 7 valores, porém estava com apenas 6

error: pathspec 'Arduino' did not match any file(s) known to git
error: pathspec 'sketchs/Reformulação/gateway/gateway.ino' did not match any file(s) known to git


Json decode's test in Arduino

Json decode's test in Arduino

#include <ArduinoJson.h>

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3
#define BUFFER_SIZE 500
#define BAUD_RATE 9600

void setup() {
	initSerial();
	pinMode(REDPIN, OUTPUT);
	pinMode(GREENPIN, OUTPUT);
	pinMode(BLUEPIN, OUTPUT);
}

void loop() {
	StaticJsonBuffer<200> jsonBuffer;

	char json[] = "{\"round\": {\"phase\": \"live\",\"bomb\": \"planted\"}}";
	JsonObject& root = jsonBuffer.parseObject(json);

	if (!root.success()) {
		Serial.println("parseObject() failed");
		return;
	}

	const char* bombStatus = root["round"]["bomb"];
	if(bombStatus == "planted") {

	}

	Serial.println(bombStatus);
}

void initSerial() {
	Serial.begin(BAUD_RATE);
	while (!Serial) {
	  ;
	}
	Serial.println("Serial ready");
}

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


Transmit Updated

Transmit Updated

#include <Adafruit_TCS34725.h>

Adafruit_TCS34725 tcs = Adafruit_TCS34725(TCS34725_INTEGRATIONTIME_2_4MS, TCS34725_GAIN_4X);
uint16_t red, green, blue, c, ered, egreen, eblue;
int r = 2;
int g = 3;
int b = 4;
int ledState = LOW;
int initDelay = 500;
int i = 0;

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

  pinMode(r, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(b, OUTPUT);
  Serial.begin(250000);

    if (tcs.begin()) {
    Serial.println("Found sensor");
  } else {
    Serial.println("Cannot find sensor");
    while (1);
  }
  tcs.getRawData(&ered, &egreen, &eblue, &c); //store environment values

}

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

  String str;
  if (Serial.available() > 0)
  {
    str = Serial.readString(); // read a single letter if (ch >= 'a' && ch <= 'z')

    if(str == "sync")
      synchronization();
    else
    {
    for(int j=0; j<str.length(); ++j)
    {
      Serial.print(str[j] + ": ");
      flashSequence(str[j]);
      i = 0;
    }
    }
    digitalWrite(r, LOW);
    digitalWrite(g, LOW);
    digitalWrite(b, LOW);
//delay(dotDelay * 4);

    }
}

void flashSequence(char sequence)
{
  bool out[8], parity[4];

  encodeASCII(sequence, out);
  addParity(out, parity);
  bool buff[12] = {parity[0], parity[1], out[0], parity[2], out[1], out[2], out[3], parity[3],
          out[4], out[5], out[6], out[7]};

  Serial.print(sequence);
  Serial.print(": ");

  tcs.getRawData(&red, &green, &blue, &c); //store environment values
  while(green < egreen*2)
  {
    tcs.getRawData(&red, &green, &blue, &c); //store environment values
  }
  bool first = true;
  while(i<12)
  {
    if(!first)
    {
      tcs.getRawData(&red, &green, &blue, &c); //store environment values
      while(blue < eblue*2)
      {
        tcs.getRawData(&red, &green, &blue, &c); //store environment values
      }
      while(blue < eblue*2)
      {
        tcs.getRawData(&red, &green, &blue, &c); //store environment values
      }
    }

    first = false;
    if(i % 3 == 0)
    {
      flashDotOrDash(2, buff[i]);
      i++;
    }
    if(i % 3 == 1)
    {
      flashDotOrDash(3, buff[i]);
      i++;
    }
    if(i % 3 == 2)
    {
      flashDotOrDash(4, buff[i]);
      i++;
    }
    delay(1000);
  }
  Serial.println();

}

void flashDotOrDash(int color, bool dotOrDash)
{
  Serial.print(dotOrDash);
  if(dotOrDash)
    digitalWrite(color, HIGH);
  else
   digitalWrite(color, LOW);
}

void synchronization(void)
{
  digitalWrite(r, HIGH);
  delay(initDelay);
  digitalWrite(r, LOW);

  digitalWrite(g, HIGH);
  delay(initDelay);
  digitalWrite(g, LOW);

  digitalWrite(b, HIGH);
  delay(initDelay);
  digitalWrite(b, LOW);

  digitalWrite(r, HIGH);
  digitalWrite(g, HIGH);
  delay(initDelay);
  digitalWrite(r, LOW);
  digitalWrite(g, LOW);

  digitalWrite(r, HIGH);
  digitalWrite(b, HIGH);
  delay(initDelay);
  digitalWrite(r, LOW);
  digitalWrite(b, LOW);

  digitalWrite(g, HIGH);
  digitalWrite(b, HIGH);
  delay(initDelay);
  digitalWrite(g, LOW);
  digitalWrite(b, LOW);

  digitalWrite(r, HIGH);
  digitalWrite(g, HIGH);
  digitalWrite(b, HIGH);
  delay(initDelay);
  digitalWrite(r, LOW);
  digitalWrite(g, LOW);
  digitalWrite(b, LOW);
  delay(initDelay);
}

void encodeASCII(char in, bool out[])
{
    for(int j = 0; j < 8; j++)
        out[j] = 0;

    out[0] = 0;
    if(in % 2)
        out[7] = 1;
    in = in / 2;
    if(in % 2)
        out[6] = 1;
    in = in / 2;
    if(in % 2)
        out[5] = 1;
    in = in / 2;
    if(in % 2)
        out[4] = 1;
    in = in / 2;
    if(in % 2)
        out[3] = 1;
    in = in / 2;
    if(in % 2)
        out[2] = 1;
    in = in / 2;
    if(in % 2)
        out[1] = 1;
    in = in / 2;
}

void addParity(bool data[], bool parity[])
{

  parity[0]=data[0]^data[1]^data[3]^data[4]^data[6];
  parity[1]=data[0]^data[2]^data[3]^data[5]^data[6];
  parity[2]=data[1]^data[2]^data[3]^data[7];
  parity[3]=data[4]^data[5]^data[6]^data[7];
}

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


Integration of the sound sensor and rfid

#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9

#define LIMIT 10

// Definicoes pino modulo RC522
MFRC522 mfrc522(SS_PIN, RST_PIN);

//Led para liberacao do rfid
int led_rfid = 5;

//Led para debug de ruido
int led_sound_sensor = 4;

//Definicao dos pinos do sensor de ruido
int pino_analogico = A5;
int pino_digital = 7;

int valor_A0 = 0;
int valor_D = 0;

int control_sound_sensor = 0;

int op = 0;

void getSoundSensor(){
	if(control_sound_sensor > LIMIT){
		op = 1;
		return;
	}
	// put your main code here, to run repeatedly:
  	valor_A0 = analogRead(pino_analogico);
 	valor_D = digitalRead(pino_digital);
 	Serial.print(valor_A0);
 	Serial.print(" ");
 	Serial.println(valor_D);
 	control_sound_sensor++;
}

void getRFID(){
	//Reset sound sensor
	op = 0;
	control_sound_sensor = 0;

	// Aguarda a aproximacao do cartao
  	if ( ! mfrc522.PICC_IsNewCardPresent())
  	{
   	 	return;
  	}
  	// Seleciona um dos cartoes
  	if ( ! mfrc522.PICC_ReadCardSerial())
  	{
   	 	return;
  	}

  	String conteudo = "";
  	byte letra;

  	for (byte i = 0; i < mfrc522.uid.size; i++)
  	{
     	conteudo.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     	conteudo.concat(String(mfrc522.uid.uidByte[i], HEX));
  	}

  	conteudo.toUpperCase();
  	//Enviar conteudo.substring(1) via serial
  	Serial.println(conteudo.substring(1));

  	digitalWrite(led_rfid, HIGH);
  	delay(200);
  	digitalWrite(led_rfid, LOW);
  	delay(200);
}

void setup(){
	// Inicia a serial
  	Serial.begin(9600);
  	//Led rifd sensor
	pinMode(led_rfid, OUTPUT);
	//Led sound sensor
	pinMode(led_sound_sensor, OUTPUT);
  	//inicia RFID
  	mfrc522.PCD_Init();
  	//Define pinos sensor como entrada
  	pinMode(pino_analogico, INPUT);
  	pinMode(pino_digital, INPUT);
}

void loop(){
	switch(op){
		case 0:
			getSoundSensor();
			break;
		case 1:
			getRFID();
			break;
	}
}

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


Create arduino.ino

Create arduino.ino

char incomingByte;  // incoming data
int  LED = 13;      // LED pin
int i = 0;

void setup() {
  Serial.begin(9600); // initialization
  pinMode(LED, OUTPUT);
  Serial.println("Press 1 to LED ON or 0 to LED OFF...");
}

void loop() {
  if (Serial.available() > 0) {  // if the data came
    incomingByte = Serial.read(); // read byte
    if(incomingByte == '0') {
       digitalWrite(LED, LOW);  // if 1, switch LED Off
       Serial.println("LED OFF. Press 1 to LED ON!");  // print message
    }
    if(incomingByte == '1') {
       digitalWrite(LED, HIGH); // if 0, switch LED on
       Serial.println("LED ON. Press 0 to LED OFF!");
    }

    if(incomingByte == '2') {
      Serial.println("LED ON. Press 0 to LED OFF!");
      for(i=0;i<10;i++){
       digitalWrite(LED, HIGH); // if 0, switch LED on
       delay(300);
       digitalWrite(LED, LOW); // if 0, switch LED on
       delay(300);
      }
    }
  }
}

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


Create wemos_remote.ino

Create wemos_remote.ino

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


arduino code updates

arduino code updates

error: pathspec 'src/arduino' did not match any file(s) known to git
error: pathspec 'code/delta5-race-timer-node/delta5-race-timer-node.ino' did not match any file(s) known to git


Update esp8266_remote.ino

Update esp8266_remote.ino


minor change

minor change

error: pathspec 'Sensor' did not match any file(s) known to git
error: pathspec 'Modules/Sound' did not match any file(s) known to git
error: pathspec 'Sensor/SoundSensorATtiny/SoundSensorATtiny.ino' did not match any file(s) known to git


Create Arduino.ino

Create Arduino.ino

/*
*An Arduino Sketch...
*Waiting to be uploaded
*...
*/

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


Added rpm and torque formulas that use measured motor datapoints (#define's). Un-broke loop due to missing flag. Added duty_cycle bump at the end of its while() loop so it could get back into it.

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


Added arduino firmware for single LED

Added arduino firmware for single LED

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/Annath/bamboo-monitor.git/'


add arduino code

add arduino code

long int cnt = 0;

void setup() {
  for(int i=0; i<=13; i++)
    pinMode(i, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  int tl = 500;
  cnt++;

  int d = cnt % 14;
  for(int i=0; i<=13; i++)
    digitalWrite(i, d==i ? HIGH : LOW);
  Serial.println(d);
  delay(tl);
}

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