Create tft-test.ino

Create tft-test.ino

First working draft running 2 TFT LCD screens with text inversion off the same Arduino Mega. (Pro tip: hook RST of each TFT LCD to the Mega's RESET pin)

/**************************************************************************
  This is a library for several Adafruit displays based on ST77* drivers.

  Works with the Adafruit 1.8" TFT Breakout w/SD card
    ----> http://www.adafruit.com/products/358
  The 1.8" TFT shield
    ----> https://www.adafruit.com/product/802
  The 1.44" TFT breakout
    ----> https://www.adafruit.com/product/2088
  The 1.14" TFT breakout
  ----> https://www.adafruit.com/product/4383
  The 1.3" TFT breakout
  ----> https://www.adafruit.com/product/4313
  The 1.54" TFT breakout
    ----> https://www.adafruit.com/product/3787
  The 1.69" TFT breakout
    ----> https://www.adafruit.com/product/5206
  The 2.0" TFT breakout
    ----> https://www.adafruit.com/product/4311
  as well as Adafruit raw 1.8" TFT display
    ----> http://www.adafruit.com/products/618

  Check out the links above for our tutorials and wiring diagrams.
  These displays use SPI to communicate, 4 or 5 pins are required to
  interface (RST is optional).

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  MIT license, all text above must be included in any redistribution
 **************************************************************************/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>

#if defined(ARDUINO_FEATHER_ESP32) // Feather Huzzah32
  #define TFT_CS         14
  #define TFT_RST        15
  #define TFT_DC         32

#elif defined(ESP8266)
  #define TFT_CS         4
  #define TFT_RST        16
  #define TFT_DC         5

#else
  // For the breakout board, you can use any 2 or 3 pins.
  // These pins will also work for the 1.8" TFT shield.
  #define TFT_CS        10
  #define TFT_RST        9 // Or set to -1 and connect to Arduino RESET pin
  #define TFT_DC         8
#endif

// OPTION 1 (recommended) is to use the HARDWARE SPI pins, which are unique
// to each board and not reassignable. For Arduino Uno: MOSI = pin 11 and
// SCLK = pin 13. This is the fastest mode of operation and is required if
// using the breakout board's microSD card.

// For 1.44" and 1.8" TFT with ST7735 use:
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
Adafruit_ST7735 tft2 = Adafruit_ST7735(7, TFT_DC, TFT_RST);

// For 1.14", 1.3", 1.54", 1.69", and 2.0" TFT with ST7789:
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// OPTION 2 lets you interface the display using ANY TWO or THREE PINS,
// tradeoff being that performance is not as fast as hardware SPI above.
//#define TFT_MOSI 11  // Data out
//#define TFT_SCLK 13  // Clock out

// For ST7735-based displays, we will use this call
//Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

// OR for the ST7789-based displays, we will use this call
//Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);

float p = 3.1415926;

void setup(void) {
  Serial.begin(9600);
  Serial.print(F("Hello! ST77xx TFT Test"));

  // Use this initializer if using a 1.8" TFT screen:
  //tft.initR(INITR_BLACKTAB);      // Init ST7735S chip, black tab

  // OR use this initializer if using a 1.8" TFT screen with offset such as WaveShare:
   tft.initR(INITR_GREENTAB);      // Init ST7735S chip, green tab
   tft2.initR(INITR_GREENTAB);

  // OR use this initializer (uncomment) if using a 1.44" TFT:
  //tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab

  // OR use this initializer (uncomment) if using a 0.96" 160x80 TFT:
  //tft.initR(INITR_MINI160x80);  // Init ST7735S mini display

  // OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT:
  //tft.init(240, 240);           // Init ST7789 240x240

  // OR use this initializer (uncomment) if using a 1.69" 280x240 TFT:
  //tft.init(240, 280);           // Init ST7789 280x240

  // OR use this initializer (uncomment) if using a 2.0" 320x240 TFT:
  //tft.init(240, 320);           // Init ST7789 320x240

  // OR use this initializer (uncomment) if using a 1.14" 240x135 TFT:
  //tft.init(135, 240);           // Init ST7789 240x135

  // OR use this initializer (uncomment) if using a 1.47" 172x320 TFT:
  //tft.init(172, 320);           // Init ST7789 172x320

  // SPI speed defaults to SPI_DEFAULT_FREQ defined in the library, you can override it here
  // Note that speed allowable depends on chip and quality of wiring, if you go too fast, you
  // may end up with a black screen some times, or all the time.
  //tft.setSPISpeed(40000000);

  Serial.println(F("Initialized"));

  uint16_t time = millis();
  tft.fillScreen(ST77XX_BLACK);
  tft2.fillScreen(ST77XX_BLACK);
  time = millis() - time;

  Serial.println(time, DEC);
  delay(500);

  // large block of text
  tft.fillScreen(ST77XX_BLACK);
  tft2.fillScreen(ST77XX_BLACK);
  testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE);
  delay(1000);
/*
  // tft print function!
  tftPrintTest();
  delay(4000);

  // a single pixel
  tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN);
  delay(500);

  // line draw test
  testlines(ST77XX_YELLOW);
  delay(500);

  // optimized lines
  testfastlines(ST77XX_RED, ST77XX_BLUE);
  delay(500);

  testdrawrects(ST77XX_GREEN);
  delay(500);

  testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA);
  delay(500);

  tft.fillScreen(ST77XX_BLACK);
  testfillcircles(10, ST77XX_BLUE);
  testdrawcircles(10, ST77XX_WHITE);
  delay(500);

  testroundrects();
  delay(500);

  testtriangles();
  delay(500);

  mediabuttons();
  delay(500);

  Serial.println("done");
  delay(1000);
  */
}

void loop() {
  tft.invertDisplay(true);
  tft2.invertDisplay(true);
  delay(500);
  tft.invertDisplay(false);
  tft2.invertDisplay(false);
  delay(500);
}

void testlines(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, 0, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, 0, 0, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(0, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(0, tft.height()-1, tft.width()-1, y, color);
    delay(0);
  }

  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color);
    delay(0);
  }
  for (int16_t y=0; y < tft.height(); y+=6) {
    tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color);
    delay(0);
  }
}

void testdrawtext(char *text, uint16_t color) {
  tft.setCursor(0, 0);
  tft.setTextColor(color);
  tft.setTextWrap(true);
  tft.print(text);

  tft2.setCursor(0, 0);
  tft2.setTextColor(color);
  tft2.setTextWrap(true);
  tft2.print(text);
}

void testfastlines(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t y=0; y < tft.height(); y+=5) {
    tft.drawFastHLine(0, y, tft.width(), color1);
  }
  for (int16_t x=0; x < tft.width(); x+=5) {
    tft.drawFastVLine(x, 0, tft.height(), color2);
  }
}

void testdrawrects(uint16_t color) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=0; x < tft.width(); x+=6) {
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color);
  }
}

void testfillrects(uint16_t color1, uint16_t color2) {
  tft.fillScreen(ST77XX_BLACK);
  for (int16_t x=tft.width()-1; x > 6; x-=6) {
    tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1);
    tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2);
  }
}

void testfillcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=radius; x < tft.width(); x+=radius*2) {
    for (int16_t y=radius; y < tft.height(); y+=radius*2) {
      tft.fillCircle(x, y, radius, color);
    }
  }
}

void testdrawcircles(uint8_t radius, uint16_t color) {
  for (int16_t x=0; x < tft.width()+radius; x+=radius*2) {
    for (int16_t y=0; y < tft.height()+radius; y+=radius*2) {
      tft.drawCircle(x, y, radius, color);
    }
  }
}

void testtriangles() {
  tft.fillScreen(ST77XX_BLACK);
  uint16_t color = 0xF800;
  int t;
  int w = tft.width()/2;
  int x = tft.height()-1;
  int y = 0;
  int z = tft.width();
  for(t = 0 ; t <= 15; t++) {
    tft.drawTriangle(w, y, y, x, z, x, color);
    x-=4;
    y+=4;
    z-=4;
    color+=100;
  }
}

void testroundrects() {
  tft.fillScreen(ST77XX_BLACK);
  uint16_t color = 100;
  int i;
  int t;
  for(t = 0 ; t <= 4; t+=1) {
    int x = 0;
    int y = 0;
    int w = tft.width()-2;
    int h = tft.height()-2;
    for(i = 0 ; i <= 16; i+=1) {
      tft.drawRoundRect(x, y, w, h, 5, color);
      x+=2;
      y+=3;
      w-=4;
      h-=6;
      color+=1100;
    }
    color+=100;
  }
}

void tftPrintTest() {
  tft.setTextWrap(false);
  tft.fillScreen(ST77XX_BLACK);
  tft.setCursor(0, 30);
  tft.setTextColor(ST77XX_RED);
  tft.setTextSize(1);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_YELLOW);
  tft.setTextSize(2);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_GREEN);
  tft.setTextSize(3);
  tft.println("Hello World!");
  tft.setTextColor(ST77XX_BLUE);
  tft.setTextSize(4);
  tft.print(1234.567);
  delay(1500);
  tft.setCursor(0, 0);
  tft.fillScreen(ST77XX_BLACK);
  tft.setTextColor(ST77XX_WHITE);
  tft.setTextSize(0);
  tft.println("Hello World!");
  tft.setTextSize(1);
  tft.setTextColor(ST77XX_GREEN);
  tft.print(p, 6);
  tft.println(" Want pi?");
  tft.println(" ");
  tft.print(8675309, HEX); // print 8,675,309 out in HEX!
  tft.println(" Print HEX!");
  tft.println(" ");
  tft.setTextColor(ST77XX_WHITE);
  tft.println("Sketch has been");
  tft.println("running for: ");
  tft.setTextColor(ST77XX_MAGENTA);
  tft.print(millis() / 1000);
  tft.setTextColor(ST77XX_WHITE);
  tft.print(" seconds.");
}

void mediabuttons() {
  // play
  tft.fillScreen(ST77XX_BLACK);
  tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE);
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED);
  delay(500);
  // pause
  tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE);
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN);
  delay(500);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE);
  delay(50);
  // pause color
  tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED);
  tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED);
  // play color
  tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN);
}

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


New WT12 preparation sketch for reset/config for 38400 baud

HardwareSerial Serial1 = HardwareSerial();

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

    Serial.println("The WT12 Prep sketch will attempt to communicate with the WT12 and set");
    Serial.println("necessary configuration options for Keyglove operation, finishing up by");
    Serial.println("setting the baud rate to 38400 instead of the the default. If successful,");
    Serial.println("this sketch will not run a second time since the baud rate will be");
    Serial.println("mismatched.\r\n");
    Serial.println("Note that you should see responses from the WT12 if the sketch is");
    Serial.println("communicating correctly. If you see binary or gibberish, the baud rate");
    Serial.println("is already mismatched.\r\n");
    Serial.println("Enter '1' to try 115200 baud, or '2' to use 38400 to perform a factory");
    Serial.println("reset only without modifying settings. Entering '2' will require you to");
    Serial.println("run the sketch again and enter '1' to finish the preparation.\r\n");

    while (Serial.available());
    uint8_t ch;
    do { ch = Serial.read(); } while (ch != '1' && ch != '2');

    if (ch == '1') {
        Serial1.begin(115200);
        Serial.println("Resetting iWRAP to factory defaults...");
        Serial1.print("\r\nSET RESET\r\n");
        Serial1.flush();
        delay(3000);
        while (Serial1.available()) Serial.print((char)Serial1.read());
        Serial.println("");

        Serial.println("Setting device name...");
        Serial1.print("SET BT NAME Keyglove\r\n");
        Serial1.flush();
        delay(500);
        while (Serial1.available()) Serial.print((char)Serial1.read());
        Serial.println("");

        Serial.println("Setting device identity...");
        Serial1.print("SET BT IDENT BT:47 f000 4.0.0 Keyglove Input Device\r\n");
        Serial1.flush();
        delay(500);
        while (Serial1.available()) Serial.print((char)Serial1.read());
        Serial.println("");

        Serial.println("Setting device class to keyboard/mouse...");
        Serial1.print("SET BT CLASS 005C0\r\n");
        Serial1.flush();
        delay(500);
        while (Serial1.available()) Serial.print((char)Serial1.read());
        Serial.println("");

        Serial.println("Setting Secure Simple Pairing (SSP) mode to 3/0...");
        Serial1.print("SET BT SSP 3 0\r\n");
        Serial1.flush();
        delay(500);
        while (Serial1.available()) Serial.print((char)Serial1.read());
        Serial.println("");

        Serial.println("Enabling GPIO7 toggling on Carrier Detect (link active mode)...");
        Serial1.print("SET CONTROL CD 80 0\r\n");
        Serial1.flush();
        delay(500);
        while (Serial1.available()) Serial.print((char)Serial1.read());
        Serial.println("");

        Serial.println("Enabling GPIO6 DTR detection for entering command mode (ESCAPE char disabled)...");
        Serial1.print("SET CONTROL ESCAPE - 40 1\r\n");
        Serial1.flush();
        delay(500);
        while (Serial1.available()) Serial.print((char)Serial1.read());
        Serial.println("");

        Serial.println("Changing baud rate to 38400...sketch will end after this. Bye!");
        Serial1.print("SET CONTROL BAUD 38400,8n1\r\n");
        Serial1.flush();
        delay(100);
    } else {
        Serial1.begin(38400);
        Serial.println("Resetting iWRAP to factory defaults...sketch will end after this. Bye!");
        Serial1.print("\r\nSET RESET\r\n");
        Serial1.flush();
    }
}

void loop() {
    // nothing to do here
}

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


Robotcontrol

Robotcontrol

Robotcontrol with android, still needs to be edited

#include <MeetAndroid.h>
#include <Servo.h>
Servo myservo;

#define LEFTSIDE_NEG   2
#define LEFTSIDE_POS   3
#define RIGHTSIDE_NEG  6
#define RIGHTSIDE_POS  7
#define TRIGGER_PIN    8
#define ECHO_PIN       12

MeetAndroid meetAndroid;

void setup(){
 /* myservo.attach(11);
  int pos = myservo.read();
  //set servo at to 180 degrees to begin with
//  while (pos != 180) {
//    myservo.write(pos);
//    delay(15);
//    pos++;
}*/

 Serial.begin(9600);

 meetAndroid.registerFunction(forward, 'w');
 meetAndroid.registerFunction(backward, 's');
 meetAndroid.registerFunction(leftTurn, 'a');
 meetAndroid.registerFunction(rightTurn, 'd');
 meetAndroid.registerFunction(stopIt, 'x');

  pinMode(LEFTSIDE_NEG, OUTPUT);
  pinMode(LEFTSIDE_POS, OUTPUT);
  pinMode(RIGHTSIDE_NEG, OUTPUT);
  pinMode(RIGHTSIDE_POS, OUTPUT);

}

void loop(){
  //meetAndroid.receive();

  //while (getSonar() > 30) {
    forward2();
  //}

  //while (getSonar() < 30) {
    //rightTurn2();
    //delay(50);
  //}

  delay(100);

}

void forward(byte flag, byte numOfValues)
{
  analogWrite(LEFTSIDE_POS, meetAndroid.getInt());
  analogWrite(RIGHTSIDE_POS,meetAndroid.getInt());
  analogWrite(LEFTSIDE_NEG,0);
  analogWrite(LEFTSIDE_NEG,0);
}

void forward2()
{
  analogWrite(LEFTSIDE_POS, 255);
  analogWrite(RIGHTSIDE_POS, 255);
  analogWrite(LEFTSIDE_NEG,255);
  analogWrite(LEFTSIDE_NEG,255);
}

void backward(byte flag, byte numOfValues)
{
  analogWrite(LEFTSIDE_POS,0);
  analogWrite(RIGHTSIDE_POS,0);
  analogWrite(LEFTSIDE_NEG,meetAndroid.getInt());
  analogWrite(LEFTSIDE_NEG,meetAndroid.getInt());
}

void stopIt(byte flag, byte numOfValues)
{
  analogWrite(LEFTSIDE_POS,meetAndroid.getInt());
  analogWrite(RIGHTSIDE_POS,meetAndroid.getInt());
  analogWrite(LEFTSIDE_NEG,meetAndroid.getInt());
  analogWrite(RIGHTSIDE_NEG,meetAndroid.getInt());
}

void leftTurn(byte flag, byte numOfValues){
  analogWrite(LEFTSIDE_POS,0);
  analogWrite(LEFTSIDE_NEG,meetAndroid.getInt());
  analogWrite(RIGHTSIDE_POS,meetAndroid.getInt());
  analogWrite(RIGHTSIDE_NEG,0);
  Serial.print(meetAndroid.getInt());
}

void rightTurn(byte flag, byte numOfValues){
   analogWrite(LEFTSIDE_POS,meetAndroid.getInt());
   analogWrite(LEFTSIDE_NEG,0);
   analogWrite(RIGHTSIDE_POS,0);
   analogWrite(RIGHTSIDE_NEG,meetAndroid.getInt());
}

void rightTurn2(){
   analogWrite(LEFTSIDE_POS, 255);
   analogWrite(LEFTSIDE_NEG,0);
   analogWrite(RIGHTSIDE_POS,0);
   analogWrite(RIGHTSIDE_NEG, 255);
}

int getSonar(){
  int duration,distance;

  duration = pulseIn(ECHO_PIN,HIGH);
  distance = (duration/2)/29.1;

  return distance;
}

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


verification by renaming …

verification by renaming …

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


Add arduino serial test sketch

Add arduino serial test sketch

void setup() {
  Serial.begin(9600);
  Serial.println("Application Started");
}

void loop() {
  Serial.println("Hello From The Other Side!");
  delay(1000);
}

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


starting with source from http://www.radiation-watch.org/

//////////////////////////////////////////////////
// Radiation-Watch.org
// URL http://www.radiation-watch.org/
//////////////////////////////////////////////////

///　Digital I/O PIN Settings　///
int signPin = 2; //Radiation Pulse (Yellow)
int noisePin = 5; //Vibration Noise Pulse (White)
//VCC 5V (Red)
//GND (Blue)
////////////////////////////////

const double alpha=53.032; // cpm = uSv x alpha

int index=0; //Number of loops
char msg[256]=""; //Message buffer for serial output

int signCount=0;  //Counter for Radiation Pulse
int noiseCount=0;  //Counter for Noise Pulse

int sON=0;//Lock flag for Radiation Pulse
int nON=0;//Lock flag for Noise Puls

double cpm = 0; //Count rate [cpm] of current
double cpmHistory[200]; //History of count rates
int cpmIndex=0;//Position of current count rate on cpmHistory[]
int cpmIndexPrev=0;//Flag to prevent duplicative counting

//Timing Settings for Loop Interval
int prevTime=0;
int currTime=0;

int totalSec=0; //Elapsed time of measurement [sec]
int totalHour=0; //Elapsed time of measurement [hour]

//Time settings for CPM calcuaration
int cpmTimeMSec=0;
int cpmTimeSec=0;
int cpmTimeMin=0;

//String buffers of float values for serial output
char cpmBuff[20];
char uSvBuff[20];
char uSvdBuff[20];

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

  //PIN setting for Radiation Pulse
  pinMode(signPin,INPUT);
  digitalWrite(signPin,HIGH);

  //PIN setting for Noise Pulse
  pinMode(noisePin,INPUT);
  digitalWrite(noisePin,HIGH);

  //CSV-formatting for serial output (substitute , for _)
  Serial.println("hour[h]_sec[s]_count_cpm_uSv/h_uSv/hError");

  //Initialize cpmHistory[]
  for(int i=0; i<200;i++ )
  {
    cpmHistory[i]=0;
  }

  //Get start time of a loop
  prevTime = millis();
}

void loop()
{
  // Raw data of Radiation Pulse: Not-detected -> High, Detected -> Low
  int sign = digitalRead(signPin);

  // Raw data of Noise Pulse: Not-detected -> Low, Detected -> High
  int noise = digitalRead(noisePin);

  //Radiation Pulse normally keeps low for about 100[usec]
  if(sign==0 && sON==0)
  {//Deactivate Radiation Pulse counting for a while
    sON = 1;
    signCount++;
  }else if(sign==1 && sON==1){
    sON = 0;
  }

  //Noise Pulse normally keeps high for about 100[usec]
  if(noise==1 && nON==0)
  {//Deactivate Noise Pulse counting for a while
    nON = 1;
    noiseCount++;
  }else if(noise==0 && nON==1){
    nON = 0;
  }

  //Output readings to serial port, after 10000 loops
  if(index==10000) //About 160-170 msec in Arduino Nano(ATmega328)
  {
    //Get current time
    currTime = millis();

    //No noise detected in 10000 loops
    if(noiseCount == 0)
    {
      //Shift an array for counting log for each 6 sec.
      if( totalSec % 6 == 0 && cpmIndexPrev != totalSec)
      {
        cpmIndexPrev = totalSec;
        cpmIndex++;

        if(cpmIndex >= 200)
        {
          cpmIndex = 0;
        }

        if(cpmHistory[cpmIndex] > 0)
        {
          cpm -= cpmHistory[cpmIndex];
        }
        cpmHistory[cpmIndex]=0;
      }

      //Store count log
      cpmHistory[cpmIndex] += signCount;
      //Add number of counts
      cpm += signCount;

      //Get ready time for 10000 loops
      cpmTimeMSec += abs(currTime - prevTime);
      //Transform from msec. to sec. (to prevent overflow)
      if(cpmTimeMSec >= 1000)
      {
        cpmTimeMSec -= 1000;
        //Add measurement time to calcurate cpm readings (max=20min.)
        if( cpmTimeSec >= 20*60 )
        {
          cpmTimeSec = 20*60;
        }else{
          cpmTimeSec++;
        }

        //Total measurement time
        totalSec++;
        //Transform from sec. to hour. (to prevent overflow)
        if(totalSec >= 3600)
        {
          totalSec -= 3600;
          totalHour++;
        }
      }

      //Elapsed time of measurement (max=20min.)
      double min = cpmTimeSec / 60.0;
      if(min!=0)
      {
        //Calculate cpm, uSv/h and error of uSv/h
        dtostrf(cpm / min, -1, 3, cpmBuff);
        dtostrf(cpm / min / alpha, -1, 3, uSvBuff);
        dtostrf(sqrt(cpm) / min / alpha, -1, 3, uSvdBuff);
      }else{
        //Devision by zero
        dtostrf(0, -1, 3, cpmBuff);
        dtostrf(0, -1, 3, uSvBuff);
        dtostrf(0, -1, 3, uSvdBuff);
      }

      //Create message for serial port
      sprintf(msg, "%d,%d.%03d,%d,%s,%s,%s",
      totalHour,totalSec,
      cpmTimeMSec,
      signCount,
      cpmBuff,
      uSvBuff,
      uSvdBuff
        );

      //Send message to serial port
      Serial.println(msg);

      index=0;
    }

    //Initialization for next 10000 loops
    prevTime = currTime;
    signCount=0;
    noiseCount=0;
  }
  index++;
}


New Sketch: sparkcore-random-rgbled

New Sketch: sparkcore-random-rgbled

Fix https://github.com/gmacario/learning-arduino/issues/28

Signed-off-by: Gianpaolo Macario <f8885408b8c3d931b330bae3c3a28a3af912c463@gmail.com>

int led_r = A4;
int led_g = A5;
int led_b = A6;

void setup() {
    pinMode(led_r, OUTPUT);
    pinMode(led_g, OUTPUT);
    pinMode(led_b, OUTPUT);
}

void loop() {
    int value_r, value_g, value_b;

    value_r = random (0, 256);
    value_g = random (0, 256);
    value_b = random (0, 256);

    analogWrite(led_r, value_r);
    analogWrite(led_g, value_g);
    analogWrite(led_b, value_b);
    delay(2000);
}

error: pathspec 'Sketches/sparkcore-random-rgbled/sparkcore-random-rgbled.ino' did not match any file(s) known to git


Initial commit

Initial commit

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/timkettering/TabernacleDisplay.git/'


[lmr] Adjust window size when the packet is lost so we can predict when the next receive will need to be now rather than then

#include <avr/wdt.h>
#include <avr/sleep.h>
#include <rf12_itplus.h>

// Power down CPU as much as possible, and attempt to sync receiver at exact
// transmit time. Can't be used with LMREMOTE_SERIAL
// Or if an output is defined (fan/servo)
#define MINIMAL_POWER_MODE
// Enabling LMREMOTE_SERIAL also disables MINIMAL_POWER_MODE
#define LMREMOTE_SERIAL 38400

// Base Idenfier for the RFM12B (0-63)
// The transmitted ID is this ID plus the pin number
const char _rfNodeBaseId = 0;
// RFM12B band RF12_433MHZ, RF12_868MHZ, RF12_915MHZ
const unsigned char _rfBand = RF12_915MHZ;
// How many seconds to delay between measurements
const unsigned char _sleepInterval = 2;
// Analog pins to read. This is a bitfield, LSB is analog 0
const unsigned char _enabledProbePins = 0x01;
// Analog pin connected to source power.  Set to 0xff to disable sampling
const unsigned char _pinBattery = 1;
// Digital pins for LEDs, 0xff to disable
const unsigned char _pinLedRx = 0xff;
const unsigned char _pinLedTx = 0xff; //9
// Digital pin used for sourcing power to the probe dividers
const unsigned char _pinProbeSupply = 4;
// Percentage (integer) of VCC where the battery is considered low (33% = 1.1V)
#define BATTERY_LOW_PCT 33
// Number of seconds to keep the "recent/new" bit set
#define RECENT_EXPIRE_SECS 1800
// Number of oversampling bits when measuring temperature [0-2]
#define TEMP_OVERSAMPLE_BITS 1

#define RF_PINS_PER_SOURCE 6
#define PIN_DISABLED(pin) ((_enabledProbePins & (1 << pin)) == 0)

// Bits used in output packet
// byte0/1 reserved Node IDs
#define NODEID_MASTER      0x3F
// byte1
#define BYTE1_DUAL_PROBE   0x10
#define BYTE1_RECENT_BOOT  0x20
// hygro byte
#define HYGRO_BATTERY_OK   0x00
#define HYGRO_BATTERY_LOW  0x80
#define HYGRO_NO_HYGRO     0x6A
#define HYGRO_SECOND_PROBE 0x7D
#define HYGRO_LMREMOTE_KEY 0x7F

#ifdef LMREMOTE_SERIAL
#undef MINIMAL_POWER_MODE
#endif

#if defined(MINIMAL_POWER_MODE)
  #define SLEEPMODE_TX    2
  #define SLEEPMODE_ADC   SLEEP_MODE_ADC
#else
  #define SLEEPMODE_TX    1
  #define SLEEPMODE_ADC   SLEEP_MODE_IDLE
#endif

#define RECV_CYCLE_TIME  5000    // expected receive cycle, millisecond
#define MIN_RECV_WIN     8       // minimum window size, power of 2
#define MAX_RECV_WIN     512     // maximum window size, power of 2

static unsigned int _previousReads[RF_PINS_PER_SOURCE];
static unsigned long _tempReadLast;
static unsigned int _loopCnt;
static unsigned char _sameCount;
static unsigned char _isRecent = BYTE1_RECENT_BOOT;
static unsigned char _isBattLow;

static unsigned int _recvCycleAct;
static unsigned int _recvWindow;
static unsigned long _recvLast;
static bool _recvSynced;

static bool packetReceived(unsigned char nodeId, unsigned int val)
{
#if LMREMOTE_SERIAL
  Serial.print(F("IN("));
  Serial.print(nodeId);
  Serial.print(',');
  Serial.print(rf12_rssi(), DEC);
  Serial.print(F(")="));
  Serial.print(val);
  Serial.print('\n');
#endif

  if (nodeId != NODEID_MASTER)
    return false;
  // val contains requested fan speed percent
  return true;
}

static bool rf12_doWork(void)
{
  if (rf12_recvDone() && rf12_crc == 0)
  {
    if (_pinLedRx != 0xff) digitalWrite(_pinLedRx, HIGH);

    unsigned char nodeId = ((rf12_buf[0] & 0x0f) << 2) | (rf12_buf[1] >> 6);
    unsigned int val = (rf12_buf[1] & 0x0f) << 8 | rf12_buf[2];
    return packetReceived(nodeId, val);
  }
  if (_pinLedRx != 0xff) digitalWrite(_pinLedRx, LOW);
  return false;
}

static volatile bool _adcBusy;
ISR(ADC_vect) { _adcBusy = false; }

static unsigned int analogReadSleep(unsigned char pin)
{
  _adcBusy = true;
  ADMUX = (DEFAULT << 6) | pin;
  bitSet(ADCSRA, ADIE);
  set_sleep_mode(SLEEPMODE_ADC);
  while (_adcBusy)
    sleep_mode();
  return ADC;
}

// The WDT is used solely to wake us from sleep
#if defined(MINIMAL_POWER_MODE)
static volatile bool _watchdogWaiting;
ISR(WDT_vect) { _watchdogWaiting = false; }

static void sleepPeriod(uint8_t wdt_period)
{
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  // Set the watchdog to wake us up and turn on its interrupt
  wdt_enable(wdt_period);
  WDTCSR |= bit(WDIE);

  // Turn off Brown Out Detector
  // sleep must be entered within 3 cycles of BODS being set
  sleep_enable();
  MCUCR = MCUCR | bit(BODSE) | bit(BODS);
  MCUCR = (MCUCR & ~bit(BODSE)) | bit(BODS);

  // Sleep
  sleep_cpu();

  // Back from sleep
  wdt_disable();
  sleep_disable();
}

static void sleepPwrDown(unsigned int msec)
// Code copied from Sleepy::loseSomeSleep(), jeelib
{
  unsigned int msleft = msec;
  while (msleft >= 16)
  {
    char wdp = 0; // wdp 0..9 corresponds to roughly 16..8192 ms
    // calc wdp as log2(msleft/16), i.e. loop & inc while next value is ok
    for (unsigned int m = msleft; m >= 32; m >>= 1)
      if (++wdp >= 9)
        break;
    _watchdogWaiting = true;
    sleepPeriod(wdp);
    unsigned int halfms = 8 << wdp;
    msleft -= halfms;
    if (_watchdogWaiting)
      continue;
    msleft -= halfms;
  }

  // adjust the milli ticks, since we will have missed several
#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny85__) || defined (__AVR_ATtiny44__)
    extern volatile unsigned long millis_timer_millis;
    millis_timer_millis += msecs - msleft;
#else
    extern volatile unsigned long timer0_millis;
    timer0_millis += msec - msleft;
#endif
}
#endif

static void sleepIdle(unsigned int msec)
{
  unsigned long start = millis();
  set_sleep_mode(SLEEP_MODE_IDLE);
  while (millis() - start < msec)
    sleep_mode();
}

static void sleep(unsigned int msec)
{
#if defined(MINIMAL_POWER_MODE)
  sleepPwrDown(msec);
#else
  sleepIdle(msec);
#endif /* SLEEP_MODE_PWR_DOWN */
}

static void resetEstimate(void)
{
#if defined(LMREMOTE_SERIAL) && defined(_DEBUG)
  Serial.print(F("Resetting Estimate\n"));
#endif
  _recvCycleAct = RECV_CYCLE_TIME;
  _recvWindow = MAX_RECV_WIN;
  _recvSynced = false;

  unsigned long start = millis();
  while (!rf12_doWork())
    if (millis() - start > RECV_CYCLE_TIME)
      return;
  _recvLast = millis();
}

static bool optimalSleep(void)
// Code adapted from jeelib/examples/syncRecv optimalSleep()
{
  unsigned char lost = (millis() - _recvLast + _recvCycleAct / 2) / _recvCycleAct;
  if (lost > 10)
  {
    resetEstimate();
    return false;
  }

  unsigned long predict = _recvLast + (lost + 1) * _recvCycleAct;
  unsigned int sleepDur =  predict - _recvWindow - millis();
  sleep(sleepDur);
  rf12_sleep(RF12_WAKEUP);

  unsigned long recvTime;
  unsigned long timeout = predict + _recvWindow;
  do {
    recvTime = millis();
    if ((long)(recvTime - timeout) >= 0)
    {
#if defined(LMREMOTE_SERIAL) && defined(_DEBUG)
      Serial.print(" f "); Serial.print(lost);
      Serial.print(" s "); Serial.print(sleepDur);
      Serial.print(" e "); Serial.print(_recvCycleAct);
      Serial.print(" w "); Serial.print(_recvWindow);
      Serial.print(" p "); Serial.print(predict);
      Serial.print(" r "); Serial.println(recvTime);
      Serial.flush();
#endif
      // double the window every N/2 packets lost
      ++lost;
      if (lost % 2 == 1 && _recvWindow < MAX_RECV_WIN)
        _recvWindow *= 2;

      return false;
    }
  } while (!rf12_doWork());

  unsigned int newEst = (recvTime - _recvLast) / (lost + 1);
  if (_recvSynced)
    _recvCycleAct = (4 * _recvCycleAct + newEst + 3) / 5; // 5-fold smoothing
  else
    _recvCycleAct = newEst;
  _recvLast = recvTime;

#if defined(LMREMOTE_SERIAL) && defined(_DEBUG)
  Serial.print(" n "); Serial.print(lost);
  Serial.print(" e "); Serial.print(_recvCycleAct);
  Serial.print(" E "); Serial.print(newEst);
  Serial.print(" w "); Serial.print(_recvWindow);
  Serial.print(" p "); Serial.print(predict);
  Serial.print(" r "); Serial.println(recvTime);
#endif

  if (_recvWindow > MIN_RECV_WIN)
    _recvWindow /= 2;
  else
    _recvSynced = true;

  return true;
}

static void updateBatteryLow(void)
{
  const unsigned char BATREAD_COUNT = 4;

  _isBattLow = HYGRO_BATTERY_OK;
  if (_pinBattery != 0xff)
  {
    unsigned int adcSum = 0;
    unsigned char battPct;
    for (unsigned char i=0; i<BATREAD_COUNT; ++i)
      adcSum += analogReadSleep(_pinBattery);
    // Percent of VCC
    battPct = (adcSum * 100UL) / (1024 * BATREAD_COUNT);

#ifdef LMREMOTE_SERIAL
    Serial.print("Battery %: "); Serial.print(battPct, DEC); Serial.print('\n');
#endif

    if (battPct < BATTERY_LOW_PCT)
      _isBattLow = HYGRO_BATTERY_LOW;
  }
}

static void transmitTemp(unsigned char pin)
{
  unsigned char outbuf[4];
  unsigned char nodeId = _rfNodeBaseId + pin;
  unsigned int val = _previousReads[pin];
  val <<= (12 - (10 + TEMP_OVERSAMPLE_BITS));
  outbuf[0] = 0x90 | ((nodeId & 0x3f) >> 2);
  outbuf[1] = ((nodeId & 0x3f) << 6) | _isRecent | (val >> 8);
  outbuf[2] = (val & 0xff);
  outbuf[3] = HYGRO_LMREMOTE_KEY | _isBattLow;
  //Serial.println(outbuf[3], HEX);

  // Don't check for air to be clear, we just woke from sleep and it will be milliseconds before
  // the RFM chip is actually up and running
  rf12_sendStart(outbuf, sizeof(outbuf));
  rf12_sendWait(SLEEPMODE_TX);
}

static void newTempsAvailable(void)
{
  // Enable the transmitter because it takes 1-5ms to turn on (3ms in my testing)
  rf12_sleep(RF12_WAKEUP);

  updateBatteryLow();
  // We're done with the ADC shut it down until the next wake cycle
  ADCSRA &= ~bit(ADEN);
  if (_isRecent && (millis() > RECENT_EXPIRE_SECS))
  {
    //Serial.print("No longer recent\n");
    _isRecent = 0;
  }

  boolean hasTransmitted = false;
  for (unsigned char pin=0; pin < RF_PINS_PER_SOURCE; ++pin)
  {
    if (PIN_DISABLED(pin))
      continue;
    if (hasTransmitted) sleep(16);
    transmitTemp(pin);
    hasTransmitted = true;
  }

  rf12_sleep(RF12_SLEEP);
  if (_pinLedTx != 0xff)
  {
    digitalWrite(_pinLedTx, HIGH);
    sleep(16);
    digitalWrite(_pinLedTx, LOW);
  }
}

static void stabilizeAdc(void)
{
  const unsigned char INTERNAL_REF = 0b1110;
  unsigned int last;
  unsigned char totalCnt = 0;
  unsigned char sameCnt = 0;
  unsigned int curr = analogReadSleep(INTERNAL_REF);
  // Reads the adc a bunch of times until the value settles
  // Usually you hear "discard the first few ADC readings after sleep"
  // but this seems a bit more scientific as we wait for the AREF cap to charge
  do {
    ++totalCnt;
#ifdef LMREMOTE_SERIAL
    Serial.print(curr, DEC);
    Serial.print(' ');
#endif
    last = curr;
    curr = analogReadSleep(INTERNAL_REF);
    if (last == curr)
      ++sameCnt;
    else
      sameCnt = 0;
  } while ((totalCnt < 64) && (sameCnt < 4));
}

static void checkTemps(void)
{
  const unsigned char OVERSAMPLE_COUNT[] = {1, 4, 16, 64};  // 4^n
  boolean modified = false;
  unsigned int oversampled_adc = 0;

#ifdef LMREMOTE_SERIAL
  Serial.print(millis(), DEC);
  Serial.print(" Checking temps: ");
#endif

  // Enable the ADC
  ADCSRA |= bit(ADEN);
  // The probe themistor voltage dividers are normally powered down
  // to save power, using digital lines to supply Vcc to them.
  digitalWrite(_pinProbeSupply, HIGH);
  // Wait for AREF capacitor to charge
  stabilizeAdc();

  for (unsigned char pin=0; pin < RF_PINS_PER_SOURCE; ++pin)
  {
    if (PIN_DISABLED(pin))
      continue;

    for (unsigned char o=0; o<OVERSAMPLE_COUNT[TEMP_OVERSAMPLE_BITS]; ++o)
    {
      unsigned int adc = analogReadSleep(pin);
      if (adc == 0 || adc >= 1023)
      {
        oversampled_adc = 0;
        break;
      }
      oversampled_adc += adc;
    }
    oversampled_adc = oversampled_adc >> TEMP_OVERSAMPLE_BITS;

#ifdef LMREMOTE_SERIAL
    Serial.print(oversampled_adc, DEC); Serial.print(' ');
#endif
    if (oversampled_adc != _previousReads[pin])
      modified = true;
    _previousReads[pin] = oversampled_adc;
  }
  digitalWrite(_pinProbeSupply, LOW);

#ifdef LMREMOTE_SERIAL
  Serial.print('\n');
#endif

  if (modified || (_sameCount > (30 / _sleepInterval)))
  {
    _sameCount = 0;
    newTempsAvailable();
  }
  else
    ++_sameCount;
  // Disable the ADC
  ADCSRA &= ~bit(ADEN);

  _tempReadLast = millis();
}

void setup(void)
{
  // Turn off the units we never use (this only affects non-sleep power)
  PRR = bit(PRUSART0) | bit(PRTWI) | bit(PRTIM1) | bit(PRTIM2);
  // Disable digital input buffers on the analog in ports
  DIDR0 = bit(ADC5D) | bit(ADC4D) | bit(ADC3D) | bit(ADC2D) | bit(ADC1D) | bit(ADC0D);
  DIDR1 = bit(AIN1D) | bit(AIN0D);

#ifdef LMREMOTE_SERIAL
  PRR &= ~bit(PRUSART0);
  Serial.begin(LMREMOTE_SERIAL); Serial.println("$UCID,lmremote"); Serial.flush();
#endif

  rf12_initialize(_rfBand);
  // Crystal 1.66MHz Low Battery Detect 2.2V
  rf12_control(0xC040);

  if (_pinLedRx != 0xff) pinMode(_pinLedRx, OUTPUT);
  if (_pinLedTx != 0xff) pinMode(_pinLedTx, OUTPUT);

  pinMode(_pinProbeSupply, OUTPUT);

  // Force a transmit on next read
  memset(_previousReads, 0xff, sizeof(_previousReads));
}

void loop(void)
{
  if (_loopCnt % 2 == 0)
    checkTemps();

#ifdef LMREMOTE_SERIAL
  Serial.flush();
#endif

  if (_recvLast == 0)
    resetEstimate();
  else
    optimalSleep();
  rf12_sleep(RF12_SLEEP);

  ++_loopCnt;
}

#include <avr/wdt.h>
#include <avr/sleep.h>
#include <rf12_itplus.h>

// Power down CPU as much as possible, and attempt to sync receiver at exact
// transmit time. Can't be used with LMREMOTE_SERIAL
// Or if an output is defined (fan/servo)
#define MINIMAL_POWER_MODE
// Enabling LMREMOTE_SERIAL also disables MINIMAL_POWER_MODE
#define LMREMOTE_SERIAL 38400

// Base Idenfier for the RFM12B (0-63)
// The transmitted ID is this ID plus the pin number
const char _rfNodeBaseId = 0;
// RFM12B band RF12_433MHZ, RF12_868MHZ, RF12_915MHZ
const unsigned char _rfBand = RF12_915MHZ;
// How many seconds to delay between measurements
const unsigned char _sleepInterval = 2;
// Analog pins to read. This is a bitfield, LSB is analog 0
const unsigned char _enabledProbePins = 0x01;
// Analog pin connected to source power.  Set to 0xff to disable sampling
const unsigned char _pinBattery = 1;
// Digital pins for LEDs, 0xff to disable
const unsigned char _pinLedRx = 0xff;
const unsigned char _pinLedTx = 0xff; //9
// Digital pin used for sourcing power to the probe dividers
const unsigned char _pinProbeSupply = 4;
// Percentage (integer) of VCC where the battery is considered low (33% = 1.1V)
#define BATTERY_LOW_PCT 33
// Number of seconds to keep the "recent/new" bit set
#define RECENT_EXPIRE_SECS 1800
// Number of oversampling bits when measuring temperature [0-2]
#define TEMP_OVERSAMPLE_BITS 1

#define RF_PINS_PER_SOURCE 6
#define PIN_DISABLED(pin) ((_enabledProbePins & (1 << pin)) == 0)

// Bits used in output packet
// byte0/1 reserved Node IDs
#define NODEID_MASTER      0x3F
// byte1
#define BYTE1_DUAL_PROBE   0x10
#define BYTE1_RECENT_BOOT  0x20
// hygro byte
#define HYGRO_BATTERY_OK   0x00
#define HYGRO_BATTERY_LOW  0x80
#define HYGRO_NO_HYGRO     0x6A
#define HYGRO_SECOND_PROBE 0x7D
#define HYGRO_LMREMOTE_KEY 0x7F

#ifdef LMREMOTE_SERIAL
#undef MINIMAL_POWER_MODE
#endif

#if defined(MINIMAL_POWER_MODE)
  #define SLEEPMODE_TX    2
  #define SLEEPMODE_ADC   SLEEP_MODE_ADC
#else
  #define SLEEPMODE_TX    1
  #define SLEEPMODE_ADC   SLEEP_MODE_IDLE
#endif

#define RECV_CYCLE_TIME  5000    // expected receive cycle, millisecond
#define MIN_RECV_WIN     8       // minimum window size, power of 2
#define MAX_RECV_WIN     512     // maximum window size, power of 2

static unsigned int _previousReads[RF_PINS_PER_SOURCE];
static unsigned long _tempReadLast;
static unsigned int _loopCnt;
static unsigned char _sameCount;
static unsigned char _isRecent = BYTE1_RECENT_BOOT;
static unsigned char _isBattLow;

static unsigned int _recvCycleAct;
static unsigned int _recvWindow;
static unsigned long _recvLast;
static bool _recvSynced;

static bool packetReceived(unsigned char nodeId, unsigned int val)
{
#if LMREMOTE_SERIAL
  Serial.print(F("IN("));
  Serial.print(nodeId);
  Serial.print(',');
  Serial.print(rf12_rssi(), DEC);
  Serial.print(F(")="));
  Serial.print(val);
  Serial.print('\n');
#endif

  if (nodeId != NODEID_MASTER)
    return false;
  // val contains requested fan speed percent
  return true;
}

static bool rf12_doWork(void)
{
  if (rf12_recvDone() && rf12_crc == 0)
  {
    if (_pinLedRx != 0xff) digitalWrite(_pinLedRx, HIGH);

    unsigned char nodeId = ((rf12_buf[0] & 0x0f) << 2) | (rf12_buf[1] >> 6);
    unsigned int val = (rf12_buf[1] & 0x0f) << 8 | rf12_buf[2];
    return packetReceived(nodeId, val);
  }
  if (_pinLedRx != 0xff) digitalWrite(_pinLedRx, LOW);
  return false;
}

static volatile bool _adcBusy;
ISR(ADC_vect) { _adcBusy = false; }

static unsigned int analogReadSleep(unsigned char pin)
{
  _adcBusy = true;
  ADMUX = (DEFAULT << 6) | pin;
  bitSet(ADCSRA, ADIE);
  set_sleep_mode(SLEEPMODE_ADC);
  while (_adcBusy)
    sleep_mode();
  return ADC;
}

// The WDT is used solely to wake us from sleep
#if defined(MINIMAL_POWER_MODE)
static volatile bool _watchdogWaiting;
ISR(WDT_vect) { _watchdogWaiting = false; }

static void sleepPeriod(uint8_t wdt_period)
{
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

  // Set the watchdog to wake us up and turn on its interrupt
  wdt_enable(wdt_period);
  WDTCSR |= bit(WDIE);

  // Turn off Brown Out Detector
  // sleep must be entered within 3 cycles of BODS being set
  sleep_enable();
  MCUCR = MCUCR | bit(BODSE) | bit(BODS);
  MCUCR = (MCUCR & ~bit(BODSE)) | bit(BODS);

  // Sleep
  sleep_cpu();

  // Back from sleep
  wdt_disable();
  sleep_disable();
}

static void sleepPwrDown(unsigned int msec)
// Code copied from Sleepy::loseSomeSleep(), jeelib
{
  unsigned int msleft = msec;
  while (msleft >= 16)
  {
    char wdp = 0; // wdp 0..9 corresponds to roughly 16..8192 ms
    // calc wdp as log2(msleft/16), i.e. loop & inc while next value is ok
    for (unsigned int m = msleft; m >= 32; m >>= 1)
      if (++wdp >= 9)
        break;
    _watchdogWaiting = true;
    sleepPeriod(wdp);
    unsigned int halfms = 8 << wdp;
    msleft -= halfms;
    if (_watchdogWaiting)
      continue;
    msleft -= halfms;
  }

  // adjust the milli ticks, since we will have missed several
#if defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny85__) || defined (__AVR_ATtiny44__)
    extern volatile unsigned long millis_timer_millis;
    millis_timer_millis += msecs - msleft;
#else
    extern volatile unsigned long timer0_millis;
    timer0_millis += msec - msleft;
#endif
}
#endif

static void sleepIdle(unsigned int msec)
{
  unsigned long start = millis();
  set_sleep_mode(SLEEP_MODE_IDLE);
  while (millis() - start < msec)
    sleep_mode();
}

static void sleep(unsigned int msec)
{
#if defined(MINIMAL_POWER_MODE)
  sleepPwrDown(msec);
#else
  sleepIdle(msec);
#endif /* SLEEP_MODE_PWR_DOWN */
}

static void resetEstimate(void)
{
#if defined(LMREMOTE_SERIAL) && defined(_DEBUG)
  Serial.print(F("Resetting Estimate\n"));
#endif
  _recvCycleAct = RECV_CYCLE_TIME;
  _recvWindow = MAX_RECV_WIN;
  _recvSynced = false;

  unsigned long start = millis();
  while (!rf12_doWork())
    if (millis() - start > RECV_CYCLE_TIME)
      return;
  _recvLast = millis();
}

static bool optimalSleep(void)
// Code adapted from jeelib/examples/syncRecv optimalSleep()
{
  unsigned char lost = (millis() - _recvLast + _recvCycleAct / 2) / _recvCycleAct;
  if (lost > 10)
  {
    resetEstimate();
    return false;
  }

  unsigned long predict = _recvLast + (lost + 1) * _recvCycleAct;
  unsigned int sleepDur =  predict - _recvWindow - millis();
  sleep(sleepDur);
  rf12_sleep(RF12_WAKEUP);

  unsigned long recvTime;
  unsigned long timeout = predict + _recvWindow;
  do {
    recvTime = millis();
    if ((long)(recvTime - timeout) >= 0)
    {
#if defined(LMREMOTE_SERIAL) && defined(_DEBUG)
      Serial.print(" f "); Serial.print(lost);
      Serial.print(" s "); Serial.print(sleepDur);
      Serial.print(" e "); Serial.print(_recvCycleAct);
      Serial.print(" w "); Serial.print(_recvWindow);
      Serial.print(" p "); Serial.print(predict);
      Serial.print(" r "); Serial.println(recvTime);
      Serial.flush();
#endif
      // double the window every N packets lost
      ++lost;
      if (lost % 2 == 0 && _recvWindow < MAX_RECV_WIN)
        _recvWindow *= 2;

      return false;
    }
  } while (!rf12_doWork());

  unsigned int newEst = (recvTime - _recvLast) / (lost + 1);
  if (_recvSynced)
    _recvCycleAct = (4 * _recvCycleAct + newEst + 3) / 5; // 5-fold smoothing
  else
    _recvCycleAct = newEst;
  _recvLast = recvTime;

#if defined(LMREMOTE_SERIAL) && defined(_DEBUG)
  Serial.print(" n "); Serial.print(lost);
  Serial.print(" e "); Serial.print(_recvCycleAct);
  Serial.print(" E "); Serial.print(newEst);
  Serial.print(" w "); Serial.print(_recvWindow);
  Serial.print(" p "); Serial.print(predict);
  Serial.print(" r "); Serial.println(recvTime);
#endif

  if (_recvWindow > MIN_RECV_WIN)
    _recvWindow /= 2;
  else
    _recvSynced = true;

  return true;
}

static void updateBatteryLow(void)
{
  const unsigned char BATREAD_COUNT = 4;

  _isBattLow = HYGRO_BATTERY_OK;
  if (_pinBattery != 0xff)
  {
    unsigned int adcSum = 0;
    unsigned char battPct;
    for (unsigned char i=0; i<BATREAD_COUNT; ++i)
      adcSum += analogReadSleep(_pinBattery);
    // Percent of VCC
    battPct = (adcSum * 100UL) / (1024 * BATREAD_COUNT);

#ifdef LMREMOTE_SERIAL
    Serial.print("Battery %: "); Serial.print(battPct, DEC); Serial.print('\n');
#endif

    if (battPct < BATTERY_LOW_PCT)
      _isBattLow = HYGRO_BATTERY_LOW;
  }
}

static void transmitTemp(unsigned char pin)
{
  unsigned char outbuf[4];
  unsigned char nodeId = _rfNodeBaseId + pin;
  unsigned int val = _previousReads[pin];
  val <<= (12 - (10 + TEMP_OVERSAMPLE_BITS));
  outbuf[0] = 0x90 | ((nodeId & 0x3f) >> 2);
  outbuf[1] = ((nodeId & 0x3f) << 6) | _isRecent | (val >> 8);
  outbuf[2] = (val & 0xff);
  outbuf[3] = HYGRO_LMREMOTE_KEY | _isBattLow;
  //Serial.println(outbuf[3], HEX);

  // Don't check for air to be clear, we just woke from sleep and it will be milliseconds before
  // the RFM chip is actually up and running
  rf12_sendStart(outbuf, sizeof(outbuf));
  rf12_sendWait(SLEEPMODE_TX);
}

static void newTempsAvailable(void)
{
  // Enable the transmitter because it takes 1-5ms to turn on (3ms in my testing)
  rf12_sleep(RF12_WAKEUP);

  updateBatteryLow();
  // We're done with the ADC shut it down until the next wake cycle
  ADCSRA &= ~bit(ADEN);
  if (_isRecent && (millis() > RECENT_EXPIRE_SECS))
  {
    //Serial.print("No longer recent\n");
    _isRecent = 0;
  }

  boolean hasTransmitted = false;
  for (unsigned char pin=0; pin < RF_PINS_PER_SOURCE; ++pin)
  {
    if (PIN_DISABLED(pin))
      continue;
    if (hasTransmitted) sleep(16);
    transmitTemp(pin);
    hasTransmitted = true;
  }

  rf12_sleep(RF12_SLEEP);
  if (_pinLedTx != 0xff)
  {
    digitalWrite(_pinLedTx, HIGH);
    sleep(16);
    digitalWrite(_pinLedTx, LOW);
  }
}

static void stabilizeAdc(void)
{
  const unsigned char INTERNAL_REF = 0b1110;
  unsigned int last;
  unsigned char totalCnt = 0;
  unsigned char sameCnt = 0;
  unsigned int curr = analogReadSleep(INTERNAL_REF);
  // Reads the adc a bunch of times until the value settles
  // Usually you hear "discard the first few ADC readings after sleep"
  // but this seems a bit more scientific as we wait for the AREF cap to charge
  do {
    ++totalCnt;
#ifdef LMREMOTE_SERIAL
    Serial.print(curr, DEC);
    Serial.print(' ');
#endif
    last = curr;
    curr = analogReadSleep(INTERNAL_REF);
    if (last == curr)
      ++sameCnt;
    else
      sameCnt = 0;
  } while ((totalCnt < 64) && (sameCnt < 4));
}

static void checkTemps(void)
{
  const unsigned char OVERSAMPLE_COUNT[] = {1, 4, 16, 64};  // 4^n
  boolean modified = false;
  unsigned int oversampled_adc = 0;

#ifdef LMREMOTE_SERIAL
  Serial.print(millis(), DEC);
  Serial.print(" Checking temps: ");
#endif

  // Enable the ADC
  ADCSRA |= bit(ADEN);
  // The probe themistor voltage dividers are normally powered down
  // to save power, using digital lines to supply Vcc to them.
  digitalWrite(_pinProbeSupply, HIGH);
  // Wait for AREF capacitor to charge
  stabilizeAdc();

  for (unsigned char pin=0; pin < RF_PINS_PER_SOURCE; ++pin)
  {
    if (PIN_DISABLED(pin))
      continue;

    for (unsigned char o=0; o<OVERSAMPLE_COUNT[TEMP_OVERSAMPLE_BITS]; ++o)
    {
      unsigned int adc = analogReadSleep(pin);
      if (adc == 0 || adc >= 1023)
      {
        oversampled_adc = 0;
        break;
      }
      oversampled_adc += adc;
    }
    oversampled_adc = oversampled_adc >> TEMP_OVERSAMPLE_BITS;

#ifdef LMREMOTE_SERIAL
    Serial.print(oversampled_adc, DEC); Serial.print(' ');
#endif
    if (oversampled_adc != _previousReads[pin])
      modified = true;
    _previousReads[pin] = oversampled_adc;
  }
  digitalWrite(_pinProbeSupply, LOW);

#ifdef LMREMOTE_SERIAL
  Serial.print('\n');
#endif

  if (modified || (_sameCount > (30 / _sleepInterval)))
  {
    _sameCount = 0;
    newTempsAvailable();
  }
  else
    ++_sameCount;
  // Disable the ADC
  ADCSRA &= ~bit(ADEN);

  _tempReadLast = millis();
}

void setup(void)
{
  // Turn off the units we never use (this only affects non-sleep power)
  PRR = bit(PRUSART0) | bit(PRTWI) | bit(PRTIM1) | bit(PRTIM2);
  // Disable digital input buffers on the analog in ports
  DIDR0 = bit(ADC5D) | bit(ADC4D) | bit(ADC3D) | bit(ADC2D) | bit(ADC1D) | bit(ADC0D);
  DIDR1 = bit(AIN1D) | bit(AIN0D);

#ifdef LMREMOTE_SERIAL
  PRR &= ~bit(PRUSART0);
  Serial.begin(LMREMOTE_SERIAL); Serial.println("$UCID,lmremote"); Serial.flush();
#endif

  rf12_initialize(_rfBand);
  // Crystal 1.66MHz Low Battery Detect 2.2V
  rf12_control(0xC040);

  if (_pinLedRx != 0xff) pinMode(_pinLedRx, OUTPUT);
  if (_pinLedTx != 0xff) pinMode(_pinLedTx, OUTPUT);

  pinMode(_pinProbeSupply, OUTPUT);

  // Force a transmit on next read
  memset(_previousReads, 0xff, sizeof(_previousReads));
}

void loop(void)
{
  if (_loopCnt % 2 == 0)
    checkTemps();

#ifdef LMREMOTE_SERIAL
  Serial.flush();
#endif

  if (_recvLast == 0)
    resetEstimate();
  else
    optimalSleep();
  rf12_sleep(RF12_SLEEP);

  ++_loopCnt;
}


trying to configure the TMC260

trying to configure the TMC260


Added synchronised threads (semaphores) example

#include <stdio.h>

IO::PIC32 Core;
IO::Pin LED(Core, 13, IO::OUTPUT, IO::LOW);

const char states[] = {'Z', 'R', 'S', 'H', 'M', 'W'};

thread blnk;
thread topscreen;

semaphore sem;

void setup() {
	printf("\e[2J");
	blnk = Thread::Create("blink",blinker, 0, 512);
	topscreen = Thread::Create("top",top, 0, 512);
}

uint32_t spoon;

void blinker(uint32_t x) {
	while(1) {
		Thread::Signal(sem);
		LED.write(IO::HIGH);
		Thread::Sleep(100);
		LED.write(IO::LOW);
		Thread::Sleep(500);
	}
}

extern thread ThreadList;
extern thread currentThread;

void top(uint32_t x) {
	while(1) {
		Thread::Wait(sem);
	    printf("\e[0;0H");
	    printf("Uptime: %lums\n", Thread::Milliseconds());
	    printf("Entry    Thread     Stack %%CPU S A\n");
	    for (thread scan = ThreadList; scan; scan = scan->next) {
	        printf("%08X %-10s %-4d %4d%% %c %c\n",
	            scan->entry,
	            scan->name, (scan->stack_head - scan->sp) * 4,
	            Thread::Runtime(scan) * 100 / Thread::Milliseconds(),
	            states[scan->state],
	            scan == currentThread? '*' : ' '
	        );
	    }
		Thread::Sleep(100);
	}
}

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


Change to drive 24 NeoPixels

Change to drive 24 NeoPixels

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


beginnings of arduino code stitch

beginnings of arduino code stitch

#include <Wire.h>
//#include <SPI.h>
#include <RTC_DS3231.h>  // rtc

RTC_DS3231 RTC;

void setup() {

  Wire.begin(); // I2C init as master

  setupRTC();

}

void setupRTC() {

  RTC.begin();

  if (!RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

  // set the date on the RTC to be the date and time of compilation.
  // this may result in a few-second offset between "real" time and
  // RTC time, but this is negligible as temperature will not change
  // drastically in a matter of a few seconds
  DateTime now = RTC.now();
  DateTime compiled = DateTime(__DATE__, __TIME__);
  if (now.unixtime() < compiled.unixtime()) {
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }
}

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

}

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


Ajout du code Arduino (Programme principal)

- Implémentation de l'envoie des informations
de l'ultrason toutes les secondes sur le port Serial
- Implémentation de 'PUMP_IN' représenté par une LED

#define VITESSE 340000 //vitesse du son 340000 mm/s

const int USTrig = 8; // Déclencheur sur la broche 8
const int USEcho = 9; // Réception sur la broche 9
const int led = 2; // LED sur la broche 2

String command = "";
boolean commandComplete = false;
boolean isSent = false;

void setup() {
    Serial.begin(9600);
    pinMode(led, OUTPUT);
    digitalWrite(led, HIGH);

    command.reserve(200);
    setupWaterLevel();
}

void loop() {
  if (checkSending()) {
    // Send values
    readWaterLevel();
  }

  if (commandComplete) {
    checkCommand(command);

    // Clear the command:
    command = "";
    commandComplete = false;
  }
}

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

boolean checkSending() {
  if ((millis() % 1000) < 500) {
    if (!isSent) {
      isSent = true;
      return true;
    }
  } else {
    isSent = false;
  }

  return false;
}

void checkCommand(String command) {
  Serial.print(command);
  if (command.startsWith("PUMP_IN=0")) {
    Serial.println("LED OFF");
    digitalWrite(led, HIGH);
  } else if (command.startsWith("PUMP_IN=1")) {
    Serial.println("LED ON");
    digitalWrite(led, LOW);
  }
}

void setupWaterLevel() {
  pinMode(USTrig, OUTPUT);
  pinMode(USEcho, INPUT);

  digitalWrite(USTrig, LOW);
}

void readWaterLevel() {
  // 1. Un état haut de 10 microsecondes est mis sur la broche "Trig"
  digitalWrite(USTrig, HIGH);
  delayMicroseconds(10); //on attend 10 µs
  // 2. On remet à l’état bas la broche Trig
  digitalWrite(USTrig, LOW);

  // 3. On lit la durée d’état haut sur la broche "Echo"
  unsigned long duree = pulseIn(USEcho, HIGH);

  if(duree > 30000)
  {
    // si la durée est supérieure à 30ms, l'onde est perdue
    //Serial.println("Onde perdue, mesure échouée !");
  }
  else
  {
    // 4. On divise cette durée par deux pour n'avoir qu'un trajet
    duree = duree/2;

    // 5. On calcule la distance avec la formule d=v*t
    float temps = duree/1000000.0; //on met en secondes
    long distance = long(temps*VITESSE); //on multiplie par la vitesse, d=t*v

    // 6. On affiche la distance
    Serial.println(distance); //affiche la distance mesurée (en mètres)
  }
}

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


develop

develop

//
//  Air Quality Sensor Suite
//
#include <Bridge.h>
Process p;

//
// Bridge and Modbus helper functions
//

// write a float to the bridge
void setFloat(char *a, float v) {
  Bridge.put(a, String(v));
}
// read a float from the bridge
#define BUF_SIZE 32
float getFloat(char *a) {
  char buf[BUF_SIZE];
  Bridge.get(a, buf, BUF_SIZE);
  return atof(buf);
}

//
// Modbus register map
//
// modpoll -m tcp -0 -c7 -t 4:float -r 40001 [ip_addr]
// modpoll -m tcp -0 -c3 -t 4:float -r 40101 [ip_addr]
//
#define RO_START "40001" // ro block
#define RO_LENGTH "7"
#define S0_CurrentMillis         "40001"
#define S1_TemperatureF          "40003"
#define S1_Humidity              "40005"
#define S2_ConcentrationPM10     "40007"
#define S2_ConcentrationPM25     "40009"
#define S3_Concentration         "40011"
#define S3_Alarm                 "40013"

#define RW_START "40101" // rw block
#define RW_LENGTH "3"
#define S1_UpdateInterval        "40101"
#define S2_UpdateInterval        "40103"
#define S2_FilterWeight          "40105"

//
// S1 Adafruit DHT22
// https://learn.adafruit.com/dht/connecting-to-a-dhtxx-sensor
//
#include "DHT.h"
#define S1_Pin 11
#define S1_Type DHT22
DHT dht(S1_Pin, S1_Type);

//
// S2 - Shinyei Model PPD42NS Particle Sensor
// http://www.sca-shinyei.com/pdf/PPD42NS.pdf
// SW-PWM-01A
// http://www.mouser.com/pdfdocs/AAS920643ATelaireDustSensor081414web.PDF
// http://www.digikey.com/Web%20Export/Supplier%20Content/amphenol-advanced-sensors-45/pdf/amphenol-advanced-smart-sensor.pdf?redirected=1
//
#define S2_P1_Pin 10
#define S2_P2_Pin  9

//
// S3 - MQ-2
//
#define MQ2_D  12
#define MQ2_A  A0

void setup(void)
{
//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(RO_START);                      // read only start address
  p.addParameter(RO_LEN);                        // read only number of holding registers
  p.addParameter(RW_START);                      // read/write start address (optional)
  p.addParameter(RW_LEN);                        // read/write number of holding registers (optional)
  p.runAsynchronously();

  // Initialize S1
  dht.begin();
  setFloat(S1_UpdateInterval, 10000.0);

  // Initialize S2
  pinMode(S2_P1_Pin, INPUT);

  //  digitalWrite(S2_P1_Pin, HIGH);
  pinMode(S2_P2_Pin, INPUT);

  //  digitalWrite(S2_P2_Pin, HIGH);
  setFloat(S2_UpdateInterval, 10000.0);
  setFloat(S2_FilterWeight, 30.0);

  // pin change interrupt
  PCMSK0 |= bit (PCINT5);  // want pin  9
  PCMSK0 |= bit (PCINT6);  // want pin 10
  PCIFR  |= bit (PCIF0);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0);   // enable pin change interrupts for D8 to D13

  // Initialize S3
  pinMode(MQ2_A, INPUT);
  pinMode(MQ2_D, INPUT);
}

// interrupt and timer storage
unsigned long S1StartTime = 0, S2StartTime = 0;
int state09 = HIGH, state10 = HIGH;
unsigned long start09, start10;
volatile unsigned long lpo09, lpo10;

// optional limiter for S2
unsigned long limit(unsigned long x) {
  //  return (x < 10000ul || x > 90000ul) ? 0 : x;
  return x;
}
// interrupt service routine
ISR (PCINT0_vect) {
  unsigned long us = micros();
  if (state09 != digitalRead(S2_P2_Pin))
    if ((state09 = digitalRead(S2_P2_Pin)) == LOW)
      start09 = us;
    else
      lpo09 += limit(us - start09);
  if (state10 != digitalRead(S2_P1_Pin))
    if ((state10 = digitalRead(S2_P1_Pin)) == LOW)
      start10 = us;
    else
      lpo10 += limit(us - start10);
}

//
// poll the sensors and update the bridge
//
void loop(void)
{
  unsigned long curMillis = millis();
  float x, y;

  // S0 - suite
  setFloat(S0_CurrentMillis, curMillis);

  // S1 - temperature and humidity
  if (curMillis - S1StartTime > getFloat(S1_UpdateInterval)) {
    digitalWrite(13, HIGH);
    setFloat(S1_TemperatureF, dht.readTemperature(true) - 4.0); // correction for mounting too close to MQ-2
    setFloat(S1_Humidity, dht.readHumidity());

    S1StartTime = curMillis;
    digitalWrite(13, LOW);
  }

  // S2 - particulate dust
  if (curMillis - S2StartTime > getFloat(S2_UpdateInterval)) {
    digitalWrite(13, HIGH);
    x = 0.1 * float(lpo10) / getFloat(S2_UpdateInterval);
    y = 1.1 * x * x * x  - 3.8 * x * x + 520 * x; // + 0.62;
    setFloat(S2_ConcentrationPM10, (y + getFloat(S2_ConcentrationPM10) * (getFloat(S2_FilterWeight) - 1.0)) / getFloat(S2_FilterWeight));
    lpo10 = 0;

    x = 0.1 * float(lpo09) / getFloat(S2_UpdateInterval);
    y = 1.1 * x * x * x  - 3.8 * x * x + 520 * x; // + 0.62;
    setFloat(S2_ConcentrationPM25, (y + getFloat(S2_ConcentrationPM25) * (getFloat(S2_FilterWeight) - 1.0)) / getFloat(S2_FilterWeight));

    lpo09 = 0;
    S2StartTime = curMillis;
    digitalWrite(13, LOW);
  }

  // S3 - volatile organic compounds
  setFloat(S3_Concentration, (5.0 / 4.0) * (float(analogRead(MQ2_A)) / 1024.0));
  setFloat(S3_Alarm, float(digitalRead(MQ2_D)));
}

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


test version of a master node

test version of a master node

#include <SPI85.h>
#include <Mirf.h>
#include <nRF24L01.h>
#include <MirfHardwareSpi85Driver.h>

const uint64_t ADDRESS = 0x45;
byte addr[mirf_ADDR_LEN] = { ADDRESS, 0, 0, 0, 0 };

void setup()
{
    Serial.begin(9600);
    Serial.println("master starting");

    Mirf.spi = &MirfHardwareSpi85;
    Mirf.cePin = 7;
    Mirf.csnPin = 3;
    Mirf.init();
    Mirf.setRADDR((byte *)"abcde");
    Mirf.payload = 3;
    Mirf.channel = 160;
    Mirf.configRegister(RF_SETUP,0x05); // 1mbps rate, HIGH transmit rate
    //Mirf.configRegister(EN_AA, 0);      // turn off auto ack for all channels.
    Mirf.baseConfig = _BV(EN_CRC) | _BV(CRCO);
    Mirf.config();
    delay(100);

    Serial.println("startup complete:" + String(Mirf.getStatus()));
    pinMode(1, OUTPUT);
}

uint32_t color_wheel(byte WheelPos, byte color[3])
{
    WheelPos = 255 - WheelPos;
    if(WheelPos < 85)
    {
        color[0] = 255 - WheelPos * 3;
        color[1] = 0;
        color[2] = WheelPos * 3;
    }
    else if(WheelPos < 170)
    {
        WheelPos -= 85;
        color[0] = 0;
        color[1] = WheelPos * 3;
        color[2] = 255 - WheelPos * 3;
    }
    else
    {
        WheelPos -= 170;
        color[0] = WheelPos * 3;
        color[1] = 255 - WheelPos * 3;
        color[2] = 0;
    }
}

void loop()
{
    uint16_t j;
    byte col[3];

    Mirf.setTADDR((byte *)"aaaaa");

    //col[0] = i % 2 ? 255 : 0;
    //col[1] = 0;
    //col[2] = i % 2 ? 0 : 255;
    //Serial.println("data: " + String(col[0]) + " " + String(col[1]) + " " + String(col[2]));

    for(j=0; j<256*5; j++)
    {
        color_wheel(j & 255, col);
        Mirf.send(col);
        while(Mirf.isSending())
            ;

        if (j % 2)
            digitalWrite(1, HIGH);
        else
            digitalWrite(1, LOW);
        delay(20);
    }
}

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


add new ledNode example sketch

add new ledNode example sketch

// Programmable color ramps for the LED drivers on the LED Node
// 2011-10-26 <jcw@equi4.com> http://opensource.org/licenses/mit-license.php

#include <JeeLib.h>
#include <EEPROM.h>
#include <avr/sleep.h>

#define EEPROM_BASE 0x100 // store ramps starting at this offset
#define RAMP_LIMIT 100    // room for ramps 0..99, stored in EEPROM

#define LED_R 6   // the PWM pin which drives the red LED
#define LED_G 9   // the PWM pin which drives the green LED
#define LED_B 5   // the PWM pin which drives the blue LED

// a "Ramp" is a target RGB color and the time in seconds to reach that color
// ramps can be chained together with a non-zero ramp index in the chain field
typedef struct {
  byte colors[3]; // red, green, blue, 0..255
  byte steps;     // number of seconds used to reach given RGB colors
  byte chain;     // next ramp to use when done, or 0 to stay as is
} Ramp;

long now[3];      // current PWM values, as 9+23 bit fractional int
long delta[3];    // current PWM deltas, as 9+23 bit fractional int
word duration;    // number of 0.01s steps remaining in this ramp
byte nextRamp;    // which saved ramp to use next (or none if zero)
MilliTimer timer; // used as timer for the 0.01s steps

static Ramp stdRamps[] = {
  {   0,   0,   0, 0, 0    }, // 0: instant off
  { 255, 100,  50, 0, 0    }, // 1: instant warm white
  { 255, 200, 150, 0, 0    }, // 2: instant cold white
  {   0,   0,   0, 0, 300  }, // 3: 3s off
  { 255, 100,  50, 0, 300  }, // 4: 3s warm white
  { 255, 200, 150, 0, 300  }, // 5: 3s cold white
  { 255,   0,   0, 7, 300  }, // 6: 3s red -> green -> blue
  {   0, 255,   0, 8, 300  }, // 7: 3s green -> blue -> red
  {   0,   0, 255, 6, 300  }, // 8: 3s blue -> red -> green
  {   7,   1,   0, 0, 0    }, // 9: instant faint red'ish yellow
};

static void setLeds () {
  // set to bits 30..23, but rounded by one extra bit (i.e. bit 22)
  analogWrite(LED_R, (byte) (((word) (now[0] >> 22) + 1) >> 1));
  analogWrite(LED_G, (byte) (((word) (now[1] >> 22) + 1) >> 1));
  analogWrite(LED_B, (byte) (((word) (now[2] >> 22) + 1) >> 1));
}

static void useRamp (const void* ptr) {
  const Ramp* ramp = (const Ramp*) ptr;
  nextRamp = ramp->chain;
  duration = ramp->steps * 100;
  for (byte i = 0; i < 3; ++i) {
    long target = (long) ramp->colors[i] << 23;
    if (duration > 0)
      delta[i] = (target - now[i]) / duration;
    else
      now[i] = target;
  }
  setLeds();
}

static void loadRamp (byte pos) {
  if (pos < RAMP_LIMIT) {
    word addr = EEPROM_BASE + pos * sizeof (Ramp);
    Ramp ramp;
    for (byte i = 0; i < sizeof (Ramp); ++i)
      ((byte*) &ramp)[i] = EEPROM.read(addr+i);
    useRamp(&ramp);
  }
}

static void saveRamp (byte pos, const void* data) {
  if (pos < RAMP_LIMIT) {
    word addr = EEPROM_BASE + pos * sizeof (Ramp);
    for (byte i = 0; i < sizeof (Ramp); ++i)
      EEPROM.write(addr+i, ((const byte*) data)[i]);
  }
}

void setup () {
  for (byte i = 0; i < sizeof stdRamps / sizeof *stdRamps; ++i)
    saveRamp(i, stdRamps + i);
  rf12_initialize(1, RF12_868MHZ, 19);
}

void loop () {
  set_sleep_mode(SLEEP_MODE_IDLE);
  sleep_mode();

  if (timer.poll(10)) {
    if (duration > 0) {
      --duration;
      for (byte i = 0; i < 3; ++i)
        now[i] += delta[i];
      setLeds();
    } else if (nextRamp != 0)
      loadRamp(nextRamp);
  }

  if (rf12_recvDone() && rf12_crc == 0) {
    const byte* p = (const byte*) rf12_data;
    if (rf12_len == 1) {
      // a single byte loads the ramp from EEPROM
      loadRamp(rf12_data[0]);
    } else if (rf12_len == 1 + sizeof (Ramp)) {
      // 6 bytes, either a save or an immediate command
      // make sure that slot zero, i.e. "all-off", is never overwritten
      if (rf12_data[0] > 0) // save the date to EEPROM, if slot is not zero
        saveRamp(rf12_data[0], (const Ramp*) (rf12_data + 1));
      else // use the ramp as is without saving, if slot is zero
        useRamp((const Ramp*) (rf12_data + 1));
    }
  }
}

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


Working accelstepper version

Working accelstepper version

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


example file

example file

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


Optimized encryption

Optimized encryption

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

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


Changed arduino code.

Changed arduino code.

Conflicts:
	arduino/eva.ino

#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>
#include <Hash.h>

WebSocketsServer webSocket = WebSocketsServer(81);

#define USE_SERIAL Serial1

#define ECHO_PIN1     5//D1
#define TRIGGER_PIN1  4//D2

#define ECHO_PIN2     0//D3
#define TRIGGER_PIN2  2//D4

#define ECHO_PIN3     14//D5
#define TRIGGER_PIN3  12//D6

#define ECHO_PIN4     13//D7
#define TRIGGER_PIN4  15//D8

#define ECHO_PIN5     16//D0
#define TRIGGER_PIN5  15//D8

const char* ssid     = "emag.net";
const char* password = "<aici e parola de la emag.net>";

long Distance(long time)
{
    // speed of sound at sea level = 340.29 m / s
    // ((time)*(Speed of sound))/ toward and backward of object) * 10

    long DistanceCalc;                      // Calculation variable
    DistanceCalc = time * 0.034 / 2;        // Actual calculation in cm
    //DistanceCalc = (time / 2.9) / 2;      // Actual calculation in mm
    //DistanceCalc = time / 74 / 2;         // Actual calculation in inches

    return DistanceCalc;                    // return calculated value
}

long getSonicSensorData(uint8_t trigger, uint8_t echo) {
  long duration, distance;

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

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

  digitalWrite(trigger, LOW);

  duration = pulseIn(echo, HIGH);
  distance = Distance(duration);

  Serial.print("Sensor ");
  Serial.print(trigger);
  Serial.print(" -> ");
  Serial.println(distance);

  return distance;
}

char* getJsonDataFromSensors() {
      StaticJsonBuffer<200> jsonBuffer;

      JsonObject& object = jsonBuffer.createObject();

      object.set("sens_length_init", 148);
      object.set("sens_length_1", getSonicSensorData(TRIGGER_PIN1, ECHO_PIN1));
      delay(100);
      object.set("sens_length_2", getSonicSensorData(TRIGGER_PIN2, ECHO_PIN2));
      delay(100);

      object.set("sens_width_init", 98);
      object.set("sens_width_1", getSonicSensorData(TRIGGER_PIN3, ECHO_PIN3));
      delay(100);
      object.set("sens_width_2", getSonicSensorData(TRIGGER_PIN4, ECHO_PIN4));
      delay(100);

      object.set("sens_height_init", 100);
      object.set("sens_height_1", getSonicSensorData(TRIGGER_PIN5, ECHO_PIN5));

      char json[256];
      object.printTo(json, sizeof(json));

      return json;
}

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
    String pld = (char*)payload;

    switch(type) {
        case WStype_DISCONNECTED:
            USE_SERIAL.printf("[%u] Disconnected!\n", num);
            Serial.println("User disconnected from websocket.");

            break;
        case WStype_CONNECTED:
            {
                IPAddress ip = webSocket.remoteIP(num);
                USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
                Serial.println("User connected to websocket.");

                // send message to client
                //webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
            USE_SERIAL.printf("[%u] get Text: %s\n", num, payload);
            Serial.println(pld);

            if (pld == "GET_MEASUREMENTS") {
                // send message to client
                webSocket.sendTXT(num, getJsonDataFromSensors());
            }

            // send data to all connected clients
            // webSocket.broadcastTXT("message here");
            break;
        case WStype_BIN:
            USE_SERIAL.printf("[%u] get binary lenght: %u\n", num, lenght);
            hexdump(payload, lenght);

            // send message to client
            // webSocket.sendBIN(num, payload, lenght);
            break;
    }

}

void WiFiEvent(WiFiEvent_t event) {
    Serial.printf("[WiFi-event] event: %d\n", event);

    switch(event) {
        case WIFI_EVENT_STAMODE_GOT_IP:
            Serial.println("WiFi connected");
            Serial.println("IP address: ");
            Serial.println(WiFi.localIP());
            break;
        case WIFI_EVENT_STAMODE_DISCONNECTED:
            Serial.println("WiFi lost connection");
            break;
    }
}

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

    // delete old config
    WiFi.disconnect(true);

    delay(1000);

    WiFi.onEvent(WiFiEvent);

    WiFi.begin(ssid, password);

    Serial.println();
    Serial.println();
    Serial.println("Wait for WiFi... ");

    webSocket.begin();
    webSocket.onEvent(webSocketEvent);

    pinMode(TRIGGER_PIN1, OUTPUT);
    pinMode(ECHO_PIN1, INPUT);

    pinMode(TRIGGER_PIN2, OUTPUT);
    pinMode(ECHO_PIN2, INPUT);

    pinMode(TRIGGER_PIN3, OUTPUT);
    pinMode(ECHO_PIN3, INPUT);

    pinMode(TRIGGER_PIN4, OUTPUT);
    pinMode(ECHO_PIN4, INPUT);

    pinMode(TRIGGER_PIN5, OUTPUT);
    pinMode(ECHO_PIN5, INPUT);
}

void loop() {
    delay(1000);
    webSocket.loop();
}

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


Testing

Testing

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


First Working Code

First Working Code

This code has the basics of functionality for most mission aspects. It
does not contain radio at the moment.

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/tylergrreid/Arduino_Flight_Computer.git/'


添加多多二代futaba舵机控制程序，包含巡线采集程序

添加多多二代futaba舵机控制程序，包含巡线采集程序

#include <ros.h>
#include <Servo.h>
#include <dependant_api/robotcmd_motor.h>
#include <dependant_api/Int16Array.h>

dependant_api::Int16Array raw;
ros::Publisher ir_line_scanner_pub("ir_raw_data", &raw);
int sensor_number = 8;
int print_value;

ros::NodeHandle nh;
Servo servo_vertical;
Servo servo_horizontal;
int pos_vertical = 50;
int pos_horizontal = 90;
int vertical = 50;
int horizontal = 90;

void servoCallback(const dependant_api::robotcmd_motor& cloud_terrace)
{
  //id = cloud_terrace.id;
  vertical = cloud_terrace.ver_angle;
  horizontal = cloud_terrace.hor_angle;
}

ros::Subscriber<dependant_api::robotcmd_motor> servo("steering_duoduo_2", servoCallback);

void setup()
{
  nh.initNode();
  nh.subscribe(servo);
  servo_horizontal.attach(2);
  servo_vertical.attach(3);
  nh.advertise(ir_line_scanner_pub);
}

void loop()
{
  int i, j, k, raw_data[11] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
  raw_data[0] = analogRead(0);
  raw_data[1] = analogRead(1);
  raw_data[2] = analogRead(2);
  raw_data[3] = analogRead(3);
  raw_data[4] = analogRead(4);
  raw_data[5] = analogRead(5);
  raw_data[6] = analogRead(6);
  raw_data[7] = analogRead(7);
  raw_data[8] = analogRead(8);
  raw_data[9] = analogRead(9);
  raw_data[10] = analogRead(10);

  for (k = 0; k < sensor_number; k++)
    raw.data[k] = raw_data[k];
  ir_line_scanner_pub.publish(&raw);

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

  nh.spinOnce();

  if (horizontal > pos_horizontal && pos_horizontal < 170 && horizontal - pos_horizontal != 1)
    pos_horizontal += 2;
  else if (horizontal < pos_horizontal && pos_horizontal > 10 && horizontal - pos_horizontal != -1)
    pos_horizontal -= 2;

  if (vertical > pos_vertical && pos_vertical < 75 && vertical - pos_vertical != 1)
    pos_vertical += 2;
  else if (vertical < pos_vertical && pos_vertical > 30 && vertical - pos_vertical != -1)
    pos_vertical -= 2;

  servo_horizontal.write(pos_horizontal);
  servo_vertical.write(pos_vertical);

  /*print_value++;
  if (print_value >= 10)
  {
    for (k = 0; k < sensor_number; k++)
    {
      Serial.print(raw_data[k]);
      Serial.print("\t");
    }
    Serial.println();
    print_value = 0;
  }*/
}

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


removed stabilization

removed stabilization

rip

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


Update pt_remote controlled car.ino

Update pt_remote controlled car.ino

pt_remote controlled car/pt_remote controlled car.ino

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


Initial Sketch

Initial Sketch

Initial Arduino Sketch for sending data.

//Message
byte input_byte;
//Setup
void setup(){
  //Serial baud rate 9600.
  Serial.begin(9600);
}
//Main loop.
void loop(){
  //Buffer size is 1 byte.
  if(Serial.available() == 1){
    //Read from buffer.
    input_byte = Serial.read();
  }
  if(input_byte == 0){
    Serial.print("THIS IS ARDUINO!");
    return;
  }
  //Scores
  byte left_score = input_byte >> 4;
  byte right_score = input_byte & B00001111;
  //Clear message.
  input_byte = 0;
  Serial.print("READY TO COMMUNICATE");
}

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


update to send the state on all 6 heaters

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/tylergrreid/BRIC_II.git/'


added my main .ino file

added my main .ino file

wires up 9 buttons to Arduino Mega's analog pins.

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/CanTireInnovations/G35-MEO-Programs.git/'


do we have enough to drive?

do we have enough to drive?

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


this example demonstrates both usages of 'clear' method

#include "Nokia_5110.h"

#define RST 2
#define CE 3
#define DC 4
#define DIN 5
#define CLK 6

Nokia_5110 lcd = Nokia_5110(RST, CE, DC, DIN, CLK);

void setup() {
    lcd.setCursor(5, 2);
	lcd.print("Clear methods");
	delay(4000);

	/**
	 * Clear method with no parameter, clears the whole sceen and then sets the cursor to the first row and first column. X=0, Y=0 .
	 */
	lcd.clear(); // One way of using clear method.

	lcd.setCursor(15, 2);
    lcd.print("Timer");

	lcd.setCursor(15, 3);
    lcd.print("00 : 00 : 00");
}

void hours(){
    static unsigned int hours = 0;

    if(hours <= 22){
        hours++;
    }else{
        hours = 0;
    }

    lcd.clear(3, 15, 25); // This is another way of using clear method. It only clears a portion of the screen

    char temp[3];
    dtostrf(hours, 2, 0, temp); // converts integer to char datatype
    lcd.print(temp);
}

void minutes(){
    static unsigned int minutes = 0;

    if(minutes <= 58){
        minutes++;
    }else{
        minutes = 0;
        hours();
    }

    lcd.clear(3, 36, 46); // This is another way of using clear method. It only clears a portion of the screen

    char temp[3];
    dtostrf(minutes, 2, 0, temp); // converts integer to char datatype
    lcd.print(temp);
}

void seconds(){
    static unsigned int seconds = 0;

    if(seconds <= 58) {
        seconds++;
    }else{
        seconds = 0;
        minutes();
    }

    lcd.clear(3, 57, 70); // This is another way of using clear method. It only clears a portion of the screen

    char temp[3];
    dtostrf(seconds, 2, 0, temp); // converts integer to char datatype
    lcd.print(temp);
}

void timer(){
	static unsigned long timerState = 0;
	unsigned long timer = (millis() / 1000);
    if(timer != timerState){
        timerState = timer;
        seconds();
    }
}

void loop() {
    timer();
}

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


add watering unit

add watering unit

/*
    Description: Read the ADC value measured by the Watering Unit, and the water pump can be switched on and off through the middle button.
*/

#include <M5Stack.h>

#define INPUT_PIN 36
#define PUMP_PIN 26

bool flag = true;
int rawADC;

void setup() {
    M5.begin();
    M5.Lcd.setTextColor(GREEN);
    M5.Lcd.setTextSize(3);
    M5.Lcd.setTextDatum(TC_DATUM);
    M5.Lcd.drawString("Watering TEST", 160, 20, 1);
    M5.Lcd.drawString("ON/OFF PUMP", 160, 200, 1);
    pinMode(INPUT_PIN,INPUT);
    pinMode(PUMP_PIN,OUTPUT);
    pinMode(25,OUTPUT);
    digitalWrite(25,0);
}

char info[30];

void loop() {
  rawADC = analogRead(INPUT_PIN);
  M5.lcd.fillRect(80, 100, 240, 50, BLACK);
  M5.Lcd.setCursor(80, 100);
  M5.Lcd.print("ADC: "+ String(rawADC));
  Serial.print("Watering ADC value: ");
  Serial.println(rawADC);
  if(M5.BtnB.wasPressed()){
      digitalWrite(PUMP_PIN,flag);
      flag = !flag;
  }
  M5.update();
  delay(100);
}

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


anavi-led-dimmer: Add pir-motion-led-dimmer.ino

Add Arduino example sketch for detecting motion with PIR sensor.
Turn on the lights for 10 seconds if motion is detected. It is
also possible to turn on or off the lights manually by pressing
the button.

Signed-off-by: Leon Anavi <be92910ae7bb6f58bb9b7c6f845bc30640119592@anavi.org>

// Pin for the button
#define BUT 1
// Pin to drive the LED strip
#define PWM 0
// Analog 1 corresponds to pin PB2
#define POT 1
#define PIR 4
// Time period to keep the lights on
#define DELAY 10000

int potValue = 0;

// the current state of LED
int ledState = HIGH;
// the previous state of button
int lastButtonState = HIGH;
// the current state of button
int currentButtonState = HIGH;

int pirState = LOW;
unsigned long motionTime = 0;

void setup()
{
	pinMode(PWM, OUTPUT);
	analogWrite(PWM, 0);
	pinMode(BUT, INPUT_PULLUP);
	currentButtonState = digitalRead(BUT);
	pinMode(PIR, INPUT_PULLUP);
}

void loop()
{
	// Allow to turn on or off the lights with the button
	// no matter what is the state of the PIR motion sensor
	lastButtonState = currentButtonState;
	// Check the status of the button
	currentButtonState = digitalRead(BUT);
	if ( (HIGH == lastButtonState) && (LOW == currentButtonState) )
	{
		// toggle state of LED
		ledState = !ledState;
		if (LOW != ledState)
		{
			motionTime = millis();
		}
	}

	if (HIGH == digitalRead(PIR))
	{
		if (LOW == pirState)
		{
			motionTime = millis();
			ledState = HIGH;
			pirState = HIGH;
		}
	}
	else
	{
		pirState = LOW;
	}

	if ((millis() - DELAY) > motionTime)
	{
		ledState = LOW;
	}

	if (LOW == ledState)
	{
		// Turn off the LED strip
		analogWrite(PWM, 0);
	}
	else
	{
		// Read potentiometer value in range 0 - 1024
		// and map it to the LED
		potValue = map(analogRead(1), 0, 1023, 0, 255);
		analogWrite(PWM, potValue);
	}
}

error: pathspec 'anavi-led-dimmer/pir-motion-led-dimmer/pir-motion-led-dimmer.ino' did not match any file(s) known to git


roll-pitch pid code

roll-pitch pid code

#include <PinChangeInt.h>
#include <PID_v1.h>
#include <Servo.h>

// Define value of pi
#define PI 3.141592653589793
#define g  9.80665
#define NITER  5

// 20 ms wait for serial signal
#define MAX_MILLIS_TO_WAIT 20

// Define RC channels pin numbers
#define RC_THROTTLE      2
#define RC_ROLL          4
#define RC_PITCH         7
#define RC_YAW           8
#define RC_IN_PIN_5     12
#define RC_IN_PIN_6     13

// These bit flags are set in bUpdateFlagsShared to indicate which
// channels have new signals
#define THROTTLE_FLAG   1
#define ROLL_FLAG       2
#define PITCH_FLAG      4
#define YAW_FLAG        8

// Define drone motor pin numbers
#define MOTOR_FL        11
#define MOTOR_FR         6
#define MOTOR_BL        10
#define MOTOR_BR         9

// RC Radio min/max for each stick
#define RC_MIN       1100
#define RC_MID       1500
#define RC_MAX       1900
#define ESC_MIN      1450
#define ESC_MAX      1830

// Define ESC servo objects
Servo ESC1;
Servo ESC2;
Servo ESC3;
Servo ESC4;

// Various global variables
int channels[4];
volatile uint8_t bUpdateFlagsShared;
long rcthr, rcyaw, rcpit, rcroll, pwm1, pwm2, pwm3, pwm4;
uint32_t ulThrottleStart, ulYawStart, ulPitchStart, ulRollStart;
volatile uint16_t unThrottleInShared, unYawInShared, unPitchInShared, unRollInShared;

unsigned long starttime;
float euler[] = {0.0, 0.0, 0.0};
float gyro[] = {0.0, 0.0, 0.0};
float accl[] = {0.0, 0.0, 0.0};
double roll, pitch, yaw, x_gyro, y_gyro, z_gyro;
float roll_val[NITER], pitch_val[NITER], yaw_val[NITER], x_gyro_val[NITER], y_gyro_val[NITER], z_gyro_val[NITER];

// PID variables and arrays
double roll_out, pitch_out, yaw_out;
double roll_stab_out, pitch_stab_out, yaw_stab_out;

double roll_stab_param[] = {0.1, 0.0, 0.0};
double pitch_stab_param[] = {0.1, 0.0, 0.0};
double yaw_stab_param[] = {0.1, 0.0, 0.0};

double roll_rate_param[] = {0.1, 0.0, 0.0};
double pitch_rate_param[] = {0.1, 0.0, 0.0};
double yaw_rate_param[] = {0.1, 0.0, 0.0};

PID roll_stab_pid((double *)&rcroll, &roll_stab_out, &roll, roll_stab_param[0], roll_stab_param[1], roll_stab_param[2], DIRECT);
PID pitch_stab_pid((double *)&rcpit, &pitch_stab_out, &pitch, pitch_stab_param[0], pitch_stab_param[1], pitch_stab_param[2], DIRECT);
PID yaw_stab_pid((double *)&rcyaw, &yaw_stab_out, &yaw, yaw_stab_param[0], yaw_stab_param[1], yaw_stab_param[2], DIRECT);

PID roll_rate_pid((double *)&roll_stab_out, &roll_out, &x_gyro, roll_rate_param[0], roll_rate_param[1], roll_rate_param[2], DIRECT);
PID pitch_rate_pid((double *)&pitch_stab_out, &pitch_out, &y_gyro, pitch_rate_param[0], pitch_rate_param[1], pitch_rate_param[2], DIRECT);
PID yaw_rate_pid((double *)&yaw_stab_out, &yaw_out, &z_gyro, yaw_rate_param[0], yaw_rate_param[1], yaw_rate_param[2], DIRECT);

// ==================  IMU control code  ==============================================
// Determine mean value
float mean(float* val) {
  float temp = 0.0;
  for(int i = 0; i < NITER; i++){
    temp += val[i];
  }
  return temp/NITER;
}

// Function to convert angles in radians to degree
float rad2deg(float angle) {
    return (180/PI) * angle;
}

// Get Euler angles, gyro an accelerometer values from the IMU
byte readIMU(float* euler, float* gyro, float* accl) {
    byte cmd[] = {0x75,0x65,0x0C,0x0D,0x0D,0x01,0x00,0x03,0x0C,0x00,0x00,0x04,0x00,0x00,0x05,0x00,0x00,0x19,0xE5};
    byte reply[58];

    // Variables to receive euler angles, gyro and accelerometer values
    union {
     float val;
     unsigned char b[4];
    } uav_value;

    // Send serial command
    Serial.write(cmd, sizeof(cmd));

    // Delay of 1 ms
    delay(1);

    starttime = millis();

    // Wait till all 58 bytes are recieved or 100 ms has gone bye
    while ((Serial.available() < 58) && ((millis() - starttime) < MAX_MILLIS_TO_WAIT)) {
    }

    // If less than 58 bytes are available on serial register, return \x01 error
    // code else send \x00 success code and populate euler angles
    if (Serial.available() < 58) {
       return byte(1);
    }
    else {
       for (int n = 0; n < 58; n++) {
           reply[n] = Serial.read();
           delay(1);
       }

       // Roll angle
       uav_value.b[0] = reply[19];
       uav_value.b[1] = reply[18];
       uav_value.b[2] = reply[17];
       uav_value.b[3] = reply[16];
       euler[0] = uav_value.val;

       // Pitch  angle
       uav_value.b[0] = reply[23];
       uav_value.b[1] = reply[22];
       uav_value.b[2] = reply[21];
       uav_value.b[3] = reply[20];
       euler[1] = uav_value.val;

       // Yaw angle
       uav_value.b[0] = reply[27];
       uav_value.b[1] = reply[26];
       uav_value.b[2] = reply[25];
       uav_value.b[3] = reply[24];
       euler[2] = uav_value.val;

       // X Acceleration
       uav_value.b[0] = reply[33];
       uav_value.b[1] = reply[32];
       uav_value.b[2] = reply[31];
       uav_value.b[3] = reply[30];
       accl[0] = uav_value.val;

       // Y Acceleration
       uav_value.b[0] = reply[37];
       uav_value.b[1] = reply[36];
       uav_value.b[2] = reply[35];
       uav_value.b[3] = reply[34];
       accl[1] = uav_value.val;

       // Z Acceleration
       uav_value.b[0] = reply[41];
       uav_value.b[1] = reply[40];
       uav_value.b[2] = reply[39];
       uav_value.b[3] = reply[38];
       accl[2] = uav_value.val;

       // X gyro
       uav_value.b[0] = reply[47];
       uav_value.b[1] = reply[46];
       uav_value.b[2] = reply[45];
       uav_value.b[3] = reply[44];
       gyro[0] = uav_value.val;

       // Y gyro
       uav_value.b[0] = reply[51];
       uav_value.b[1] = reply[50];
       uav_value.b[2] = reply[49];
       uav_value.b[3] = reply[48];
       gyro[1] = uav_value.val;

       // Z gyro
       uav_value.b[0] = reply[55];
       uav_value.b[1] = reply[54];
       uav_value.b[2] = reply[53];
       uav_value.b[3] = reply[52];
       gyro[2] = uav_value.val;

       return reply[7];
    }
}

// =================== RC/MOTOR control code ===========================================
// simple interrupt service routine
void calcThrottle()
{
  if(digitalRead(RC_THROTTLE) == HIGH)
  {
    ulThrottleStart = micros();
  }
  else
  {
    unThrottleInShared = (uint16_t)(micros() - ulThrottleStart);
    bUpdateFlagsShared |= THROTTLE_FLAG;
  }
}

void calcYaw()
{
  if(digitalRead(RC_YAW) == HIGH)
  {
    ulYawStart = micros();
  }
  else
  {
    unYawInShared = (uint16_t)(micros() - ulYawStart);
    bUpdateFlagsShared |= YAW_FLAG;
  }
}

void calcPitch()
{
  if(digitalRead(RC_PITCH) == HIGH)
  {
    ulPitchStart = micros();
  }
  else
  {
    unPitchInShared = (uint16_t)(micros() - ulPitchStart);
    bUpdateFlagsShared |= PITCH_FLAG;
  }
}

void calcRoll()
{
  if(digitalRead(RC_ROLL) == HIGH)
  {
    ulRollStart = micros();
  }
  else
  {
    unRollInShared = (uint16_t)(micros() - ulRollStart);
    bUpdateFlagsShared |= ROLL_FLAG;
  }
}

void readRC(int channels[]) {
   // local copy of channel inputs
   static uint16_t unThrottleIn, unYawIn, unPitchIn, unRollIn;

   // local copy of update flags
   static uint8_t bUpdateFlags;

   // check shared update flags to see if any channels have a new signal
   if(bUpdateFlagsShared)
   {
     noInterrupts(); // turn interrupts off quickly while we take local copies of the shared variables

     // take a local copy of which channels were updated in case we need to use this in the rest of loop
     bUpdateFlags = bUpdateFlagsShared;

     if(bUpdateFlags & THROTTLE_FLAG)
     {
       unThrottleIn = unThrottleInShared;
     }

     if(bUpdateFlags & ROLL_FLAG)
     {
       unRollIn = unRollInShared;
     }

     if(bUpdateFlags & PITCH_FLAG)
     {
       unPitchIn = unPitchInShared;
     }

     if(bUpdateFlags & YAW_FLAG)
     {
       unYawIn = unYawInShared;
     }

     bUpdateFlagsShared = 0;

     interrupts();
   }

   if(bUpdateFlags & THROTTLE_FLAG)
   {
     channels[0] = unThrottleIn;
   }

   if(bUpdateFlags & ROLL_FLAG)
   {
     channels[1] = unRollIn;
   }

   if(bUpdateFlags & PITCH_FLAG)
   {
     channels[2] = unPitchIn;

   }

   if(bUpdateFlags & YAW_FLAG)
   {
     channels[3] =  unYawIn;
   }

   bUpdateFlags = 0;
}

void setup()
{
  // Start serial communication channel
  Serial.begin(115200);

  // Attach interrupts to RC arduino pins
  PCintPort::attachInterrupt(RC_THROTTLE,calcThrottle,CHANGE);
  PCintPort::attachInterrupt(RC_ROLL,calcRoll,CHANGE);
  PCintPort::attachInterrupt(RC_PITCH,calcPitch,CHANGE);
  PCintPort::attachInterrupt(RC_YAW,calcYaw,CHANGE);

  // Attach ESC's to arduino pins
  ESC1.attach(MOTOR_FL);
  ESC2.attach(MOTOR_FR);
  ESC3.attach(MOTOR_BL);
  ESC4.attach(MOTOR_BR);

  // Set RC channel value to "rest"
  channels[0] = RC_MIN;
  channels[1] = RC_MID;
  channels[2] = RC_MID;
  channels[3] = RC_MID;

  // Read "rest" euler, gyro and accl values
  if (readIMU(euler, gyro, accl) == '\x00') {
       roll = rad2deg(euler[0]);
       pitch = rad2deg(euler[1]);
       yaw = rad2deg(euler[2]);
       x_gyro = rad2deg(gyro[0]);
       y_gyro = rad2deg(gyro[1]);
       z_gyro = rad2deg(gyro[2]);
  }
  else {
       roll = 0.0;
       pitch = 0.0;
       yaw = 0.0;
       x_gyro = 0.0;
       y_gyro = 0.0;
       z_gyro = 0.0;
  }

  // Set PID mode
  yaw_stab_pid.SetMode(AUTOMATIC);

  // Delay of 10 ms
  delay(10);
}

void loop()
{
  // Read IMU 10-15 times and average the Euler angle and rotational speed values
  for (int i = 0; i < NITER; i++){
    if (readIMU(euler, gyro, accl) == '\x00'){
        roll_val[i] = rad2deg(euler[0]);
        pitch_val[i] = rad2deg(euler[1]);
        yaw_val[i] = rad2deg(euler[2]);
        x_gyro_val[i] = rad2deg(gyro[0]);
        y_gyro_val[i] = rad2deg(gyro[1]);
        z_gyro_val[i] = rad2deg(gyro[2]);
    }
  }

  // Mean value of Euler angles and rotational speed
  roll = mean(roll_val);
  pitch = mean(pitch_val);
  yaw = mean(yaw_val);
  x_gyro = mean(x_gyro_val);
  y_gyro = mean(y_gyro_val);
  z_gyro = mean(z_gyro_val);

  // Display IMU values
  Serial.println(roll);
  Serial.println(pitch);
  Serial.println(yaw);
  Serial.println(x_gyro);
  Serial.println(y_gyro);
  Serial.println(z_gyro);

  // Read RC channel values
  readRC(channels);

  if (channels[1] == 0 & channels[2] == 0 & channels[3] == 0) {
    channels[0] = RC_MIN;
    channels[1] = RC_MID;
    channels[2] = RC_MID;
    channels[3] = RC_MID;
  }

  // Apart from throttle, map roll, pitch and yaw to angles in degrees
  rcthr = channels[0];
  rcroll = map(channels[1], RC_MIN, RC_MAX, -15, 15);
  rcpit = map(channels[2], RC_MIN, RC_MAX, -15, 15);
  rcyaw = map(channels[3], RC_MIN, RC_MAX, -150, 150);

  Serial.println("RC constrained values:");
  Serial.println(rcthr);
  Serial.println(rcroll);
  Serial.println(rcpit);
  Serial.println(rcyaw);

  // Stablization PID
  //roll_stab_pid.Compute();
  //pitch_stab_pid.Compute();
  //yaw_stab_pid.Compute();

  //Serial.println(roll_stab_out);
  //Serial.println(pitch_stab_out);
  //Serial.println(yaw_stab_out);

  //roll_stab_out = constrain(roll_stab_out, -250, 250);
  //pitch_stab_out = constrain(pitch_stab_out, -250, 250);
  //yaw_stab_out = constrain(yaw_stab_out, -360, 360);

  // Rate PID
  //roll_rate_pid.Compute();
  //pitch_rate_pid.Compute();
  //yaw_rate_pid.Compute();

  //Serial.println(roll_out);
  //Serial.println(pitch_out);
  //Serial.println(yaw_out);

  //roll_output = constrain(roll_out, -150, 150);
  //pitch_output = constrain(pitch_out, -150, 150);
  //yaw_output = constrain(yaw_out, -500, 500);

  pwm1 = constrain(rcthr - rcroll - rcpit - rcyaw, RC_MIN, RC_MAX);
  pwm2 = constrain(rcthr + rcroll - rcpit + rcyaw, RC_MIN, RC_MAX);
  pwm3 = constrain(rcthr - rcroll + rcpit + rcyaw, RC_MIN, RC_MAX);
  pwm4 = constrain(rcthr + rcroll + rcpit - rcyaw, RC_MIN, RC_MAX);

  //pwm1 = constrain(rcthr - roll_output - pitch_output - yaw_output, RC_MIN, RC_MAX);
  //pwm2 = constrain(rcthr + roll_output - pitch_output + yaw_output, RC_MIN, RC_MAX);
  //pwm3 = constrain(rcthr - roll_output + pitch_output + yaw_output, RC_MIN, RC_MAX);
  //pwm4 = constrain(rcthr + roll_output + pitch_output - yaw_output, RC_MIN, RC_MAX);

  pwm1 = map(pwm1, RC_MIN, RC_MAX, ESC_MIN, ESC_MAX);
  pwm2 = map(pwm2, RC_MIN, RC_MAX, ESC_MIN, ESC_MAX);
  pwm3 = map(pwm3, RC_MIN, RC_MAX, ESC_MIN, ESC_MAX);
  pwm4 = map(pwm4, RC_MIN, RC_MAX, ESC_MIN, ESC_MAX);

  Serial.println("ESC pwm values:");
  Serial.println(pwm1);
  Serial.println(pwm2);
  Serial.println(pwm3);
  Serial.println(pwm4);

  ESC1.writeMicroseconds(pwm1);
  ESC2.writeMicroseconds(pwm2);
  ESC3.writeMicroseconds(pwm3);
  ESC4.writeMicroseconds(pwm4);
}

error: pathspec 'arduino/src/T-80AFLAME/uav_pid_roll_pitch/uav_pid_roll_pitch.ino' did not match any file(s) known to git


Adds two sonar sketch

Adds two sonar sketch

#include <config.h>
#include <utilsawesome.h>

/*
Freakduino Chibi-9000

Collects data from different sensors and sends it to
the aggregator as defined in "config.h"
*/

#include <chibi.h>

/**************************************************************************/
// Initialize
/**************************************************************************/
void setup()
{
  // Initialize the chibi command line and set the speed to 57600 bps
  chibiCmdInit(57600);

  // Initialize the chibi wireless stack
  chibiInit();

//  Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");
}

/**************************************************************************/
// Loop
/**************************************************************************/
void loop()
{

  byte tx_buf[TX_LENGTH];
  memset(tx_buf, 0, TX_LENGTH);
  long duration, inches, cm;

  // Read sonar distance
  float distance = sonar_measure_distance(A0);
  if (distance > 0) {
    Reading dist = {"distance", distance, millis()};
    add_to_tx_buf((char*)tx_buf, &dist);
  }

  distance = sonar_measure_distance(A1);
  if (distance > 0) {
    Reading dist = {"distance", distance, millis()};
    add_to_tx_buf((char*)tx_buf, &dist);
  }

  //Send data stored on "tx_buf" to collector
  chibiTx(AGGREGATOR_SHORT_ADDRESS, tx_buf, TX_LENGTH);

  // Debug print
  Serial.println((char*) tx_buf);

  free(tx_buf);
  //Wait
  delay(1000);
}

float sonar_measure_distance(int pin){
  int checkTimes = 10;
  long duration, cm;

  // read sensor data and send average data
  int sum = 0;
  for (int i=0; i<checkTimes; i++){
    delay(10);
    // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
    // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    delayMicroseconds(2);
    digitalWrite(pin, HIGH);
    delayMicroseconds(5);
    digitalWrite(pin, LOW);

    // The same pin is used to read the signal from the PING))): a HIGH
    // pulse whose duration is the time (in microseconds) from the sending
    // of the ping to the reception of its echo off of an object.
    pinMode(pin, INPUT);
    duration = pulseIn(pin, HIGH);

    // convert the time into a distance
    cm = microsecondsToCentimeters(duration);
    if(VERBOSE == 1){
      Serial.print(i);
      Serial.print(cm, 1);
      Serial.print("cm");
      Serial.println();
    }

    sum += cm;
  }
  float average = sum/(float)checkTimes;
  if(VERBOSE == 1){
    Serial.print("Average: ");
    Serial.println(average, 1);
    Serial.println();
  }
  return average;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

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