add final test 3g arduino code

add final test 3g arduino code

/*
 *  3G + GPS shield
 *
 *  Copyright (C) Libelium Comunicaciones Distribuidas S.L.
 *  http://www.libelium.com
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  a
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/.
 *
 *  Version:           2.0
 *  Design:            David Gascón
 *  Implementation:    Alejandro Gallego & Victor Boria
 */

//Change here your data
const char pin_number[] = "1234";
const char apn[] = "*********";
const char user_name[] = "*********";
const char password[] = "*********";

char url[ ]="haggis.ensta-bretagne.fr";
int port= 3000;
char post[ ] ="{\"sensor_id\":\"1\",\"value\":\"58\",\"datetime\":\"2015-06-01 23:56:52\"}\r\n\r\n";
String postdata=post;
char request_first[ ]="POST /measurements HTTP/1.1\r\nHost: haggis.ensta-bretagne.fr\r\nContent-Type: application/json\r\nContent-Length: 63\r\n\r\n";
char request[500];

//sprintf(postHeader2,"%s%d\r\n\r\n",postLen,postdata.length());
//sprintf(postHeader,"%s%s",postHeader1,postHeader2);
//sprintf(request, "%s%s", postHeader,postdata);

int8_t answer;
int onModulePin = 2, aux;
int data_size = 0;
int end_file = 0;
char aux_str[50];
char data[400];
int http_x;
int http_status; // 0: end, 1 waiting data with header, 2 waiting data without header, 3 timeout waiting data, 4 unknow response
int x = 0;
long previous;

void setup(){
  pinMode(onModulePin, OUTPUT);
  Serial.begin(115200);
  sprintf( request,"%s%s",request_first, post);
  Serial.println("Starting...");
  power_on();

  delay(3000);

  //sets the PIN code
  sprintf(aux_str, "AT+CPIN=%s", pin_number);
  sendATcommand(aux_str, "OK", 2000);

  delay(3000);

  while( (sendATcommand("AT+CREG?", "+CREG: 0,1", 500) ||
    sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0 );

  // sets APN, user name and password
  sprintf(aux_str, "AT+CGSOCKCONT=1,\"IP\",\"%s\"", apn);
  sendATcommand(aux_str, "OK", 2000);

  sprintf(aux_str, "AT+CSOCKAUTH=1,1,\"%s\",\"%s\"", user_name, password);
  sendATcommand(aux_str, "OK", 2000);
}

void loop(){

  // request the url

  previous = millis();
  sprintf(aux_str, "AT+CHTTPACT=\"%s\",%d", url, port);
  answer = sendATcommand(aux_str, "+CHTTPACT: REQUEST", 60000);

  // Sends the request
  Serial.println(request);
  // Sends <Ctrl+Z>
  Serial.write(0x1A);
  http_status = 1;

  while ((http_status == 1) || (http_status == 2))
  {
    answer = sendATcommand("", "+CHTTPACT: ", 60000);
    if (answer == 0)
    {
      if (http_status == 1)
      {
        http_status = 3;
      }
      if (http_status == 2)
      {
        http_status = 5;
      }
    }
    else
    {
      // answer == 1
      while(Serial.available()==0);
      aux_str[0] = Serial.read();

      if ((aux_str[0] == 'D') && (http_status == 1))
      {
        // Data packet with header
        while(Serial.available()<4);
        Serial.read();  // A
        Serial.read();  // T
        Serial.read();  // A
        Serial.read();  // ,

        // Reads the packet size
        x=0;
        do{
          while(Serial.available()==0);
          aux_str[x] = Serial.read();
          x++;
        }
        while((aux_str[x-1] != '\r') && (aux_str[x-1] != '\n'));

        aux_str[x-1] = '\0';
        data_size = atoi(aux_str);

        // Now, search the end of the HTTP header (\r\n\r\n)
        do{
          while (Serial.available() < 3);

          data_size--;
          if (Serial.read() == '\r')
          {
            data_size--;
            if (Serial.read() == '\n')
            {
              data_size--;
              if (Serial.read() == '\r')
              {
                data_size--;
                if (Serial.read() == '\n')
                {
                  // End of the header found
                  http_status = 2;
                }
              }
            }
          }
        }
        while ((http_status == 1) && (data_size > 0));

        if (http_status == 2)
        {
          // Reads the data
          http_x = 0;
          do{
            if(Serial.available() != 0){
              data[http_x] = Serial.read();
              http_x++;
              data_size--;
            }
            else
            {
              delay(1);
            }
          }
          while(data_size > 0);
          data[http_x] = '\0';
        }
      }
      else if ((aux_str[0] == 'D') && (http_status == 2))
      {
        // Data packet with header
        while(Serial.available()<4);
        Serial.read();  // A
        Serial.read();  // T
        Serial.read();  // A
        Serial.read();  // ,

        // Reads the packet size
        x=0;
        do{
          while(Serial.available()==0);
          aux_str[x] = Serial.read();
          x++;
        }
        while((aux_str[x-1] != '\r') && (aux_str[x-1] != '\n'));

        aux_str[x-1] = '\0';
        data_size = atoi(aux_str);

        do{
          if(Serial.available() != 0){
            data[http_x] = Serial.read();
            http_x++;
          }
          else
          {
            delay(1);
          }
        }
        while(data_size > 0);
        data[http_x] = '\0';

      }
      else if (aux_str[0] == '0')
      {
        // end of the AT command
        http_status = 0;
      }
      else
      {
        // unknow response
        http_status = 4;
        Serial.print(char(aux_str[0]));
        Serial.print(char(Serial.read()));
        Serial.print(char(Serial.read()));
        Serial.print(char(Serial.read()));
        Serial.print(char(Serial.read()));
        Serial.print(char(Serial.read()));
        Serial.print(char(Serial.read()));
        Serial.print(char(Serial.read()));
        Serial.print(char(Serial.read()));
      }
    }
  }

  previous = millis() - previous;

  Serial.println(previous, DEC);
  if (http_status == 0)
  {
    Serial.print(F("HTTP data: "));
    Serial.println(data);
  }
  else
  {
    Serial.print(F("http_status: "));
    Serial.println(http_status, DEC);
  }

  delay(10000);

}

void power_on(){

  uint8_t answer=0;

  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    // power on pulse
    digitalWrite(onModulePin,HIGH);
    delay(3000);
    digitalWrite(onModulePin,LOW);

    // waits for an answer from the module
    while(answer == 0){
      // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
    }
  }

}

int8_t sendATcommand(char* ATcommand, char* expected_answer1, unsigned int timeout) {

  uint8_t x = 0,  answer = 0;
  char response[100];
  unsigned long previous;

  memset(response, '\0', 100);    // Initialize the string

  delay(100);

  while ( Serial.available() > 0) Serial.read();   // Clean the input buffer

  Serial.println(ATcommand);    // Send the AT command

  x = 0;
  previous = millis();

  // this loop waits for the answer
  do {
    // if there are data in the UART input buffer, reads it and checks for the asnwer
    if (Serial.available() != 0) {
      response[x] = Serial.read();
      x++;
      // check if the desired answer is in the response of the module
      if (strstr(response, expected_answer1) != NULL)
      {
        answer = 1;
      }
    }
    // Waits for the asnwer with time out
  }
  while ((answer == 0) && ((millis() - previous) < timeout));

  return answer;
}

int8_t sendATcommand2(char* ATcommand, char* expected_answer1, char* expected_answer2, unsigned int timeout)
{

  uint8_t x=0,  answer=0;
  char response[100];
  unsigned long previous;

  memset(response, '\0', 100);    // Initialize the string

  delay(100);

 // while( Serial.available() > 0) Serial.read();    // Clean the input buffer

  Serial.println(ATcommand);    // Send the AT command

    x = 0;
  previous = millis();

  // this loop waits for the answer
  do{

    if(Serial.available() != 0){
      response[x] = Serial.read();
      x++;
      // check if the desired answer is in the response of the module
      if (strstr(response, expected_answer1) != NULL)
      {
        answer = 1;
      }
      // check if the desired answer is in the response of the module
      if (strstr(response, expected_answer2) != NULL)
      {
        answer = 2;
      }
    }
    // Waits for the asnwer with time out
  }
  while((answer == 0) && ((millis() - previous) < timeout));

  return answer;
}

error: pathspec 'hardware/Arduino_Code/test_3g_final/test_3g.ino' did not match any file(s) known to git


fan-example.ino: Turn on/off ANAVI Fume Extractor

Simple example to turn on/off the 80mm fan of ANAVI Fume Extractor
by pressing the fan switch button.

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

#include <FS.h>                   //this needs to be first, or it all crashes and burns...

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

#define PIN_FAN         12
#define PIN_FAN_BUTTON  13

bool fanOn = false;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println();

  delay(10);

  pinMode(PIN_FAN, OUTPUT);
  pinMode(PIN_FAN_BUTTON, INPUT);

  Serial.println("ANAVI Fume Extractor");
  Serial.println("--------------------");
  Serial.println("Fan Example");
  Serial.println("--------------------");

  delay(1000);
  digitalWrite(PIN_FAN, LOW);
  fanOn = false;
}

void loop()
{
  if (LOW == digitalRead(PIN_FAN_BUTTON))
  {
    Serial.print("Fan: ");
    if (false == fanOn)
    {
      digitalWrite(PIN_FAN, HIGH);
      fanOn = true;
      Serial.println("ON");
    }
    else
    {
      digitalWrite(PIN_FAN, LOW);
      fanOn = false;
      Serial.println("OFF");
    }
    // Give the fan 3 seconds between swithing it again
    delay(3000);
  }
}

error: pathspec 'anavi-fume-extractor/fan-example/fan-example.ino' did not match any file(s) known to git


Adding new version

Adding new version

I've made some changes, see the documentation in the file.  From now on,
any changes I make will be tracked through GitHub on this file.  The
other .ino files can be deleted.

//ENGR 421 Team 4
//2013

//Written by Dean Reading

/*******************************************************************************************/
// Changelog
/*******************************************************************************************
 * Version control can now be handled by GitHub...
 *
 * Version 0.2
 * Included a timeout when waiting for a character.
 * Added the sendMessage function to communicate with laptop.
 * Added in error messages for invalid command IDs, shooter numbers and angles.
 * Added in lower and upper limits to the angles that can be used.
 *
 *
 * Version 0.1
 * Includes command receiving and execution, with 'Aim' and 'Shoot' commands.
 * <angle> input is a byte that should range from 0 to 180, with 90 being pointing forward.
 * All DC motor pins are set up and PWM is created.
 * setShooterAngle, releaseBall and checkSolenoids functions are included.
 * 'GO' & 0x80 is sent to indicate game start.
 *
 *
 */

/*
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 // Pre-Start
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 */

// Pins
/*******************************************************************************************/
#define pinMotor1 5
#define pinMotor2 2
#define pinMotor3 3

#define pinServo1 46
#define pinServo2 45
#define pinServo3 44

#define pinSolenoid1 4
#define pinSolenoid2 6
#define pinSolenoid3 7

// Parameters
/*******************************************************************************************/
#define DEBUG //Defining DEBUG turns ON debugging messages

#define commsTimeout 200 //The maximum time that a received serial command can take, in mS

#define ballReleaseTime 100 //The time that the solenoid needs to be activated for to release a ball, in mS

#define motorLevel1 255
#define motorLevel2 255
#define motorLevel3 255

#define angleLowest 30 //The minimum allowable angle
#define angleHighest 150 //The maximum allowable angle

// Libraries & Objects
/*******************************************************************************************/
#include <Servo.h>
Servo servo1; //Declare 3 instances of servo objects
Servo servo2;
Servo servo3;

//Function Prototypes
void sendMessage (byte CMD,byte in1 = 255, byte in2 = 255, byte in3 = 255);

// Constants
/*******************************************************************************************/
byte commandLength[255]; //The number of data bytes for each command type for serial comms
const byte solenoidPins[] = {
  0,pinSolenoid1,pinSolenoid2,pinSolenoid3}; //A map for the solenoid pins
const byte motorPins[] = {
  0,pinMotor1,pinMotor2,pinMotor3}; //A map for the solenoid pins

// Global Variables
/*******************************************************************************************/
byte commandID=0;
byte bytesRemaining; //
char buffer[5];
unsigned long timer; //A multi-purpose timer

unsigned long ballReleaseTimer[4]; //Saves when the last ball was released.
boolean ballReleasing[] = {
  0,0,0,0}; //Indicates whether we are in the process of releasing a ball

/*
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 // Setup
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 */
void setup(){
  // Constants
  /*******************************************************************************************/
  commandLength[1]=2;
  commandLength[2]=1;

  commandLength[0x80]=0;
  commandLength[0xE0]=1;
  commandLength[0xE1]=1;
  commandLength[0xE2]=2;

  // Pin Modes and Setup
  /*******************************************************************************************/
  for (byte i=1;i<4;i++){
    pinMode(motorPins[i],OUTPUT);
    pinMode(solenoidPins[i],OUTPUT);

    analogWrite(motorPins[i],255);
    digitalWrite(solenoidPins[i],LOW);
  }

  // Other Setup Code
  /*******************************************************************************************/
  Serial.begin(9600);
  Serial.setTimeout(commsTimeout);
#ifdef DEBUG
  Serial.println("Arduino Start");
#endif

  //Attach the servo objects
  servo1.attach(pinServo1,900,2100); //Include the maximum and minimum pulse widths.
  servo2.attach(pinServo2,900,2100);
  servo3.attach(pinServo3,900,2100);

  //Wait until 'Game Start' button is pressed

  //add here later
  //Send 'Game Start' message to laptop
  sendMessage(0x80);

  //Set up the PWM DC motor control signals
  analogWrite(pinMotor1,motorLevel1);
  analogWrite(pinMotor2,motorLevel2);
  analogWrite(pinMotor3,motorLevel3);

  //Prototyping stuff DELETE ME!  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  //analogWrite(pinMotor1,0);

  //    releaseBall(1);

  //  while (true) { //Cycle endlessly
  //    setShooterAngle(1,90);
  //    delay(1000);
  //    setShooterAngle(1,45);
  //    delay(1000);
  //    setShooterAngle(1,135);
  //    delay(1000);
  //  }

}

/*
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 // Loop
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
 */
void loop(){
  checkSerial(); //Check for incoming commands, and execute them

  checkSolenoids(); //Deactivates any solenoids when needed

}

/*▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
/*checkSerial
/*******************************************************************************************/
void checkSerial(){
  if (Serial.available()) {
    //Search for the initization sequence
    if (Serial.read()=='G'){
      timer=millis()+commsTimeout;
      while (!Serial.available()){ //Wait until another character is available
        if (millis()>timer) { //Exit the loop if we don't receive another character
          break;
        }
      }
      if (Serial.peek()=='O'){
        Serial.read(); //Remove the 'O' from the serial buffer.
        //Initialization Sequence detected!

#ifdef DEBUG
        Serial.println("'G O' found!");
#endif

        timer=millis()+commsTimeout;
        while (!Serial.available()){ //Wait until another character is available
          if (millis()>timer) { //Exit the loop if we don't receive another character
            break;
          }
        }
        commandID=Serial.read(); //This byte is the command ID

        //Now, read the required number of data bytes into the array 'buffer'
        Serial.readBytes(buffer,commandLength[commandID]);

        //Execute the command
        executeCommand();
      }
    }
  }
}

/*▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
/*executeCommand
/*******************************************************************************************/
//This function executes whatever the necessary action is, as told by the command and data
//received through serial comms
void executeCommand(){
  switch (commandID){
  case 1:
    //Aim shooter <db1> to angle defined by <db2>
    setShooterAngle(buffer[0],(byte) buffer[1]);
    break;
  case 2:
    //Release a ball on shooter <db1>
    releaseBall(buffer[0]);
    break;
  default:
#ifdef DEBUG
    Serial.print("Unrecognized command ID: ");
    Serial.println(commandID);
#endif
    //Send error feedback to laptop
    sendMessage(0xE0,commandID);
  }
}

/*▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
/*setShooterAngle
/*******************************************************************************************/
//This function changes the servo signal for shooter <shooterNum> to the angle defined by
// <angle>.  <angle> is a byte that ranges from 180, which maps from 900 to 2100 mS.
void setShooterAngle(byte shooterNum, byte angle){

  //  unsigned int output =   (((unsigned int) angle-1)*137)/29+900; // 137/29 = 4.724 = 1200/254, the scaling factor to get to uS

#ifdef DEBUG
  Serial.print("Setting shooter ");
  Serial.print(shooterNum);
  Serial.print(" to ");
  Serial.println(angle);
#endif

  //Set the servo output.  Use a switch statement to use the correct servo object.
  if (angle<angleLowest || angle>angleHighest) {
    //The angle is invalid! Don't move the shooter, and send feedback
    sendMessage(0xE2,shooterNum,angle);
  }
  else{
    switch (shooterNum) {
    case 1:
      servo1.write(angle);
      break;
    case 2:
      servo2.write(angle);
      break;
    case 3:
      servo1.write(angle);
      break;
    default:
#ifdef DEBUG
      Serial.print("Unrecognized shooter Num: ");
      Serial.println(shooterNum);
#endif
      //Send error feedback to laptop
      sendMessage(0xE1,shooterNum);
    }
  }
}

/*▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
/*releaseBall
/*******************************************************************************************/
//This function releases one BB (hopefully) from shooter <shooterNum>
void releaseBall(byte shooterNum) {

#ifdef DEBUG
  Serial.print("Releasing ball from shooter: ");
  Serial.println(shooterNum);
#endif

  digitalWrite(solenoidPins[shooterNum],HIGH); //Activate the solenoid: open the passage

  ballReleaseTimer[shooterNum]=millis()+ballReleaseTime; //Set the timer for deactivating the solenoid
  ballReleasing[shooterNum]=1; //Indicate that we are releasing a ball
}

/*▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
/*checkSolenoids
/*******************************************************************************************/
//Check whether there are any solenoids that need to be deactivated
void checkSolenoids(){
  for (byte i=1;i<4;i++){ //Check all 3 solenoids
    if (ballReleasing[i]==1){ //If a ball is currently being released
      if (millis()>ballReleaseTimer[i]){ //If enough time has passed
        digitalWrite(solenoidPins[i],LOW); //Deactivate the solenoid: close the passage
        ballReleasing[i]=0; //Indicate that the ball is no longer being released
#ifdef DEBUG
        Serial.print("Deactivating solenoid: ");
        Serial.println(i);
#endif
      }
    }
  }
}

/*▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
/*sendMessage
/*******************************************************************************************/
//This function sends commands to the laptop.  It has optional inputs.
void sendMessage (byte CMD,byte in1, byte in2, byte in3) {
  Serial.print("GO");
  if (commandLength[CMD]>0){
    Serial.print(in1);
    if (commandLength[CMD]>1){
      Serial.print(in2);
      if (commandLength[CMD]>2){
        Serial.print(in3);
      }
    }
  }
  Serial.println(); //Print a new line character
}

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


letting servo handle minutia of turning from a start degree to an end degree

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

void setup()
{
  Serial.begin(9600);
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  rndTurn(70, 90);
  rndDelay();

  rndTurn(120, 140);
  rndDelay();
}

void rndDelay()
{
  int ms = random(3000, 7000);

  Serial.print("delay:\t");
  Serial.println(ms);

  delay(ms);
}

void rndTurn(int low, int high)
{
  int angle = random(low, high);

  Serial.print("angle:\t");
  Serial.println(angle);

  myservo.write(angle);
}

error: pathspec 'direct-servo-turns/direct-servo-turns.ino' did not match any file(s) known to git


fix comments and reduce delay between updates

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/manashmndl/bluebrain.git/'


Initial FlyByWire commit

Initial FlyByWire commit

Commit the current draft of the FlyByWire code that Soren wrote.

// Carpet CANTroller II  Source Code  - For Arduino Mega 2560 with Adafruit 2.8inch Captouch TFT shield.

// Libraries to include.  Note all these have example code when installed into arduino ide
#include <Servo.h>   // Makes PWM output to control motors (for our gas and steering)
#include <FastPID.h>  // Fixed-point math based PID loop (for our brakes and maybe cruise control)
#include <SPI.h>   // SPI serial bus needed to talk to the LCD and the SD card
#include <Wire.h>      // Contains I2C serial bus, needed to talk to touchscreen chip
#include <Adafruit_ILI9341.h>   // For interfacing with the TFT LCD controller chip
#include <Adafruit_FT6206.h>   // For interfacing with the cap touchscreen controller chip
#include <SdFat.h>        // SD card & FAT filesystem library
#include <Adafruit_GFX.h>    // For drawing pictures & text on the screen
//#include <Adafruit_ImageReader.h>  // We don't really need thihs but can use it to test that SD flash is working
//#include "TouchScreen.h"  // Touchscreen library (I don't think we need it? Maybe for resistive TP we're not using)

/*
# Here are the different runmodes documented
#
# ** Shutdown Mode **
# - Required: Ignition Off
# - Priority: 1 (Highest)
# This mode is active whenever the ignition is off.  In other words, whenever the
# little red pushbutton switch by the joystick is unclicked.  This happens before the
# ignition is pressed before driving, but it also may happen if the driver needs to
# panic and E-stop due to loss of control or any other reason.  The ignition will get cut
# independent of the controller, but we can help stop the car faster by applying the
# brakes. Once car is stopped, we release all actuators and go to low power mode.
# - Actions: 1. Release throttle. If car is moving AND BasicMode Off, apply brakes to stop car
# - Actions: 2: Deactivate all actuators including steering
#
# ** Basic Mode **
# - Required: BasicMode switch On & Ignition On
# - Priority: 2
# The gas and brake don't do anything in Basic Mode. Just the steering works, so use the pedals.
# This mode is enabled with a toggle switch in the controller box.  When in Basic Mode, the only
# other valid mode is Shutdown Mode. Shutdown Mode may override Basic Mode.
# - Actions: Release and deactivate brake and gas actuators.  Steering PID keep active
#
# ** Stall Mode **
# - Required: Engine stopped & BasicMode switch Off & Ignition On
# - Priority: 3
# This mode is active when the engine is not running.  If car is moving, then it presumably may
# coast to a stop.  The actuators are all enabled and work normally.  Starting the engine will
# bring you into Hold Mode.  Shutdown Mode and Basic Mode both override Stall Mode. Note: This
# mode allows for driver to steer while being towed or pushed, or working on the car.
# - Actions: Enable all actuators
#
# ** Hold Mode **
# - Required: Engine running & JoyVert<=Center & BasicMode switch Off & Ignition On
# - Priority: 4
# This mode is entered from Stall Mode once engine is started, and also, whenever the car comes
# to a stop while driving around in Fly Mode.  This mode releases the throttle and will
# continuously increase the brakes until the car is stopped, if it finds the car is moving.
# Pushing up on the joystick from Hold mode releases the brakes & begins Fly Mode.
# Shutdown, Basic & Stall Modes override Hold Mode.
# # Actions: Close throttle, and Apply brake to stop car, continue to ensure it stays stopped.
#
# ** Fly Mode **
# - Required: (Car Moving OR JoyVert>Center) & In gear & Engine running & BasicMode Off & Ign On
# - Priority: 5
# This mode is for driving under manual control. In Fly Mode, vertical joystick positions
# result in a proportional level of gas or brake (AKA "Manual" control).  Fly Mode is
# only active when the car is moving - Once stopped or taken out of gear, we go back to Hold Mode.
# If the driver performs a special secret "cruise gesture" on the joystick, then go to Cruise Mode.
# Special cruise gesture might be: Pair of sudden full-throttle motions in rapid succession
# - Actions: Enable all actuators, Watch for gesture
#
# ** Cruise Mode **
# - Required: Car Moving & In gear & Engine running & BasicMode switch Off & Ignition On
# - Priority: 6 (Lowest)
# This mode is entered from Fly Mode by doing a special joystick gesture. In Cruise Mode,
# the brake is disabled, and the joystick vertical is different: If joyv at center, the
# throttle will actively maintain current car speed.  Up or down momentary joystick presses
# serve to adjust that target speed. A sharp, full-downward gesture will drop us back to
# Fly Mode, promptly resulting in braking (if kept held down).
# - Actions: Release brake, Maintain car speed, Handle joyvert differently, Watch for gesture
*/

// Some human readable integers for array indexing
#define STR 0   // indexer for steering values
#define BRK 1   // indexer for brake values
#define GAS 2   // indexer for throttle values
#define H 0   // indexer for horizontal values
#define V 1   // indexer for vertical values
#define BOOT -1
#define SHUTDOWN 0
#define BASIC 1
#define STALL 2
#define HOLD 3
#define FLY 4
#define CRUISE 5

#define arraysize(x)  (sizeof(x) / sizeof((x)[0]))  // To determine the length of string arrays

// LCD is 2.8in diagonal, 240x320 pixels
// LCD supports 18-bit color, but GFX library uses 16-bit color, organized (MSB) 5b-red, 6b-green, 5b-blue (LSB)
// Since the RGB don't line up with the nibble boundaries, it's tricky to quantify a color, here are some colors:
#define BLACK    0x0000
#define BLUE     0x001F
#define RED      0xF800
#define GREEN    0x07E0
#define CYAN     0x07FF
#define MAGENTA  0xF81F
#define YELLOW   0xFFE0
#define WHITE    0xFFFF

// void drawChar(uint16_t x, uint16_t y, char c, uint16_t color, uint16_t bg, uint8_t size);
//void setCursor(uint16_t x0, uint16_t y0);
//void setTextColor(uint16_t color);
//void setTextColor(uint16_t color, uint16_t backgroundcolor);
//void setTextSize(uint8_t size);
//void setTextWrap(boolean w);

// Defines for all the GPIO pins we're using
#define enc_b_pin 2  // Int input, Encoder is user input knob for the UI.  This is its B quadrature output, active low (needs pullup)
#define enc_a_pin 3  // Int input, Encoder is user input knob for the UI.  This is its A quadrature output, active low (needs pullup)
#define usd_cs_pin 4  // Output, active low, Chip select allows SD card controller chip use of the SPI bus
#define tft_ledk_pin 5   // Output, Optional PWM signal to control brightness of LCD backlight (needs modification to shield board to work)
#define brake_pwm_pin 6  // Output, PWM signal duty cycle sets speed of brake actuator from full speed extend to full speed retract, (50% is stopped)
#define tp_irq_pin 7  // Optional int input so touchpanel can interrupt us (need to modify shield board for this to work)
#define steer_pwm_pin 8  // Output, PWM signal duty cycle sets speed of steering motor from full speed left, to full speed right, (50% is stopped)
#define tft_dc_pin 9  // Output, Assert when sending data to display chip to indicate commands vs. screen data
#define tft_cs_pin 10  // Output, active low, Chip select allows ILI9341 display chip use of the SPI bus
#define gas_pwm_pin 13 // Output, PWM signal duty cycle controls throttle target
#define ignition_pin 15  // Input tells us if ignition signal is on or off, active high (no pullup)
#define neutral_pin 16  // Input, active low, is asserted when car is in neutral, i.e. out of gear.  (needs pullup)
#define basicmodesw_pin 17  // Input, active low, asserted to tell us to run in basic mode.   (needs pullup)
#define tach_pulse_pin 18  // Int Input, active high, asserted when magnet is in range of sensor. 4 pulses per engine rotation. (no pullup)
#define speedo_pulse_pin 19  // Int Input, active high, asserted when magnet is in range of sensor. 8 pulses per driven pulley rotation. (no pullup)
#define enc_sw_pin 20  // Int input, Encoder is user input knob for the UI.  This is its pushbutton output, active low (needs pullup)
#define joy_horz_pin A0  // Analog input, tells us up-down position of joystick
#define joy_vert_pin A1  // Analog input, tells us left-right position of joystick
#define brake_pres_pin A2  // Analog input, tells us brake fluid pressure (5V = 1000psi)
#define brake_pos_pin A6  // Analog input, tells us linear position of brake actuator
#define mule_volt_pin A7  // Analog input, mule battery voltage level, full scale is 5V * 3.1276 = 15.638V

// Readily available possibilities we could wire up if we want
//
// * Status LEDs (digital out)
// * UI Potentiometer (analog in)
// * Control of steering motor coast vs. brake
// * Control of brake motor coast vs. brake
// * CAN bus as a superior interface to brake and steering Jaguars (only on Due I think?)
// * Steering limit switches left and right, handle here instead of in Jaguar (digital in)
// * Engine temperature module overheat panic input (digital in)
// * Remote E-Stop panic inputs (digital in)
// * Serial interface to the lighting controller (if we can think of a reason)
// * Mule starter (digital out)
// * E-brake handle position (digital in)

#define disp_lineheight 15
#define disp_linewidth 320
#define disp_screenheight 240

#define adcrange 1024    // = 1024
#define adcmidscale 512    // = 1024
//int adcrange = 2^10;    // = 1024
//int adcmidscale = adcrange/2;    // = 1024

// Constants
//
char telemetry[16][14] = {
    "   Run Mode: ",
    "  Air Speed: ",
    "   Joy Horz: ",
    "   Joy Vert: ",
    "SteerTarget: ",
    "  Steer PWM: ",
    "BrakeTarget: ",
    "  Brake PWM: ",
    "BrakePressr: ",
    "  GasTarget: ",
    "    Gas PWM: ",
    " Engine RPM: ",
    "    Touch X: ",
    "    Touch Y: ",
    "JoyHorz Raw: ",
    "         NA: "
};
char modecard[6][9] = {
    "Shutdown",
    "Basic   ",
    "Stall   ",
    "Hold    ",
    "Fly     ",
    "Cruise  "
};
/*
char actioncard[6][9] = {
    "Unknown ",
    "Stopping",
    "New Mode",
    "Flying  ",
    "Cruising",
    "Releasng",
    "Holding "
};
*/

// Settable calibration values and control parameters
//
float steer_kp = 0.0;  // PID proportional coefficient (steering)
float steer_ki = 0.0;  // PID integral coefficient (steering)
float steer_kd = 0.0;  // PID derivative coefficient (steering)
int steer_pid_freq = 10;  // How fast to loop in Hz
int steer_stop = 90;  // Servo target corresponding to no steering (zero steering speed)
int steer_max_speed = 90;  // Fastest steering we want.  (in change of PWM duty from center)
float brake_kp = 0.1;  // PID proportional coefficient (brake)
float brake_ki = 0.5;  // PID integral coefficient (brake)
float brake_kd = 0.0;  // PID derivative coefficient (brake)
int brake_pid_freq = 10;  // How fast to loop in Hz
int brake_min_release = 0;  // Brake pressure when brakes are effectively off
int brake_max_pressure = 0;  // Highest possible pressure achievable by the actuator
int brake_hold_initial = 0;  // Pressure initially applied when brakes are hit to auto-stop the car
int brake_hold_increment = 0;  // Incremental pressure per second added until car stops (when auto stopping)
int brake_pos_full_retract = 0;  // Brake position value corresponding to retract limit of actuator
int brake_pos_full_extend = 0;  // Brake position value corresponding to extend limit of actuator
int brake_increment_interval = 1000;  // How often to apply increment during auto-stopping
float gas_kp = 0.0;  // PID proportional coefficient (gas)
float gas_ki = 0.0;  // PID integral coefficient (gas)
float gas_kd = 0.0;  // PID derivative coefficient (gas)
int gas_pid_freq = 10;  // How fast to loop in Hz
int throttle_min_closed = 45;  // servo target angle setting (in degrees) corresponding to fully closed throttle
int throttle_max_open = 120;  // servo target angle setting (in degrees) corresponding to full open throttle
int engine_rpm_min_idle = 0;  // Min value for engine_rpm, corresponding to low idle
int engine_rpm_max_redline = 0;  // Max value for engine_rpm, pedal to the metal
int engine_rpm_timeout = 400;  // ms since last magnet pulse when we can assume the engine is stopped
float cruise_kp = 0.0;  // PID proportional coefficient (cruise)
float cruise_ki = 0.0;  // PID integral coefficient (cruise)
float cruise_kd = 0.0;  // PID derivative coefficient (cruise)
int cruise_pid_freq = 10;  // How fast to loop in Hz
int cruise_max_change = 0;  // What's the max car speed change from a single joystick motion in cruise mode?
int cruise_max_carspeed = 0;  // How fast can we go?
int joy_min_v = 0;  // ADC count of furthest joy position in down direction
int joy_max_v = 0;  // ADC count of furthest joy position in up direction
int joy_min_h = 0;  // ADC count of furthest joy position in left direction
int joy_max_h = 0;  // ADC count of furthest joy position in right direction
int joy_deadband_v = 140;  // ADC count width of inert readings around center which we should treat as center (vertical)
int joy_deadband_h = 140;  // ADC count width of inert readings around center which we should treat as center (horizontal)
int gesture_adj_timeout = 1000;  // How many ms allowed to complete a speed adjustment gesture
int gesture_fly_timeout = 500;  // How many ms allowed to push joy down to go to Fly mode from Cruise mode
int car_speed_timeout = 400;  // ms since last magnet pulse when we can assume the car is stopped

// Non-settable control variables
//
int steer_max_left = steer_stop+steer_max_speed;   // PWM duty cycle from 0-255
int steer_max_right = steer_stop-steer_max_speed;    // PWM duty cycle from 0-255
int steer_fullrange = abs(steer_max_left-steer_max_right);  // Possible range for target values
int steer_target = 0;  // Stores new setpoint to give to the pid loop (steering)
int steer_pwm = 0;  // pid loop output to send to the actuator (steering)
int brake_fullrange = brake_max_pressure-brake_min_release;  // Possible range for target values
int brake_target = 0;  // Stores new setpoint to give to the pid loop (brake)
int brake_pwm = 0;  // pid loop output to send to the actuator (brake)
int gas_target = 0;  // Stores new setpoint to give to the pid loop (gas)
int gas_pwm = 0;  // pid loop output to send to the actuator (gas)
int throttle_fullrange = throttle_max_open-throttle_min_closed;  // Possible range for target values
int engine_rpm_fullrange = engine_rpm_max_redline-engine_rpm_min_idle;  // Possible range for target values
int joy_deadband_bot_v = int((adcrange-joy_deadband_v)/2);  // Lower threshold of vertical joystick deadband
int joy_deadband_top_v = int((adcrange+joy_deadband_v)/2);  // Upper threshold of vertical joystick deadband
int joy_deadband_bot_h = int((adcrange-joy_deadband_h)/2);  // Lower threshold of horizontal joystick deadband
int joy_deadband_top_h = int((adcrange+joy_deadband_h)/2);  // Upper threshold of horizontal joystick deadband
int car_speed = -1;  // This is in units of rotations per minute of the driven torque converter pulley
int engine_rpm = -1;  // This is in units of rotations per minute of the engine crankshaft
const int gesture_complete = 0;  // How many steps are there in the Cruise Mode gesture
int gesture_extent = 0;  // Keeps track of max joystick movement during cruise mode speed adjustments

int brake_timer = 0;  // Timer used to control braking increments
int cruise_target = 0;  // Stores new setpoint to give to the pid loop (cruise)
int gesture_timer = 0;  // Used to keep track of time for gesturing
int gesture_progress = 0;  // How many steps of the Cruise Mode gesture have you completed successfully (from Fly Mode)
long steer_fullrange_long = (long)steer_fullrange;
const long adcrange_long = (long)adcrange;
long joy_deadband_bot_h_long = (long)joy_deadband_bot_h;
long joy_deadband_top_h_long = (long)joy_deadband_top_h;

// State variables
//
int runmode = SHUTDOWN;  // Variable to store what mode we're in
int oldmode = SHUTDOWN;  // So we can tell when the mode has just changed
bool we_just_switched_modes = true;  // For mode logic to set things up upon first entry into mode
bool shutdown_complete = true;  // Shutdown mode has completed its work and can stop activity

// Initialization of global variables, tunable parameters, etc.
int output_bits = 8;
bool output_signed = false;

boolean RecordOn = false;

unsigned long tach_old_time, speedo_old_time, tach_time, speedo_time;

// Instantiate objects
Adafruit_FT6206 touchpanel = Adafruit_FT6206();
Adafruit_ILI9341 tft = Adafruit_ILI9341(tft_cs_pin, tft_dc_pin);
static Servo steer_motor;
static Servo gas_servo;
FastPID brake_pid(brake_kp, brake_ki, brake_kd, brake_pid_freq, output_bits, output_signed);
SdFat SD;         // SD card filesystem

// Instantiate PID loops
//
// Steering:
//   Setpoint Value: Proportional to Joystick Horz ADC value.  0V = Full Left, 2.5V = Stop, 5V = Full Right
//   Measured Value: We have no feedback.  Try using a value proportional to the current actuator output
//   Actuator Output Value: PWM signal to Steering Jaguar unit.  0% duty = Full Left, 50% = Stop, 100% = Full Right
//   Limits: Reed switch limit signals for left and right may be handled by us, or by the jaguar controller
//   Setpoint scaling: Kp/Ki/Kd values should decrease appropriately as a function of vehicle speed (safety)
//
//   Notes: The steering has no feedback sensing, other than two digital limit switches at the ends of travel.
//   So just consider the error to be the difference between the joystick position and the last output value.
//
// Brakes:
//   Setpoint Value: * Default: Setpoint proportional to Joystick Vert distance from center when below center.
//       * In Hold Mode: Brake adjusts automatically to keep car stopped, as long as joystick below center
//       * In Cruise Mode: Brake is disabled
//   Measured Value: Analog voltage from brake fluid pressure sensor. 0-3.3V proportional to 0-1000psi
//   Actuator Output Value: PWM signal to Brake Jaguar unit.
//       0% duty = Full speed extend (less brake), 50% = Stop, 100% = Full speed Retract (more brake)
//   Position: Analog 0-3.3V proportional to the travel length of the actuator (not used as feedback)
//
// Gas:
//   Setpoint Value: * Default: Servo angle is proportional to Joystick Vert distance from center when above center.
//       * In Cruise Mode: Upward or downward joy vert motions modify vehicle speed setpoint
//   Measured Value: * Default: Engine speed determined from tach pulses
//   Actuator Output Value: PWM signal to throttle servo
//       0% duty = Fully close throttle.  This will idle.  100% duty = Fully open throttle.
//
// Cruise:
//   Setpoint Value: * Default: Set to the current vehicle speed when mode is entered.
//       * In Cruise Mode: Upward or downward joy vert motions modify vehicle speed setpoint
//   Measured Value: * Vehicle speed determined from tach pulses
//   Actuator Output Value: Cruise PID output values are setpoint values for the Gas PID above
//       0% duty = Car stopped.  100% duty = Car max speed.

static Servo steering_servo;
// Setup code runs once at boot time

bool encb_isr_flag = false;
bool enca_isr_flag = false;
bool encsw_isr_flag = false;
bool tach_isr_flag = false;
bool speedo_isr_flag = false;

void setup() {
    pinMode(enc_b_pin, INPUT_PULLUP);
    pinMode(enc_a_pin, INPUT_PULLUP);
    pinMode(brake_pwm_pin, OUTPUT);
    pinMode(steer_pwm_pin, OUTPUT);
    pinMode(tft_dc_pin, OUTPUT);
    pinMode(enc_sw_pin, INPUT_PULLUP);
    pinMode(gas_pwm_pin, OUTPUT);
    pinMode(ignition_pin, INPUT);
    pinMode(neutral_pin, INPUT_PULLUP);
    pinMode(basicmodesw_pin, INPUT_PULLUP);
    pinMode(tach_pulse_pin, INPUT);
    pinMode(speedo_pulse_pin, INPUT);
    pinMode(joy_horz_pin, INPUT);
    pinMode(joy_vert_pin, INPUT);
    pinMode(brake_pres_pin, INPUT);
    pinMode(brake_pos_pin, INPUT);
    pinMode(mule_volt_pin, INPUT);
    pinMode(usd_cs_pin, OUTPUT);
    pinMode(tft_cs_pin, OUTPUT);
    //pinMode(tft_ledk_pin, OUTPUT);
    //pinMode(tp_irq_pin, INPUT);

    // Set all outputs to known sensible values
    digitalWrite(tft_cs_pin, HIGH);   // Prevent bus contention
    digitalWrite(usd_cs_pin, HIGH);   // Prevent bus contention
    digitalWrite(tft_dc_pin, LOW);
    analogWrite(brake_pwm_pin, 128);   // Write values range from 0 to 255
    analogWrite(steer_pwm_pin, 128);
    analogWrite(gas_pwm_pin, throttle_min_closed);

    // Timers T0 (8b): pins 4,13 - T1 (16b): pins 11,12 - T2 (8b): pins 9,10 - T3 (16b): pins 2,3,5 - T4 (16b): pins 6,7,8 - T5 (16b): pins 44,45,46
    // Registers: TCCRx = Timer control, prescalar, TCNTx = Timer value, OCRx = Output compare, ICRx = Input Capture, TIMSKx = Int mask, TIFRx = Int Flags
    TCCR0B = TCCR0B & B11111000 | B00000101; // set timer 0 divisor to  1024 for PWM frequency of    61.04 Hz (Gas Servo)
    TCCR4B = TCCR4B & B11111000 | B00000100; // set timer 4 divisor to   256 for PWM frequency of   122.55 Hz (Brake & Steering)

    //while (!Serial);     // needed for debugging?!
    Serial.begin(115200);
    tft.begin();

    Serial.println(F("Captouch initialization"));
    if (! touchpanel.begin(40)) {     // pass in 'sensitivity' coefficient
        Serial.println("Couldn't start FT6206 touchscreen controller");
        while (1);
    }
    Serial.println("Capacitive touchscreen started");
    tft.fillScreen(BLACK);
    tft.setRotation(1);  // origin = left,top landscape (USB left upper)

    Serial.print(F("Initializing filesystem..."));  // SD card is pretty straightforward, a single call.
    if (! SD.begin(usd_cs_pin, SD_SCK_MHZ(25))) {   // ESP32 requires 25 MHz limit
        Serial.println(F("SD begin() failed"));
        for(;;); // Fatal error, do not continue
    }
    Serial.println(F("Filesystem started"));
    //tft.fillScreen(ILI9341_BLUE);  // Fill screen blue.

    steer_motor.attach(steer_pwm_pin);
    gas_servo.attach(gas_pwm_pin);

    // Set up our interrupts
    attachInterrupt(digitalPinToInterrupt(enc_b_pin), EncoderB_ISR, CHANGE);
    attachInterrupt(digitalPinToInterrupt(enc_a_pin), EncoderA_ISR, CHANGE);
    attachInterrupt(digitalPinToInterrupt(enc_sw_pin), EncoderSw_ISR, CHANGE);
    attachInterrupt(digitalPinToInterrupt(tach_pulse_pin), Tach_ISR, RISING);
    attachInterrupt(digitalPinToInterrupt(speedo_pulse_pin), Speedo_ISR, RISING);

    int i;
    for (i=0; i<=arraysize(telemetry); i++)  {
        writeline(i+1, telemetry[i]);
    }
}

void EncoderB_ISR(void) {
    encb_isr_flag = true;
}
void EncoderA_ISR(void) {
    enca_isr_flag = true;
}
void EncoderSw_ISR(void) {
    encsw_isr_flag = true;
}
void Tach_ISR(void) {
    tach_time = millis();  // This might screw up things.  Anders would remember
    tach_isr_flag = true;
}
void Speedo_ISR(void) {
    speedo_time = millis();  // This might screw up things.  Anders would remember
    speedo_isr_flag = true;
}

void set_steer_pwm(int target_in_degrees) {
    steer_motor.write(target_in_degrees);
}

void set_gas_pwm(int target_in_degrees) {
    gas_servo.write(target_in_degrees);
}

// Returns: The value read on the joystick from 0 (maximum left) to 1024 (maximum right).
// Zero values correspond to the deadband at the center position.
int read_joy_vert(void)  {
    int adc_value = analogRead(joy_vert_pin);
    int joy_vert;

    if ((adc_value > joy_deadband_bot_v) && (adc_value < joy_deadband_top_v)) {
        joy_vert = adcmidscale;  // return 0 input if value is in the deadband
    }
    else  {
        joy_vert = adcrange-adc_value;
    }
    return joy_vert;
}

int read_joy_horz(void)  {
    int adc_value = analogRead(joy_horz_pin);
    int joy_horz;

    if ((adc_value > joy_deadband_bot_h) && (adc_value < joy_deadband_top_h)) {
        joy_horz = adcmidscale;  // return 0 input if value is in the deadband
    }
    else  {
        joy_horz = adcrange-adc_value;
    }
    return joy_horz;
}

// Inputs: The joystick input between -512 and 512.
// Returns: The joystick target to output from 0 to 180 degrees.
int joy_horz_to_target(int joy_input) {
    int target;
    long joy_input_long = (long)joy_input;
    long max_target_deg_long = (long)steer_fullrange;
    long adcrange_long = (long)adcrange;

    target = (int)((joy_input_long*max_target_deg_long)/adcrange_long);
    return target;
}

int joy_vert_to_target(int joy_input) {
    int target;
    long joy_input_long = (long)joy_input;

    long max_target_deg_long;
    long adcrange_long = (long)adcrange;
    if (joy_input > joy_deadband_top_v)  {
        max_target_deg_long = (long)engine_rpm_max_redline;
    }
    else  {
        max_target_deg_long = (long)brake_max_pressure;
    }
    target = (int)((joy_input_long*max_target_deg_long)/(2*adcrange_long));
    return target;
}
/*int* read_joy_values(void) {
    int joy_raw_values[2];
    joy_raw_values[H] = analogRead(joy_horz_pin);
    joy_raw_values[V] = analogRead(joy_vert_pin);

    int joy_values[2];

    for (axis=H; axis<=V; axis++) {
        //check if the value is in the deadband, return 0 input if it is
        if ((joy_raw_values[axis] > joy_deadband_bot_) && (joy_raw_values[axis] < joy_deadband_top[axis])) {
            joy_values[axis] = adcmidscale;
        }
        else {
            joy_values[axis] = adcrange-joy_raw_values[axis];
        }
    return joy_values;
}

int *joy_to_actuator_targets(int *joy_values) {
    long servo_max_target_deg_long = (long)steer_fullrange;
    long adcmidscale_long = (long)adcmidscale;
    long adcrange_long = (long)adcrange;

    int actuator_targets[3];
    long joy_values_long[2];

    joy_values_long[H] = (long)joy_values[H];
    joy_values_long[V] = (long)joy_values[V];

    actuator_targets[STR] = (int)((joy_values_long[H]*servo_max_target_deg_long)/adcrange_long);

    //actuator_targets[BRK] = BRAKE_FULL_EXTEND_TARGET;
    //if (joy_values[V] < adcmidscale)
    //{
    //  actuator_targets[BRK] = (int)((adcmidscale_long-joy_values_long[V])*servo_max_target_deg_long/adcmidscale_long);
    //}

    actuator_targets[GAS] = throttle_min_closed;
    if (joy_values[V] > adcmidscale) {
        actuator_targets[GAS] = (int)((joy_values_long[V]-adcmidscale_long)/adcmidscale_long);
    }

    return actuator_targets;
}
*/

void writevalue(int lineno, char *value) {
    tft.fillRect(80, (lineno-1)*disp_lineheight, 55, disp_lineheight, BLACK);
    //tft.fillRect(0, (lineno-1)*disp_lineheight, disp_linewidth, disp_lineheight, ILI9341_BLACK);
    tft.setCursor(86, ((lineno-1)*disp_lineheight)+disp_lineheight/2);
    tft.setTextColor(WHITE);
    tft.setTextSize(1);
    tft.println(value);
    RecordOn = false;
}

void writeline(int lineno, char *value) {
    tft.fillRect(0, (lineno-1)*disp_lineheight, disp_linewidth, disp_lineheight, BLACK);
    tft.setCursor(6, ((lineno-1)*disp_lineheight)+disp_lineheight/2);
    tft.setTextColor(WHITE);
    tft.setTextSize(1);
    tft.println(value);
    RecordOn = false;
}

void loop() {
    // Main loop.  Each time through we do these eight steps:
    //
    // 1) Gather new telemetry
    // 2) Check if our current runmode has been overridden by certain specific conditions
    // 3) Read joystick horizontal and determine new steering setpoint
    // 4) Do actions based on which runmode we are in (including gas & brake setpoint), and possibly change runmode
    // 5) Step the PID loops and update the actuation outputs
    // 6) Service the user interface
    // 7) Log to SD card
    // 8) Do the control loop bookkeeping at the end of each loop

    // Initialize variables
    //
    int joy_vert, joy_horz, old_joy_vert, old_joy_horz;
    char buffer[6];
    int steer_target, brake_target, gas_target, old_steer_target, old_brake_target, old_gas_target;
    int steer_pwm, brake_pwm, gas_pwm, old_steer_pwm, old_brake_pwm, old_gas_pwm;
    int engine_rpm, old_engine_rpm, car_speed, old_car_speed;
    int before, after;
    int old_brake_pressure;
    int pwmtimer;

    // 1) Gather new telemetry
    //
    int now = millis();
    if (tach_isr_flag == true) {       // Update engine rpm value
        float engine_rpm = 60*1000/(4*(tach_time-tach_old_time));
        tach_old_time = tach_time;
        tach_isr_flag = false;
    }
    else if (now-tach_old_time > engine_rpm_timeout) {
        engine_rpm = 0;
    }
    if (speedo_isr_flag == true) {   // Update car speed value
        float car_speed = 60*1000/(8*(speedo_time-speedo_old_time));
        speedo_old_time = speedo_time;
        speedo_isr_flag = false;
    }  // Mule gearing:  Total -19.845x (lo) ( Converter: -3.5x to -0.96x Tranny -3.75x (lo), -1.821x (hi), Final drive -5.4x )
    else if (now-speedo_old_time > car_speed_timeout) {
        car_speed = 0;
    }

    // Read the sensors
    int brake_pressure = analogRead(brake_pres_pin);
    int brake_pos = analogRead(brake_pos_pin);
    int mule_voltage = analogRead(mule_volt_pin);
    int neutral = digitalRead(neutral_pin);
    int ignition = digitalRead(ignition_pin);
    //int basicmodesw = digitalRead(basicmodesw_pin);
    int basicmodesw = 1;  // Disable for now until connected

    // 2) Check if our current runmode has been overridden by certain specific conditions
    //
    if (ignition == 0)  {           // if ignition off --> Shutdown Mode
        runmode = SHUTDOWN;
    }
    else if (basicmodesw == 0) {    // elif basicmode switch on --> Basic Mode
        runmode = BASIC;
    }
    else if (engine_rpm == 0)  {    // elif engine not running --> Stall Mode
        runmode = STALL;
    }

    // 3) Read joystick horizontal and determine new steering setpoint
    //
    joy_vert = read_joy_vert();
    joy_horz = read_joy_horz();

    if (!(runmode == SHUTDOWN && (car_speed == 0 or shutdown_complete == true)))  { // The only time we don't want steering
        long joy_horz_long = (long)joy_horz;
         if (joy_horz < joy_deadband_bot_h)  {    // If we are trying to turn left
            // This should determine how hard we're trying to turn (0 to 1 range)
            int temp = (int)((joy_deadband_bot_h_long-joy_horz_long)/joy_deadband_bot_h_long);
            int steer_target = (steer_fullrange_long/2)*(1-temp);
        }
        else if (joy_horz > joy_deadband_top_h)  {  // If we are trying to turn right
            // This should determine how hard we're trying to turn (0 to 1 range)
            int temp = (int)((joy_horz_long-joy_deadband_top_h_long)/joy_deadband_bot_h_long);
            int steer_target = (steer_fullrange_long/2)*(1+temp);
            //int steer_target = (steer_fullrange_long/2)*(1+(int)((joy_horz_long-joy_deadband_top_h_long)/joy_deadband_bot_h_long));
        }
        else {
            steer_target = steer_stop;  // adjust to actual center
        }
    }
    // Try this with the commented function above
    // joy_values = read_joy_values();
    // joy_horz = joy_values[0];
    // joy_vert = joy_values[1];

    // Old: steer_target = joy_horz_to_target(joy_horz);
    // Old: gas_target = joy_vert_to_target(joy_vert);

    // 4) Do actions based on which runmode we are in (and set gas/brake setpoints), and possibly change runmode
    //
    now = millis();

    if (runmode == SHUTDOWN)  {
        if (basicmodesw == 0)  {   // If basic mode switch is enabled
            shutdown_complete = true;
        }
        else if (we_just_switched_modes == true)  {  // If basic switch is off, we need to stop the car then release brakes and gas before shutting down
            gas_target = engine_rpm_min_idle;  //  Begin Letting off the gas all the way
            shutdown_complete = false;
            if (car_speed > 0)  {
                brake_target = brake_hold_initial;  // More brakes, etc. to stop the car
                brake_timer = now;
            }
        }
        if (shutdown_complete == false)  {  // If we haven't yet stopped the car and released the brakes and gas all the way
            if (car_speed == 0)  {  // Car is stopped, but maybe we still need to release the brakes
                brake_target = brake_min_release;  // Start to Fully release brakes
                if (brake_pressure == brake_min_release)  {
                    shutdown_complete = true;  // With this set, we will do nothing from here on out (until mode changes, i.e. ignition)
                }
            }
            else if (brake_timer-now > brake_increment_interval)  {
                brake_target += brake_hold_increment;  // Slowly add more brakes until car stops
                brake_timer = now;
            }
        }
    }
    else if (runmode == BASIC)  {
        if (basicmodesw == 1 && engine_rpm > 0)  {  // If we turned off the basic mode switch with engine running, go to Hold mode
            runmode = HOLD;   //  If engine is not running, we'll end up in Stall Mode automatically
        }
    }
    else if (runmode == STALL)  {   // In stall mode, the gas doesn't have feedback}
        // PID limits don't apply any more when not using engine rpm as fb.  Fix this
        if (engine_rpm > 0)  {  //  enter Hold Mode if we started the car
            runmode = HOLD;
        }
        else {
            gas_target = engine_rpm_min_idle;  // Default when joystick not pressed
            brake_target = brake_min_release;  // Default when joystick not pressed
            if (joy_vert > joy_deadband_top_v)  { //  If we are pushing up
                gas_target = engine_rpm_fullrange*(joy_vert-joy_deadband_top_v)/joy_deadband_bot_v;
            }
            else if (joy_vert < joy_deadband_bot_v)  {  // If we are pushing down
                brake_target = brake_fullrange*(joy_deadband_bot_v-joy_vert)/joy_deadband_bot_v;
            }
        }
    }
    else if (runmode == HOLD)  {
        if (joy_vert > joy_deadband_top_v)  { // Enter Fly Mode if joystick is pushed up
            runmode = FLY;
        }
        else if (we_just_switched_modes == true)  {  // Release throttle and push brake upon entering hold mode
            gas_target = engine_rpm_min_idle;  // Let off gas
            brake_target = brake_hold_initial;  // Apply brakes to preset setpoint
            brake_timer = now;
        }
        else if (car_speed > 0 && brake_timer-now > brake_increment_interval)  {  // If car starts moving again, push harder
            brake_target += brake_hold_increment; //  Increase the brake pressure slowly when trying to stop car
            brake_timer = now;
        }
    }
    else if (runmode == FLY)  {
        if (we_just_switched_modes == true)  {
            gesture_progress = 0;
            gesture_timer = now;
        }
        // else if (gesture motion detected)  {   // If next motion of gesture completed in time
        //     // Add checks to identify conditions to satisfy steps of the gesture
        //     gesture_progress++;
        //     gesture_timer = now;
        // }
        else if (gesture_progress == gesture_complete)  { // Series of motions is complete
            runmode = CRUISE;
        }
        else if (now-gesture_timer > gesture_adj_timeout)  {  // Gesture timed out
            gesture_progress = 0;
        }
        if ((car_speed == 0 && joy_vert < joy_deadband_bot_v) || neutral)  {
            runmode = HOLD;  // Back to Hold Mode if we have braked to a stop or shifted out of gear
        }
        else  {  // Use PID to drive
            gas_target = engine_rpm_min_idle;  // Default when joystick not pressed
            brake_target = brake_min_release;  // Default when joystick not pressed
            if (joy_vert > joy_deadband_top_v)  {  // If we are trying to accelerate
                gas_target = engine_rpm_fullrange*(joy_vert-joy_deadband_top_v)/joy_deadband_bot_v;
            }
            else if (joy_vert < joy_deadband_bot_v)  {  // If we are trying to brake
                brake_target = brake_fullrange*(joy_deadband_bot_v-joy_vert)/joy_deadband_bot_v;
            }
        }
    }
    else if (runmode == CRUISE)  { // Maybe the elif clauses within here should be if clauses.  Maybe doesn't matter
        if (car_speed == 0 or neutral > 0)  {  // this should never happen
            runmode = HOLD;  // Back to Hold Mode because we don't understand what's going on
        }
        else if (we_just_switched_modes == true)  {
            cruise_target = car_speed;
            brake_target = brake_min_release;
            gesture_extent = adcrange/2;  // Variable to keep track of our joystick motion for speed adjustments
        }
        if (joy_deadband_bot_v < joy_vert && joy_deadband_top_v > joy_vert)  {  // joystick within deadband near center: do speed adjustment, and reset gesture timer
            if (gesture_extent > joy_deadband_top_v && now-gesture_timer < gesture_adj_timeout)  { // Adjust speed upward based on how high we were pushed
                cruise_target += cruise_max_change*(gesture_extent-joy_deadband_top_v)/joy_deadband_bot_v;
            }
            else if (gesture_extent < joy_deadband_bot_v && now-gesture_timer < gesture_adj_timeout)  {
                cruise_target -= cruise_max_change*(joy_deadband_bot_v-gesture_extent)/joy_deadband_bot_v;
            }
            gesture_extent = adcrange/2;  // Reset for next time
            gesture_timer = now;
        }
        else if (joy_vert == joy_min_v && now-gesture_timer < gesture_fly_timeout)  { // If joystick quickly pushed down
            runmode = FLY;
        }
        else if (joy_vert > joy_deadband_top_v && joy_vert > gesture_extent)  {  // We pushed it even further up
            gesture_extent = joy_vert;  // Remember our highest point
        }
        else if (joy_vert < joy_deadband_bot_v && joy_vert < gesture_extent)  {  // We pushed it even further down
            gesture_extent = joy_vert;  // Remember our lowest point
        }
        // Commented out during initial debug
        //gas_target = cruise_pid.step(feedback=car_speed, setpoint = cruise_target);
    }
    else  { // Obviously this should never happen
        runmode = HOLD;
    }

    // 5) Step the pids, update the actuator outputs
    //
    // The pid approach is the most cool.  Fix and uncomment these as we can
    if (! (runmode == SHUTDOWN && shutdown_complete == true))  {  // The only time we don't want steering
        // steering_pwm = steering_pid.step(feedback=none, setpoint = steer_target);

        if (! basicmodesw == 0)  {  // If basicmode switch is disabled we want brake and gas
            // brake_pwm = brake_pid.step(feedback=brake_pressure, setpoint = brake_target);

            if (runmode == STALL)  {
                // gas_pwm = throttle_pid.step(feedback=none, setpoint = gas_target);
            }
            else {
                // gas_pwm = throttle_pid.step(feedback=engine_rpm, setpoint = gas_target);
            }
        }
    }

    now = millis();

    // Update gas and steering output only every 15ms
    if (now-pwmtimer > 15)  {
        set_steer_pwm(steer_target);
        set_gas_pwm(gas_target);
        pwmtimer = now;
    }

    // Step the brake pid
    before = micros();
    brake_target = brake_pid.step(brake_min_release, brake_pressure);
    // uint8_t brake_target = brake_pid.step(brake_min_release, brake_pressure);
    after = micros();
    analogWrite(brake_pwm_pin, brake_pwm);
    Serial.print("runtime: ");
    Serial.print(after - before);
    Serial.print(" sp: ");
    Serial.print(brake_min_release);
    Serial.print(" fb: ");
    Serial.print(brake_pressure);
    Serial.print(" out: ");
    Serial.println(brake_target);

    // Try this later
    // if (car_speed != old_car_speed) {
    //    writevalue(11, (char*)car_speed;
    //    old_car_speed = car_speed;
    // }

    set_steer_pwm(steer_target);
    set_gas_pwm(gas_target);

    // 6) Service the user interface
    //
    // Act on any encoder action

    // See if someone is groping the touch screen
    if (touchpanel.touched())  {  // See if there's any  touch data for us
        TS_Point touchpoint = touchpanel.getPoint();   // Retreive a point
        touchpoint.x = map(touchpoint.x, 0, 240, 240, 0);  // Rotate touch coordinates to match tft
        touchpoint.y = map(touchpoint.y, 0, 320, 320, 0);
        int y = tft.height()-touchpoint.x;
        int x = touchpoint.y;
        memset(buffer,0,strlen(buffer));
        itoa(x, buffer, 10);
        writevalue(13, buffer);
        memset(buffer,0,strlen(buffer));
        itoa(y, buffer, 10);
        writevalue(14, buffer);
    }

    // Write new values to the screen

    if (runmode != oldmode) {
        writevalue(1, modecard[runmode]);
    }
    if (car_speed != old_car_speed) {
        memset(buffer,0,strlen(buffer));
        itoa(car_speed, buffer, 10);
        writevalue(2, buffer);
        old_car_speed = car_speed;
    }
    if (joy_horz != old_joy_horz) {
        memset(buffer,0,strlen(buffer));
        itoa(joy_horz, buffer, 10);
        writevalue(3, buffer);
        old_joy_horz = joy_horz;
    }
    if (joy_vert != old_joy_vert) {
        memset(buffer,0,strlen(buffer));
        itoa(joy_vert, buffer, 10);
        writevalue(4, buffer);
        old_joy_vert = joy_vert;
    }
    if (steer_target != old_steer_target) {
        memset(buffer,0,strlen(buffer));
        itoa(steer_target, buffer, 10);
        writevalue(5, buffer);
        old_steer_target = steer_target;
    }
    if (steer_pwm != old_steer_pwm) {
        memset(buffer,0,strlen(buffer));
        itoa(steer_pwm, buffer, 10);
        writevalue(6, buffer);
        old_steer_pwm = steer_pwm;
    }
    if (brake_target != old_brake_target) {
        memset(buffer,0,strlen(buffer));
        itoa(brake_target, buffer, 10);
        writevalue(7, buffer);
        old_brake_target = brake_target;
    }
    if (brake_pwm != old_brake_pwm) {
        memset(buffer,0,strlen(buffer));
        itoa(brake_pwm, buffer, 10);
        writevalue(8, buffer);
        old_brake_pwm = brake_pwm;
    }
    if (brake_pressure != old_brake_pressure) {
        memset(buffer,0,strlen(buffer));
        itoa(brake_pressure, buffer, 10);
        writevalue(9, buffer);
        old_brake_pressure = brake_pressure;
    }
    if (gas_target != old_gas_target) {
        memset(buffer,0,strlen(buffer));
        itoa(gas_target, buffer, 10);
        writevalue(10, buffer);
        old_gas_target = gas_target;
    }
    if (gas_pwm != old_gas_pwm) {
        memset(buffer,0,strlen(buffer));
        itoa(gas_pwm, buffer, 10);
        writevalue(11, buffer);
        old_gas_pwm = gas_pwm;
    }
    if (engine_rpm != old_engine_rpm) {
        memset(buffer,0,strlen(buffer));
        itoa(engine_rpm, buffer, 10);
        writevalue(12, buffer);
        old_engine_rpm = engine_rpm;
    }
    memset(buffer,0,strlen(buffer));
    itoa(analogRead(joy_horz_pin), buffer, 10);
    writevalue(15, buffer);

    // 7) Log to SD card
    //
    // [write current state with timestamp to the SD card]

    // 8) Do the control loop bookkeeping at the end of each loop
    //
    old_joy_vert = joy_vert;
    if (! oldmode == runmode)  {      // If changing runmode
        we_just_switched_modes = true;    // So new mode logic can perform initial actions
    }
    else {
        we_just_switched_modes = false;    // Reset this variable
    }
    oldmode = runmode;   // remember what mode we're in for next time

    delay(10);

}

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


Switched to use hmtl_next_sensor()

Switched to use hmtl_next_sensor()

/*******************************************************************************
 * Author: Adam Phelps
 * License: Create Commons Attribution-Non-Commercial
 * Copyright: 2014
 *
 * Code for a fully contained module which handles HMTL formatted messages
 * from a serial or RS485 connection.
 ******************************************************************************/

#include "EEPROM.h"
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>

#define DEBUG_LEVEL 4
#include <Debug.h>

#include "SerialCLI.h"

#include <RS485_non_blocking.h>
#include "Socket.h"
#include "RS485Utils.h"

// Note: These are only needed for ArduinoIDE compilation.  With this environment
// make sure to set DISABLE_MPR121 in the HMTLTypes.h, otherwise the static
// memory allocation (blame Wire.h) will exceed some limit and this won't work
#include "SPI.h"
#include "EEPROM.h"
#include "GeneralUtils.h"
#include "EEPromUtils.h"
#include "Wire.h"
#include "MPR121.h"
#include "FastLED.h"
#include "PixelUtil.h"
// End note

#include "HMTLTypes.h"
#include "HMTLMessaging.h"
#include "HMTLProtocol.h"

#define NUM_OUTPUTS 3
config_rgb_t rgb_output;

#define SEND_BUFFER_SIZE 64
byte databuffer[RS485_BUFFER_TOTAL(SEND_BUFFER_SIZE)];
byte *send_buffer;
RS485Socket rs485;

SerialCLI serialcli(64, cliHandler);

config_hdr_t config;

void setup() {
  Serial.begin(9600);
  DEBUG2_PRINTLN("*** HMTL_Command_CLI starting ***");

  config_max_t readoutputs[HMTL_MAX_OUTPUTS];
  int32_t outputs_found = hmtl_setup(&config, readoutputs,
                                     NULL, NULL, HMTL_MAX_OUTPUTS,
                                     &rs485, NULL, NULL,
                                     &rgb_output, NULL,
                                     NULL);

  /* Setup the RS485 connection */
  rs485.setup();
  send_buffer = rs485.initBuffer(databuffer);

  DEBUG2_VALUELN("*** HMTL_Command_CLI initialized.  Address:", config.address);
  print_usage();
}

void loop() {

  /* Check for message over RS485 */
  unsigned int msglen;
  msg_hdr_t *msg_hdr = hmtl_rs485_getmsg(&rs485, &msglen, config.address);
  if (msg_hdr != NULL) {
    process_message(msg_hdr, msglen);
  }

  /* Handle commands from the Serial CLI connection */
  serialcli.checkSerial();
}

void print_usage() {
Serial.print(F(" \n"
  "Usage:\n"
  "  h - print this help\n"
  "  s <addr> - Send sensor check\n"
  "  p <addr> - Send poll request\n"
               ));
}
void cliHandler(char **tokens, byte numtokens) {
  switch (tokens[0][0]) {

    case 'h': {
      print_usage();
      break;
    }

    case 's': {
      if (numtokens < 2) return;
      uint16_t address = atoi(tokens[1]);
      DEBUG1_VALUELN("* Sensor request to: ", address);
      hmtl_send_sensor_request(&rs485, send_buffer, SEND_BUFFER_SIZE, address);
      break;
    }

    case 'p': {
      if (numtokens < 2) return;
      uint16_t address = atoi(tokens[1]);
      DEBUG1_VALUELN("* Poll request to: ", address);
      hmtl_send_poll_request(&rs485, send_buffer, SEND_BUFFER_SIZE, address);
      break;
    }

  }
}

void process_message(msg_hdr_t *msg, unsigned int msglen) {
  DEBUG1_VALUE("Recieved rs485 msg len:", msglen);
  DEBUG1_VALUE(" src:", RS485_SOURCE_FROM_DATA(msg));
  DEBUG1_VALUE(" dst:", RS485_ADDRESS_FROM_DATA(msg));
  DEBUG1_VALUE(" len:", msg->length);
  DEBUG1_VALUE(" type:", msg->type);
  DEBUG1_HEXVAL(" flags:0x", msg->flags);
  DEBUG1_PRINT(" data:");
  DEBUG1_COMMAND(
                 print_hex_string((byte *)msg, msglen)
                 );
  DEBUG_PRINT_END();

  switch (msg->type) {
    case MSG_TYPE_SENSOR: {
      DEBUG1_PRINTLN(" * Sensor data:");

      msg_sensor_data_t *sense = NULL;
      while (sense = hmtl_next_sensor(msg, sense)) {
        DEBUG1_VALUE(" ptr:", (int)sense);
        DEBUG1_VALUE(" type:", sense->sensor_type);
        DEBUG1_VALUE(" datalen:", sense->data_len);

        switch (sense->sensor_type) {
          case HMTL_SENSOR_SOUND: {
            DEBUG1_PRINT(" SOUND:");
            uint16_t *data = (uint16_t *)&sense->data;
            for (byte i = 0; i < sense->data_len / sizeof (uint16_t); i++) {
              DEBUG1_HEXVAL(" ", data[i]);
            }
            break;
          }
          case HMTL_SENSOR_LIGHT: {
            uint16_t *data = (uint16_t *)&sense->data;
            DEBUG1_VALUE(" LIGHT:", *data);
            break;
          }
          case HMTL_SENSOR_POT: {
            uint16_t *data = (uint16_t *)&sense->data;
            DEBUG1_VALUE(" POT:", *data);
            break;
          }
          default: {
            DEBUG1_PRINT(" ERROR: UNKNOWN TYPE");
            return;
          }
        }

        DEBUG_PRINT_END();
      }
      break;
    }
    case MSG_TYPE_POLL: {
      DEBUG1_PRINT("POLL");
      break;
    }
  }

  DEBUG_PRINT_END();
}

/*******************************************************************************
 * Author: Adam Phelps
 * License: Create Commons Attribution-Non-Commercial
 * Copyright: 2014
 *
 * Code for a fully contained module which handles HMTL formatted messages
 * from a serial or RS485 connection.
 ******************************************************************************/

#include "EEPROM.h"
#include <RS485_non_blocking.h>
#include <SoftwareSerial.h>

#define DEBUG_LEVEL 4
#include <Debug.h>

#include "SerialCLI.h"

#include <RS485_non_blocking.h>
#include "Socket.h"
#include "RS485Utils.h"

// Note: These are only needed for ArduinoIDE compilation.  With this environment
// make sure to set DISABLE_MPR121 in the HMTLTypes.h, otherwise the static
// memory allocation (blame Wire.h) will exceed some limit and this won't work
#include "SPI.h"
#include "EEPROM.h"
#include "GeneralUtils.h"
#include "EEPromUtils.h"
#include "Wire.h"
#include "MPR121.h"
#include "FastLED.h"
#include "PixelUtil.h"
// End note

#include "HMTLTypes.h"
#include "HMTLMessaging.h"
#include "HMTLProtocol.h"

#define NUM_OUTPUTS 3
config_rgb_t rgb_output;

#define SEND_BUFFER_SIZE 64
byte databuffer[RS485_BUFFER_TOTAL(SEND_BUFFER_SIZE)];
byte *send_buffer;
RS485Socket rs485;

SerialCLI serialcli(64, cliHandler);

config_hdr_t config;

void setup() {
  Serial.begin(9600);
  DEBUG2_PRINTLN("*** HMTL_Command_CLI starting ***");

  config_max_t readoutputs[HMTL_MAX_OUTPUTS];
  int32_t outputs_found = hmtl_setup(&config, readoutputs,
                                     NULL, NULL, HMTL_MAX_OUTPUTS,
                                     &rs485, NULL, NULL,
                                     &rgb_output, NULL,
                                     NULL);

  /* Setup the RS485 connection */
  rs485.setup();
  send_buffer = rs485.initBuffer(databuffer);

  DEBUG2_VALUELN("*** HMTL_Command_CLI initialized.  Address:", config.address);
  print_usage();
}

void loop() {

  /* Check for message over RS485 */
  unsigned int msglen;
  msg_hdr_t *msg_hdr = hmtl_rs485_getmsg(&rs485, &msglen, config.address);
  if (msg_hdr != NULL) {
    process_message(msg_hdr, msglen);
  }

  /* Handle commands from the Serial CLI connection */
  serialcli.checkSerial();
}

void print_usage() {
Serial.print(F(" \n"
  "Usage:\n"
  "  h - print this help\n"
  "  s <addr> - Send sensor check\n"
  "  p <addr> - Send poll request\n"
               ));
}
void cliHandler(char **tokens, byte numtokens) {
  switch (tokens[0][0]) {

    case 'h': {
      print_usage();
      break;
    }

    case 's': {
      if (numtokens < 2) return;
      uint16_t address = atoi(tokens[1]);
      DEBUG1_VALUELN("* Sensor request to: ", address);
      hmtl_send_sensor_request(&rs485, send_buffer, SEND_BUFFER_SIZE, address);
      break;
    }

    case 'p': {
      if (numtokens < 2) return;
      uint16_t address = atoi(tokens[1]);
      DEBUG1_VALUELN("* Poll request to: ", address);
      hmtl_send_poll_request(&rs485, send_buffer, SEND_BUFFER_SIZE, address);
      break;
    }

  }
}

void process_message(msg_hdr_t *msg, unsigned int msglen) {
  DEBUG1_VALUE("Recieved rs485 msg len:", msglen);
  DEBUG1_VALUE(" src:", RS485_SOURCE_FROM_DATA(msg));
  DEBUG1_VALUE(" dst:", RS485_ADDRESS_FROM_DATA(msg));
  DEBUG1_VALUE(" len:", msg->length);
  DEBUG1_VALUE(" type:", msg->type);
  DEBUG1_HEXVAL(" flags:0x", msg->flags);
  DEBUG1_PRINT(" data:");
  DEBUG1_COMMAND(
                 print_hex_string((byte *)msg, msglen)
                 );
  DEBUG_PRINT_END();

  switch (msg->type) {
    case MSG_TYPE_SENSOR: {
      DEBUG1_PRINTLN(" * Sensor data:");
      byte *curr_ptr = (uint8_t *)(msg + 1);
      do {
        msg_sensor_data_t *sense = (msg_sensor_data_t *)(curr_ptr);
        DEBUG1_VALUE(" ptr:", (int)sense);
        DEBUG1_VALUE(" type:", sense->sensor_type);
        DEBUG1_VALUE(" datalen:", sense->data_len);
        curr_ptr += sizeof (msg_sensor_data_t) + sense->data_len;

        switch (sense->sensor_type) {
          case HMTL_SENSOR_SOUND: {
            DEBUG1_PRINT(" SOUND:");
            uint16_t *data = (uint16_t *)&sense->data;
            for (byte i = 0; i < sense->data_len / sizeof (uint16_t); i++) {
              DEBUG1_HEXVAL(" ", data[i]);
            }
            break;
          }
          case HMTL_SENSOR_LIGHT: {
            uint16_t *data = (uint16_t *)&sense->data;
            DEBUG1_VALUE(" LIGHT:", *data);
            break;
          }
          case HMTL_SENSOR_POT: {
            uint16_t *data = (uint16_t *)&sense->data;
            DEBUG1_VALUE(" POT:", *data);
            break;
          }
          default: {
            DEBUG1_PRINT(" ERROR: UNKNOWN TYPE");
            return;
          }
        }

        DEBUG_PRINT_END();
      } while (curr_ptr < (byte *)msg + msg->length);

      break;
    }
    case MSG_TYPE_POLL: {
      DEBUG1_PRINT("POLL");
      break;
    }
  }

  DEBUG_PRINT_END();
}


neopixel: add example file

neopixel: add example file

Just to show that it works.

Signed-off-by: Sean Cross <d7e19930cc1f42c2d0781f4d9e6f1fe5891bf9cf@xobs.io>

#include "Adafruit_NeoPixel.h"

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
Adafruit_NeoPixel strip = Adafruit_NeoPixel(1, LED_BUILTIN_RGB,
                                            NEO_GRB + NEO_KHZ800);

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

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

extern "C" double sin(double f);
#define double float
double test_d = 4.3L;
int test_thingy(int start) {
  static int val = start;

  test_d += sin(start);
  return ++val;
}

void loop() {
  printf("Hello, world!\r\n");

  test_thingy(micros());
  // Some example procedures showing how to display to the pixels:
  colorWipe(strip.Color(255, 0, 0), 50); // Red
  colorWipe(strip.Color(0, 255, 0), 50); // Green
  colorWipe(strip.Color(0, 0, 255), 50); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
  theaterChase(strip.Color(127, 127, 127), 50); // White
  theaterChase(strip.Color(127, 0, 0), 50); // Red
  theaterChase(strip.Color(0, 0, 127), 50); // Blue

  rainbow(20);
  rainbowCycle(20);
  theaterChaseRainbow(50);
}

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


neo pixel strandtest initi commit

neo pixel strandtest initi commit

// A basic everyday NeoPixel strip test program.

// NEOPIXEL BEST PRACTICES for most reliable operation:
// - Add 1000 uF CAPACITOR between NeoPixel strip's + and - connections.
// - MINIMIZE WIRING LENGTH between microcontroller board and first pixel.
// - NeoPixel strip's DATA-IN should pass through a 300-500 OHM RESISTOR.
// - AVOID connecting NeoPixels on a LIVE CIRCUIT. If you must, ALWAYS
//   connect GROUND (-) first, then +, then data.
// - When using a 3.3V microcontroller with a 5V-powered NeoPixel strip,
//   a LOGIC-LEVEL CONVERTER on the data line is STRONGLY RECOMMENDED.
// (Skipping these may work OK on your workbench but can fail in the field)

#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
 #include <avr/power.h> // Required for 16 MHz Adafruit Trinket
#endif

// Which pin on the Arduino is connected to the NeoPixels?
// On a Trinket or Gemma we suggest changing this to 1:
#define LED_PIN    6

// How many NeoPixels are attached to the Arduino?
#define LED_COUNT 8

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);
// Argument 1 = Number of pixels in NeoPixel strip
// Argument 2 = Arduino pin number (most are valid)
// Argument 3 = Pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)

// setup() function -- runs once at startup --------------------------------

void setup() {
  // These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
  // Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
  // END of Trinket-specific code.

  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  strip.show();            // Turn OFF all pixels ASAP
  strip.setBrightness(50); // Set BRIGHTNESS to about 1/5 (max = 255)
}

// loop() function -- runs repeatedly as long as board is on ---------------

void loop() {
  // Fill along the length of the strip in various colors...
  colorWipe(strip.Color(255,   0,   0), 50); // Red
  delay(1000);
  colorWipe(strip.Color(  0, 255,   0), 50); // Green
  delay(1000);
  colorWipe(strip.Color(  0,   0, 255), 50); // Blue
  delay(1000);
  colorWipe(strip.Color(  255,   0, 255), 50); // Purple
  delay(1000);
  colorWipe(strip.Color(  0,   255, 255), 50); // Cyan
  delay(1000);
  colorWipe(strip.Color(  255,   255, 255), 50); // White
  delay(1000);
  colorWipe(strip.Color(  127,   127, 127), 50); // White
  delay(1000);
  colorWipe(strip.Color(  255,   255, 0), 50); // Yellow
  delay(1000);

  // Do a theater marquee effect in various colors...
  theaterChase(strip.Color(127, 127, 127), 50); // White, half brightness
  theaterChase(strip.Color(127,   0,   0), 50); // Red, half brightness
  theaterChase(strip.Color(  0,   0, 127), 50); // Blue, half brightness

  rainbow(10);             // Flowing rainbow cycle along the whole strip
  theaterChaseRainbow(50); // Rainbow-enhanced theaterChase variant
}

// Some functions of our own for creating animated effects -----------------

// Fill strip pixels one after another with a color. Strip is NOT cleared
// first; anything there will be covered pixel by pixel. Pass in color
// (as a single 'packed' 32-bit value, which you can get by calling
// strip.Color(red, green, blue) as shown in the loop() function above),
// and a delay time (in milliseconds) between pixels.
void colorWipe(uint32_t color, int wait) {
  for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
    strip.setPixelColor(i, color);         //  Set pixel's color (in RAM)
    strip.show();                          //  Update strip to match
    delay(wait);                           //  Pause for a moment
  }
}

// Theater-marquee-style chasing lights. Pass in a color (32-bit value,
// a la strip.Color(r,g,b) as mentioned above), and a delay time (in ms)
// between frames.
void theaterChase(uint32_t color, int wait) {
  for(int a=0; a<10; a++) {  // Repeat 10 times...
    for(int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();         //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in steps of 3...
      for(int c=b; c<strip.numPixels(); c += 3) {
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show(); // Update strip with new contents
      delay(wait);  // Pause for a moment
    }
  }
}

// Rainbow cycle along whole strip. Pass delay time (in ms) between frames.
void rainbow(int wait) {
  // Hue of first pixel runs 5 complete loops through the color wheel.
  // Color wheel has a range of 65536 but it's OK if we roll over, so
  // just count from 0 to 5*65536. Adding 256 to firstPixelHue each time
  // means we'll make 5*65536/256 = 1280 passes through this outer loop:
  for(long firstPixelHue = 0; firstPixelHue < 5*65536; firstPixelHue += 256) {
    for(int i=0; i<strip.numPixels(); i++) { // For each pixel in strip...
      // Offset pixel hue by an amount to make one full revolution of the
      // color wheel (range of 65536) along the length of the strip
      // (strip.numPixels() steps):
      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());
      // strip.ColorHSV() can take 1 or 3 arguments: a hue (0 to 65535) or
      // optionally add saturation and value (brightness) (each 0 to 255).
      // Here we're using just the single-argument hue variant. The result
      // is passed through strip.gamma32() to provide 'truer' colors
      // before assigning to each pixel:
      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents
    delay(wait);  // Pause for a moment
  }
}

// Rainbow-enhanced theater marquee. Pass delay time (in ms) between frames.
void theaterChaseRainbow(int wait) {
  int firstPixelHue = 0;     // First pixel starts at red (hue 0)
  for(int a=0; a<30; a++) {  // Repeat 30 times...
    for(int b=0; b<3; b++) { //  'b' counts from 0 to 2...
      strip.clear();         //   Set all pixels in RAM to 0 (off)
      // 'c' counts up from 'b' to end of strip in increments of 3...
      for(int c=b; c<strip.numPixels(); c += 3) {
        // hue of pixel 'c' is offset by an amount to make one full
        // revolution of the color wheel (range 65536) along the length
        // of the strip (strip.numPixels() steps):
        int      hue   = firstPixelHue + c * 65536L / strip.numPixels();
        uint32_t color = strip.gamma32(strip.ColorHSV(hue)); // hue -> RGB
        strip.setPixelColor(c, color); // Set pixel 'c' to value 'color'
      }
      strip.show();                // Update strip with new contents
      delay(wait);                 // Pause for a moment
      firstPixelHue += 65536 / 90; // One cycle of color wheel over 90 frames
    }
  }
}

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


wled06_usermod.ino

wled06_usermod.ino

This section is used to read the temperature from the sensor and prints it using the MQTT service started by Aircoookie.

//starts Dallas Temp service on boot
void userSetup()
{
// Start the DS18B20 sensor
  sensors.begin();
}

//gets called every time WiFi is (re-)connected. Initialize own network interfaces here
void userConnected()
{

}

void userLoop()
{
  temptimer = millis();

// Timer to publishe new temperature every 60 seconds
  if (temptimer - lastMeasure > 60000) {
    lastMeasure = temptimer;

//Check if MQTT Connected, otherwise it will crash the 8266
    if (mqtt != nullptr){
      sensors.requestTemperatures();

//Gets prefered temperature scale based on selection in definitions section
      #ifdef Celsius
      float board_temperature = sensors.getTempCByIndex(0);
      #else
      float board_temperature = sensors.getTempFByIndex(0);
      #endif

//Create character string populated with user defined device topic from the UI, and the read temperature. Then publish to MQTT server.
      char subuf[38];
      strcpy(subuf, mqttDeviceTopic);
      strcat(subuf, "/temperature");
      mqtt->publish(subuf, 0, true, String(board_temperature).c_str());
    return;}
  return;}
return;
}

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


Fixed a missing variable declaration.

Fixed a missing variable declaration.

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/tectronics/turbull-encabulator.git/'


add arduino sketch

add arduino sketch

const int numSensors = 5;
const int numReadings = 10;
const int printFrequency = 10;

int sensors[numSensors] = {
  A0, A1, A2, A3, A4
};
int readings[numSensors][numReadings];
int indices[numSensors];
int total[numSensors];
int average[numSensors];
int printCounter = 0;

void setup() {
  for (int i = 0; i < numSensors; i++) {
    pinMode(sensors[i], INPUT);
    indices[i] = 0;
    total[i] = 0;
    average[i] = 0;
    for (int j = 0; j < numReadings; j++) {
      readings[i][j] = 0;
    }
  }
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
}

void loop() {
  printCounter += 1;

  for (int i = 0; i < numSensors; i++) {
    updateDataForSensor(i, analogRead(sensors[i]));
    if (printCounter >= printFrequency) {
      Serial.print(average[i]);
      Serial.print(";");
    }
  }

  if (printCounter >= printFrequency) {
    printCounter = 0;
    Serial.println();
  }

  delay(10);
}

void updateDataForSensor(int sensorIndex, int value) {
  int index = indices[sensorIndex];

  total[sensorIndex] = total[sensorIndex] - readings[sensorIndex][index];
  readings[sensorIndex][index] = value;
  total[sensorIndex] = total[sensorIndex] + readings[sensorIndex][index];
  index += 1;

  average[sensorIndex] = total[sensorIndex] / numReadings;

  if (index >= numReadings) {
    index = 0;
  }
  indices[sensorIndex] = index;
}

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


Getting started

Getting started

// This #include statement was automatically added by the Spark IDE.
#include "neopixel/neopixel.h"

#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(24, PIN, WS2812);

class Snow {

    unsigned long interval;
    unsigned long previousMillis;

    public:
    Snow(unsigned long interval) {
        interval = interval;
        previousMillis = 0;
    }

    void Run() {
        // int randomPixel = random(0, Adafruit_NeoPixel::numPixels());

        unsigned long currentMillis = millis();

        if(currentMillis - previousMillis > interval) {
            previousMillis = currentMillis;
            // Adafruit_NeoPixel::setPixelColor(randomPixel, Adafruit_NeoPixel::Color(127, 127, 127));
            // Adafruit_NeoPixel::show();
        }

        // Adafruit_NeoPixel::setPixelColor(randomPixel, 0);
    }

};

void setup() {
    strip.begin();
    strip.show(); // Initialize all pixels to 'off'
    randomSeed(analogRead(0));
}

void loop() {

}

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


sent temp via mqttn on arduino

sent temp via mqttn on arduino

#include <Adafruit_SleepyDog.h>
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include "utility/debug.h"
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_CC3000.h"

#define CC3000_IRQ   3
#define CC3000_VBAT  5
#define CC3000_CS    10

// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2
// cannot be longer than 32 characters!
#define WLAN_SSID       "HUAWEI-DevTech"
// For connecting router or AP, don't forget to set the SSID and password here!!
#define WLAN_PASS       "Autodesk123"

/************************* mqtt server setup *********************************/
// http://www.cloudmqtt.com

#define AIO_SERVER      "m11.cloudmqtt.com"
#define AIO_SERVERPORT  15521
#define AIO_USERNAME    "danieldu"
#define AIO_KEY         "Autodesk123"

// Store the MQTT server, username, and password in flash memory.
// This is required for using the Adafruit MQTT library.
const char MQTT_SERVER[] PROGMEM    = AIO_SERVER;
const char MQTT_USERNAME[] PROGMEM  = AIO_USERNAME;
const char MQTT_PASSWORD[] PROGMEM  = AIO_KEY;

//The sensor id in mongoDB, currently we have only one sensor
#define SENSOR_ID "561083be06dd6162658ae8c8"

Adafruit_CC3000 cc3000 = Adafruit_CC3000(
                           CC3000_CS,
                           CC3000_IRQ,
                           CC3000_VBAT,
                           SPI_CLOCK_DIVIDER); // you can change this clock speed

// Setup the CC3000 MQTT class by passing in the CC3000 class and MQTT server and login details.
Adafruit_MQTT_CC3000 mqtt(&cc3000, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);

// You don't need to change anything below this line!
#define halt(s) { Serial.println(F( s )); while(1);  }

/****************************** Feeds ***************************************/

// Setup a feed called 'temperature-center' for publishing.
const char TEMPERATURE_FEED[] PROGMEM = "temperature-center";
Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, TEMPERATURE_FEED);

static Adafruit_CC3000_Client client;

uint32_t ip = 0;

unsigned long lastConnectionTime = 0;            // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 5L * 1000L; // delay between updates, in milliseconds

unsigned long lastConnectWifiTime = 0;
const unsigned long checkNetworkInterval = 30L * 1000L * 60L; //reconnect WIFI every 20 min

void setup() {

  Serial.begin(115200);

  initWifiConnection();
}

void loop() {

  if (millis() - lastConnectWifiTime > checkNetworkInterval) {

    initWifiConnection();

    lastConnectWifiTime = millis();
  }

    // Make sure to reset watchdog every loop iteration!
    Watchdog.reset();

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

    //get temperature value
    float temp = 0.0;
    // get the current temperature from sensor
    int reading = analogRead(0);
    temp = reading * 0.0048828125 * 100;
    Serial.print(F("Current temp"));
    Serial.println(temp);

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

    // ping the server to keep the mqtt connection alive
    if(! mqtt.ping()) {
      Serial.println(F("MQTT Ping failed."));
    }

}

void initWifiConnection()
{

  /* Initialise the module */
  //Serial.println(F("\nInitialising the CC3000 ..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
    while (1);
  }

  /* Attempt to connect to an access point */
  char *ssid = WLAN_SSID;             /* Max 32 chars */
  Serial.print(F("\nAttempting to connect to "));
  Serial.println(ssid);

  /* NOTE: Secure connections are not available in 'Tiny' mode!
   By default connectToAP will retry indefinitely, however you can pass an
   optional maximum number of retries (greater than zero) as the fourth parameter.
   */
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while (1);
  }

  //Serial.println("\nconnected to WIFI.");

  /* Wait for DHCP to complete */
  //Serial.println("\nRequest DHCP");
  while (!cc3000.checkDHCP())
  {
    delay(1000); // ToDo: Insert a DHCP timeout!
  }

  //Serial.println("\nDHCP is OK");

  Serial.println("Initialization completed.\n");

}

// Function to connect and reconnect as necessary to the MQTT server.
// Should be called in the loop function and it will take care if connecting.
void MQTT_connect() {
  int8_t ret;

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

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

  while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
       Serial.println(mqtt.connectErrorString(ret));
       if (ret < 0){
            //lets connect to wifi again
            initWifiConnection();
       }
       Serial.println("Retrying MQTT connection in 5 seconds...");
       mqtt.disconnect();
       delay(5000);  // wait 5 seconds
  }
  Serial.println("MQTT Connected!");
}

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