initilize arduino_motor.ino

initilize arduino_motor.ino

#include <PololuWheelEncoders.h>
#include <PID_v1.h>
//#include <PinChangeInt.h>

//#include <DistanceGP2Y0A02YK.h>
//#include <DistanceGP2Y0A21YK.h>
#include <Servo.h>

/* Serial write for sensing obstacles: 0 = ready to receive data from raspberry pi,
   1 = center sensor only, 2 = left sensor only, 3 = right sensor only,
   4 = center and left sensors, 5 = center and right sensors, 6 = left and right sensors,
   7 = all three sensors, 8 = default none sensed

   Serial read: 1 = move forward, 2 = turn left, 3 = turn right, 4 = stop */

static boolean informReadyOnce = false;
static boolean countTicksForAngleOrDist = false;

Servo myServo;
//PololuWheelEncoders encoder;

//const float pi = 3.14159;
const int wheelDiameter = 6;
const int countsPerRevolution = 2249;
const float thresh = 20;
//const float noOfTicksPerCm = 2249/(PI*6);
const float noOfCmPerTick = (PI*6)/2249;
//const float noOfCmPerDegree = (PI*17.2)/360;
//float leftCounter, rightCounter;

// Analog Pins; middle sensor [0], left sensor [1], right sensor [2]
const int sensorPin0 = 0, sensorPin1 = 1, sensorPin2 = 2, sensorPin3 = 3;
const int maxSpeedA = 225; // Max speed for motor based on pwn A (right)
const int maxSpeedB = 225; // Max speed for motor based on pwn B (left)

// Digital Pins
int pwm_right = 3;  // PWM control for motor outputs 1 and 2 is on digital pin 3
int pwm_left = 11;  // PWM control for motor outputs 3 and 4 is on digital pin 11
int dir_right = 12;  // Direction control for motor outputs 1 and 2 is on digital pin 12
int dir_left = 13;  // Direction control for motor outputs 3 and 4 is on digital pin 13
int caseCheck = 8;

//PI variables
//double leftOut, rightOut;
//double err;
//double err2 = 0;
//double Kp = 4 ;
//double Ki = 5;

// 2249 ticks for one full revolution
double leftWheelTickCount = 0;
double rightWheelTickCount = 0;
float leftTicksForAngleOrDist = 0;
float rightTicksForAngleOrDist = 0;

//int delta_left = 0;
//int delta_right = 0;
//double setPointL = 0;
//double setPointR = 0;
//double setPointMid;
//double actual_speed_left = 0;
//double actual_speed_right = 0;
//double actual_speed;
//double pwm_mid;
//double pwm_left;
//double pwm_right;

//int angleTurn = 0;
//int distanceMove = 0;

int LOOPTIME = 100;
unsigned long lastMilli = 0;

long timing = 0;
long previousLeftTick = 0;
long previousRightTick = 0;
double SetpointLeft, InputLeft, OutputLeft;
double SetpointRight, InputRight, OutputRight;
double SetpointMid, InputMid, OutputMid;
PID leftPID(&InputLeft, &OutputLeft, &SetpointLeft,1,1,0, DIRECT);
PID rightPID(&InputRight, &OutputRight, &SetpointRight,1,1,0, DIRECT);
PID midPID(&InputMid, &OutputMid, &SetpointMid,1,1,1, DIRECT);

float distanceS, deltaHeading, deltaX, deltaY;

int rightEncoderOne = 6;
int rightEncoderTwo = 7;
int leftEncoderOne = 8;
int leftEncoderTwo = 9;
long currentTicks = 0;

//unsigned long leftPololuCount = 0;
//unsigned long rightPololuCount = 0;

//int encoderLeftCount;
//int encoderRightCount;

double setMotor;

//static long last_count_left = 0;
//static long last_count_right = 0;

void setup()
{
  // Set sensor control pins to be outputs
  pinMode(sensorPin0, OUTPUT);
  pinMode(sensorPin1, OUTPUT);
  pinMode(sensorPin2, OUTPUT);
  pinMode(sensorPin3, OUTPUT);

  // Set motor control pins to be outputs
  pinMode(pwm_right, OUTPUT);
  pinMode(pwm_left, OUTPUT);
  pinMode(dir_right, OUTPUT);
  pinMode(dir_left, OUTPUT);

  // Check for each ticks on wheels
//  PCintPort::attachInterrupt(6, incLeftCount, CHANGE);
//  PCintPort::attachInterrupt(7, incLeftCount, CHANGE);
//  PCintPort::attachInterrupt(8, incRightCount, CHANGE);
//  PCintPort::attachInterrupt(9, incRightCount, CHANGE);

  PololuWheelEncoders::init(rightEncoderOne,rightEncoderTwo,leftEncoderOne,leftEncoderTwo);

  //PID_left.SetMode(AUTOMATIC);
  //PID_right.SetMode(AUTOMATIC);
  deltaHeading = PI/2;
  leftPID.SetMode(AUTOMATIC);
  rightPID.SetMode(AUTOMATIC);
  midPID.SetMode(AUTOMATIC);
  leftPID.SetSampleTime(10);
  rightPID.SetSampleTime(10);
  midPID.SetSampleTime(10);
  SetpointLeft = 2000;
  SetpointRight = 2000;
  SetpointMid = 0;
  leftPID.SetOutputLimits(0, 3400);
  rightPID.SetOutputLimits(0, 3400);
  midPID.SetOutputLimits(-1000, 1000);

  Serial.begin(9600);  // sets the serial port to 9600
  timing = millis();
  //PID_mid.SetMode(AUTOMATIC);
  //PID_mid.SetSampleTime(100);
  //PID_mid.SetOutputLimits(0, 225);
  //PID_left.SetSampleTime(100);
  //PID_right.SetSampleTime(100);

//  dist1 = sensor1.getDistanceCentimeter();
  //encoder
//  encoder.init(7,6,8,9);

  myServo.attach(A4);
 //myServo.write(90);
// delay(500);yy
 //myServo.detach();

  //moveForward(20);
  /*
for(int i=0; i<2; i++) {
  delay(1000);
moveForward(50);
resetPololuTicks();
delay(1000);
turnRight(90);
resetPololuTicks();
delay(1000);
moveForward(50);
resetPololuTicks();
delay(1000);
turnLeft(90);
resetPololuTicks();
delay(1000);
moveForward(50);
resetPololuTicks();
delay(1000);
turnLeft(180);
resetPololuTicks();
}
*/

/*
for(int i=0; i<10; i++) {
  moveForward(20);
  resetPololuTicks();
  delay(1000);
  turnLeft(90);
}

for(int i=0; i<10; i++) {
  moveForward(20);
  resetPololuTicks();
  delay(1000);
  turnRight(90);
}
*/
//moveForward(200);
//turnRight(1440);
//turnRight(180);
//delay(5000);
//turnRight(90);
}

// Uses specified distance(cm) to calculate the distance
float distCentimeter(float centimeter) {
  float divisibleTicks;
  if (centimeter <= 10) {
    divisibleTicks = 19.3;
  }

  else if (centimeter <= 20) {
    divisibleTicks = 18.65;
  }

  else if (centimeter <= 35) {
    divisibleTicks = 19.05;
  }

  else if (centimeter <= 50) {
    divisibleTicks = 18.5;
  }

  else if (centimeter <= 75) {
    divisibleTicks = 18.9;
  }

  else {
    divisibleTicks = 18.7;
  }

  float ticksForOneCentimeter = 2249/divisibleTicks;
  float dist = ticksForOneCentimeter * centimeter;
  return dist;
}

// Uses specified angle(degree) to calculate the turns
float turnAngle(int angle) {
  float divisibleTicks;
  if (angle <= 90) {
    divisibleTicks = 126.7;  // 127.5
  }

  else if (angle <= 180) {
    divisibleTicks = 125.5;  // 64.5
  }

  else if (angle <= 270) {
    divisibleTicks = 126.7;
  }

  else if (angle <= 450) {
    divisibleTicks = 125.6;
  }

  else if (angle <= 540) {
    divisibleTicks = 125;
  }

  else if (angle <= 630) {
    divisibleTicks = 125;
  }
  else {
    divisibleTicks = 125;
  }

  float ticksForOneDegree = 2249/divisibleTicks;
  float angleToTurn = ticksForOneDegree * angle;
  return angleToTurn;
}

float turnAngleR(int angle) {
  float divisibleTicks;
  if (angle <= 90) {
    divisibleTicks = 127.5;  // 127.5
  }

  else if (angle <= 180) {
    divisibleTicks = 125.5;  // 64.5
  }

  else if (angle <= 270) {
    divisibleTicks = 126.7;
  }

  else if (angle <= 450) {
    divisibleTicks = 125.6;
  }

  else if (angle <= 540) {
    divisibleTicks = 125;
  }

  else if (angle <= 630) {
    divisibleTicks = 125;
  }
  else {
    divisibleTicks = 125;
  }

  float ticksForOneDegree = 2249/divisibleTicks;
  float angleToTurn = ticksForOneDegree * angle;
  return angleToTurn;
}
// Infinite loop routine for robot
void loop()
{
  if (informReadyOnce != true) {
    for (int i=0; i<10; i++)
      Serial.write("99/;");
    informReadyOnce = true;
  }

  //leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
  //rightPololuCount = abs(PololuWheelEncoders::getCountsM2());

  int sensorValue0 = analogRead(sensorPin0);       // read analog input pin 0
  int sensorValue1 = analogRead(sensorPin1);       // read analog input pin 1 (left sensor from back view)
  int sensorValue2 = analogRead(sensorPin2);       // read analog input pin 2 (right sensor from back view)
  int sensorValue3 = analogRead(sensorPin3);

//  runRobotAuto(sensorValue0, sensorValue1, sensorValue2); // run robot with internal logic for obstable avoidance
  if (Serial.available()) {
    executeCommand();
  }
  //Serial.println("outside millis");
  //if((millis()-lastMilli) >= LOOPTIME){
     //lastMilli = millis();
     //Serial.println("in millis");
     //leftMotorConfigure();
     //rightMotorConfigure();
  //}

  //configureMotor();
//  leftCounter = encoder.getCountsAndResetM1();
//  rightCounter = encoder.getCountsAndResetM2();

  detectObstacle();
  readSensor(sensorValue0, sensorValue1, sensorValue2, sensorValue3); // prints sensors' readings

  //PIController();
}

void configureMotorForTurn() {
  //resetPololuTicks();
  long leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
  long rightPololuCount = abs(PololuWheelEncoders::getCountsM2());
  /*Serial.print("leftPololuCount =");
    Serial.print(leftPololuCount);
    Serial.print("\t");
    Serial.print("rightPololuCount =");
    Serial.println(rightPololuCount);*/
  if(leftPololuCount < 30000){
    if(millis() - timing >= 10){
      long leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
      long rightPololuCount = abs(PololuWheelEncoders::getCountsM2());
      long timez = millis()-timing;
      //double speed1 =  ((leftPololuCount -prevouslefttick)/1000);

      float leftTime = leftPololuCount - previousLeftTick;
      float rightTime = rightPololuCount - previousRightTick;

      float leftcm = noOfCmPerTick * leftTime;
      float rightcm = noOfCmPerTick * rightTime;
      /*float distanceToTravel = (leftcm + rightcm)/2;
      deltaHeading =  (leftcm-rightcm) / 17.2 + deltaHeading;
      deltaX = distanceToTravel * cos(deltaHeading) + deltaX;
      deltaY = distanceToTravel * sin(deltaHeading) + deltaY;*/
      leftTime = leftTime / (timez);
      leftTime = leftTime * 1000;
      rightTime = rightTime / (timez);
      rightTime = rightTime * 1000;
      //InputMid = deltaX * 10000;

      InputLeft = leftTime;
      InputRight = rightTime;

      //midPID.Compute();

      //OutputMid
      //SetpointRight = 2000 + map(OutputMid,-1000,1000,-2000,1400);
      rightPID.Compute();
      leftPID.Compute();
      previousLeftTick = leftPololuCount;
      previousRightTick = rightPololuCount;
      timing = millis();

      runMotor(map(OutputRight,0,3400,150,255), map(OutputLeft,0,3400,150,255));
    }
  }
  else{
    halt();
  }
}

void configureMotor() {
  //resetPololuTicks();
  //Serial.println(deltaX);
  long leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
  long rightPololuCount = abs(PololuWheelEncoders::getCountsM2());
  /*Serial.print("leftPololuCount =");
    Serial.print(leftPololuCount);
    Serial.print("\t");
    Serial.print("rightPololuCount =");
    Serial.println(rightPololuCount);*/
  //SetpointMid = 0;
/*  int sensorLeft = analogRead(sensorPin1);
  //int detectedObstacle = 0;

  while (sensorLeft > 200) {
    Serial.print("new deltaX = ");
    Serial.println(deltaX);
    SetpointMid = -500;*/
  if(leftPololuCount < 30000){
    if(millis() - timing >= 10){
      leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
      rightPololuCount = abs(PololuWheelEncoders::getCountsM2());
      long timez = millis()-timing;
      //double speed1 =  ((leftPololuCount -prevouslefttick)/1000);

      float leftTime = leftPololuCount -previousLeftTick;
      float rightTime = rightPololuCount -previousRightTick;

      float leftcm = noOfCmPerTick * leftTime;
      float rightcm = noOfCmPerTick * rightTime;
      float distanceToTravel = (leftcm + rightcm)/2;
      deltaHeading =  (leftcm-rightcm) / 17.2 + deltaHeading;
      deltaX = (distanceToTravel * cos(deltaHeading) + deltaX); // + 0.2
      deltaY = distanceToTravel * sin(deltaHeading) + deltaY;
      leftTime = leftTime / (timez);
      leftTime = leftTime * 1000;
      rightTime = rightTime / (timez);
      rightTime = rightTime * 1000;
      InputMid = deltaX * 10000;

      InputLeft = leftTime;
      InputRight = rightTime;

      midPID.Compute();

      //OutputMid
      SetpointRight = 2000 + map(OutputMid,-1000,1000,-2000,1400);
      rightPID.Compute();
      leftPID.Compute();
      previousLeftTick = leftPololuCount;
      previousRightTick = rightPololuCount;
      timing = millis();

      //runMotor(map(OutputRight,0,3400,50,150), map(OutputLeft,0,3400,50,150));
      runMotor(map(OutputRight,0,3400,150,255), map(OutputLeft,0,3400,150,255));
    }
  }
  else{
    halt();
  }

  //sensorLeft = analogRead(sensorPin1);
  //detectedObstacle = 1;
  //}

  /*if (detectedObstacle = 1) {
    long leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
    long rightPololuCount = abs(PololuWheelEncoders::getCountsM2());
    currentTicks = (leftPololuCount + rightPololuCount) / 2;
    resetPololuTicks();
    detectedObstacle = 0;
  }*/

  /*if (sensorLeft < 200) {
    SetpointMid = 0;
    //Serial.print("new deltaX = ");
    Serial.println(deltaX);
  if(leftPololuCount < 30000){
    if(millis() - timing >= 10){
      leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
      rightPololuCount = abs(PololuWheelEncoders::getCountsM2());
      long timez = millis()-timing;
      //double speed1 =  ((leftPololuCount -prevouslefttick)/1000);

      float leftTime = leftPololuCount -previousLeftTick;
      float rightTime = rightPololuCount -previousRightTick;

      float leftcm = noOfCmPerTick * leftTime;
      float rightcm = noOfCmPerTick * rightTime;
      float distanceToTravel = (leftcm + rightcm)/2;
      deltaHeading =  (leftcm-rightcm) / 17.2 + deltaHeading;
      deltaX = distanceToTravel * cos(deltaHeading) + deltaX;
      deltaY = distanceToTravel * sin(deltaHeading) + deltaY;
      leftTime = leftTime / (timez);
      leftTime = leftTime * 1000;
      rightTime = rightTime / (timez);
      rightTime = rightTime * 1000;
      InputMid = deltaX * 10000;

      InputLeft = leftTime;
      InputRight = rightTime;

      midPID.Compute();

      //OutputMid
      SetpointRight = 2000 + map(OutputMid,-1000,1000,-2000,1400);
      rightPID.Compute();
      leftPID.Compute();
      previousLeftTick = leftPololuCount;
      previousRightTick = rightPololuCount;
      timing = millis();

      runMotor(map(OutputRight,0,3400,150,255), map(OutputLeft,0,3400,150,255));
    }
  }
  else{
    halt();
  }
  }*/
}

/*void configureMotor() {
  actual_speed = (encoderLeftCount + encoderRightCount)/2;
  PID_mid.Compute();

  encoderLeftCount = abs(PololuWheelEncoders::getCountsM1());
  encoderRightCount = abs(PololuWheelEncoders::getCountsM2());

  long differenceCount = encoderRightCount - encoderLeftCount;

  if((pwm_mid > 100)){

    //check1 = true;
    //checkStop = false;

    if(differenceCount > 50)
    {
      setMotor = 50;
    }
    else if(differenceCount > 40)
    {
      setMotor = 47;
    }
    else if(differenceCount > 30)
    {
      setMotor = 45;
    }
    else if(differenceCount > 20)
    {
      setMotor = 42;
    }
    else if(differenceCount > 10)
    {
      setMotor = 40;
    }
    else if (differenceCount > 0){
      setMotor = 26;
    }

    else if(differenceCount < -50)
    {
      setMotor = -35;
    }
    else if(differenceCount < -40)
    {
      setMotor = -28;
    }
    else if(differenceCount < -30)
    {
      setMotor = -22;
    }
    else if(differenceCount < -20)
    {
      setMotor = -21;
    }
    else if(differenceCount < -10)
    {
      setMotor = -20;
    }
    else if (differenceCount < 0){
      setMotor =  26;
    }
    else {
      setMotor = 23;
    }
    pwm_left = pwm_mid + setMotor ;
    pwm_right = pwm_mid - setMotor;
    //    Serial.println(myLeftPWM);
    //    Serial.println(myRightPWM);
    //    Serial.println();
    runMotor(pwm_left, pwm_right);
    //setPWM(pwm_left, pwm_right);
    //delay(50);

  }
  else {
    pwm_left = 0;
    pwm_right = 0;
    setMotor = 0;

    //halt();
    //resetPololuTicks();

    /*fcStart();
    delay (500);
    if((check == true && check1 == true)){
      if(checkStop == true){
        myPIDMid.SetMode(MANUAL);
        Serial.println("OK");
        check = false;
        check1 = false;
        checkStop = false;

      }
      else
      {
        encoderLeftCount = 0 ;
        encoderRightCount = 0 ;
      }
    }

  }
}*/

/*void leftMotorConfigure() {
  //static long last_count_left = 0;
  delta_left = leftPololuCount -last_count_left;
  actual_speed_left = (abs(leftPololuCount-last_count_left)*(60*(1000/LOOPTIME)))/2249;//(16*29);          // 16 pulses X 29 gear ratio = 464 counts per output shaft rev
  PID_left.Compute();
  if (actual_speed_left < 0 || actual_speed_left > 300){
      actual_speed_left = 0;
  }

  Serial.print("actual_speed_left ");
  Serial.println(actual_speed_left);

  //if (delta_left <0)
  //{
  //    resetDefaultWheelTicks();
  //}

  last_count_left = leftPololuCount;
}

void rightMotorConfigure() {
  //static long last_count_right = 0;
  delta_right = rightPololuCount-last_count_right;

  actual_speed_right = (abs(rightPololuCount-last_count_right)*(60*(1000/LOOPTIME)))/2249;//(16*29);          // 16 pulses X 29 gear ratio = 464 counts per output shaft rev
  PID_right.Compute();
  if (actual_speed_right < 0 || actual_speed_right > 300){
      actual_speed_right = 0;
  }

  Serial.print("actual_speed_right ");
  Serial.println(actual_speed_right);

  //if (delta_right <0)
  //{
  //    resetDefaultWheelTicks();
  //}

  last_count_right = rightPololuCount;
}*/

void detectObstacle() {
  int sensorValue0, sensorValue1, sensorValue2, sensorValue3;
  int meanSensorValue0 = 0, meanSensorValue1 = 0, meanSensorValue2 = 0, meanSensorValue3 = 0;
  int sensorSampleLength = 10;
  int distCoveredBeforeObstacle = 0;

  for (int currSample = 0; currSample < sensorSampleLength; currSample++) {
    sensorValue0 = analogRead(sensorPin0);       // read analog input pin 0
    sensorValue1 = analogRead(sensorPin1);       // read analog input pin 1 (left sensor from back view)
    sensorValue2 = analogRead(sensorPin2);       // read analog input pin 2 (right sensor from back view)
    sensorValue3 = analogRead(sensorPin3);
    meanSensorValue0 += sensorValue0;
    meanSensorValue1 += sensorValue1;
    meanSensorValue2 += sensorValue2;
    meanSensorValue3 += sensorValue3;
  }

  // Calculate mean of sample sensor values for reliable reading
  meanSensorValue0 /= sensorSampleLength;
  meanSensorValue1 /= sensorSampleLength;
  meanSensorValue2 /= sensorSampleLength;
  meanSensorValue3 /= sensorSampleLength;

//  readSensor(meanSensorValue0, meanSensorValue1, meanSensorValue2); // prints sensors' readings

  int middleSensorObstacleDist = middleSensorDistanceMeasuredInCM(meanSensorValue0);
  int leftSensorObstacleDist = leftSensorDistanceMeasuredInCM(meanSensorValue1);
  int rightSensorObstacleDist = rightSensorDistanceMeasuredInCM(meanSensorValue2);
  int bottomSensorObstacleDist = bottomSensorDistanceMeasuredInCM(meanSensorValue3);

  int smallSensorRange = 19;
  int smallMIDDLESensorRange = 14;
  int largeFrontSensorRange = 80;

  if (middleSensorObstacleDist <= largeFrontSensorRange && bottomSensorObstacleDist<=smallMIDDLESensorRange) {
    if (leftSensorObstacleDist <= smallSensorRange && rightSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220 && meanSensorValue2 >= 220) {// && meanSensorValue1 >= 350 && meanSensorValue2 >= 350
      Serial.write("15/");
    }
    else if (rightSensorObstacleDist <= smallSensorRange && meanSensorValue2 >= 220) {
      Serial.write("14/");
    }
    else if (leftSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220) {
      Serial.write("13/");
    }
    else{
      Serial.write("12/");
    }
    Serial.print(middleSensorObstacleDist);
    Serial.write(";");
  }
  else if (middleSensorObstacleDist <= largeFrontSensorRange) {
    if (leftSensorObstacleDist <= smallSensorRange && rightSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220 && meanSensorValue2 >= 220) {
      Serial.write("11/");
    }
    else if (rightSensorObstacleDist <= smallSensorRange && meanSensorValue2 >= 220) {
      Serial.write("10/");
    }
    else if (leftSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220) {
      Serial.write("9/");
    }
    else{
      Serial.write("8/");
    }
    Serial.print(middleSensorObstacleDist);
    Serial.write(";");
  }
  else if (bottomSensorObstacleDist<=smallMIDDLESensorRange && meanSensorValue3 >= 220) {
    if (leftSensorObstacleDist <= smallSensorRange && rightSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220 && meanSensorValue2 >= 220) {
      Serial.write("7/;");
    }
    else if (rightSensorObstacleDist <= smallSensorRange && meanSensorValue2 >= 220) {
      Serial.write("5/;");
    }
    else if (leftSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220) {
      Serial.write("4/;");
    }
    else{
      Serial.write("1/;");
    }
  }
  else if (leftSensorObstacleDist <= smallSensorRange && rightSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220 && meanSensorValue2 >= 220) {//&& meanSensorValue1 >= 350 && meanSensorValue2 >= 350
    Serial.write("6/;");
  }
  else if(leftSensorObstacleDist <= smallSensorRange && meanSensorValue1 >= 220) {
    Serial.write("2/;");
  }
  else if (rightSensorObstacleDist <= smallSensorRange && meanSensorValue2 >= 220) {
    Serial.write("3/;");
  }
  else {
    Serial.write("16/;");
  }
  /*
  if (middleSensorObstacleDist <= largeFrontSensorRange) {
    if (leftSensorObstacleDist <= smallSensorRange  && rightSensorObstacleDist <= smallSensorRange) {
      Serial.write("7/");
      Serial.print(middleSensorObstacleDist);
      Serial.write(";");
    }
    else if (leftSensorObstacleDist <= smallSensorRange) {
      Serial.write("4/");
      Serial.print(middleSensorObstacleDist);
      Serial.write(";");
    }
    else if (rightSensorObstacleDist <= smallSensorRange) {
        Serial.write("5/");
        Serial.print(middleSensorObstacleDist);
        Serial.write(";");
    }
    else{
      Serial.write("1/");
      Serial.print(middleSensorObstacleDist);
      Serial.write(";");
    }
  }
  else if (leftSensorObstacleDist <= smallSensorRange  && rightSensorObstacleDist <= smallSensorRange) {
    Serial.write("6/;");
  }
  else if(leftSensorObstacleDist <= smallSensorRange) {
    Serial.write("2/;");
  }
  else if (rightSensorObstacleDist <= smallSensorRange) {
    Serial.write("3/;");
  }
  else {
    Serial.write("8/;");
  }
  */
  /*
  // Main(center) sensor senses obstacle
  if (middleSensorObstacleDist <= 25) {
    // Both left and right sensors sense obstacle as well
    if (leftSensorObstacleDist <= smallSensorRange && rightSensorObstacleDist <= smallSensorRange) {
      Serial.write("7/;");
//      caseCheck = 7;
//      halt();
    }

    // Only right sensor senses obstacle as well
    else if (rightSensorObstacleDist <= smallSensorRange) {
      Serial.write("5/;");
//      caseCheck = 5;
//      halt();
    }

    // Only left sensor senses obstacle as well
    else if (leftSensorObstacleDist <= smallSensorRange) {
      Serial.write("4/;");
//      caseCheck = 4;
//      halt();
    }
    */
    /* Left and right sensor sense nothing
       i.e. Only main(center) sensor sense obstacle */
       /*
    else {
//      Serial.println("1");
      Serial.write("1/");
      Serial.print(middleSensorObstacleDist);
      Serial.write(";");
//      caseCheck = 1;
//      halt();
    }
  }
  else if (middleSensorObstacleDist <= 80) {
      Serial.write("1/");
      Serial.print(middleSensorObstacleDist);
      Serial.write(";");
  }

  // Only left and right sensor senses obstacle
  else if (leftSensorObstacleDist <= smallSensorRange  && rightSensorObstacleDist <= smallSensorRange) {
    Serial.write("6/;");
//    caseCheck = 6;
//    halt();
  }

  // Only right sensor senses obstacle
  else if (rightSensorObstacleDist <= smallSensorRange) {
//          Serial.println("3");
    Serial.write("3/;");
//    caseCheck = 3;
//    halt();
  }

  // Only left sensor senses obstacle
  else if (leftSensorObstacleDist <= smallSensorRange) {
    Serial.write("2/;");
//    caseCheck = 2;
//    halt();
  }

  // No obstacles around
  else {
    Serial.write("8/;");
  }
  */
//  switch(caseCheck) {
//
//    // Command: Get Distance
//    case 5: {
//      if (rightSensorObstacleDist > 15 || leftSensorObstacleDist > 15)
//        caseCheck = 8;
//      break;
//    }
//
//    case 6: {
//      if (rightSensorObstacleDist > 15 || leftSensorObstacleDist > 15)
//        caseCheck = 8;
//      break;
//    }
//
//    case 7: {
//      if (middleSensorObstacleDist > 25 || rightSensorObstacleDist > 15 || leftSensorObstacleDist > 15)
//        caseCheck = 8;
//      break;
//    }
}

//PI Controller
//void PIController()
//{
//  if(leftCounter >= 0 && rightCounter >= 0)
//  {
//    Serial.print("leftCounter is ");
//    Serial.println(leftCounter);
//    Serial.print("rightCounter is ");
//    Serial.println(rightCounter);
//
//    err = (leftCounter - rightCounter)/((leftCounter + rightCounter)/2) * 255;
//    Serial.print("err is ");
//    Serial.println(round(err));
//    if (abs(err) < thresh){ // prevent integral 'windup'
//      err2 = err2 + err; // accumulate the error integral
//    }
//    else {
//      err2 = 0; // zero it if out of bounds
//    }
//
//    Serial.print("round(err)/Kp is ");
//    Serial.println(round(err)/Kp);
//    Serial.print("round(err2)/Ki is ");
//    Serial.println(round(err2)/Ki);
//    rightOut += round(err)/Kp + round(err2)/Ki;
//
//    if(abs(rightOut) >= 255) { // prevent overlimit
//        rightOut = 255;
//        Serial.println(rightOut);
//    }
//
//    analogWrite(pwm_right, round(rightOut));
//  }
//}

//void runRobotAuto(int sensorValue0, int sensorValue1, int sensorValue2) {
//
//  // Main(center) sensor senses obstable
//  if (sensorValue0 >= 570) {
//    // Both left and right sensors sense obstacle as well
//    if (sensorValue1 >= 250 && sensorValue2 >= 250) {
//      turnLeft(timeDelayByAngle(180));
//      moveForward(timeDelayByCentimeter(0));
//    }
//
//    // Only right sensor senses obstacle as well
//    else if (sensorValue2 >= 400) {
//      turnLeft(timeDelayByAngle(90));
//      moveForward(timeDelayByAngle(135));
//      turnRight(timeDelayByAngle(90));
//      moveForward(timeDelayByCentimeter(0));
//    }
//
//    // Only left sensor senses obstacle as well
//    else if (sensorValue1 >= 400) {
//      turnRight(timeDelayByAngle(90));
//      moveForward(timeDelayByAngle(135));
//      turnLeft(timeDelayByAngle(90));
//      moveForward(timeDelayByCentimeter(0));
//    }
//
//    /* Left and right sensor sense nothing
//       i.e. Only main(center) sensor sense obstacle */
//    else {
//      turnLeft(timeDelayByAngle(90));
//      moveForward(timeDelayByCentimeter(0));
//    }
//  }
//
//  // Only right sensor senses obstacle
//  else if (sensorValue2 >= 630) {
//    turnLeft(timeDelayByAngle(18));
//    moveForward(timeDelayByCentimeter(0));
//  }
//
//  // Only left sensor senses obstacle
//  else if (sensorValue1 >= 630) {
//    turnRight(timeDelayByAngle(18));
//    moveForward(timeDelayByCentimeter(0));
//  }
//
//  // No obstacles around
//  else {
//    moveForward(timeDelayByCentimeter(0));
//  }
//}

// Read value from sensors
void readSensor(int sensorValue0, int sensorValue1, int sensorValue2, int sensorValue3) {
  int rightDistance = rightSensorDistanceMeasuredInCM(sensorValue2);
  int leftDistance = leftSensorDistanceMeasuredInCM(sensorValue1);
  int middleDistance = middleSensorDistanceMeasuredInCM(sensorValue0);
  int bottomDistance = bottomSensorDistanceMeasuredInCM(sensorValue3);
  /*
  Serial.print("Middle Sensor: ");
  Serial.print(sensorValue0, DEC);  // prints the value read in decimal
  Serial.print("\t");
  Serial.print("Left Sensor: ");
  Serial.print(sensorValue1, DEC);  // prints the value read in decimal
  Serial.print("\t");
  Serial.print("Right Sensor: ");
  Serial.print(sensorValue2, DEC);  // prints the value read in decimal
  Serial.print("\t");
  Serial.print("Bottom Sensor: ");
  Serial.println(sensorValue3, DEC);  // prints the value read in decimal
  */
}

// Listen for serial data from raspberry
long readSerial() {
  unsigned long serialData = 0;
  int byteRead = 0;

  // Append command data until full command has been sent
  while (byteRead != '/') {
    byteRead = Serial.read(); // Serial read by a byte each time

    if (byteRead > 0 && byteRead != '/') {
      char byteChar[1];
      byteChar[0] = byteRead;
      byteRead = atoi(byteChar);
      serialData = serialData * 10 + byteRead;
      //print out the received data
      Serial.println(serialData, DEC);
    }
  }

  return serialData;
}

void executeCommand() {
  //resetPololuTicks();
  float timeDelay, multiple;
  long serialData = readSerial();

  if(serialData==1){
    serialData = readSerial();
    moveForward(serialData);
    for (int i=0; i<10; i++)
      Serial.write("51/;");
  }
  else if(serialData==2){
    serialData = readSerial();
    turnLeft(serialData);
    for (int i=0; i<10; i++)
      Serial.write("52/;");
  }
  else if(serialData==3){
    serialData = readSerial();
    turnRight(serialData);
    for (int i=0; i<10; i++)
      Serial.write("53/;");
  }
  else if(serialData==4){
    halt();
  }
  else if(serialData==5){
    runMotor(pwm_left, pwm_right);
  }
  else if(serialData==6){
    if(serialData!=0){
      serialData = readSerial();
      servoTurn(serialData);
    }
  }
  //resetPololuTicks();
  /*else if(serialData==9){
    int distCovered = getDistance();
      Serial.write("9/");
      Serial.print(distCovered);
      Serial.write(";");
      resetDefaultWheelTicks();
  }*/
  informReadyOnce = false;
  /*
  switch(serialData) {

    // Command: Move Foward
    case 1: {
      serialData = readSerial();
      moveForward(serialData);
      break;
    }

    // Command: Turn Left
    case 2: {
      serialData = readSerial();
      turnLeft(serialData);
      break;
    }

    // Command: Turn Right
    case 3: {
      serialData = readSerial();
      turnRight(serialData);
      break;
    }

    // Command: Halt
    case 4: {
      halt();
      break;
    }

    // Command: Run Motor
    case 5: {
      runMotor(maxSpeedA, maxSpeedB);
      break;
    }

    // Command: Servo Turn
    case 6: {
      serialData = readSerial();
      servoTurn(serialData);
      break;
    }

    // Command: Get Distance
    case 9: {
      int distCovered = getDistance();
      Serial.write("9/");
      Serial.print(distCovered);
      Serial.write(";");
      resetDefaultWheelTicks();
      break;
    }

    // No command: continue moving forward
    default: {
//      moveForward(distCentimeter(0));
    }
  }
  */
}

//void incLeftCount() {
//  leftWheelTickCount++;
//  if (countTicksForAngleOrDist == true) {
//    leftTicksForAngleOrDist++;
//  }
//}
//
//void incRightCount() {
//  rightWheelTickCount++;
//  if (countTicksForAngleOrDist == true) {
//    rightTicksForAngleOrDist++;
//  }
//}
//
//void resetDefaultWheelTicks() {
//  leftWheelTickCount = 0;
//  rightWheelTickCount = 0;
//}

//void resetTicksForAngleOrDistance() {
//  angleTurn = 0;
//  distanceMove = 0;
//  countTicksForAngleOrDist = false;
//  leftTicksForAngleOrDist = 0;
//  rightTicksForAngleOrDist = 0;
//}

void resetPololuTicks() {
  PololuWheelEncoders::getCountsAndResetM1();
  PololuWheelEncoders::getCountsAndResetM2();
}

float getDistance() {
//  int totalAvgNoOfTicks = (leftWheelTickCount + rightWheelTickCount) / 2;
//  int distanceCoveredInCm = totalAvgNoOfTicks / noOfTicksPerCm;
//  return distanceCoveredInCm;

  long leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
  long rightPololuCount = abs(PololuWheelEncoders::getCountsM2());
  float leftcm = ((PI*6)/2249) * leftPololuCount;
  float rightcm = ((PI*6)/2249) * rightPololuCount;
  float averageDist = (leftcm + rightcm) / 2;
  return averageDist;
}

// Run robot at max speed
void runMotor(int moveSpeedA, int moveSpeedB) {
  analogWrite(pwm_right, moveSpeedA);
  analogWrite(pwm_left, moveSpeedB);
}

// Move forward
void moveForward(float dist) {
  //resetPololuTicks();
  digitalWrite(dir_right, LOW); //Set motor direction, 1 low, 2 high
  digitalWrite(dir_left, LOW);  //Set motor direction, 3 high, 4 low

  float noOfTicksForDist = distCentimeter(dist);

  // ------ Distance to ticks formula ------- //
  //float noOfTicksPerCm = 2249/(PI*6); // adjust 6
  //float noOfTicksForDist = noOfTicksPerCm * dist;
  //setPointMid = noOfTicksForDist;
  //countTicksForAngleOrDist = true;
  float avgTicksForAngleOrDist = 0;

  long firstLeftCount = abs(PololuWheelEncoders::getCountsM1());
  long firstRightCount = abs(PololuWheelEncoders::getCountsM2());

  /*delta_left = firstLeftCount -last_count_left;
  delta_right = firstRightCount-last_count_right;

  if (delta_left < 0 || delta_right < 0) {
    last_count_left = 0;
    last_count_right = 0;
    resetPololuTicks();
  }*/

  while (avgTicksForAngleOrDist < noOfTicksForDist) {
    leftTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM1());
    leftTicksForAngleOrDist = leftTicksForAngleOrDist - firstLeftCount;

    rightTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM2());
    rightTicksForAngleOrDist = rightTicksForAngleOrDist - firstRightCount;

    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;

    //avgTicksForAngleOrDist = leftTicksForAngleOrDist;
    configureMotor();

    /*if (currentTicks != 0) {
      avgTicksForAngleOrDist = currentTicks + ((leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2);
    }*/
    //leftPololuCount = abs(PololuWheelEncoders::getCountsM1());
    //rightPololuCount = abs(PololuWheelEncoders::getCountsM2());

  /*  if((millis()-lastMilli) >= LOOPTIME){
      lastMilli = millis();
      //leftMotorConfigure();
      //rightMotorConfigure();
      configureMotor();
      runMotor(pwm_left, pwm_right); //Set both motors to run at 100% duty cycle (fast)
    }*/
  }
 //currentTicks = 0;
//  while (avgTicksForAngleOrDist < noOfTicksForDist) {
//    Serial.println("");
//    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;
//  }

  //resetTicksForAngleOrDistance();
  //setMotor = 0;

  digitalWrite(dir_left, HIGH); //Set motor direction, 1 low, 2 high
  digitalWrite(dir_right, HIGH);  //Set motor direction, 3 high, 4 low
  delay(40);
  halt();

  //if (pwm_left > pwm_right) {
  //int ticksToCompensate = 50;
    //digitalWrite(dir_left, HIGH);  //Set motor direction, 3 high, 4 low
    //runMotor(0,100); // Right
    //delay(30);
  //}

  /*else if (pwm_right > pwm_left) {
    digitalWrite(dir_right, HIGH);  //Set motor direction, 3 high, 4 low
    runMotor(100,0); // Right
    delay(30);
  }*/
  //pwm_left = 0;
  //pwm_right = 0;
  //digitalWrite(dir_left, LOW);  //Set motor direction, 3 high, 4 low
  //delay(20);
  //halt();
//  int ticksToCompensate = 50;
//  digitalWrite(dir_right, LOW);  //Set motor direction, 3 high, 4 low
//  runMotor(100,0); // Right
//  delay(70);
  //halt();
  //resetPololuTicks();

  //if() {
    /*int leftCount = abs(PololuWheelEncoders::getCountsM1());
    int rightCount = abs(PololuWheelEncoders::getCountsM2());
    Serial.print("left count =");
    Serial.print(leftCount);
    Serial.print("\t");
    Serial.print("right count =");
    Serial.println(rightCount);*/
  //}
}

// Turn right
void turnRight(int angle) {
  resetPololuTicks();
  //runMotor(maxSpeedA, maxSpeedB); //Set both motors to run at 100% duty cycle (fast)
  digitalWrite(dir_right, HIGH); //Set motor direction, 1 low, 2 high (right)
  digitalWrite(dir_left, LOW);  //Set motor direction, 3 high, 4 low (left)

  float noOfTicksForAngle = turnAngleR(angle);

  // ------ Angle to ticks formula ------- //
  //float noOfTicksPerCm = 2249/(PI*6);
  //float noOfCmPerDegreeForRightTurn = (PI*17.494)/360; // adjust 17.2
  //float totalCmForAngle = noOfCmPerDegreeForRightTurn * angle;
  //float noOfTicksForAngle = noOfTicksPerCm * totalCmForAngle;
  //360*(60/172)/2249/2;

  //countTicksForAngleOrDist = true;

  float avgTicksForAngleOrDist = 0;
  long firstLeftCount = abs(PololuWheelEncoders::getCountsM1());
  long firstRightCount = abs(PololuWheelEncoders::getCountsM2());

  while (avgTicksForAngleOrDist < noOfTicksForAngle) { //noOfTicksForAngle - change to 'angle' for other formula
    leftTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM1());
    leftTicksForAngleOrDist = leftTicksForAngleOrDist - firstLeftCount;

    rightTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM2());
    rightTicksForAngleOrDist = rightTicksForAngleOrDist - firstRightCount;

    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;
    //avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) * 0.02795;
    configureMotor();
  }

//  while (avgTicksForAngleOrDist < noOfTicksForAngle) {
//    Serial.println("");
//    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;
//  }

  //resetTicksForAngleOrDistance();

  digitalWrite(dir_right, LOW); //Set motor direction, 1 low, 2 high
  digitalWrite(dir_left, HIGH);  //Set motor direction, 3 high, 4 low
  delay(40);
  halt();
  //reverse(0.2);
  resetPololuTicks();
}

// Turn left
void turnLeft(int angle) {
  resetPololuTicks();
  //runMotor(maxSpeedA, maxSpeedB); //Set both motors to run at 100% duty cycle (fast)
  digitalWrite(dir_right, LOW);  //Set motor direction, 1 low, 2 high
  digitalWrite(dir_left, HIGH); //Set motor direction, 3 high, 4 low
  //turnAngle(angle+1);

  float noOfTicksForAngle = turnAngle(angle);
  //float noOfTicksPerCm = 2249/(PI*6); // adjust 6
  //float noOfCmPerDegreeForLeftTurn = (PI*17.494)/360; // adjust 17.2
  //float totalCmForAngle = noOfCmPerDegreeForLeftTurn * angle;
  //float noOfTicksForAngle = noOfTicksPerCm * totalCmForAngle;

  //countTicksForAngleOrDist = true;
  float avgTicksForAngleOrDist = 0;

  long firstLeftCount = abs(PololuWheelEncoders::getCountsM1());
  long firstRightCount = abs(PololuWheelEncoders::getCountsM2());

  while (avgTicksForAngleOrDist < noOfTicksForAngle) {
    leftTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM1());
    leftTicksForAngleOrDist = leftTicksForAngleOrDist - firstLeftCount;

    rightTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM2());
    rightTicksForAngleOrDist = rightTicksForAngleOrDist - firstRightCount;

    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;
    configureMotor();
  }

//  while (avgTicksForAngleOrDist < noOfTicksForAngle) {
//    Serial.println("");
//    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;
//  }

  //resetTicksForAngleOrDistance();

  digitalWrite(dir_right, HIGH); //Set motor direction, 1 low, 2 high
  digitalWrite(dir_left, LOW);  //Set motor direction, 3 high, 4 low
  delay(40);
  halt();
  //reverse(0.2);
  resetPololuTicks();
}

// Reverse backwards
void reverse(float dist) {
  //resetPololuTicks();
  runMotor(100, 100); //Set both motors to run at 100% duty cycle (fast)
  digitalWrite(dir_right, HIGH); //Set motor direction, 1 low, 2 high
  digitalWrite(dir_left, HIGH);  //Set motor direction, 3 high, 4 low
  delay(70);

//  float noOfTicksForDist = distCentimeter(dist);
//  //countTicksForAngleOrDist = true;
//  float avgTicksForAngleOrDist = 0;
//
//  int firstLeftCount = abs(PololuWheelEncoders::getCountsM1());
//  int firstRightCount = abs(PololuWheelEncoders::getCountsM2());
//
//  while (avgTicksForAngleOrDist < noOfTicksForDist) {
//    leftTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM1());
//    leftTicksForAngleOrDist = leftTicksForAngleOrDist - firstLeftCount;
//
//    rightTicksForAngleOrDist = abs(PololuWheelEncoders::getCountsM2());
//    rightTicksForAngleOrDist = rightTicksForAngleOrDist - firstRightCount;
//
//    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;
//  }
//
//  while (avgTicksForAngleOrDist < noOfTicksForDist) {
//    Serial.println("");
//    avgTicksForAngleOrDist = (leftTicksForAngleOrDist + rightTicksForAngleOrDist) / 2;
//  }

  //resetTicksForAngleOrDistance();

  digitalWrite(dir_right, LOW); //Set motor direction, 1 low, 2 high
  digitalWrite(dir_left, LOW);  //Set motor direction, 3 high, 4 low
  delay(30);
  halt();
  //resetPololuTicks();
}

// Stop movement
void halt()
{
  analogWrite(pwm_right, 0);
  analogWrite(pwm_left, 0);
  delay(100);
  //resetPololuTicks();
}

float middleSensorDistanceMeasuredInCM(int middleSensor) {
  //float volts = middleSensor * 0.0050528125; // worked out from graph 65 = theoretical distance / (1/Volts)S - luckylarry.co.uk
  //float distance = 65 * pow(volts, -1.10);
  //return distance;

  float distance = (6762 / (middleSensor - 9)) - 4;
  return distance;
}

float leftSensorDistanceMeasuredInCM(int leftSensor) {
  float distance = (6762 / (leftSensor - 9)) - 4;
  return distance;
}

float rightSensorDistanceMeasuredInCM(int rightSensor) {
  float distance = (6762 / (rightSensor - 9)) - 4;
  return distance;
}
float bottomSensorDistanceMeasuredInCM(int btmSensor) {
  float distance = (6762 / (btmSensor - 9)) - 4;
  return distance;
}

// Servo Turn
void servoTurn(int angle) {
  if(angle>=0 && angle<5){
    myServo.write(179);
  }
  else if(angle>=5 && angle<15){
    myServo.write(168.5);
  }
  else if(angle>=15 && angle<25){
    myServo.write(158);
  }
  else if(angle>=25 && angle<35){
    myServo.write(147.5);
  }
  else if(angle>=35 && angle<45){
    myServo.write(137);
  }
  else if(angle>=45 && angle<55){
    myServo.write(126.5);
  }
  else if(angle>=55 && angle<65){
    myServo.write(116);
  }
  else if(angle>=65 && angle<75){
    myServo.write(105.5);
  }
  else if(angle>=75 && angle<85){
    myServo.write(95);
  }
  else if(angle>=85 && angle<95){
    myServo.write(83);
  }
  else if(angle>=95 && angle<105){
    myServo.write(73.6);
  }
  else if(angle>=105 && angle<115){
    myServo.write(64.4);
  }
  else if(angle>=115 && angle<125){
    myServo.write(55.2);
  }
  else if(angle>=125 && angle<135){
    myServo.write(46);
  }
  else if(angle>=135 && angle<145){
    myServo.write(36.8);
  }
  else if(angle>=145 && angle<155){
    myServo.write(27.6);
  }
  else if(angle>=155 && angle<165){
    myServo.write(18.4);
  }
  else if(angle>=165 && angle<175){
    myServo.write(9.2);
  }
  else if(angle>=175 && angle<=180){
    myServo.write(0);
  }

}

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


Update Arduino

Update Arduino

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/WestwoodRobotics/BEST-2014.git/'


after test OK

after test OK

//
// Test code for LCM1602 I2C-LCD interface module used in the 4m Transverter
//
// It uses a variant for PCF8574 I2C extender chips:
// http://playground.arduino.cc/Code/LCDi2c
//
// see also: Sketchbook/Display/LCM1602test
//
// $Id$
//

#include <Wire.h>
#include <LiquidCrystal_I2C.h>

// set the LCD address to 0x27 for a 20 chars and 2 line display
LiquidCrystal_I2C lcd(0x27,20,2);

void setup() {

  lcd.init();
  lcd.backlight();
  lcd.setCursor(0, 0);
  lcd.print("LCM1602 test ...");
  lcd.setCursor(0, 1);
  lcd.print("Voltage: ");
  lcd.setCursor(13, 1);
  lcd.print("V");
}

void loop() {

  int val;
  float temp;

  val = analogRead(0);
  temp = val/4.092;
  val = (int)temp;

  lcd.setCursor(9, 1);
  lcd.print((uint8_t)(0x30+val/100));
  lcd.print((uint8_t)(0x30+(val%100)/10));
  lcd.print('.');
  lcd.print((uint8_t)(0x30+val%10));

  delay(100);
}

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


Removed unneeded include.

Removed unneeded include.

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/FirstBuild/pizzaduino.git/'


ino sketch

ino sketch

#include "variant.h"
#include <stdio.h>
#include <adk.h>

#define  LED_PIN  13

// Accessory descriptor. It's how Arduino identifies itself to Android.
char descriptionName[] = "ArduinoADK_2";
char modelName[] = "UDOO_ADK";           // your Arduino Accessory name (Need to be the same defined in the Android App)
char manufacturerName[] = "Aidilab";     // manufacturer (Need to be the same defined in the Android App)

// Make up anything you want for these
char versionNumber[] = "1.0";            // version (Need to be the same defined in the Android App)
char serialNumber[] = "1";
char url[] = "http://www.udoo.org";      // If there isn't any compatible app installed, Android suggest to visit this url

USBHost Usb;
ADK adk(&Usb, manufacturerName, modelName, descriptionName, versionNumber, url, serialNumber);

#define RCVSIZE 128
uint8_t buf[RCVSIZE];
uint32_t bytesRead = 0;

void setup()
{
    Serial.begin(115200);
    pinMode(LED_PIN, OUTPUT);
    delay(500);
    Serial.println("UDOO ADK demo start...");
}

void loop()
{
    Usb.Task();

    if (adk.isReady()) {
      adk.read(&bytesRead, RCVSIZE, buf);// read data into buf variable
      if (bytesRead > 0) {
        if (parseCommand(buf[0]) == 1) {// compare received data
          // Received "1" - turn on LED
          digitalWrite(LED_PIN, HIGH);
        } else if (parseCommand(buf[0]) == 0) {
          // Received "0" - turn off LED
          digitalWrite(LED_PIN, LOW);
        }
      }
    } else {
      digitalWrite(LED_PIN , LOW); // turn off light
    }

    delay(10);
}

// the characters sent to Arduino are interpreted as ASCII, we decrease 48 to return to ASCII range.
uint8_t parseCommand(uint8_t received) {
  return received - 48;
}

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


adding arduino code

adding arduino code

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


Added basic sketch of traffic light that is controlled by a remote using IR.

#include <IRremote.h>

const unsigned long LIGHT_RED_KEY = 0xFFA25D;
const unsigned long LIGHT_YELLOW_KEY = 0xFF629D;
const unsigned long LIGHT_GREEN_KEY = 0xFFE21D;
const unsigned long FLASH_RED_KEY = 0xFF22DD;
const unsigned long FLASH_YELLOW_KEY = 0xFF02FD;
const unsigned long FLASH_GREEN_KEY = 0xFFC23D;
const unsigned long LIGHTS_OFF_KEY = 0xFFE01F;

const int IR_PIN = 7;
IRrecv irrecv(IR_PIN);
decode_results results;

const int RED_PIN = 4;
const int YELLOW_PIN = 3;
const int GREEN_PIN = 2;

const int VOID_PIN= -1;

const int pins[] = { RED_PIN, YELLOW_PIN, GREEN_PIN };
const int pinCount = sizeof(pins) / sizeof(int);

int flashingPin = VOID_PIN;
boolean flashingHigh;
const unsigned long flashDuration = 750;
unsigned long flashStartTime;
unsigned long lastKeyValue;

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

    pinMode(RED_PIN, OUTPUT);
    pinMode(YELLOW_PIN, OUTPUT);
    pinMode(GREEN_PIN, OUTPUT);
}

void loop() {

    if (flashingPin != VOID_PIN) {
        if ((millis() - flashStartTime) >= flashDuration) {
            flashingHigh = !flashingHigh;
            flashStartTime = millis();

            digitalWrite(flashingPin, flashingHigh);
        }
    }

    if (irrecv.decode(&results)) {

        Serial.println(results.value, HEX);

        unsigned long keyValue = results.value;

        if (keyValue == lastKeyValue || keyValue == REPEAT) {
            irrecv.resume();
            return;
        }
        else {
            lastKeyValue = keyValue;
        }

        if (keyValue == LIGHT_RED_KEY) {
            lightPinExclusive(RED_PIN);
        }
        else if (keyValue == LIGHT_YELLOW_KEY) {
            lightPinExclusive(YELLOW_PIN);
        }
        else if (keyValue == LIGHT_GREEN_KEY) {
            lightPinExclusive(GREEN_PIN);
        }
        else if (keyValue == FLASH_RED_KEY) {
            flashPinExclusive(RED_PIN);
        }
        else if (keyValue == FLASH_YELLOW_KEY) {
            flashPinExclusive(YELLOW_PIN);
        }
        else if (keyValue == FLASH_GREEN_KEY) {
            flashPinExclusive(GREEN_PIN);
        }
        else if (keyValue == LIGHTS_OFF_KEY) {
            lightPinExclusive(VOID_PIN);
        }

        irrecv.resume();
    }
}

void lightPinExclusive(int pin) {
    flashingPin = VOID_PIN;

    for (int i = 0; i < pinCount; i++) {
        digitalWrite(pins[i], pins[i] == pin ? HIGH : LOW);
    }
}

void flashPinExclusive(int pin) {
    lightPinExclusive(pin);

    flashingPin = pin;
    flashingHigh = true;
    flashStartTime = millis();
}

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


Update Sensor-rcv-ucg. Still not working.

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


Writer now initializes cards

Writer now initializes cards

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


Beginning integration with front desk

Beginning integration with front desk

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


Adding a basic encode/decode example

Adding a basic encode/decode example

#include <Base64.h>

/*
 Base64 Encode/Decode example

 Encodes the text "Hello world" to "SGVsbG8gd29ybGQA" and decodes "Zm9vYmFy" to "foobar"

 Created 29 April 2015
 by Nathan Friedly - http://nfriedly.com/

 This example code is in the public domain.

 */

void setup()
{
  // start serial port at 9600 bps:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Base64 example");

  // encoding
  char input[] = "Hello world";
  int inputLen = sizeof(input);

  int encodedLen = base64_enc_len(inputLen);
  char encoded[encodedLen];

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

  // note input is consumed in this step: it will be empty afterwards
  base64_encode(encoded, input, inputLen);

  Serial.println(encoded);

  // decoding
  char input2[] = "Zm9vYmFy";
  int input2Len = sizeof(input2);

  int decodedLen = base64_dec_len(input2, input2Len);
  char decoded[decodedLen];

  base64_decode(decoded, input2, input2Len);

  Serial.print(input2); Serial.print(" = "); Serial.println(decoded);
}

void loop()
{

}

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


initial example

initial example

#include <SoftwareSerial.h>

typedef void (*func) (String cmd);
extern func functions[];

SoftwareSerial bt(9, 10); // (tx,rx)
const int LED1 = 8; // led pin

// key value struct
struct key_func {
  String key;
  func fn;
};

// function declerations
int getIntParam(String, String, int);
boolean isExistParam(String, String);
void blink(String);
void listenBluetooth();
void listenSerial();

// commands array
key_func func_map[1];

void setup() {
  bt.begin(9600);
  Serial.begin(19200);
  pinMode(LED1, OUTPUT);

  // key and function name must be same
  func_map[0].key = "blink"; // command name
  func_map[0].fn = blink;    // command function

}

String bluetoothData = "";
String serialData = "";

void loop() {
  // blink -t 20 -i 100 -a
  listenBluetooth();
  // blink -t 20 -i 100 -a
  listenSerial();
}

void listenBluetooth(){
  while (bt.available() > 0) {
    char chr = bt.read();
    if (chr != '\n') bluetoothData.concat(chr);
    if (chr == '\n') {
      for (int i = 0; i < sizeof func_map / sizeof func_map[0]; i++) {
        if (bluetoothData.startsWith(func_map[i].key)) {
          func_map[i].fn(bluetoothData);
        }
      }
      bluetoothData = "";
    }
  }
}

void listenSerial(){
  while (Serial.available() > 0) {
    char chr = Serial.read();
    if (chr != '\n') serialData.concat(chr);
    if (chr == '\n') {
      for (int i = 0; i < sizeof func_map / sizeof func_map[0]; i++) {
        if (serialData.startsWith(func_map[i].key)) {
          func_map[i].fn(serialData);
        }
      }
      serialData = "";
    }
  }
}

void blink(String cmd) {
  String paramsStr = cmd.substring(sizeof __func__ / sizeof __func__[0]);

  int times = getIntParam("-t", paramsStr, 10);
  int interval = getIntParam("-i", paramsStr, 250);

  for (int i = 0; i < times ; i++) {
    digitalWrite(LED1, HIGH);
    delay(interval);
    digitalWrite(LED1, LOW);
    delay(interval);
  }

  if (isExistParam("-a", paramsStr)) {
    digitalWrite(LED1, HIGH);
  } else {
    digitalWrite(LED1, LOW);
  }

}

int getIntParam(String param_name, String params, int default_value) {
  int position = params.indexOf(param_name);

  if (position > -1) {
    return params.substring(position + param_name.length() + 1, params.indexOf(' ', position + param_name.length() + 1)).toInt();
  }
  return default_value;
}

boolean isExistParam(String param_name, String params) {
  return params.indexOf(param_name) > -1;
}

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


Test Flip-Dot library

Test Flip-Dot library

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


Added closet_mote_v0_1

Added closet_mote_v0_1

#include <ESP8266WiFi.h>
#include <Wire.h>
#include <PubSubClient.h>

#define wifi_ssid "brulenet"
#define wifi_password "01266606296606269306260626"

#define mqtt_server "mqtt.dev.brule.net"
#define mqtt_user ""
#define mqtt_password ""

#define TMP36_PIN  A0
#define temperature_topic "sensor/temperature"

WiFiClient espClient;
PubSubClient client(espClient);

unsigned long previousMillis = 0;  // will store last temp was read
const long interval = 10000;        // interval at which to read sensor

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);

  WiFi.begin(wifi_ssid, wifi_password);

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

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

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Attempt to connect
    // If you do not want to use a username and password, change next line to
    // if (client.connect("ESP8266Client")) {
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

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

  gettemperature();
}

void gettemperature() {
  // Wait at least 2 seconds seconds between measurements.
  // if the difference between the current time and last time you read
  // the sensor is bigger than the interval you set, read the sensor
  // Works better than delay for things happening elsewhere also
  unsigned long currentMillis = millis();

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

    int reading = analogRead(TMP36_PIN);
    float voltage = reading * 3.3;
    voltage /= 1024.0;

    Serial.print(voltage); Serial.println(" volts");

    // now print out the temperature
    float temperatureC = (voltage - 0.5) * 100 ;  //converting from 10 mv per degree wit 500 mV offset
                                                  //to degrees ((voltage - 500mV) times 100)
    Serial.print(temperatureC); Serial.println(" degrees C");

    // now convert to Fahrenheit
    float temperatureF = (temperatureC * 9.0 / 5.0) + 32.0;
    Serial.print(temperatureF); Serial.println(" degrees F");

    client.publish(temperature_topic, String(temperatureF).c_str(), true);
  }
}

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


Add files via upload

Add files via upload

This generates sin-cosine waves on an Arduino Due at controlled frequencies.

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


nichtstabil

nichtstabil

#include "TheThingsUno.h"
/*#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX*/
String inString = "";

// Set your DevAddr
const byte devAddr[4] = {0x01, 0x61, 0xB5, 0xFB}; //for example: {0x02, 0xDE, 0xAE, 0x00};

// Set your NwkSKey and AppSKey
const byte nwkSKey[16] = {0x05, 0xED, 0x38, 0x5B, 0xF7, 0x83, 0xAA, 0x99, 0x98, 0x99, 0x29, 0xCA, 0xD7, 0x51, 0xA7, 0xF6}; //for example: {0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C};
const byte appSKey[16] = {0x20, 0x49, 0x5A, 0x2B, 0x18, 0xD4, 0xDB, 0x74, 0x20, 0x85, 0xFA, 0x4F, 0xA9, 0x7F, 0xB8, 0x60}; //for example: {0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C};

#define debugSerial Serial
#define loraSerial Serial1

#define debugPrintLn(...) { if (debugSerial) debugSerial.println(__VA_ARGS__); }
#define debugPrint(...) { if (debugSerial) debugSerial.print(__VA_ARGS__); }

TheThingsUno ttu;

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

  loraSerial.begin(57600);
//  Serial.begin(57600);
//  while (!Serial) {
//    ; // wait for serial port to connect. Needed for native USB port only
//  }
  delay(3000);
  //Start Einstellungen:
  ttu.init(loraSerial, debugSerial);
  ttu.reset();
  ttu.personalize(devAddr, nwkSKey, appSKey);
  ttu.showStatus();

  debugPrintLn("Setup for The Things Network complete");

//  ttu.sendCommand("mac set ch dcycle 0 99"); //<dutyCycle> = (100/X) – 1
//  ttu.sendCommand("mac set ch dcycle 1 99");
//  ttu.sendCommand("mac set ch drrange 1 0 7");
//  ttu.sendCommand("mac set ch dcycle 2 99");
//  ttu.sendCommand("mac set ch freq 3 868850000");
//  ttu.sendCommand("mac set ch dcycle 3 999");
//  ttu.sendCommand("mac set ch drrange 3 0 5");
//  ttu.sendCommand("mac set ch status 3 on");
//  ttu.sendCommand("mac set ch freq 4 869050000");
//  ttu.sendCommand("mac set ch drrange 4 0 5");
//  ttu.sendCommand("mac set ch status 4 on");
//  ttu.sendCommand("mac set ch freq 5 869525000");
//  ttu.sendCommand("mac set ch dcycle 5 9");
//  ttu.sendCommand("mac set ch drrange 5 0 5");
//  ttu.sendCommand("mac set ch status 5 on");
//  ttu.sendCommand("mac save");
  //delay(4000);

}

void loop() {

  //Chanal ändern
  //String inString = "00,500,10";  // Testnummer, Counter, Scenario
/*
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
  delay(500);
  Serial.println("Half a second later");

  inString = Serial.readString();
  if(inString) {
    Serial.println("Input: " + inString);
  }

  */
  ttu.sendString("Input: " + String(inString));
  //  if (Serial.available() > 0) {
  //    int inChar = Serial.read();
  //    if (isDigit(inChar)) {
  //      // convert the incoming byte to a char
  //      // and add it to the string:
  //      inString += (char)inChar;
  //    }
  // Input:  x,y,z
  String temp1 = inString.substring(inString.indexOf(',') + 1); // ,y,x
  String testnr = inString.substring(0, inString.indexOf(',')); //x

  String temp2 = temp1.substring(temp1.indexOf(',') + 1); //x
  String counter = temp1.substring(0, temp1.indexOf(',')); //Testnummer :12 Temp1 : 34, 56   Counter :34  Temp2 : 56   Scenario : 56

  String scenario = temp2;
  // Serial.println( "Testnummer " + testnr + "   Counter " + counter + "   Scenario " + scenario);
  //  }

  int dr = -1;
  switch (scenario.toInt()) {
    case 7:
      dr = 5;
      break;
    case 8:
      dr = 4;
      break;
    case 9:
      dr = 3;
      break;
    case 10:
      dr = 2;
      break;
    case 11:
      dr = 1;
      break;
    case 12:
      dr = 0;
      break;
    default:
      debugPrintLn("Invalid SF")
      break;
  }
  if (dr > -1)

  { //ttu.sendCommand("mac set dr " + String(dr));}

  }
  ttu.sendCommand("mac set retx 0");
  ttu.sendCommand("mac set upctr " + String(counter) );
  //ttu.sendCommand("mac tx cnf 4 " + testnr );

  ttu.sendString("Team Rocket");

  delay(4000);
}

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


add bandGap demo sketch

add bandGap demo sketch

// Try reading the bandgap reference voltage to measure current VCC voltage.
// 2012-04-22 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

static int vccRead (byte us =250) {
  analogRead(6);    // set up "almost" the proper ADC readout
  bitSet(ADMUX, 3); // then fix it to switch to channel 14
  delayMicroseconds(us); // delay substantially improves accuracy
  bitSet(ADCSRA, ADSC);
	while (bit_is_set(ADCSRA, ADSC))
	  ;
  word x = ADC;
  return x ? (1100L * 1023) / x : -1;
}

void setup() {
  Serial.begin(57600);
  Serial.println("\n[bandgap]");
}

void loop() {
  analogRead(0); // just to check that it doesn't affect result
  Serial.println(vccRead());
  delay(500);
}

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


updated documentation

updated documentation

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/relayr/Arduino-Bridge-Library.git/'


hmm, this sseems to work

hmm, this sseems to work

at least the movements are correctly added …

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


add arduino sketch

add arduino sketch

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/thintsa/rotating-target-controller.git/'


Create modem_mqtt.ino

Create modem_mqtt.ino

#include <SoftwareSerial.h>
#include "sim800_mqtt.h"
#include "Adafruit_MQTT.h"

SoftwareSerial ss = SoftwareSerial(6, 7);

Modem modem = Modem(4);  //RST

  // Optionally configure a GPRS APN, username, and password.
  // You might need to do this to access your network's GPRS/data
  // network.  Contact your provider for the exact APN, username,
  // and password values.  Username and password are optional and
  // can be removed, but APN is required.
#define APN       "web.gprs.mtnnigeria.net"

#define SERVER      "cloud.nodewire.org"
#define SERVERPORT  1883

// Setup the SIM800 MQTT class by passing in the Modem object and MQTT server and login details.
Modem_MQTT mqtt(&modem, SERVER, SERVERPORT, "arduinoClient");

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

// modemSetup is a helper function that sets up the SIM800 and connects to
// the GPRS network. See the modemHelper.cpp tab above for the source!
boolean modemSetup(const __FlashStringHelper *apn);

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

Adafruit_MQTT_Subscribe iot_in = Adafruit_MQTT_Subscribe(&mqtt, "sadiqahmad2/#");

/*************************** Sketch Code ************************************/

void setup() {
  while (!Serial);

  // Watchdog is optional!
  //Watchdog.enable(8000);

  Serial.begin(9600);

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

  // Initialise the modem
  while (! modemSetup(F(APN))) {
    Serial.println("Retrying modem");
  }

  Serial.println(F("Connected to Cellular!"));

  mqtt.subscribe(&iot_in);
  Serial.println("Subscribed to sadiqahmad/#");

  //Watchdog.reset();
  delay(5000);  // wait a few seconds to stabilize connection
  //Watchdog.reset();
}

void loop() {
  // 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();

  //Watchdog.reset();
  // this is our 'wait for incoming subscription packets' busy subloop
  Adafruit_MQTT_Subscribe *subscription;
  while ((subscription = mqtt.readSubscription(5000))) {
    if (subscription == &iot_in) {
      Serial.print(F("\tReceived: "));
      Serial.println((char *)iot_in.lastread);
    }
  }

  //ping the server to keep the mqtt connection alive, only needed if we're not publishing
  if(! mqtt.ping()) {
    Serial.println(F("MQTT Ping failed."));
  }

}

// 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));
    Serial.println("Retrying MQTT connection in 5 seconds...");
    mqtt.disconnect();
    delay(5000);  // wait 5 seconds
  }
  Serial.println("MQTT Connected!");
}

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


add example to change communication speed

#include "DynamixelMotor.h"

const uint8_t id=1;

DynamixelInterface &interface=*createSerialInterface(Serial);
DynamixelMotor motor(interface, id);

// demonstrate how to change communication speed
// the led should blink three time
void setup()
{
  //start at 1MBd
  delay(100);
  interface.begin(1000000);

  motor.init();
  motor.led(HIGH);
  delay(1000);
  motor.led(LOW);
  delay(1000);

  //switch motor to 9600Bd
  motor.communicationSpeed(9600);

  //switch interface speed to 9600Bd
  delay(100);
  interface.begin(9600);

  motor.led(HIGH);
  delay(1000);
  motor.led(LOW);
  delay(1000);

  //switch back to 1MBd
  motor.communicationSpeed(1000000);

  delay(100);
  interface.begin(1000000);

  motor.led(HIGH);
  delay(1000);
  motor.led(LOW);
  delay(1000);
}

void loop(){}

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


Added Arduino code for paddle controllers.

/**
 * Radsensor
 * für das Pong zum Hechtfest 2016
 *
 * Benötigt:
 * - AS5601-Treiber
 *   https://github.com/bitfasching/AS5601
 *
 * nick@bitfasching.de
 * KAZOOSH!
 */

#include <Arduino.h>
#include <AS5601.h>

// Kalibrierungszeit [ms]
const unsigned int calibrationTime = 10000;

// Sensorrauschunterdrückung (Änderungsschwelle für Positionsübernahme)
const int sensorNoise = 4;

// Magnetsensor vorbereiten
AS5601 Sensor;

// globale Variable für Messwerte
int referenceAngle;

// globale Variablen für Kalibrierungszustand und Startzeitpunkt
enum State { IDLE, WAITING, CALIBRATING, TRACKING } State;
unsigned long startTime;

// Sensor auslesen und Position ermitteln
void updatePosition( int &position )
{
    int newAngle, delta;

    // aktuellen Winkel einlesen
    newAngle = (int) Sensor.getRawAngle();

    // Differenz ermitteln
    delta = newAngle - referenceAngle;

    // Rauschen unterdrücken und kleine Änderungen ignorieren
    if ( abs( delta ) < sensorNoise ) { return; }

    // Überdrehung abfangen
    if ( delta >  2048 ) { delta = delta - 4096; }
    if ( delta < -2048 ) { delta = delta + 4096; }

    // fortlaufenden Winkel weiterzählen
    position = position + delta;

    // Referenzwinkel aktualisieren
    referenceAngle = newAngle;
}

// Nachkalibrierung von Ober- & Untergrenze
bool calibrate( int position, int &top, int &bottom, int &middle, int length )
{
    int offset = 0;

    // Überschreitung?
    if ( position > top )
    {
        // positive Differenz
        offset = position - top;
    }
    // Unterschreitung?
    else if ( position < bottom )
    {
        // negative Differenz
        offset = position - bottom;
    }

    // wenn Anpassung notwendig…
    if ( offset != 0 )
    {
        // beide Grenzen synchron nachführen (hält Weglänge zwischen Grenzen konstant)
        top += offset;
        bottom += offset;

        // Mitte neu berechnen
        middle = bottom + length / 2;
    }
}

// Start
void setup()
{
    // kurz warten und USB einschalten
    delay( 1000 );
    Serial.begin( 115200 );

    // Hallo sagen
    Serial.println( F("[Radsensor Pong 2016]") );

    // Startwinkel setzen
    referenceAngle = (int) Sensor.getRawAngle();
}

// Hauptschleife
void loop()
{
    static int position = 0;
    static int top, bottom, middle, length;

    // Sensor abfragen und Position ermitteln
    updatePosition( position );

    // Weglänge kalibriert?
    if ( State == TRACKING )
    {
        // Nachkalibrierung: Grenzen nachführen
        calibrate( position, top, bottom, middle, length );

        // neuer Wert angefragt?
        if ( Serial.read() != -1 )
        {
            // Position auf ±1024 mappen
            int scaledPosition = (long) ( position - middle ) * 2048 / length;

            // Wert als 16-bit-Wort ausgeben (Big Endian)
            Serial.write( highByte( scaledPosition ) );
            Serial.write( lowByte( scaledPosition ) );
            //Serial.println( scaledPosition );
        }
    }
    // noch nicht kalibriert
    else
    {
        // Kalibrierung noch gar nicht gestartet?
        if ( State == IDLE )
        {
            // beide Grenzen zum Start auf aktuelle Position setzen
            top = position;
            bottom = position;

            // nächster Zustand: Warten auf Bewegung
            State = WAITING;

            // Status ausgeben
            Serial.print( F("Waiting ") );
        }
        // Warten auf Bewegung?
        else if ( State == WAITING )
        {
            // sobald Bewegung stattgefunden hat (also Position verändert wurde)…
            if ( length > 0 )
            {
                // Startzeit festhalten
                startTime = millis();

                // nächster Zustand: Kalibrieren
                State = CALIBRATING;

                // Status ausgeben
                Serial.print( F("Calibrating ") );
            }
        }

        // Obergrenze und Untergrenze ausweiten
        if ( position > top ) { top = position; }
        if ( position < bottom ) { bottom = position; }

        // Gesamtweg und Mitte berechnen
        length = top - bottom;
        middle = bottom + length / 2;

        // Kalibrierungszeit abgelaufen?
        if ( State == CALIBRATING && millis() > startTime + calibrationTime )
        {
            // Kalibrierung für abgeschlossen erklären
            State = TRACKING;

            // Status ausgeben
            Serial.println( F("Tracking") );
        }
    }
}

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


Add button example with leds

Add button example with leds

/*
 * Blink example with serial
 */

// Connect the button to pin 2 in arduino
const int buttonPin = 2;
// Pin 13 has an LED connected on most Arduino boards.
const int ledPin = 13;
//The button state (0 = released, HIGH = pressed)
const int buttonState = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);
  // initialize the button pin as an input.
  // connect the button in VDD and PIN 2
  pinMode(buttonPin, INPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.println("LED ON");  // send a message via serial interface
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  Serial.println("LED OFF"); // send a message via serial interface
  delay(1000);               // wait for a second
}

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


Keypad working with servo and buzzer

Keypad working with servo and buzzer

/*4x4 Matrix Keypad connected to Arduino
This code prints the key pressed on the keypad to the serial port*/

#include <Keypad.h>

const byte numRows= 4; //number of rows on the keypad
const byte numCols= 4; //number of columns on the keypad

//keymap defines the key pressed according to the row and columns just as appears on the keypad
char keymap[numRows][numCols]=
{
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};

//Code that shows the the keypad connections to the arduino terminals
byte rowPins[numRows] = /*{9,8,7,6};*/ {6,7,8,9};//Rows 0 to 3
byte colPins[numCols]=  /*{5,4,3,2};*/{2,3,4,5};//Columns 0 to 3

//initializes an instance of the Keypad class
Keypad myKeypad= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);
#define ledpin 13
void setup()
{
pinMode(ledpin,OUTPUT);
  digitalWrite(ledpin, HIGH);
  Serial.begin(9600);;
}

//If key is pressed, this key is stored in 'keypressed' variable
//If key is not equal to 'NO_KEY', then this key is printed out
//if count=17, then count is reset back to 0 (this means no key is pressed during the whole keypad scan process
void loop()
{
char key = myKeypad.getKey();
  if(key)  // Check for a valid key.
  {
    switch (key)
    {
      case '*':
        digitalWrite(ledpin, LOW);
        break;
      case '#':
        digitalWrite(ledpin, HIGH);
        break;
      default:
        Serial.println(key);
    }
  }
}

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


add motor test

add motor test

#include <Motor.h>

Motor motor(8, 9, 10, 11);

void setup() {
    Serial.begin(9600);
    while(!Serial);
}

void loop() {
    if (Serial.available()) {
        int steps = Serial.parseInt();
        motor.rotateSteps(steps);
        Serial.write("Done");
    }
}

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


Rename Hub to Package

Rename Hub to Package

// HouseWare Package Firmware
// Created by Andrew Fugier

// Includes
#include <SoftwareSerial.h>

// Common variables that chage
const char* VERSION = "0.0.2";   // version number
const int   DELAY   = 10;        // loop delay

SoftwareSerial mySerial =  SoftwareSerial(2, 3);    // XBee connected on pins D2 and D3
char str[20];    // used for most string operations - a single 20 byte memory segement
char out[20];    // buffer used for output storage
int pDoor = 0;   // state of the door

/* Sends the contents of out[] to the XBee and local Serial */
void sendMsg(){
  Serial.println(out);
  mySerial.println(out);
}

/* Firmware setup function */
void setup() {
  Serial.begin(9600);    // Local Serial Communications
  mySerial.begin(9600);  // XBee Communications

  strcpy(out, "Init HouseWare Hub");
  sendMsg();

  pinMode(4, INPUT);    // door pin
  pinMode(13, OUTPUT);  // light pin
}

/* Read a message from the XBee interface */
/* Specify a char array as well as the array size */
int getMsg(char* m, int bsize){
  if (mySerial.available()) {                          // XBee has data
    int p = 0;                                         // buffer pos
    while(mySerial.available()){                       // Until buffer is empty
      if(mySerial.read() == '{'){                      // Start of JSON data
        while(mySerial.peek() != '}' && p < bsize){    // until the end of JSON data
          m[p++]=mySerial.read();                      // build the 'm' buffer
        }
        m[p++]=0;                                      // null terminate the 'm' buffer
      }
    }
    return 1;    // got a vailid message
  }
  return 0;      // no valid message
}

/* Process a givin JSON message */
/* Specify the char array */
int processMsg(char* m){
  switch(m[1]){
    case 'r':            // request
      switch(m[7]){
        case 'a':
          // TODO: code to return all sensor values
          break;
        default:
          // assume a pin xy  (pin > 50, analog - eg, pin 54 is analog 04)
          int t = 0;            // type:  0 -> Digital / 1 -> Analog
          int x = m[6] - '0';
          int y = m[7] - '0';
          int v = 0;            // value: sensor value

          // determine if digital or analog pin
          if(x >= 5) {
            t = 1;
            x = x - 5;
          }
          int z = (x * 10) + y; // the pin orginally requested, in int form

          if(t == 0){            // digital read
            v = digitalRead(z);
          }
          else if(t == 1){       // analog read
            v = analogRead(z);
          }

          // Build and return JSON
          sprintf(out, "{\"dat\":\"%i:%i\"}", (t*50)+z, v);
          sendMsg();
          break;
        }
      return 0;
      break;

    case 's':            // system
      switch(m[7]){
        case 'v':        // get version
          strcpy(out, "{\"dat\":\"v:");
          strcat(out, VERSION);
          strcat(out, "\"}");
          sendMsg();
          break;
        case 'r':       // reset system
          // TODO; Send notification of user reset
          asm volatile ("  jmp 0");    // hack-ish was to reset
          break;
      }
      return 0;
      break;

    case 'd':            // data
      return 0;
      break;

    case 'e':            // error
      return 0;
      break;

    // undefined
    strcpy(out, "{\"err\":001}");
    sendMsg();
    return -1;
  }
}

void loop() {
  // check the door
  if(digitalRead(4) != pDoor){
    processMsg("\"req\":04");
    pDoor = !pDoor;
  }

  // get and process messages
  if(getMsg(str, 20)){
    processMsg(str);
  }

  delay(DELAY);
}

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


Se crea proyecto de sensor hc-sr04

Se crea proyecto de sensor hc-sr04

//Se declaran los pines para el sensor
int const TRIG = 9;
int const ECHO = 8;

//Variables de calculo
float distancia;
float tiempo;

void setup(){
  Serial.begin(9600);
  //Activación del pin como salida: para el pulso ultrasónico
  pinMode(TRIG, OUTPUT);
  //Activación del pin como entrada: tiempo del rebote del ultrasonido
  pinMode(ECHO, INPUT);
}

void loop(){
  //Por cuestión de estabilización del sensor
  digitalWrite(TRIG,LOW);
  delayMicroseconds(5);
  //envío del pulso ultrasónico
  digitalWrite(TRIG, HIGH);
  delayMicroseconds(10);
  /* Función para medir la longitud del pulso entrante.
  Mide el tiempo que transcurrido entre el envío
  del pulso ultrasónico y cuando el sensor recibe el rebote, e
  s decir: desde que el pin 12 empieza a recibir el rebote, HIGH, hasta que
  deja de hacerlo, LOW, la longitud del pulso entrante*/
  tiempo=pulseIn(ECHO, HIGH);
  /*fórmula para calcular la distancia obteniendo un valor entero*/
  /*Monitorización en centímetros por el monitor serial*/
  distancia= int(0.017*tiempo);
  Serial.print("Distancia ");
  Serial.print(distancia);
  Serial.print(" cm");
  Serial.println("");
  delay(1000);
}

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


Running at 10 ms and outputs periodic temps.

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/FirstBuild/pizzaduino.git/'


Bumping version for release.

Bumping version for release.


Optimise data types

Optimise data types

fatal: remote error: upload-pack: not our ref 29efaf4f36ed5c786260bf5fe9b92d500c50911e
fatal: the remote end hung up unexpectedly


Create proton_pack.ino

Create proton_pack.ino

// Required by SD card
#include <FatReader.h>
#include <SdReader.h>
#include <avr/pgmspace.h>
#include "WaveUtil.h"
#include "WaveHC.h"

SdReader card;    // This object holds the information for the card.
FatVolume vol;    // This holds the information for the partition on the card.
FatReader root;   // This holds the information for the filesystem on the card.
FatReader f;      // This holds the information for the file we're play.
WaveHC wave;      // This is the only wave (audio) object, since we will only play one at a time.

// Timekeeping
long previousMillis_off = 0;  // will store last updated time.
long previousMillis_on = 0;
long previousMillis_fire = 0;
long off_interval = 30;
long pwrcl_interval = 60;     // interval at which to cycle lights (milliseconds).
long firing_interval = 40;    // interval at which to cycle firing lights (milliseconds).

// ===============================================================================================
// BUTTONS
// array is in the format: buttons[power_on, gun_fire, music_change]
// thus, whatever pin is set to buttons[0] switches on the power cell.
// ===============================================================================================
#define DEBOUNCE 5  // button debouncer.
byte buttons[] = {14, 15, 16};  // Analog 0, 1 and 2 respectively.
// This handy macro lets us determine how big the array up above is, by checking the size.
#define NUMBUTTONS sizeof(buttons)
// we will track if a button is just pressed, just released, or 'pressed' (the current state).
volatile byte pressed[NUMBUTTONS], justpressed[NUMBUTTONS], justreleased[NUMBUTTONS];

//Pin connected to ST_CP of 74HC595 (pin 12)
int latchPin = 8;
//Pin connected to SH_CP of 74HC595 (pin 11)
int clockPinPWR = 6;  // Power cell
int clockPinGUN = 18;  // Gun
////Pin connected to DS of 74HC595 (pin 14)
int dataPinPWR = 7;  // Power cell
int dataPinGUN = 19; // Gun

// PINS SUMMARY:
// 2, 3, 4, 5, 10 = audioshield
// 6, 7, 18, 19 = 595's
// 11, 12, 13 = SD card i/o

//holders for information we're going to pass to shifting function
byte dataPWRCL1;
byte dataPWRCL2;
byte dataGUN1;
byte dataGUN2;
byte dataGUNON1;
byte dataGUNON2;
// data arrays
byte daPWRCL1[15];
byte daPWRCL2[15];
byte daGUN1[26];
byte daGUN2[26];
byte daGUNON1[15];
byte daGUNON2[15];

int freeRam(void) {
    extern int  __bss_end;
    extern int  *__brkval;
    int free_memory;
    if((int)__brkval == 0) {
        free_memory = ((int)&free_memory) - ((int)&__bss_end);
    }
    else {
        free_memory = ((int)&free_memory) - ((int)__brkval);
    }
    return free_memory;
}

void setup() {
    byte i;

    /*
    // set up serial port
    Serial.begin(9600);
    putstring_nl("WaveHC with ");
    Serial.print(NUMBUTTONS, DEC);
    putstring_nl("buttons");

    putstring("Free RAM: ");       // This can help with debugging, running out of RAM is bad
    Serial.println(freeRam());      // if this is under 150 bytes it may spell trouble!
    */

    // Set the output pins for the DAC control. This pins are defined in the library
    pinMode(2, OUTPUT);
    pinMode(3, OUTPUT);
    pinMode(4, OUTPUT);
    pinMode(5, OUTPUT);
    pinMode(10, OUTPUT);

    pinMode(latchPin, OUTPUT);
    // power cell LEDs 0 through 7
    daPWRCL1[0] = 0x80;  //10000000
    daPWRCL1[1] = 0xC0;  //11000000
    daPWRCL1[2] = 0xE0;  //11100000
    daPWRCL1[3] = 0xF0;  //11110000
    daPWRCL1[4] = 0xF8;  //11111000
    daPWRCL1[5] = 0xFC;  //11111100
    daPWRCL1[6] = 0xFE;  //11111110
    daPWRCL1[7] = 0xFF;  //11111111
    daPWRCL1[8] = 0xFF;  //11111111
    daPWRCL1[9] = 0xFF;  //11111111
    daPWRCL1[10] = 0xFF; //11111111
    daPWRCL1[11] = 0xFF; //11111111
    daPWRCL1[12] = 0xFF; //11111111
    daPWRCL1[13] = 0xFF; //11111111
    daPWRCL1[14] = 0xFF; //11111111

    // Power cell LEDs 8 through 15
    daPWRCL2[0] = 0x00;  //00000000
    daPWRCL2[1] = 0x00;  //00000000
    daPWRCL2[2] = 0x00;  //00000000
    daPWRCL2[3] = 0x00;  //00000000
    daPWRCL2[4] = 0x00;  //00000000
    daPWRCL2[5] = 0x00;  //00000000
    daPWRCL2[6] = 0x00;  //00000000
    daPWRCL2[7] = 0x80;  //10000000
    daPWRCL2[8] = 0xC0;  //11000000
    daPWRCL2[9] = 0xE0;  //11100000
    daPWRCL2[10] = 0xF0; //11110000
    daPWRCL2[11] = 0xF8; //11111000
    daPWRCL2[12] = 0xFC; //11111100
    daPWRCL2[13] = 0xFE; //11111110
    daPWRCL2[14] = 0xFF; //11111111

    //second lights
    daGUN1[0] = 0x00;  //00000000
    daGUN1[1] = 0x00;  //00000000
    daGUN1[2] = 0x00;  //00000000
    daGUN1[3] = 0x00;  //00000000
    daGUN1[4] = 0x00;  //00000000
    daGUN1[5] = 0x00;  //00000000
    daGUN1[6] = 0x00;  //00000000
    daGUN1[7] = 0x80;  //10000000
    daGUN1[8] = 0xC0;  //11000000
    daGUN1[9] = 0xE0;  //11100000
    daGUN1[10] = 0xF0; //11110000
    daGUN1[11] = 0xF8; //11111000
    daGUN1[12] = 0xFC; //11111100
    daGUN1[13] = 0xFE; //11111110
    daGUN1[14] = 0xFC; //11111100
    daGUN1[15] = 0xF8; //11111000
    daGUN1[16] = 0xF0; //11110000
    daGUN1[17] = 0xE0; //11100000
    daGUN1[18] = 0xC0; //11000000
    daGUN1[19] = 0x80; //10000000
    daGUN1[20] = 0x00; //00000000
    daGUN1[21] = 0x00; //00000000
    daGUN1[22] = 0x00; //00000000
    daGUN1[23] = 0x00; //00000000
    daGUN1[24] = 0x00; //00000000
    daGUN1[25] = 0x00; //00000000
    daGUN1[26] = 0x00; //00000000

    //first lights
    daGUN2[0] = 0x40;  //01000000
    daGUN2[1] = 0x40;  //01000000
    daGUN2[2] = 0x60;  //01100000
    daGUN2[3] = 0x70;  //01110000
    daGUN2[4] = 0x78;  //01111000
    daGUN2[5] = 0x7C;  //01111100
    daGUN2[6] = 0x7E;  //01111110
    daGUN2[7] = 0x7F;  //01111111
    daGUN2[8] = 0x7F;  //01111111
    daGUN2[9] = 0x7F;  //01111111
    daGUN2[10] = 0x7F; //01111111
    daGUN2[11] = 0x7F; //01111111
    daGUN2[12] = 0x7F; //01111111
    daGUN2[13] = 0x7F; //01111111
    daGUN2[14] = 0x7F; //01111111
    daGUN2[15] = 0x7F; //01111111
    daGUN2[16] = 0x7F; //01111111
    daGUN2[17] = 0x7F; //01111111
    daGUN2[18] = 0x7F; //01111111
    daGUN2[19] = 0x7F; //01111111
    daGUN2[20] = 0x7F; //01111111
    daGUN2[21] = 0x7E; //01111110
    daGUN2[22] = 0x7C; //01111100
    daGUN2[23] = 0x78; //01111000
    daGUN2[24] = 0x70; //01110000
    daGUN2[25] = 0x60; //01100000
    daGUN2[26] = 0x40; //01000000

    // 7 led array LEFT
    // 10000000 used for GUN strobe
    daGUNON2[0] = 0xC0;  //11000000
    daGUNON2[1] = 0x20;  //00100000
    daGUNON2[2] = 0x10;  //00010000
    daGUNON2[3] = 0x88;  //10001000
    daGUNON2[4] = 0x04;  //00000100
    daGUNON2[5] = 0x02;  //00000010
    daGUNON2[6] = 0x81;  //10000001
    daGUNON2[7] = 0x01;  //00000001
    daGUNON2[8] = 0x81;  //10000001
    daGUNON2[9] = 0x02;  //00000010
    daGUNON2[10] = 0x84; //10000100
    daGUNON2[11] = 0x08; //00001000
    daGUNON2[12] = 0x10; //00010000
    daGUNON2[13] = 0xA0; //10100000
    daGUNON2[14] = 0x40; //01000000

    // 7 led array
    // 00000001 used for gun strobe
    daGUNON1[0] = 0x02;  //00000010
    daGUNON1[1] = 0x05;  //00000101
    daGUNON1[2] = 0x08;  //00001000
    daGUNON1[3] = 0x11;  //00010001
    daGUNON1[4] = 0x20;  //00100000
    daGUNON1[5] = 0x40;  //01000000
    daGUNON1[6] = 0x81;  //10000001
    daGUNON1[7] = 0x80;  //10000000
    daGUNON1[8] = 0x81;  //10000001
    daGUNON1[9] = 0x40;  //01000000
    daGUNON1[10] = 0x20; //00100000
    daGUNON1[11] = 0x11; //00010001
    daGUNON1[12] = 0x08; //00001000
    daGUNON1[13] = 0x05; //00000101
    daGUNON1[14] = 0x02; //00000010

    // Make input & enable pull-up resistors on switch pins
    for (i=0; i< NUMBUTTONS; i++) {
        pinMode(buttons[i], INPUT);
        digitalWrite(buttons[i], HIGH);
    }

    // Initialise Power cell and gun lights
    digitalWrite(latchPin, 0);
    shiftOut(dataPinPWR, clockPinPWR, 0x00);
    shiftOut(dataPinPWR, clockPinPWR, 0x00);
    shiftOut(dataPinGUN, clockPinGUN, 0x40);
    shiftOut(dataPinGUN, clockPinGUN, 0x00);
    digitalWrite(latchPin, 1);

    //  if (!card.init(true)) { //play with 4 MHz spi if 8MHz isn't working for you
    if (!card.init()) {         //play with 8 MHz spi (default faster!)
        putstring_nl("Card init. failed!");  // Something went wrong, lets print out why
        sdErrorCheck();
        while(1);                            // then 'halt' - do nothing!
    }

    // enable optimize read - some cards may timeout. Disable if you're having problems
    card.partialBlockRead(true);

    // Now we will look for a FAT partition!
    uint8_t part;
    for (part = 0; part < 5; part++) {     // we have up to 5 slots to look in
        if (vol.init(card, part))
            break;                         // we found one, lets bail
    }
    if (part == 5) {                       // if we ended up not finding one  :(
        putstring_nl("No valid FAT partition!");
        sdErrorCheck();      // Something went wrong, lets print out why
        while(1);            // then 'halt' - do nothing!
    }

    /*
    // Lets tell the user about what we found
    putstring("Using partition ");
    Serial.print(part, DEC);
    putstring(", type is FAT");
    Serial.println(vol.fatType(), DEC);     // FAT16 or FAT32?
    */

    // Try to open the root directory
    if (!root.openRoot(vol)) {
        putstring_nl("Can't open root dir!"); // Something went wrong,
        while(1);                             // then 'halt' - do nothing!
    }

    // Whew! We got past the tough parts.
    putstring_nl("Ready!");

    TCCR2A = 0;
    TCCR2B = 1<<CS22 | 1<<CS21 | 1<<CS20;

    //Timer2 Overflow Interrupt Enable
    TIMSK2 |= 1<<TOIE2;
}

void loop() {
    unsigned long currentMillis = millis();
    byte i;
    static int g = 0;
    static int d = 0;
    // Start up power cell
    if (justpressed[0]) {
        justpressed[0] = 0;
	playfile("on.wav");
    }
    // Shut down power cell
    else if (justreleased[0]) {
        justreleased[0] = 0;
        playfile("pwroff.wav");
        // ******************************** powerdown();
        for (int j = 14; j > -1; j--) {
            if (currentMillis - previousMillis_off > off_interval) {
                previousMillis_off = currentMillis;
                // load the light sequence you want from array
    	        dataPWRCL1 = daPWRCL1[j];
    	        dataPWRCL2 = daPWRCL2[j];

                // ground latchPin and hold low for transmitting.
                digitalWrite(latchPin, 0);
                // Send data to 595's.
                shiftOut(dataPinPWR, clockPinPWR, dataPWRCL1);
                shiftOut(dataPinPWR, clockPinPWR, dataPWRCL2);
                // return the latch pin high to signal chip that it
                // no longer needs to listen for information
                digitalWrite(latchPin, 1);
                // ***** delay(30);
            }
        }
        digitalWrite(latchPin, 0);
        shiftOut(dataPinGUN, clockPinGUN, 0x40);
        shiftOut(dataPinGUN, clockPinGUN, 0x00);
        digitalWrite(latchPin, 1);

        digitalWrite(latchPin, LOW);
    }

    // Start up powercell and thrower (gun) lights when the pack is powered on.
    if (pressed[0] == HIGH) {
        for (int j = 0; j < 15; j++) {
            if (currentMillis - previousMillis_on > pwrcl_interval) {
                // save the last time you blinked the LED
                previousMillis_on = currentMillis;
                //load the light sequence you want from array
      	        dataPWRCL1 = daPWRCL1[j];
      	        dataPWRCL2 = daPWRCL2[j];

                // THIS WILL SET GUN ARRAY TO HOW EVER MANY YOU HAVE IN YOUR ARRAY
    	        if (g > 25) {
                    g = 0;
                }
    	        dataGUN1 = daGUN1[g];
    	        dataGUN2 = daGUN2[g];
    	        g++;

    	        //ground latchPin and hold low for as long as you are transmitting
                digitalWrite(latchPin, 0);
    	        //move 'em out
    	        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL1);
    	        shiftOut(dataPinPWR, clockPinPWR, dataPWRCL2);
    	        shiftOut(dataPinGUN, clockPinGUN, dataGUN2);
    	        shiftOut(dataPinGUN, clockPinGUN, dataGUN1);
    	        //return the latch pin high to signal chip that it
    	        //no longer needs to listen for information
                digitalWrite(latchPin, 1);
    	        // ***** delay(60);
            }
        }
    }

    // Thrower activation - checks if gun is ON if not it will not do anything.
    if (pressed[0] == HIGH) {
        // if the fire button is pressed
        if (pressed[1]) {
            playfile("gun2.wav");
          	while (wave.isplaying && pressed[1]) {
                    for (int j = 0; j < 15; j++) {
                        if (currentMillis - previousMillis_fire > firing_interval) {
                            previousMillis_fire = currentMillis;
              	            //load the light sequence you want from array
              		    dataPWRCL1 = daPWRCL1[j];
        		    dataPWRCL2 = daPWRCL2[j];
        		    dataGUNON1 = daGUNON1[j];
        		    dataGUNON2 = daGUNON2[j];
        		    //ground latchPin and hold low for as long as you are transmitting
        		    digitalWrite(latchPin, 0);
        		    //move 'em out
        		    shiftOut(dataPinPWR, clockPinPWR, dataPWRCL1);
        		    shiftOut(dataPinPWR, clockPinPWR, dataPWRCL2);
        		    shiftOut(dataPinGUN, clockPinGUN, dataGUNON2);
        		    shiftOut(dataPinGUN, clockPinGUN, dataGUNON1);

        		    //return the latch pin high to signal chip that it
        		    //no longer needs to listen for information
        		    digitalWrite(latchPin, 1);
        		    // ***** delay(40);
                        }
                    }
                }
            wave.stop();
        }
        //play power down file
        else if (justreleased[1]) {
            justreleased[1] = 0;
    	    playfile("off.wav");
        }
    }
    else {
        // Gun is not on
    }

    //count and increment X. this will play music and you can hit the button to go to the next song.
    static int x = 0;
    if (justpressed[2]) {
        x++;
        if (x == 1) {
            justpressed[2] = 0;
	    playfile("1.wav");
        }
        if (x == 2) {
            justpressed[2] = 0;
    	    playfile("2.wav");
        }
        if (x == 3) {
            justpressed[2] = 0;
    	    playfile("3.wav");
        }
        if (x == 4) {
    	    justpressed[2] = 0;
    	    playfile("4.wav");
        }
        if (x == 5) {
            justpressed[2] = 0;
    	    playfile("5.wav");
        }
        if (x == 6) {
            justpressed[2] = 0;
    	    playfile("6.wav");
    	    x = 0;
        }
    }
}

// this handy function will return the number of bytes currently free in RAM, great for debugging!
void sdErrorCheck(void) {
  if (!card.errorCode()) return;
      putstring("\n\rSD I/O error: ");
      Serial.print(card.errorCode(), HEX);
      putstring(", ");
      Serial.println(card.errorData(), HEX);
      while(1);
}

// Plays a full file from beginning to end with no pause.
void playcomplete(char *name) {
    // call our helper to find and play this name
    playfile(name);
    while (wave.isplaying) {
        // do nothing while its playing
    }
    // now its done playing
}

void playfile(char *name) {
    // see if the wave object is currently doing something
    if (wave.isplaying) {// already playing something, so stop it!
        wave.stop(); // stop it
    }
    // look in the root directory and open the file
    if (!f.open(root, name)) {
        putstring("Couldn't open file ");
        Serial.print(name);
        return;
    }
    // OK read the file and turn it into a wave object
    if (!wave.create(f)) {
        putstring_nl("Not a valid WAV");
        return;
    }

    // ok time to play! start playback
    wave.play();
}

// Power-down light sequence.
void powerdown() {
}

// the heart of the program
void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {
    // This shifts 8 bits out MSB first,
    // on the rising edge of the clock,
    // clock idles low

    // internal function setup
    int i = 0;
    int pinState;
    pinMode(myClockPin, OUTPUT);
    pinMode(myDataPin, OUTPUT);

    //clear everything out just in case to
    //prepare shift register for bit shifting
    digitalWrite(myDataPin, 0);
    digitalWrite(myClockPin, 0);

    //for each bit in the byte myDataOut?
    //NOTICE THAT WE ARE COUNTING DOWN in our for loop
    //This means that %00000001 or "1" will go through such
    //that it will be pin Q0 that lights.
    for (i = 7; i >= 0; i--)  {
        digitalWrite(myClockPin, 0);

        //if the value passed to myDataOut and a bitmask result
        // true then... so if we are at i=6 and our value is
        // %11010100 it would the code compares it to %01000000
        // and proceeds to set pinState to 1.
        if ( myDataOut & (1 << i) ) {
            pinState = 1;
        }
        else {
            pinState = 0;
        }

        //Sets the pin to HIGH or LOW depending on pinState
        digitalWrite(myDataPin, pinState);
        //register shifts bits on upstroke of clock pin
        digitalWrite(myClockPin, 1);
        //zero the data pin after shift to prevent bleed through
        digitalWrite(myDataPin, 0);
    }
    //stop shifting
    digitalWrite(myClockPin, 0);
}

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


testing minute calc

testing minute calc

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/janiversen/SolarPower.git/'