added ADS1115 code arduino

added ADS1115 code arduino

added arduino example code for reading 1 channel using adafruit library

#include <Wire.h>
#include <Adafruit_ADS1015.h>

// Adafruit_ADS1115 ads;  /* Use this for the 16-bit version */
Adafruit_ADS1015 ads;     /* Use thi for the 12-bit version */

  const int analogOutPin = 3; // Analog output pin
  int outputValue = 0;        // value output to the PWM (analog out)

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Hello!");

  Serial.println("Getting single-ended readings from AIN0..3");
  Serial.println("ADC Range: +/- 6.144V (1 bit = 3mV/ADS1015, 0.1875mV/ADS1115)");

  // The ADC input range (or gain) can be changed via the following
  // functions, but be careful never to exceed VDD +0.3V max, or to
  // exceed the upper and lower limits if you adjust the input range!
  // Setting these values incorrectly may destroy your ADC!
  //                                                                ADS1015  ADS1115
  //                                                                -------  -------
  // ads.setGain(GAIN_TWOTHIRDS);  // 2/3x gain +/- 6.144V  1 bit = 3mV      0.1875mV (default)
  // ads.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV      0.125mV
  // ads.setGain(GAIN_TWO);        // 2x gain   +/- 2.048V  1 bit = 1mV      0.0625mV
  // ads.setGain(GAIN_FOUR);       // 4x gain   +/- 1.024V  1 bit = 0.5mV    0.03125mV
  // ads.setGain(GAIN_EIGHT);      // 8x gain   +/- 0.512V  1 bit = 0.25mV   0.015625mV
  // ads.setGain(GAIN_SIXTEEN);    // 16x gain  +/- 0.256V  1 bit = 0.125mV  0.0078125mV

  ads.begin();

  analogWrite(analogOutPin, outputValue);

  Serial.println("AIN0:");
}

void loop(void)
{
  analogWrite(analogOutPin, outputValue);
  outputValue += 1;
  if (outputValue > 100)
  {
    outputValue = 0;
  }

  int16_t adc0, adc1, adc2, adc3;
  long ADC;

  adc0 = ads.readADC_SingleEnded(0);
  adc1 = ads.readADC_SingleEnded(0);
  adc2 = ads.readADC_SingleEnded(0);
  adc3 = ads.readADC_SingleEnded(0);

  ADC = adc0 + adc1; // + adc2 + adc3; // sum readings

  ADC = ADC >> 1; // divide by 4

//  adc1 = ads.readADC_SingleEnded(1);
//  adc2 = ads.readADC_SingleEnded(2);
//  adc3 = ads.readADC_SingleEnded(3);

//  Serial.println(ADC);
  Serial.println(adc0);

//  Serial.print("AIN1: "); Serial.println(adc1);
//  Serial.print("AIN2: "); Serial.println(adc2);
//  Serial.print("AIN3: "); Serial.println(adc3);
//  Serial.println(" ");

  delay(1000);
}

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


update

update

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/Au1st3in/fall2015-e121-arduino-code.git/'


Added Heartbeat msg every hour

Added Heartbeat msg every hour

error: pathspec 'Prototypes/A7' did not match any file(s) known to git
error: pathspec 'Test/A7_Test_Sleep/A7_Test_Sleep.ino' did not match any file(s) known to git


add voice-light-led

add voice-light-led

#define PIN_VOICE 2
#define PIN_LIGHT 0
#define PIN_LED 13

void setup() {
  pinMode(PIN_VOICE, INPUT);
  pinMode(PIN_LED, OUTPUT);
}

void loop() {
  if(digitalRead(PIN_VOICE) == LOW && analogRead(PIN_LIGHT) > 200){
    digitalWrite(PIN_LED, HIGH);
    delay(200);
    digitalWrite(PIN_LED, LOW);
    delay(10);
  }
}

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


moved code for setting button values into its own file

int lastButtonStates[] = {0, 0, 0};
long lastDebounceTimes[] = {0, 0, 0};
long debounceDelay = 50;
int lastReadings[] = {0,0,0};

void updateButtonStates() {
  for (int i = 0; i < 3; ++i) {
    int reading = digitalRead(bpins[i]);
    if (reading != lastButtonStates[i]) {
      lastDebounceTimes[i] = millis();
    }
    if ((millis() - lastDebounceTimes[i]) > debounceDelay) {
      if (reading == LOW) {
       buttons[i] = 1;
      } else {
       buttons[i] = 0;
      }
    }
    lastButtonStates[i] = reading;
  }
}

boolean pressedOnce(int b) {
  updateButtonStates();
  boolean r;
  if (buttons[b] != lastReadings[b] && buttons[b])
    r = true;
  else
    r = false;
  lastReadings[b] = buttons[b];
  return r;
}

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


Add the arduino sketch to test the rover movement.

/*
 * Author: Manuel Parra Z.
 * Date: 14/11/2015
 * License: MIT License
 * Materials:
 *      - Arduino Uno R3
 *      - DFRobot DF-MD V1.3
 *      - DFRobot Pirate 4WD
 * Description:
 *  This sketch will use as a movement test, first the rover will go foward
 * on the track, then it will go reverse, then will turn to left and finally
 * will turn to right. This sketch will show you the if you connected the
 * engines and batteries properly. Don't forget to review the fritzing
 * electronic diagram in the document section of the project
 */

int M1 = 4;
int E1 = 5;
int E2 = 6;
int M2 = 7;

void setup()
{
  Serial.begin(9600);
  pinMode(M1, OUTPUT);
  pinMode(E1, OUTPUT);
  pinMode(M2, OUTPUT);
  pinMode(E2, OUTPUT);
  Serial.println("Setup finished.");
}

void loop()
{
  Serial.println("Foward for 3 seconds.");
  digitalWrite(M1, HIGH);
  digitalWrite(M2, HIGH);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);

  Serial.println("Reverse for 3 seconds.");
  digitalWrite(M1, LOW);
  digitalWrite(M2, LOW);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);

  Serial.println("Left for 3 seconds.");
  digitalWrite(M1, LOW);
  digitalWrite(M2, HIGH);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);

  Serial.println("Right for 3 seconds.");
  digitalWrite(M1, HIGH);
  digitalWrite(M2, LOW);
  analogWrite(E1, 200);
  analogWrite(E2, 200);
  delay(3000);
}

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


initial commit of main firmware function. includes all correct pin connections as per V01 schematic. code has rough frame work. still needs many function filled out.

/*
-------------------------------------------------
| Zachary Nelson
| znelson1@ford.com
| This is the main program for the shift knob
| firmware. Attached components and functionality include:
| 1) vibration motor control
| 2) user input button
| 3) 7 segment display w/ shift register
| 4) 3 RGB LEDs
| 5) brightness control for 7 segment
| 7) serial communication with Android host device
---------------------------------------------------
*/

//libraries used:
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

// pin definitions
int motorPin = 5; //pwm
int buttonPin = 12;
int 7segBrightness = 6; //pwm
int redLED = 9; //pwm
int blueLED = 10; //pwm
int greenLED = 11; //pwm

// shift register pins
int shiftDataPin = 4;  //SERIAL
int shiftClockPin = 8; //SCK
int shiftLatchPin = 7; //RCK

//7 segment digits. individual segments are turned on when
//the cooresponding pin on the shift register is low.
int digit0 = 0b10001000;
int digit1 = 0b11101110;
int digit2 = 0b10010100;
int digit3 = 0b11000100;
int digit4 = 0b11100010;
int digit5 = 0b11000001;
int digit6 = 0b10000011;
int digit7 = 0b11101100;
int digit8 = 0b10000000;
int digit9 = 0b11100000;
// if you want to add in the decimal point simply subtract 0b10000000 from each number

String inputString = "";
boolean stringComplete = false;
int i =0;

void setup(){
  pinMode(motorPin, OUTPUT);
  pinMode(7segBrightness, OUTPUT);
  pinMode(redLED, OUTPUT);
  pinMode(blueLED, OUTPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(shiftDataPin, OUTPUT);
  pinMode(shiftClockPin, OUTPUT);
  pinMode(shiftLatchPin, OUTPUT);
  pinMode(buttonPin, INPUT);

  digitalWrite(buttonPin, HIGH); //turn on internal resistor
  digitalWrite(motorPin, LOW);
  digitalWrite(7segBrightness, HIGH);
  digitalWrite(redLED, LOW);
  digitalWrite(blueLED, LOW);
  digitalWrite(greenLED, LOW);

  PCintPort::attachInterrupt(buttonPin, onClick, FALLING);

  Serial.begin(115200);
}

void onClick() {
  delay(50); // button debounce. could be adjusted
  // let Android app know that a button has been clicked

}

void serialEvent() {
  //properly decode input serial message
 while (Serial.available()){
   char inChar = (char)Serial.read();
   inputString += inChar;
   //.......

}

void motorControl(boolean t) {
  // could add fancy motor control profiles here
  if (t) {
    analogWrite(motorPin, 255);
  }
  else {
    analogWrite(motorPin, 0);
  }
}

void update7seg(int digit) {
  digitalWrite(shiftLatchPin, LOW);
  shiftOut(shiftDataPin, shiftClockPin, LSBFIRST, digit);
  digitalWrite(shiftLatchPin, HIGH);
}

void loop(){
 //main loop function
 if (stringComplete) {
   // do something...
 }

 inputString = "";
 stringComplete = false;
}

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


Update RELAY_BETA.ino

Update RELAY_BETA.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/Garuda-1/RealityGateway.git/'


Re-factor Conway-Life

Re-factor Conway-Life

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/JulianNicholls/Arduino.git/'


Going back to basics :metal:

Going back to basics :metal:

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/hooroo/moteino_build_lights.git/'


Fixing Arduino code to enable the Lights on AUX1/P11 on the cape

#include <Servo.h>
#include <Arduino.h>
#include "Motors.h"
#include "Command.h"
#include "Device.h"
#include "Timer.h"

Motors motors(9, 10, 11);
Command cmd;
Device led("led", 4, led.analog, led.out);
Device vout("vout", 0, vout.analog, vout.in);
Timer time;

Servo tilt, light;
// IMPORTANT!
// array[0] will be the number of arguments in the command
int array[MAX_ARGS];

void setup(){

  Serial.begin(115200);

  pinMode(13, OUTPUT);

  tilt.attach(3);
  light.attach(5);

  motors.reset();
  led.reset();

  time.reset();
}

void loop(){

  if (Serial.available()) {
    // blocks output data... TODO: need a way of calculating frequency for device data
    delay(30);
    // Get command from serial buffer
    cmd.get();

    // do something with the command, what command is it?
    if (cmd.cmp("tilt")) {
      cmd.parse(array);
      int tilt_val = array[1];
      tilt.write(tilt_val);
    }
    else if (cmd.cmp("go")) {
      cmd.parse(array);
      int p = array[1];
      int v = array[2];
      int s = array[3];
      motors.go(p, v, s);
    }
    else if (cmd.cmp("light")) {
      cmd.parse(array);
      int value = array[1];
      light.write(value);
    }
    else {
      motors.stop();
    }
  }

  // send voltage
  if (time.elapsed(1000)) {
    vout.send(vout.read());
    Serial.print("time:");
    Serial.println(millis());
  }
  // else if (time.elapsed(500)) {
  //   digitalWrite(13, HIGH);
  //   delay(200);
  //   digitalWrite(13, LOW);
  // }

}

#include <Servo.h>
#include <Arduino.h>
#include "Motors.h"
#include "Command.h"
#include "Device.h"
#include "Timer.h"

Motors motors(9, 10, 11);
Command cmd;
Device led("led", 4, led.analog, led.out);
Device vout("vout", 0, vout.analog, vout.in);
Timer time;

Servo tilt, light;
// IMPORTANT!
// array[0] will be the number of arguments in the command
int array[MAX_ARGS];

void setup(){

  Serial.begin(115200);

  pinMode(13, OUTPUT);

  tilt.attach(3);
  light.attach(6);

  motors.reset();
  led.reset();

  time.reset();
}

void loop(){

  if (Serial.available()) {
    // blocks output data... TODO: need a way of calculating frequency for device data
    delay(30);
    // Get command from serial buffer
    cmd.get();

    // do something with the command, what command is it?
    if (cmd.cmp("tilt")) {
      cmd.parse(array);
      int tilt_val = array[1];
      tilt.write(tilt_val);
    }
    else if (cmd.cmp("go")) {
      cmd.parse(array);
      int p = array[1];
      int v = array[2];
      int s = array[3];
      motors.go(p, v, s);
    }
    else if (cmd.cmp("light")) {
      cmd.parse(array);
      int light = array[1];
      led.write(light);
    }
    else {
      motors.stop();
    }
  }

  // send voltage
  if (time.elapsed(1000)) {
    vout.send(vout.read());
    Serial.print("time:");
    Serial.println(millis());
  }
  // else if (time.elapsed(500)) {
  //   digitalWrite(13, HIGH);
  //   delay(200);
  //   digitalWrite(13, LOW);
  // }

}


Basic user_input.

Basic user_input.

Recieve 32 bytes and display them.

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/kdomen/Morse-Code.git/'


Add variable declarations and initalizations examples

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


Add PedalShield example code

Add PedalShield example code

.

// Licensed under a Creative Commons Attribution 3.0 Unported License.
// Based on rcarduino.blogspot.com previous work.
// www.electrosmash.com/pedalshield

int in_ADC0, in_ADC1;  //variables for 2 ADCs values (ADC0, ADC1)
int POT0, POT1, POT2, out_DAC0, out_DAC1; //variables for 3 pots (ADC8, ADC9, ADC10)
int LED = 3;
int FOOTSWITCH = 7;
int TOGGLE = 2;

void setup()
{
  //ADC Configuration
  ADC->ADC_MR |= 0x80;   // DAC in free running mode.
  ADC->ADC_CR=2;         // Starts ADC conversion.
  ADC->ADC_CHER=0x1CC0;  // Enable ADC channels 0 and 1.

  //DAC Configuration
  analogWrite(DAC0,0);  // Enables DAC0
  analogWrite(DAC1,0);  // Enables DAC0
}

void loop()
{
  //Read the ADCs
  while((ADC->ADC_ISR & 0x1CC0)!=0x1CC0);// wait for ADC 0, 1, 8, 9, 10 conversion complete.
  in_ADC0=ADC->ADC_CDR[7];               // read data from ADC0
  in_ADC1=ADC->ADC_CDR[6];               // read data from ADC1
  POT0=ADC->ADC_CDR[10];                 // read data from ADC8
  POT1=ADC->ADC_CDR[11];                 // read data from ADC9
  POT2=ADC->ADC_CDR[12];                 // read data from ADC10

  //Add volume feature with POT2
  out_DAC0=map(in_ADC0,0,4095,1,POT2);
  out_DAC1=map(in_ADC1,0,4095,1,POT2);

  //Write the DACs
  dacc_set_channel_selection(DACC_INTERFACE, 0);       //select DAC channel 0
  dacc_write_conversion_data(DACC_INTERFACE, out_DAC0);//write on DAC
  dacc_set_channel_selection(DACC_INTERFACE, 1);       //select DAC channel 1
  dacc_write_conversion_data(DACC_INTERFACE, out_DAC1);//write on DAC
}

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


Added a test read of EEPROM

#include <EepromUtil.h>
#include <EEPROM.h>

String inputString = "";         // a string to hold incoming data
boolean stringComplete = false;  // whether the string is complete
boolean written = false;
const int BUFSIZE = 50;
char buf[BUFSIZE];
void setup() {
  // initialize serial:
  Serial.begin(9600);
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
}

void loop() {

    delay(1000);
    EepromUtil::eeprom_read_string(1,buf,BUFSIZE);
    Serial.print(buf);
    Serial.println();

}

/*
  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();
    // add it to the inputString:
    inputString += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

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


Add Emo's file for setting up the esp SoC.

#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>

#define USE_SERIAL Serial

#define BUTTON_PIN 0

void setup( )
{
    WiFi.mode( WIFI_STA );
    USE_SERIAL.begin( 115200 );
    delay( 10 );

    WiFi.begin( "PhotoBooth", "random321" );
    pinMode( BUTTON_PIN, INPUT );

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

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

void loop()
{
    static unsigned long lastClick = 0;
    if( WiFi.status( ) == WL_CONNECTED )
    {
        if( !digitalRead( BUTTON_PIN ) && millis( ) > lastClick + 1000 )
        {
            USE_SERIAL.print( "[BUTTON] is down\n" );
            HTTPClient http;

            http.begin( "192.168.0.100", 4567, "/shoot" );

            int httpCode = http.GET( );

            if( httpCode )
                USE_SERIAL.printf( "[HTTP] GET... code: %d\n", httpCode );
            else
                USE_SERIAL.print( "[HTTP] GET... failed, no connection or no HTTP server\n" );

            lastClick = millis( );
        }
    }
    else
        USE_SERIAL.print( "[NOT CONNECTED]\n" );
}

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


Added sketch for programming HC-05 modules.

#include <SoftwareSerial.h>

//===== CONFIG VALUES =====
int rx = 8;
int tx = 7;
int pinKey = 9;
int role = 1; // 0 = slave  |  1 = master
String name = "SCADAcar";
String pswd = "0258";
String address = "1122,33,DDEEFF";
int baudRate = 9600;

// Here's a bluetooth device connect to pins 6 and 5
 SoftwareSerial bt(rx,tx);
 char btt = '0';
 char srl = '0';

void setup()
{
 Serial.begin(9600);
 Serial.println("System Up: BLUETOOTH SLAVE");
 bt.begin(9600);
 //SLAVE CONFIG
  pinMode(pinKey, OUTPUT);
  digitalWrite(pinKey, HIGH);
  delay(5000);
  bt.println("AT"); //start AT commands
  delay(1000);
  bt.print("AT+ROLE="); bt.println(role); //set device as slave
  delay(1000);
  if (role == 0) {
    bt.print("AT+NAME="); bt.println(name);  //set device name
    delay(1000);
    bt.print("AT+PSWD="); bt.println(pswd); //set device name
    delay(1000);
  } else {
    bt.print("AT+CMODE=0"); //send CMODE=0, set connection mode to specific address
    delay(1000);
    bt.print("AT+BIND="); bt.println(address); //send BIND=??, bind HC-05 to OBD bluetooth address
    delay(1000);
    bt.print("AT+INIT"); //send INIT, cant connect without this cmd
    delay(1000);
    bt.print("AT+PAIR="); bt.print(address); bt.println(",20"); //send PAIR, pair with OBD address
    delay(1000);
    bt.print("AT+LINK="); bt.println(address); //send LINK, link with OBD address
    delay(1000);
    bt.print("AT+UART="); bt.println(baudRate); //set baudrate
    delay(1000);
  }
  bt.println("AT+NAME?"); //get device name
  bt.println("AT+ADDR?"); //get device address (for connection)
  bt.println("AT+VERSION?"); //get device version
  digitalWrite(pinKey, LOW);
}

void loop()
{
 if (bt.available())
 {
   String command; //string to store entire command line
   while (bt.available())
   {
     btt = bt.read();
     Serial.print(btt);
     delay(50);
   }
 }

 if (Serial.available())
 {
   String command; //string to store entire command line
   while (Serial.available())
   {
     srl = Serial.read();
     Serial.print(srl);
     bt.print(srl);
     delay(50);
     command += srl; //iterates char into string
   }
   if (command == "test") //this compares catched string vs. expected command string
   {
     Serial.print("COMMAND!");
     bt.print("COMMAND!");
   }
     Serial.println("");
     bt.println("");
 }
}

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


Alternative version with delays between mutually exclusive and auto turnoff.

/*
   MQTT 32 output pins for driving 2 16-channel relay boards on an arduino mega with ethernet shield.

   NOTE: the topic is hardcoded: domogik/in/relay/r + relay number : e.g

   mosquitto_pub -t domogik/in/relay/r1 -m 1  -> turn on
   mosquitto_pub -t domogik/in/relay/r1 -m 0  -> turn off
   mosquitto_pub -t domogik/in/relay/r1 -m 2  -> toggle; so turn on again

  By Jeroen Schaeken
  Derived from http://www.esp8266.com/viewtopic.php?f=29&t=8746

  It connects to an MQTT server then:
  - on 0 switches off relay
  - on 1 switches on relay
  - on 2 switches the state of the relay

  It will reconnect to the server if the connection is lost using a blocking
  reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
  achieve the same result without blocking the main loop.

  There is a 400ms between 2 mutuallyExcluded relays

  Pins 2->7 are used as input (switch) detection. Their state are published on domogik/relayArduinoPin1

*/
#include <Ethernet.h>
#include <PubSubClient.h>
#include <Bounce2.h>
#include <AsyncDelay.h>

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEE };
byte server[] = { 192, 168, 1, 30 };
byte ip[]     = { 192, 168, 1, 98 };

EthernetClient ethernetClient;
PubSubClient client(ethernetClient);
long lastMsg = 0;
char msg[50];
int value = 0;
AsyncDelay delay_400ms;
AsyncDelay delay_30s;

//MutuallyExclude the 'on' state between pairs of relays (for shutter to prevent up and down at the same time)
//ask R1 to turn on while R2 = on -> turns off R2 first (and broadcasts 'domogik/in/relay/r2 0')
//ask R2 to turn on while R1 = on -> turns off R1 first (and broadcasts 'domogik/in/relay/r1 0')
bool isMutuallyExclude = true;

const char* outTopic = "domogik/relayClient";
const char* inTopic = "domogik/in/relay/#";
const char* outRelayTopic = "domogik/in/relay/r";
const char* outPinTopic = "domogik/relayArduinoPin";

bool relayStates[] = {
  HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH
};

int relayPins[] = {
  22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53
};       // an array of pin numbers to which LEDs are attached
int pinCount = 32;

#define PIN_DETECT_1 2
#define PIN_DETECT_2 3
#define PIN_DETECT_3 4
#define PIN_DETECT_4 5
#define PIN_DETECT_5 6
#define PIN_DETECT_6 7
Bounce debounce1 = Bounce();
Bounce debounce2 = Bounce();
Bounce debounce3 = Bounce();
Bounce debounce4 = Bounce();
Bounce debounce5 = Bounce();
Bounce debounce6 = Bounce();

boolean doSwitch = false;
boolean doAllOff = false;

void setup_ethernet() {

  delay(10);
  // We start by connecting to a WiFi network
  Ethernet.begin(mac, ip);

  digitalWrite(13, LOW);
  delay(500);
  digitalWrite(13, HIGH);
  delay(500);
  digitalWrite(13, LOW);
  delay(500);
  digitalWrite(13, HIGH);

}

void delayTimers() {
  delay_400ms.start(400, AsyncDelay::MILLIS);
  delay_30s.start(30000, AsyncDelay::MILLIS);
}
void  publishStates() {
  for (int thisPin = 0; thisPin < pinCount; thisPin++) {
    char* state = relayStates[thisPin] == HIGH ? "0" : "1";
    publishRelayState(thisPin + 1, state);
  }
}

void switchRelay(char* switchState, int pos) {
  if (switchState == '0') {
    //Turning off is safe to be done immediately
    digitalWrite(relayPins[pos], HIGH);
    relayStates[pos] = HIGH;
  } else if (switchState == '1') {
    //turning on is done in setStates
    //digitalWrite(relayPins[pos], LOW);
    relayStates[pos] = LOW;
  }
}

void setStates() {
  if (doSwitch) {
    for (int thisPin = 0; thisPin < pinCount; thisPin++) {
      digitalWrite(relayPins[thisPin], relayStates[thisPin]);
    }
    doSwitch = false;
    doAllOff = true;
    delay_30s.start(30000, AsyncDelay::MILLIS);
  }
}

void turnAllOff() {
  if (doAllOff) {
    doAllOff = false;
    for (int thisPin = 0; thisPin < pinCount; thisPin++) {
      relayStates[thisPin] = HIGH;
      publishRelayState(thisPin + 1, "0");
      switchRelay('0', thisPin);
    }
  }
}
void publishRelayState(int relayNbr, char* state) {
  char outputTopicBuff[100];
  strcpy(outputTopicBuff, outRelayTopic);
  char relaybuffer[5];
  sprintf(relaybuffer, "%d", relayNbr);
  strcat(outputTopicBuff, relaybuffer);
  client.publish(outputTopicBuff, state, true);
}

void publishPinState(int pinNbr, char* state) {
  char outputTopicBuff[100];
  strcpy(outputTopicBuff, outPinTopic);
  char relaybuffer[5];
  sprintf(relaybuffer, "%d", pinNbr);
  strcat(outputTopicBuff, relaybuffer);
  client.publish(outputTopicBuff, state);
}

void mutuallyExcludePair(char* switchState, int pos) {
  if (pos % 2 == 0 && switchState == '1') //even
  {
    if (pinCount > (pos + 1) && relayStates[pos + 1] == LOW) {
      switchRelay('0', pos + 1);
      publishRelayState(pos + 2, "0");
    }
  }
  else if (pos % 2 == 1 && switchState == '1') //odd
  {
    if ((pos - 1) >= 0 && relayStates[pos - 1] == LOW) {
      switchRelay('0', pos - 1);
      publishRelayState(pos, "0");
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
  Serial.println();
  //Comes in as domogik/in/relay/r1 ... domogik/in/relay/r16
  String topicString = String(topic);
  int relayNumber = topicString.substring(18, 20).toInt();
  int posInArray = relayNumber - 1;
  char* switchState = (char)payload[0];

  if (switchState == '2') {
    if (relayStates[posInArray] == HIGH) {
      switchState = '1';
    }
    else {
      switchState = '0';
    }
  }

  if (isMutuallyExclude) {
    mutuallyExcludePair(switchState, posInArray);
  }

  switchRelay(switchState, posInArray);
  if (switchState == '1') {
    doSwitch = true;
  }

  delayTimers();
}

void reconnect() {
  while (!client.connected()) {
    if (client.connect("RelayboardClient")) {
      Serial.println("connected");
      client.publish(outTopic, "RelayBoard booted");
      publishStates();
      client.subscribe(inTopic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      for (int i = 0; i < 5000; i++) {
        delay(1);
      }
    }
  }
}

void setup() {

  //Relayboard
  for (int thisPin = 0; thisPin < pinCount; thisPin++) {
    digitalWrite(relayPins[thisPin], HIGH);
    pinMode(relayPins[thisPin], OUTPUT);
  }
  pinMode(13, OUTPUT);

  //init state relayboard
  //turnAllOff();

  delayTimers();

  //input
  pinMode(PIN_DETECT_1, INPUT_PULLUP);
  pinMode(PIN_DETECT_2, INPUT_PULLUP);
  pinMode(PIN_DETECT_3, INPUT_PULLUP);
  pinMode(PIN_DETECT_4, INPUT_PULLUP);
  pinMode(PIN_DETECT_5, INPUT_PULLUP);
  pinMode(PIN_DETECT_6, INPUT_PULLUP);
  debounce1.attach(PIN_DETECT_1);
  debounce2.attach(PIN_DETECT_2);
  debounce3.attach(PIN_DETECT_3);
  debounce4.attach(PIN_DETECT_4);
  debounce5.attach(PIN_DETECT_5);
  debounce6.attach(PIN_DETECT_6);
  debounce1.interval(50);
  debounce2.interval(50);
  debounce3.interval(50);
  debounce4.interval(50);
  debounce5.interval(50);
  debounce6.interval(50);

  digitalWrite(13, LOW);
  delay(500);
  digitalWrite(13, HIGH);
  delay(500);

  Serial.begin(115200);
  setup_ethernet();
  client.setServer(server, 1883);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }

  if (delay_400ms.isExpired()) {
    setStates();
    delay_400ms.repeat();
  }
  if (delay_30s.isExpired()) {
    turnAllOff();
    delay_30s.repeat();
  }
  debounce1.update();
  if ( debounce1.fell() ) {
    publishPinState(1, "1");
  }
  if ( debounce1.rose() ) {
    publishPinState(1, "0");
  }
  debounce2.update();
  if ( debounce2.fell() ) {
    publishPinState(2, "1");
  }
  if ( debounce2.rose() ) {
    publishPinState(2, "0");
  }
  debounce3.update();
  if ( debounce3.fell() ) {
    publishPinState(3, "1");
  }
  if ( debounce3.rose() ) {
    publishPinState(3, "0");
  }
  debounce4.update();
  if ( debounce4.fell() ) {
    publishPinState(4, "1");
  }
  if ( debounce4.rose() ) {
    publishPinState(4, "0");
  }
  debounce5.update();
  if ( debounce5.fell() ) {
    publishPinState(5, "1");
  }
  if ( debounce5.rose() ) {
    publishPinState(5, "0");
  }
  debounce6.update();
  if ( debounce6.fell() ) {
    publishPinState(6, "1");
  }
  if ( debounce6.rose() ) {
    publishPinState(6, "0");
  }

  client.loop();
}

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


test with gearing …

test with gearing …

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


decent

decent

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

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

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

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

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

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

   Those functions will probably conflict with the
   servo library.

   Uses 5 PWM frequencies between 61Hz and 62.5kHz

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

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

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

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

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

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

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

// Terminal count
#define PWM6_13_MAX OCR4C

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

// TCCR4B configuration
TCCR4B=mode;

// TCCR4C configuration
TCCR4C=0;

// TCCR4D configuration
TCCR4D=0;

// TCCR4D configuration
TCCR4D=0;

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

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

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

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

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

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

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

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

// Pins

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

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

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

int detect = 5;

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

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

// State

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

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

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

int samples[sampleCount];
int sampleVal = 0;

// Helpers

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

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

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

}

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

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

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

    PORTF = PORTF | B01000000;
  //  PORTF = PORTF | (isSense_active[i] << 6);
    PORTF = PORTF & B01111111;
    PORTF = PORTF | B10000000;
  }
}

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

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

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

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

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

unsigned long microsdelay;

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

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

void initSense_withResistor(){
 // listen to resistor

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

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

    switchOutputs(noGlow);
    delayMicroseconds(30);

//    microsdelay = micros() - microsdelay;
}

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

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

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

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

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

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

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

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

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

    initSense_withoutResistor();

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

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

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

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

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

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

bool isSense_active[] = {true, true, true, false};
int inactiveMeasure[channelCount];
int activeProbe = 0;
// This function saves a bit of time by not measuring "inactive" channels each cycle.
// Makes the measurement go a bit faster, i.e. makes the EL dohickey brighter!
int* senseAllActive(int chargeDelay_micros = 1000, bool isGlow = true) {
  activeProbe = (activeProbe + 1) % channelCount;
  for (int i = 0; i < 4; i++) {
    if (isSense_active[activeProbe]) {
      activeProbe = (activeProbe + 1) % channelCount;
    }
    else {
      break;
    }
  }

  for (int i = 0; i < 4; i++) {
    toSense_internal[i] = isSense_active[i];
    if (i == activeProbe) {
      toSense_internal[i] = true;
    }
  }
  senseChannels_internal(chargeDelay_micros);

  if (isGlow) {
    switchOutputs(glow);
  }

  // Change threshold for activating, might want to make this smaller?
//  if (inactiveMeasure[activeProbe] - senseResults_internal[activeProbe] > 50 ||
//      senseResults_internal[activeProbe] < 400) {
//    isSense_active[activeProbe] = true;
//  }
//  else {
    inactiveMeasure[activeProbe] = senseResults_internal[activeProbe];
//  }

  for (int i = 0; i < 4; i++) {
    if (!isSense_active[i]) {
      senseResults_internal[i] = inactiveMeasure[i];
    }
  }

 // Serial.println(isSense_active[2] << 6);

  return senseResults_internal;
}

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

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

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

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

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

int* senseResults;

#define smoothedSenseSize 21
int smoothedSenseHistory[channelCount][smoothedSenseSize];
int smoothedSenseIter = 1;

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

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

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

  pinMode(10, OUTPUT);

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

  pinMode(detect, INPUT);

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

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

  analogReference(DEFAULT);

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

  // Disables channels without EL plugged in.
  senseResults = senseAll(2300, true);
  for (int i = 0; i < 4; i++) {
    if (senseResults[i] > 620) {
      isSense_active[i] = false;
    }
  }

  senseResults = senseAll(1500, true);
  for (int i = 0; i < 4; i++) {
    inactiveMeasure[i] = senseResults[i];
  }

  for (int chan = 0; chan < 4; chan++) {
    for (int s = 0; s < smoothedSenseSize; s++) {
          smoothedSenseHistory[chan][s] = senseResults[chan];
    }
  }
}

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

 #define ENABLE_LOGGING

#ifdef ENABLE_LOGGING

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

#endif

int val = 0;

int minimum = 10000;
int maximum = 0;

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

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

float change = 0;

bool shouldGlow = true;

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

#define lagWindowSize 9
#define attractingIndex 10
int senseIndex[channelCount][lagWindowSize];
int lagIter = 0;
int senseLag[] = {0, 0, 0, 0};

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

// Here are the main levers which control the operation of this program
#define increaseWindow 13
#define pureIncreaseThreshold 6
#define increaseThresholdWithImpulse 4
#define impulseThreshold 5
#define bigImpulseThreshold 15
#define glowTime_us 1300

void loop() {
    senseResults = senseAllActive(1500, true);

    smoothedSenseIter = (smoothedSenseIter + 1) % smoothedSenseSize;
    lagIter = (lagIter + 1) % lagWindowSize;
    senseHistoryIter = (senseHistoryIter + 1) % senseSize;

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

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

      sort(senseHistoryTemp, senseSize);

      int prevMeasure = smoothedSenseHistory[channel][(smoothedSenseIter - 1 + smoothedSenseSize) % smoothedSenseSize];
//      prevMeasure += 1; // slight bias up;

//      // bias towards median
//      if (prevMeasure > senseHistoryTemp[attractingIndex]) {
//        prevMeasure = prevMeasure - 1;
//      }
//      else {
//        prevMeasure = prevMeasure + 1;
//      //  prevMeasure = prevMeasure + (senseHistoryTemp[attractingIndex] - prevMeasure) / 8;
//      }

//      // slight bias to
//      if (senseLag[channel] > 1) {
//        prevMeasure = prevMeasure + 2;
//      }
//      long bestSquaredError = 10000;
      long bestScore = 0;
      int bestMatchIndex = 0;
      int startInd = senseIndex[channel][(lagIter + lagWindowSize - 1) % lagWindowSize] - 2;
      if (startInd < 0) { startInd = 0; }
      int endInd = startInd + 5 > senseSize - 10 ? senseSize - 10 : startInd + 5;

//      // bias towards median
//      if (endInd < attractingIndex) {
//        prevMeasure = prevMeasure + 3;
//      }
//      else if (startInd > attractingIndex) {
//        prevMeasure = prevMeasure - 3;
//      }

      for (int i = startInd + 1; i < endInd; i++) {
        long currSquaredError = (prevMeasure - senseHistoryTemp[i]) * (prevMeasure - senseHistoryTemp[i]);
        long currStep = senseHistoryTemp[i + 1] - senseHistoryTemp[i-1];
        long score = (currStep * currStep - currSquaredError * currSquaredError);

        if (score > bestScore) {
          bestScore = score;
          senseIndex[channel][lagIter] = i;
        }

      }

      startInd = senseIndex[channel][lagIter] + 2 > 10 ? 10 : senseIndex[channel][lagIter] + 2;
      for (int i = startInd; i > 0; i--) {
        if (senseHistoryTemp[i + 1] - senseHistoryTemp[i - 1] > 10) {
          senseIndex[channel][lagIter] = i;
          break;
        }
      }

      senseLag[channel] = senseIndex[channel][lagIter] -
                          senseIndex[channel][(lagIter + 1) % lagWindowSize];

      smoothedSenseHistory[channel][smoothedSenseIter] = senseHistoryTemp[senseIndex[channel][lagIter]];
      if (senseLag[channel] >= 2) {
//        for (int i = 0; i < 3; i++) {
//          senseHistory[channel][(senseHistoryIter + i + 5) % senseSize] = (senseHistory[channel][(senseHistoryIter + i + 5) % senseSize]
//              + senseHistoryTemp[senseIndex[channel][lagIter] - senseLag[channel] + 2]) / 2;
//        }
        smoothedSenseHistory[channel][smoothedSenseIter] = senseHistoryTemp[senseIndex[channel][(lagIter + 1) % lagWindowSize] + 2];
      }
//      if (senseLag[channel] < 0) {
//        smoothedSenseHistory[channel][smoothedSenseIter] = senseHistoryTemp[senseIndex[channel][lagIter] - senseLag[channel]];
//      }

//      if (bestSquaredError < 3) {
//        smoothedSenseHistory[channel][smoothedSenseIter] = prevMeasure;
//      }

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

    }

    }

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

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

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

        if (senseDiff > 0) {
          chanChangeCount += 1;
        }
//        if (senseDiff < -5) {
//          chanChangeCount = -1;
//          break;
//        }
      }

      if (chanChangeCount == impulseThreshold + 1) {
        chanImpulse += 5;
      }

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

#ifdef ENABLE_LOGGING

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

    switch (channel) {
      case 0:
        impulselen = sprintf(impulseBuffer, "Imp: %d, ",
                             chanImpulse);
        derivativelen = sprintf(derivativeBuffer, "Change: %d, ",
                                chanChangeCount);
        extrabufflen = sprintf(extraBuffer, "Smoothing: %d %d, ", senseIndex[channel][lagIter], senseLag[channel]);
//        extrabufflen = sprintf(extraBuffer, "Is Active: %d, ",isSense_active[channel]);
                         //     chanImpulse > bigImpulseThreshold && chanChangeCount + 1 >= increaseThresholdWithImpulse);

        break;

      case 1:
      case 2:
      case 3:
        impulselen += sprintf(impulseBuffer + impulselen, "%d, ",
                              chanImpulse);
        derivativelen += sprintf(derivativeBuffer + derivativelen, "%d, ",
                                 chanChangeCount);
        extrabufflen += sprintf(extraBuffer + extrabufflen, "%d %d, ", senseIndex[channel][lagIter], senseLag[channel]);
//        extrabufflen += sprintf(extraBuffer + extrabufflen, "%d, ", isSense_active[channel]);
                        //       chanImpulse > bigImpulseThreshold && chanChangeCount + 1 >= increaseThresholdWithImpulse);

        break;

      default:
        break;
    }
#endif

    }

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

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

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

  snprintf(logBuffer, printLineSize, "%20s %23s %20s %20s %s",
           signalBuffer,
           impulseBuffer,
           derivativeBuffer,
           extraBuffer, "");

  Serial.println(logBuffer);
#endif

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

    switchOutputs(glow);

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

    delayMicroseconds(glowTime_us);
}

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


Start of ILI9488 example

Start of ILI9488 example

#include <EEPROM.h> //' A{
#include <SPI.h>
#include <GD2.h>

#define CSX 6   // chip select, active low
#define DCX 2   // data/command select
#define SCL 3   // clock, rising edge
#define SDA 4   // data in to ILI9488
#define SDO 5   // data out from ILI9488

void setup()
{
  Serial.begin(1000000); // JCB
  // GD.begin(0);

  pinMode(CSX, OUTPUT);
  pinMode(DCX, OUTPUT);
  pinMode(SCL, OUTPUT);
  pinMode(SDA, OUTPUT);
  pinMode(SDO, INPUT);

  digitalWrite(CSX, HIGH);
}

void loop2()
{
  GD.ClearColorRGB(0x103000);
  GD.Clear();
  GD.cmd_text(GD.w / 2, GD.h / 2, 31, OPT_CENTER, "Hello world");
  GD.swap();
}

void out_8(uint8_t b)
{
  digitalWrite(CSX, LOW);
  for (int i = 0; i < 8; i++) {
    digitalWrite(SCL, LOW);
    digitalWrite(SDA, (b >> 7) & 1);
    digitalWrite(SCL, HIGH);
    b <<= 1;
  }
  digitalWrite(CSX, HIGH);
}

void loop()
{
  digitalWrite(DCX, LOW);
  out_8(0xda);  // RDID1

  Serial.println();
  digitalWrite(DCX, HIGH);
  digitalWrite(CSX, LOW);
  for (int i = 0; i < 8; i++) {
    digitalWrite(SCL, LOW);
    digitalWrite(SCL, HIGH);
    Serial.println(digitalRead(SDO), DEC);
  }
  digitalWrite(CSX, HIGH);

  delay(3000);
}

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


panasonic added

panasonic added

// Simple xPL application to control Panasonic heat pumps / airconditioning devices
// * Panasonic CKP series
// * Panasonic DKE series
//
// Connect an IR led (with 1k resistor in series)
// between GND and digital pin 3
//
// Requires the Ethernet shield and xPL
//

#include <Arduino.h>
#include "SPI.h"
#include "avr/pgmspace.h"
#include "Ethernet.h"

#include <Ethernet.h>
#include <EthernetUdp.h>
#include <EEPROM.h>
#include "xPL.h" // from https://github.com/ToniA/arduino-xpl

// xPL stuff, see the example xPL_Send_Arduino

xPL xpl;

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte macAddress[] = { 0x02, 0x26, 0x89, 0x00, 0x00, 0x00 };
char macstr[18];

IPAddress ip(192, 168, 0, 12);  // This MAC/IP address pair is also set as a static lease on the router
IPAddress broadcast(192, 168, 0, 255);
EthernetUDP Udp;

void SendUdPMessage(char *buffer)
{
    Udp.beginPacket(broadcast, xpl.udp_port);
    Udp.write(buffer);
    Udp.endPacket();
}

// Infrared LED on digital PIN 3 (needs a PWM pin)
// Connect with 1 kOhm resistor in series to GND
#define IR_LED_PIN        3

// Ethernet shield reset pin
#define ETHERNET_RST      A0

// Entropy pin needs to be unconnected
#define ENTROPY_PIN       A5

// Panasonic CKP timing constants
#define PANASONIC_AIRCON1_HDR_MARK   3400
#define PANASONIC_AIRCON1_HDR_SPACE  3500
#define PANASONIC_AIRCON1_BIT_MARK   800
#define PANASONIC_AIRCON1_ONE_SPACE  2700
#define PANASONIC_AIRCON1_ZERO_SPACE 1000
#define PANASONIC_AIRCON1_MSG_SPACE  14000

// Panasonic CKP codes
#define PANASONIC_AIRCON1_MODE_AUTO  0x06 // Operating mode
#define PANASONIC_AIRCON1_MODE_HEAT  0x04
#define PANASONIC_AIRCON1_MODE_COOL  0x02
#define PANASONIC_AIRCON1_MODE_DRY   0x03
#define PANASONIC_AIRCON1_MODE_FAN   0x01
#define PANASONIC_AIRCON1_MODE_ONOFF 0x00 // Toggle ON/OFF
#define PANASONIC_AIRCON1_MODE_KEEP  0x08 // Do not toggle ON/OFF
#define PANASONIC_AIRCON1_FAN_AUTO   0xF0 // Fan speed
#define PANASONIC_AIRCON1_FAN1       0x20
#define PANASONIC_AIRCON1_FAN2       0x30
#define PANASONIC_AIRCON1_FAN3       0x40
#define PANASONIC_AIRCON1_FAN4       0x50
#define PANASONIC_AIRCON1_FAN5       0x60
#define PANASONIC_AIRCON1_VS_AUTO    0xF0 // Vertical swing
#define PANASONIC_AIRCON1_VS_UP      0x90
#define PANASONIC_AIRCON1_VS_MUP     0xA0
#define PANASONIC_AIRCON1_VS_MIDDLE  0xB0
#define PANASONIC_AIRCON1_VS_MDOWN   0xC0
#define PANASONIC_AIRCON1_VS_DOWN    0xD0
#define PANASONIC_AIRCON1_HS_AUTO    0x08 // Horizontal swing
#define PANASONIC_AIRCON1_HS_MANUAL  0x00

// Panasonic DKE timing constants
#define PANASONIC_AIRCON2_HDR_MARK   3500
#define PANASONIC_AIRCON2_HDR_SPACE  1800
#define PANASONIC_AIRCON2_BIT_MARK   420
#define PANASONIC_AIRCON2_ONE_SPACE  1350
#define PANASONIC_AIRCON2_ZERO_SPACE 470
#define PANASONIC_AIRCON2_MSG_SPACE  10000

// Panasonic DKE codes
#define PANASONIC_AIRCON2_MODE_AUTO  0x00 // Operating mode
#define PANASONIC_AIRCON2_MODE_HEAT  0x40
#define PANASONIC_AIRCON2_MODE_COOL  0x30
#define PANASONIC_AIRCON2_MODE_DRY   0x20
#define PANASONIC_AIRCON2_MODE_FAN   0x60
#define PANASONIC_AIRCON2_MODE_OFF   0x00 // Power OFF
#define PANASONIC_AIRCON2_MODE_ON    0x01
#define PANASONIC_AIRCON2_TIMER_CNL  0x08
#define PANASONIC_AIRCON2_FAN_AUTO   0xA0 // Fan speed
#define PANASONIC_AIRCON2_FAN1       0x30
#define PANASONIC_AIRCON2_FAN2       0x40
#define PANASONIC_AIRCON2_FAN3       0x50
#define PANASONIC_AIRCON2_FAN4       0x60
#define PANASONIC_AIRCON2_FAN5       0x70
#define PANASONIC_AIRCON2_VS_AUTO    0x0F // Vertical swing
#define PANASONIC_AIRCON2_VS_UP      0x01
#define PANASONIC_AIRCON2_VS_MUP     0x02
#define PANASONIC_AIRCON2_VS_MIDDLE  0x03
#define PANASONIC_AIRCON2_VS_MDOWN   0x04
#define PANASONIC_AIRCON2_VS_DOWN    0x05
#define PANASONIC_AIRCON2_HS_AUTO    0x0D // Horizontal swing
#define PANASONIC_AIRCON2_HS_MIDDLE  0x06
#define PANASONIC_AIRCON2_HS_LEFT    0x09
#define PANASONIC_AIRCON2_HS_MLEFT   0x0A
#define PANASONIC_AIRCON2_HS_MRIGHT  0x0B
#define PANASONIC_AIRCON2_HS_RIGHT   0x0C

// Midea timing constants
#define MIDEA_AIRCON1_HDR_MARK       4350
#define MIDEA_AIRCON1_HDR_SPACE      4230
#define MIDEA_AIRCON1_BIT_MARK       520
#define MIDEA_AIRCON1_ONE_SPACE      1650
#define MIDEA_AIRCON1_ZERO_SPACE     550
#define MIDEA_AIRCON1_MSG_SPACE      5100

// MIDEA codes
#define MIDEA_AIRCON1_MODE_AUTO      0x10 // Operating mode
#define MIDEA_AIRCON1_MODE_HEAT      0x30
#define MIDEA_AIRCON1_MODE_COOL      0x00
#define MIDEA_AIRCON1_MODE_DRY       0x20
#define MIDEA_AIRCON1_MODE_FAN       0x60
#define MIDEA_AIRCON1_MODE_FP        0x70 // Not a real mode...
#define MIDEA_AIRCON1_MODE_OFF       0xFE // Power OFF - not real codes, but we need something...
#define MIDEA_AIRCON1_MODE_ON        0xFF // Power ON
#define MIDEA_AIRCON1_FAN_AUTO       0x02 // Fan speed
#define MIDEA_AIRCON1_FAN1           0x06
#define MIDEA_AIRCON1_FAN2           0x05
#define MIDEA_AIRCON1_FAN3           0x03

// Send the Panasonic CKP code

void sendPanasonicCKP(byte operatingMode, byte fanSpeed, byte temperature, byte swingV, byte swingH)
{
  byte sendBuffer[4];

  // Fan speed & temperature, temperature needs to be 27 in FAN mode
  if (operatingMode == PANASONIC_AIRCON1_MODE_FAN || operatingMode == (PANASONIC_AIRCON1_MODE_FAN | PANASONIC_AIRCON1_MODE_KEEP ))
  {
    temperature = 27;
  }

  sendBuffer[0] = fanSpeed | (temperature - 15);

  // Power toggle & operation mode
  sendBuffer[1] = operatingMode;

  // Swings
  sendBuffer[2] = swingV | swingH;

  // Always 0x36
  sendBuffer[3]  = 0x36;

  // Send the code
  sendPanasonicCKPraw(sendBuffer);
}

// Send the Panasonic CKP raw code

void sendPanasonicCKPraw(byte sendBuffer[])
{
  // 40 kHz PWM frequency
  enableIROut(40);

  // Header, two first bytes repeated
  mark(PANASONIC_AIRCON1_HDR_MARK);
  space(PANASONIC_AIRCON1_HDR_SPACE);

  for (int i=0; i<2; i++) {
    sendIRByte(sendBuffer[0], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[0], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[1], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[1], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);

    mark(PANASONIC_AIRCON1_HDR_MARK);
    space(PANASONIC_AIRCON1_HDR_SPACE);
  }

  // Pause

  mark(PANASONIC_AIRCON1_BIT_MARK);
  space(PANASONIC_AIRCON1_MSG_SPACE);

  // Header, two last bytes repeated

  mark(PANASONIC_AIRCON1_HDR_MARK);
  space(PANASONIC_AIRCON1_HDR_SPACE);

  for (int i=0; i<2; i++) {
    sendIRByte(sendBuffer[2], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[2], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[3], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[3], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);

    mark(PANASONIC_AIRCON1_HDR_MARK);
    space(PANASONIC_AIRCON1_HDR_SPACE);
  }

  mark(PANASONIC_AIRCON1_BIT_MARK);
  space(0);
}

// Send the Panasonic CKP On/Off code
//
// CKP does not have discrete ON/OFF commands, but this can be emulated by using the timer
// The side-effects of using the timer are:
// * one minute delay before the power state changes
// * the 'TIMER' led (orange) is lit

void sendPanasonicCKPOnOff(boolean powerState)
{
  byte ON_msg[] = { 0x7F, 0x38, 0xBF, 0x38, 0x10, 0x3D, 0x80, 0x3D, 0x09, 0x34, 0x80, 0x34 };  // ON at 00:10,  time now 00:09, no OFF timing
  byte OFF_msg[] = { 0x10, 0x38, 0x80, 0x38, 0x7F, 0x3D, 0xBF, 0x3D, 0x09, 0x34, 0x80, 0x34 }; // OFF at 00:10, time now 00:09, no ON timing
  byte *sendBuffer;

  if ( powerState == true ) {
    sendBuffer = ON_msg;
  } else {
    sendBuffer = OFF_msg;
  }

  // 40 kHz PWM frequency
  enableIROut(40);

  for (int i=0; i<6; i++) {
    mark(PANASONIC_AIRCON1_HDR_MARK);
    space(PANASONIC_AIRCON1_HDR_SPACE);

    sendIRByte(sendBuffer[i*2 + 0], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[i*2 + 0], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[i*2 + 1], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);
    sendIRByte(sendBuffer[i*2 + 1], PANASONIC_AIRCON1_BIT_MARK, PANASONIC_AIRCON1_ZERO_SPACE, PANASONIC_AIRCON1_ONE_SPACE);

    mark(PANASONIC_AIRCON1_HDR_MARK);
    space(PANASONIC_AIRCON1_HDR_SPACE);

    if ( i < 5 ) {
      mark(PANASONIC_AIRCON1_BIT_MARK);
      space(PANASONIC_AIRCON1_MSG_SPACE);
    }
  }

  mark(PANASONIC_AIRCON1_BIT_MARK);
  space(0);
}

// Send the Panasonic DKE code

void sendPanasonicDKE(byte operatingMode, byte fanSpeed, byte temperature, byte swingV, byte swingH)
{
  byte DKE_template[] = { 0x02, 0x20, 0xE0, 0x04, 0x00, 0x00, 0x00, 0x06, 0x02, 0x20, 0xE0, 0x04, 0x00, 0x48, 0x2E, 0x80, 0xA3, 0x0D, 0x00, 0x0E, 0xE0, 0x00, 0x00, 0x01, 0x00, 0x06, 0xA2 };
  byte checksum = 0xF4;

  DKE_template[13] = operatingMode;
  DKE_template[14] = temperature << 1;
  DKE_template[16] = fanSpeed | swingV;
  DKE_template[17] = swingH;

  // Checksum

  for (int i=0; i<26; i++) {
    checksum += DKE_template[i];
  }

  DKE_template[26] = checksum;

  // 40 kHz PWM frequency
  enableIROut(40);

  // Header
  mark(PANASONIC_AIRCON2_HDR_MARK);
  space(PANASONIC_AIRCON2_HDR_SPACE);

  // First 8 bytes
  for (int i=0; i<8; i++) {
    sendIRByte(DKE_template[i], PANASONIC_AIRCON2_BIT_MARK, PANASONIC_AIRCON2_ZERO_SPACE, PANASONIC_AIRCON2_ONE_SPACE);
  }

  // Pause
  mark(PANASONIC_AIRCON2_BIT_MARK);
  space(PANASONIC_AIRCON2_MSG_SPACE);

  // Header
  mark(PANASONIC_AIRCON2_HDR_MARK);
  space(PANASONIC_AIRCON2_HDR_SPACE);

  // Last 19 bytes
  for (int i=8; i<27; i++) {
    sendIRByte(DKE_template[i], PANASONIC_AIRCON2_BIT_MARK, PANASONIC_AIRCON2_ZERO_SPACE, PANASONIC_AIRCON2_ONE_SPACE);
  }

  mark(PANASONIC_AIRCON2_BIT_MARK);
  space(0);
}

// Send the Midea code

void sendMidea(byte operatingMode, byte fanSpeed, byte temperature)
{
  byte sendBuffer[3] = { 0x4D, 0x00, 0x00 }; // First byte is always 0x4D

  byte temperatures[] = {0, 8, 12, 4, 6, 14, 10, 2, 3, 11, 9, 1, 5, 13 };

  byte OffMsg[] = {0x4D, 0xDE, 0x07 };
  byte FPMsg[]  = {0xAD, 0xAF, 0xB5 };

  if (operatingMode == MIDEA_AIRCON1_MODE_OFF)
  {
    sendMidearaw( OffMsg );
  }
  else if (operatingMode == MIDEA_AIRCON1_MODE_FP)
  {
    sendMidearaw( FPMsg );
  }
  else
  {
    sendBuffer[1] = ~fanSpeed;

    if ( operatingMode == MIDEA_AIRCON1_MODE_FAN )
    {
      sendBuffer[2] = MIDEA_AIRCON1_MODE_DRY | 0x07;
    }
    else
    {
      sendBuffer[2] = operatingMode | temperatures[temperature-17];
    }

    // Send the code
    sendMidearaw(sendBuffer);
  }
}

// Send the Midea raw code

void sendMidearaw(byte sendBuffer[])
{
  // 40 kHz PWM frequency
  enableIROut(40);

  // Header
  mark(MIDEA_AIRCON1_HDR_MARK);
  space(MIDEA_AIRCON1_HDR_SPACE);

  // Six bytes, every second byte is a bitwise not of the previous byte
  for (int i=0; i<3; i++) {
    sendIRByte(sendBuffer[i], MIDEA_AIRCON1_BIT_MARK, MIDEA_AIRCON1_ZERO_SPACE, MIDEA_AIRCON1_ONE_SPACE);
    sendIRByte(~sendBuffer[i], MIDEA_AIRCON1_BIT_MARK, MIDEA_AIRCON1_ZERO_SPACE, MIDEA_AIRCON1_ONE_SPACE);
  }

  // Pause

  mark(MIDEA_AIRCON1_BIT_MARK);
  space(MIDEA_AIRCON1_MSG_SPACE);

  // Header, two last bytes repeated

  mark(MIDEA_AIRCON1_HDR_MARK);
  space(MIDEA_AIRCON1_HDR_SPACE);

  // Six bytes, every second byte is a bitwise not of the previous byte
  for (int i=0; i<3; i++) {
    sendIRByte(sendBuffer[i], MIDEA_AIRCON1_BIT_MARK, MIDEA_AIRCON1_ZERO_SPACE, MIDEA_AIRCON1_ONE_SPACE);
    sendIRByte(~sendBuffer[i], MIDEA_AIRCON1_BIT_MARK, MIDEA_AIRCON1_ZERO_SPACE, MIDEA_AIRCON1_ONE_SPACE);
  }

  // End mark

  mark(MIDEA_AIRCON1_BIT_MARK);
  space(0);
}

// Send a byte over IR

void sendIRByte(byte sendByte, int bitMarkLength, int zeroSpaceLength, int oneSpaceLength)
{
  for (int i=0; i<8 ; i++)
  {
    if (sendByte & 0x01)
    {
      mark(bitMarkLength);
      space(oneSpaceLength);
    }
    else
    {
      mark(bitMarkLength);
      space(zeroSpaceLength);
    }

    sendByte >>= 1;
  }
}

// 'mark', 'space' and 'enableIROut' have been taken
// from Ken Shirriff's IRRemote library:
// https://github.com/shirriff/Arduino-IRremote

void mark(int time) {
  // Sends an IR mark for the specified number of microseconds.
  // The mark output is modulated at the PWM frequency.
  (TCCR2A |= _BV(COM2B1)); // Enable pin 3 PWM output
  delayMicroseconds(time);
}

void space(int time) {
  // Sends an IR space for the specified number of microseconds.
  // A space is no output, so the PWM output is disabled.
  (TCCR2A &= ~(_BV(COM2B1))); // Disable pin 3 PWM output
  delayMicroseconds(time);
}

void enableIROut(int khz) {
  pinMode(IR_LED_PIN, OUTPUT);
  digitalWrite(IR_LED_PIN, LOW); // When not sending PWM, we want it low

  const uint8_t pwmval = F_CPU / 2000 / (khz);
  TCCR2A = _BV(WGM20);
  TCCR2B = _BV(WGM22) | _BV(CS20);
  OCR2A = pwmval;
  OCR2B = pwmval / 3;
}

// Parse the xPL message and send Panasonic CKP IR codes

void sendCKPCmd(xPL_Message * message)
{
  int param = 0;
  byte i;

  // Sensible defaults for the heat pump mode

  byte powerMode     = false;
  byte operatingMode = PANASONIC_AIRCON1_MODE_HEAT | PANASONIC_AIRCON1_MODE_KEEP;
  byte fanSpeed      = PANASONIC_AIRCON1_FAN_AUTO;
  byte temperature   = 23;
  byte swingV        = PANASONIC_AIRCON1_VS_UP;
  byte swingH        = PANASONIC_AIRCON1_HS_AUTO;

  for (i=0; i < message->command_count; i++)
  {
    param = atoi(message->command[i].value);

    if (strcmp(message->command[i].name, "power") == 0 )
    {
      switch (param)
      {
        case 1:
          powerMode = true;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "mode") == 0 )
    {
      operatingMode &= PANASONIC_AIRCON1_MODE_KEEP;

      switch (param)
      {
        case 1:
          operatingMode |= PANASONIC_AIRCON1_MODE_AUTO;
          break;
        case 2:
          operatingMode |= PANASONIC_AIRCON1_MODE_HEAT;
          break;
        case 3:
          operatingMode |= PANASONIC_AIRCON1_MODE_COOL;
          break;
        case 4:
          operatingMode |= PANASONIC_AIRCON1_MODE_DRY;
          break;
        case 5:
          operatingMode |= PANASONIC_AIRCON1_MODE_FAN;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "fan") == 0 )
    {
      switch (param)
      {
        case 1:
          fanSpeed = PANASONIC_AIRCON1_FAN_AUTO;
          break;
        case 2:
          fanSpeed = PANASONIC_AIRCON1_FAN1;
          break;
        case 3:
          fanSpeed = PANASONIC_AIRCON1_FAN2;
          break;
        case 4:
          fanSpeed = PANASONIC_AIRCON1_FAN3;
          break;
        case 5:
          fanSpeed = PANASONIC_AIRCON1_FAN4;
          break;
        case 6:
          fanSpeed = PANASONIC_AIRCON1_FAN5;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "temperature") == 0 )
    {
      if ( param >= 15 && param <= 31)
      {
        temperature = param;
      }
    }
    else if (strcmp(message->command[i].name, "vswing") == 0 )
    {
      switch (param)
      {
        case 1:
          swingV = PANASONIC_AIRCON1_VS_AUTO;
          break;
        case 2:
          swingV = PANASONIC_AIRCON1_VS_UP;
          break;
        case 3:
          swingV = PANASONIC_AIRCON1_VS_MUP;
          break;
        case 4:
          swingV = PANASONIC_AIRCON1_VS_MIDDLE;
          break;
        case 5:
          swingV = PANASONIC_AIRCON1_VS_MDOWN;
          break;
        case 6:
          swingV = PANASONIC_AIRCON1_VS_DOWN;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "hswing") == 0 )
    {
      switch (param)
      {
        case 1:
          swingH = PANASONIC_AIRCON1_HS_AUTO;
          break;
        case 2:
          swingH = PANASONIC_AIRCON1_HS_MANUAL;
          break;
      }
    }
  }

  sendPanasonicCKP(operatingMode, fanSpeed, temperature, swingV, swingH);
  delay(3000); // Sleep 3 seconds between the messages
  sendPanasonicCKPOnOff(powerMode);
}

// Parse the xPL message and send Panasonic DKE IR codes

void sendDKECmd(xPL_Message * message)
{
  int param = 0;
  byte i;

  // Sensible defaults for the heat pump mode

  byte operatingMode = PANASONIC_AIRCON2_TIMER_CNL;
  byte fanSpeed      = PANASONIC_AIRCON2_FAN_AUTO;
  byte temperature   = 23;
  byte swingV        = PANASONIC_AIRCON2_VS_UP;
  byte swingH        = PANASONIC_AIRCON2_HS_AUTO;

  for (i=0; i < message->command_count; i++)
  {
    param = atoi(message->command[i].value);

    if (strcmp(message->command[i].name, "power") == 0 )
    {
      switch (param)
      {
        case 1:
          operatingMode |= PANASONIC_AIRCON2_MODE_ON;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "mode") == 0 )
    {
      switch (param)
      {
        case 1:
          operatingMode |= PANASONIC_AIRCON2_MODE_AUTO;
          break;
        case 2:
          operatingMode |= PANASONIC_AIRCON2_MODE_HEAT;
          break;
        case 3:
          operatingMode |= PANASONIC_AIRCON2_MODE_COOL;
          break;
        case 4:
          operatingMode |= PANASONIC_AIRCON2_MODE_DRY;
          break;
        case 5:
          operatingMode |= PANASONIC_AIRCON2_MODE_FAN;
          temperature = 27; // Temperature is always 27 in FAN mode
          break;
      }
    }
    else if (strcmp(message->command[i].name, "fan") == 0 )
    {
      switch (param)
      {
        case 1:
          fanSpeed = PANASONIC_AIRCON2_FAN_AUTO;
          break;
        case 2:
          fanSpeed = PANASONIC_AIRCON2_FAN1;
          break;
        case 3:
          fanSpeed = PANASONIC_AIRCON2_FAN2;
          break;
        case 4:
          fanSpeed = PANASONIC_AIRCON2_FAN3;
          break;
        case 5:
          fanSpeed = PANASONIC_AIRCON2_FAN4;
          break;
        case 6:
          fanSpeed = PANASONIC_AIRCON2_FAN5;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "temperature") == 0 )
    {
      if ( param >= 15 && param <= 31 && temperature == 23)
      {
        temperature = param;
      }
    }
    else if (strcmp(message->command[i].name, "vswing") == 0 )
    {
      switch (param)
      {
        case 1:
          swingV = PANASONIC_AIRCON2_VS_AUTO;
          break;
        case 2:
          swingV = PANASONIC_AIRCON2_VS_UP;
          break;
        case 3:
          swingV = PANASONIC_AIRCON2_VS_MUP;
          break;
        case 4:
          swingV = PANASONIC_AIRCON2_VS_MIDDLE;
          break;
        case 5:
          swingV = PANASONIC_AIRCON2_VS_MDOWN;
          break;
        case 6:
          swingV = PANASONIC_AIRCON2_VS_DOWN;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "hswing") == 0 )
    {
      switch (param)
      {
        case 1:
          swingH = PANASONIC_AIRCON2_HS_AUTO;
          break;
        case 2:
          swingH = PANASONIC_AIRCON2_HS_MIDDLE;
          break;
        case 3:
          swingH = PANASONIC_AIRCON2_HS_LEFT;
          break;
        case 4:
          swingH = PANASONIC_AIRCON2_HS_MLEFT;
          break;
        case 5:
          swingH = PANASONIC_AIRCON2_HS_RIGHT;
          break;
        case 6:
          swingH = PANASONIC_AIRCON2_HS_MRIGHT;
          break;
      }
    }
  }

  sendPanasonicDKE(operatingMode, fanSpeed, temperature, swingV, swingH);
}

// Parse the xPL message and send Panasonic DKE IR codes

void sendMideaCmd(xPL_Message * message)
{
  int param = 0;
  byte i;

  // Sensible defaults for the heat pump mode

  byte operatingMode = MIDEA_AIRCON1_MODE_HEAT;
  byte fanSpeed      = MIDEA_AIRCON1_FAN_AUTO;
  byte temperature   = 23;

  for (i=0; i < message->command_count; i++)
  {
    param = atoi(message->command[i].value);

    if (strcmp(message->command[i].name, "power") == 0 )
    {
      switch (param)
      {
        case 0:
          // OFF is a special case
          operatingMode = MIDEA_AIRCON1_MODE_OFF;
          sendMidea(operatingMode, fanSpeed, temperature);
          return;
      }
    }
    else if (strcmp(message->command[i].name, "mode") == 0 )
    {
      switch (param)
      {
        case 1:
          operatingMode = MIDEA_AIRCON1_MODE_AUTO;
          break;
        case 2:
          operatingMode = MIDEA_AIRCON1_MODE_HEAT;
          break;
        case 3:
          operatingMode = MIDEA_AIRCON1_MODE_COOL;
          break;
        case 4:
          operatingMode = MIDEA_AIRCON1_MODE_DRY;
          break;
        case 5:
          operatingMode = MIDEA_AIRCON1_MODE_FAN;
          break;
        case 6:
          // FP is a special case
          operatingMode = MIDEA_AIRCON1_MODE_FP;
          sendMidea(operatingMode, fanSpeed, temperature);
          return;
      }
    }
    else if (strcmp(message->command[i].name, "fan") == 0 )
    {
      switch (param)
      {
        case 1:
          fanSpeed = MIDEA_AIRCON1_FAN_AUTO;
          break;
        case 2:
          fanSpeed = MIDEA_AIRCON1_FAN1;
          break;
        case 3:
          fanSpeed = MIDEA_AIRCON1_FAN2;
          break;
        case 4:
          fanSpeed = MIDEA_AIRCON1_FAN3;
          break;
      }
    }
    else if (strcmp(message->command[i].name, "temperature") == 0 )
    {
      if ( param >= 17 && param <= 31 )
      {
        temperature = param;
      }
    }
  }

  sendMidea(operatingMode, fanSpeed, temperature);
}

// parse incoming xPL message
// To test with xpl-perl:
//
// xpl-sender -m xpl-cmnd -t xpl-arduino.heatpumpctrl -c aircon.ckp power=0 mode=2 fan=3 temperature=23
// xpl-sender -m xpl-cmnd -t xpl-arduino.heatpumpctrl -c aircon.dke power=0 mode=2 fan=3 temperature=23
// xpl-sender -m xpl-cmnd -t xpl-arduino.heatpumpctrl -c aircon.midea power=0 mode=2 fan=3 temperature=23

void AfterParseAction(xPL_Message * message)
{
  if (xpl.TargetIsMe(message))
    {
      if (message->IsSchema_P(PSTR("aircon"), PSTR("dke")))
      {
        sendDKECmd(message);
      }
      else if (message->IsSchema_P(PSTR("aircon"), PSTR("ckp")))
      {
        sendCKPCmd(message);
      }
      else if (message->IsSchema_P(PSTR("aircon"), PSTR("midea")))
      {
        sendMideaCmd(message);
      }

      Serial.println("Got xPL message:");
      Serial.println(message->toString());
      Serial.println("");
    }
}

// The setup

void setup()
{
  // Initialize serial
  Serial.begin(9600);
  Serial.print("Starting... ");

  // Ethernet shield reset trick
  // Need to cut the RESET lines (also from ICSP header) and connect an I/O to RESET on the shield

  pinMode(ETHERNET_RST, OUTPUT);
  digitalWrite(ETHERNET_RST, HIGH);
  delay(50);
  digitalWrite(ETHERNET_RST, LOW);
  delay(50);
  digitalWrite(ETHERNET_RST, HIGH);
  delay(100);

  // generate or read the already generated MAC address
  generateMAC();

  // initialize the Ethernet adapter
  Ethernet.begin(macAddress, ip);

  // initialize the xPL UDP port
  Udp.begin(xpl.udp_port);

  // initialize xPL
  xpl.SendExternal = &SendUdPMessage;                                   // pointer to the send callback
  xpl.AfterParseAction = &AfterParseAction;                             // pointer to a post parsing action callback
  xpl.SetSource_P(PSTR("xpl"), PSTR("arduino"), PSTR("heatpumpctrl"));  // parameters for hearbeat message

  Serial.println("Started");
}

// The loop
// * heartbeats
// * xPL message processing

void loop()
{
  // xPL heartbeat management
  xpl.Process();

  // process incoming xPL packets
  int packetSize = Udp.parsePacket();
  if(packetSize)
  {
    char xPLMessageBuff[XPL_MESSAGE_BUFFER_MAX];

    // read the packet into packetBufffer
    Udp.read(xPLMessageBuff, XPL_MESSAGE_BUFFER_MAX);

    // parse message
    xpl.ParseInputMessage(xPLMessageBuff);
  }
}

// Random MAC based on:
// http://files.pcode.nl/arduino/EthernetPersistentMAC.ino
// A5 is the entropy PIN for random MAC generation, leave it unconnected

void generateMAC()
{
  randomSeed(analogRead(ENTROPY_PIN));

  // Uuncomment to generate a new MAC
  //EEPROM.write(E2END - 8, 0x00);
  //EEPROM.write(E2END - 7, 0x00);

  // We store the MAC address in the last 8 bytes of the EEPROM using E2END to determine it's size
  // The first of those two bytes are checked for the magic values 0x80 and 0x23 (a reference to 802.3)

  if ((EEPROM.read(E2END - 8) == 0x80) && (EEPROM.read(E2END - 7) == 0x23))
  {
    Serial.println("Reading MAC address from EEPROM");
    for (int i = 0; i <= 5; i++)
    {
       macAddress[i] = EEPROM.read(E2END - 6 + i);
    }
  }
  else
  {
    Serial.println("Writing new random MAC address to EEPROM");

    EEPROM.write(E2END - 8, 0x80);
    EEPROM.write(E2END - 7, 0x23);
    for (int i = 0; i <= 5; i++)
    {
      // Skip the Organisationally Unique Identifier (OUI)
      // Randomize only the Network Interface Controller specific part
      if (i >= 3)
      {
        macAddress[i] = random(0, 255);
      }
      EEPROM.write(E2END - 6 + i, macAddress[i]);
    }
  }
  snprintf(macstr, 18, "%02X:%02X:%02X:%02X:%02X:%02X", macAddress[0], macAddress[1], macAddress[2], macAddress[3], macAddress[4], macAddress[5]);

  // Print out the MAC address
  Serial.print("MAC: ");
  Serial.println(macstr);
}

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


Update wifi-localization.ino

Update wifi-localization.ino

error: pathspec 'The' did not match any file(s) known to git
error: pathspec 'Things' did not match any file(s) known to git
error: pathspec 'Network/localization/wifi-localization.ino' did not match any file(s) known to git


Integrated TimerTwo correctly, as implemented in testTimerTwo. Not quite done -- it's currently broken -- but commit'ing just in case I mess it up right away and want to revert. Added terrible circuit diagram. Changed code style from opening braces at the end of previous statement to opening on their own line. It's cleaner, easier to read.

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


only turn on bluetooth when the cavalry is being called

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/GalacticSmarties/electra.git/'


Add blank arduino sketch

Add blank arduino sketch


rm demo;arrange static varible;speedup parking

exploration use IR sensor to turn/src/main.ino

error: pathspec 'exploration' did not match any file(s) known to git
error: pathspec 'use' did not match any file(s) known to git
error: pathspec 'IR' did not match any file(s) known to git
error: pathspec 'sensor' did not match any file(s) known to git
error: pathspec 'to' did not match any file(s) known to git
error: pathspec 'turn/src/main.ino' did not match any file(s) known to git


Filling in the start of the connecticut halftime

brute force style.

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/meatballhat/box-o-sand.git/'


added blink and drive

added blink and drive

error: pathspec 'daily' did not match any file(s) known to git
error: pathspec 'code/Day' did not match any file(s) known to git
error: pathspec '4/blink_and_drive/blink_and_drive.ino' did not match any file(s) known to git


Arduino UNO — Quick Intro —A Workshop in BSB w Kids —Code 1

Arduino UNO — Quick Intro —A Workshop in BSB w Kids —Code 1

/*
  Kids-Serie#10
  Project : Arduino Start Up

  Ino File: _10_Blinking_LED_01.ino

  Flavour 01

  Date: Nov 2018

  Description:  Let's say I want to flash an LED connected to Pin 3

  Board: Arduino UNO

  Arduino IDE: 1.8.7

  Connections: See Fritzing in Jungletronics:

  Credits: This sketch was in public domain.

  Based on: Collin's Lab: Arduino
            https://youtu.be/pnf8ojsK6S4

  Terms of Use:  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 Softw are Foundation - There is no guarantee whatsoever :)
                 Use at your own risk!
*/

void setup() {
                            // put your setup code here, to run once:
  pinMode(3, OUTPUT);

}

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

  delay(500);

  digitalWrite(3, LOW);

  delay(500);

}

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


testing speed & position

testing speed & position


Create FlightController.ino

Create FlightController.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/GaParmar/quadcopter.git/'


Example GaussianRandomPlot created

Example GaussianRandomPlot created

This example helps to understand what is the new method "random" of
Gaussian.

#include <Gaussian.h>
void setup() {
	Serial.begin(9600);
	Serial.println("\n\nStarting Random Gaussian Distribuition...");
	delay(20);
	randomSeed(analogRead(0));
}

// The number of "slots" to record the hits of gaussian random
#define SIZE 36

// How many tests will be performed
#define TESTS 10000

// How many characters will have, in width?
#define BAR_SIZE 40

void loop() {
	Gaussian g1 = Gaussian(0, 10);
	long zero = SIZE/2 - g1.mean;
	long hits[SIZE] = {0};

	// Zero the array
	for(int i = 0; i < SIZE; i++)
		hits[i] = 0;

	// Print Header (0% ------------- 100%)
	Serial.print("0% ");

	for(int i = 3; i < BAR_SIZE - 5; i++)
		Serial.print("-");

	Serial.println(" 100%");

	// Process the gaussians and randomize 'TESTS' times
	int lastStep = 0, step;
	Serial.print("=");
	for(int i = 0; i < TESTS; i++){
		step = (double)i/TESTS*BAR_SIZE;
		if(step > lastStep){
			Serial.print("=");
			lastStep = step;
		}

		double val = g1.random();
		int place = (int)val - g1.mean + zero;
		place = constrain(place, 0, SIZE);
		hits[place]++;
	}
	Serial.print(" END!\n");

	// Just to scale the plot on the Serial, to improve visualization
	long maxHit = 0;
	for(int i = 0; i < SIZE; i++){
	maxHit = max(maxHit, hits[i]);
		// Uncomment this line if you want to see the NUMBER of hits
		// Serial.println(hits[i]);
	}

	// This will print the bar graphic
	double scale = (double)maxHit/BAR_SIZE;
	Serial.print("Scale: ");
	Serial.print(scale);
	Serial.print("\tMaxHit: ");
	Serial.println(maxHit);

	for(int i = 0; i < SIZE; i++){
		int len = hits[i]/scale;

		for(int x = 0; x < len; x++)
			Serial.print("=");

		Serial.print("\n");
	}

	// Wait until dinosaurs come back on earth
	while(1);
}

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


updated example

updated 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/arduino-org/CiaoMCU.git/'


Código fonte de comunicação serial com o arduino


Update firmware examples with the readtag.ino example frm arduino

#include <Wire.h>
#include <PN532_I2C.h>
#include <PN532.h>
#include <NfcAdapter.h>

PN532_I2C pn532_i2c(Wire);
NfcAdapter nfc = NfcAdapter(pn532_i2c);

void setup(void) {
    Serial.begin(9600);
    Serial.println("NDEF Reader");
    nfc.begin();
}

void loop(void) {
    Serial.println("\nScan a NFC tag\n");
    if (nfc.tagPresent())
    {
        NfcTag tag = nfc.read();
        tag.print();
    }
    delay(5000);
}

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


add arduino code

add arduino code

/* -*- mode: c -*- */

#define NUM_PINS_TAP 4
#define NUM_PINS_TEMP 2
#define PIN_LED 11

#define PIN_NUM_TAP(x) (21 - x)
#define PIN_NUM_TEMP(x) (21 - NUM_PINS_TAP - x)

#define NUM_PINS (NUM_PINS_TAP + NUM_PINS_TEMP)

const int pin_bytes = sizeof(uint64_t);
const int bufsize = 8 + (NUM_PINS * pin_bytes);

volatile uint64_t pulses[NUM_PINS_TAP];
uint8_t last_state[NUM_PINS_TAP];
byte buffer[bufsize] = {0};

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

  for(int i = 0; i < NUM_PINS_TAP; i++) {
    pinMode(PIN_NUM_TAP(i), INPUT_PULLUP);
    pulses[i] = 0;
    last_state[i] = digitalRead(PIN_NUM_TAP(i));
  }

  for(int i = 0; i < NUM_PINS_TEMP; i++) {
    pinMode(PIN_NUM_TEMP(i), INPUT);
  }

  OCR0A = 0xAF;
  TIMSK0 |= _BV(OCIE0A); // what

  buffer[0] = bufsize;
  buffer[1] = NUM_PINS_TAP;
  buffer[2] = NUM_PINS_TEMP;
  buffer[3] = NUM_PINS;
}

SIGNAL(TIMER0_COMPA_vect) {
  for(int i = 0; i < NUM_PINS_TAP; i++) {
    uint8_t state = digitalRead(PIN_NUM_TAP(i));

    if(state != last_state[i]) {
      pulses[i]++;
    }

    last_state[i] = state;
  }
}

void loop() {
  uint64_t tmp;

  if(Serial.available() > 0) {
    Serial.read();
    digitalWrite(PIN_LED, HIGH);

    for(int i = 0; i < NUM_PINS_TAP; i++) {
      tmp = pulses[i];
      memcpy(&buffer[(i + 1) * pin_bytes], &tmp, pin_bytes);

      pulses[i] = 0;
    }

    for(int i = 0; i < NUM_PINS_TEMP; i++) {
      tmp = (uint64_t)analogRead(PIN_NUM_TEMP(i));
      memcpy(&buffer[(i + 1 + NUM_PINS_TAP) * pin_bytes], &tmp, pin_bytes);
    }

    Serial.write(buffer, bufsize);
  }
  else {
    digitalWrite(PIN_LED, LOW);
  }

  delay(100);
}

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


Add Mr Slim Halloween Project

Add Mr Slim Halloween Project

/*********************************************************************
 * Scary Halloween Skull Eyes with Sound
 * Author: Darrell Little
 * Date: October 15, 2017
 * This software is in the Public Domain
 * Creative Commons Zero v1.0 Universal
 * The Creative Commons CC0 Public Domain Dedication waives copyright interest
 * in any work created and dedicates it to the world-wide public domain.
 *
 * PIR sensor power is connected to 5 volts, negative to ground
 * Use a function to return a boolean (True or False) if the PIR
 * sensor detects motion
 *
 * When motion is detected
 * play an audio file while
 * flashing the LED eyes multiple times using a function by passing it
 * number of times to blink and delay time.
 *
 * MP3 Player Credits
 * Based on open source library:
 *   DFPlayer - A Mini MP3 Player For Arduino
 *   <https://www.dfrobot.com/index.php?route=product/product&product_id=1121>
 *   <Angelo.qiao@dfrobot.com>
 *   WARNING: Must use voltage dropping 1k resistors on software serial TX/RX lines
 *   to the DFPlayer.
 *
 * Additional credits to Let's Code Blacksburg workshop
 * https://github.com/LetsCodeBlacksburg/arduino-talking-skull
 * LCBB_Talking-Skull_ping-servo-dfplayer_complete
 * By tweeks-pub1@theweeks.org
 *
 *********************************************************************/

#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>

// Set the constant values and variables used
const int led1 = 11; // one of two LED eyes
const int led2 = 10; // second of two LED eyes
const int pir = 6; // pin connected to the PIR sensor output
int sensorValue = LOW; // initial value of sensor reading

// DFPlayer mp3 player variables
const int ardRX = 2;       // The SoftwareSerial Receive line (Use 1K resistor, goes to DFPlayer TX)
const int ardTX = 3;       // The SoftwareSerial Transmit line (Use 1K resistor, goes to DFPlayer RX)
const int dfBusy = 12;     // Coming from DFPlayer pin 16, is active low (HIGH = not playing a sound)
int soundFile = 1;           // initial soundFile value
int fileCount = 15;         // Either set the # of files on SD card, or load it from myDFPlayer.readFileCounts()
int setVol = 20;           //Set volume value (0~30)

// Create SoftwareSerial instance
SoftwareSerial mySoftwareSerial(ardRX,ardTX); // Set the RX, TX pins

// Create DFPlayer instance
DFRobotDFPlayerMini myDFPlayer;

// Function to initialize the DFPlayer
void initDFPlayer() {
  if (myDFPlayer.begin(mySoftwareSerial)) {
    // configure settings
    myDFPlayer.setTimeOut(500); //Set serial communictaion time out 500ms
    myDFPlayer.volume(setVol);  //Set volume value (0~30).
    myDFPlayer.EQ(DFPLAYER_EQ_NORMAL);
    myDFPlayer.outputDevice(DFPLAYER_DEVICE_SD);
  }
}

// Function for reading the PIR sensor
// Return true if motion is detected
boolean isMotionDetected() {
  sensorValue = digitalRead(pir);
  if (sensorValue == HIGH) { // the sensor reads HIGH if motion is detected
    return true;
  }
  else
  {
    return false; // no motion
  }
}

// Function to blink the eyes rapidly multiple times
// pass to the function two values
void blinkEyes(int blinkRepeats, int waitTime) {
  for (int i = 0; i < blinkRepeats; i++) {
    turnOnEyes();
    delay(waitTime);
    turnOffEyes();
    delay(waitTime);
  }
}

// Function to turn on the LED eyes
void turnOnEyes() {
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
}

// Function to turn off the LED eyes
void turnOffEyes() {
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
}

void setup() {
  // Put your setup code here, initialize the pins as input or output
  pinMode(pir, INPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(ardRX, INPUT);
  pinMode(ardTX, OUTPUT);
  pinMode(dfBusy, INPUT);
  // Start SoftwareSerial, initialize DFPlayer
  mySoftwareSerial.begin(9600);
  initDFPlayer();

} // end of setup() function

void loop() {
  // put your main code logic here, to run repeatedly
  // If played the last soundFile, then reset to 1
  if (soundFile == fileCount+1) {
    soundFile = 1;
  }

  if (isMotionDetected()) {
    myDFPlayer.play(soundFile);  // Play the next mp3 file
    delay(100);
    while(digitalRead(dfBusy) == false) {
      // Blink the LED eyes while mp3 is playing
      blinkEyes(3,150);
    }

  soundFile++;  // Increment the file number
  delay(3000);
  }
  else {
    turnOffEyes();
  }

} // end of loop() function

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


Added delay before time log to send at correct intervals

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


Create yun_modbus_example.ino

Create yun_modbus_example.ino

Initial

#include <Bridge.h>

Process p;
#define BUF_SIZE 32
char buf[BUF_SIZE];

void setup() {
  Serial.begin(115200);
  // Start the bridge
  Bridge.begin();
  // Start the modbus server
  p.begin("python");
  p.addParameter("/mnt/sd/modbus_tcp_slave.py"); // modbus float holding registers
  p.addParameter("40001");                       // read only start address
  p.addParameter("6");                           // read only number of holding registers
  p.addParameter("40101");                       // read/write start address (optional)
  p.addParameter("6");                           // read/write number of holding registers (optional)
  p.runAsynchronously();
}
void loop() {
  // AVR -> WRT (modbus read only), write some values to the modbus server
  Bridge.put("40001", String(PI));
  Bridge.put("40003", String(millis()));
  Bridge.put("40005", String(5280));

  // AVR <- WRT (modbus read/write), read some values from the modbus server
  Bridge.get("40101", buf, BUF_SIZE);
  Serial.println(atof(buf));
  delay(500);
}

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