title: Want criticism on my code

text:
# Question
Title: Want criticism on my code
The code is controlling 3 blinds. There are 2 buttons for each blind for going each way and 2 buttons controlling all of them at the same time. The motorSerial is a way to control all of the blinds through the serial monitor where sending 1 goes one way and 2 the other way.

What I'm most concerned about is when pressing a button, it turns on the motor, waits for 0.2 seconds and turns the off. But if I'm holding the button down it will continuously keep turning it on and off. Does anyone have a better way of doing this?

```
const int PWMA = 13;
const int AI2_left = 12;
const int AI1_left = 11;
const int PWMB = 18;
const int BI1_middle = 10;
const int BI2_middle = 9;

const int PWMA2 = 8;
const int AI2_right = 7;
const int AI1_right = 6;

const int greenLeft1 = 5;
const int greenLeft2 = 4;
const int redMiddle1 = 3;
const int redMiddle2 = 2;
const int yellowRight1 = 14;
const int yellowRight2 = 15;
const int blueAll1 = 16;
const int blueAll2 = 17;

int motorSpeed_left = 0;
int motorSpeed_middle = 0;
int motorSpeed_right = 0;
int motorSpeed_all = 0;
int motorSerial = 0;

void setup() {
  pinMode(PWMA, OUTPUT);
  pinMode(AI2_left, OUTPUT);
  pinMode(AI1_left, OUTPUT);
  pinMode(BI1_middle, OUTPUT);
  pinMode(BI2_middle, OUTPUT);
  pinMode(PWMA2, OUTPUT);
  pinMode(AI2_right, OUTPUT);
  pinMode(AI1_right, OUTPUT);

  pinMode(greenLeft1, INPUT_PULLUP);
  pinMode(greenLeft2, INPUT_PULLUP);
  pinMode(redMiddle1, INPUT_PULLUP);
  pinMode(redMiddle2, INPUT_PULLUP);
  pinMode(yellowRight1, INPUT_PULLUP);
  pinMode(yellowRight2, INPUT_PULLUP);
  pinMode(blueAll1, INPUT_PULLUP);
  pinMode(blueAll2, INPUT_PULLUP);

  Serial.begin(9600);
}

void loop() {

  if(Serial.available() > 0) {
    motorSerial = Serial.parseInt();
  }

  if(digitalRead(greenLeft1) == LOW) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
  }
  else if(digitalRead(greenLeft2) == LOW) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
  }
  else if(digitalRead(redMiddle1) == LOW) {
    motorSpeed_middle = 200;
    spinMotor_middle(motorSpeed_middle);
    delay(200);
    motorSpeed_middle = 0;
    spinMotor_middle(motorSpeed_middle);
  }
  else if(digitalRead(redMiddle2) == LOW) {
    motorSpeed_middle = -200;
    spinMotor_middle(motorSpeed_middle);
    delay(200);
    motorSpeed_middle = 0;
    spinMotor_middle(motorSpeed_middle);
  }
  else if(digitalRead(yellowRight1) == LOW) {
    motorSpeed_right = 200;
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_right = 0;
    spinMotor_right(motorSpeed_right);
  }
  else if(digitalRead(yellowRight2) == LOW) {
    motorSpeed_right = -200;
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_right = 0;
    spinMotor_right(motorSpeed_right);
  }
  else if(digitalRead(blueAll1) == LOW) {
    motorSpeed_left = 200;
    motorSpeed_middle = 200;
    motorSpeed_right = 200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
  }
  else if(digitalRead(blueAll2) == LOW) {
    motorSpeed_left = -200;
    motorSpeed_middle = -200;
    motorSpeed_right = -200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(200);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
  }
  else if(motorSerial == 1) {
    motorSpeed_left = 200;
    motorSpeed_middle = 200;
    motorSpeed_right = 200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(2500);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    motorSerial = 0;
  }
  else if(motorSerial == 2) {
    motorSpeed_left = -200;
    motorSpeed_middle = -200;
    motorSpeed_right = -200;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    delay(2500);
    motorSpeed_left = 0;
    motorSpeed_middle = 0;
    motorSpeed_right = 0;
    spinMotor_left(motorSpeed_left);
    spinMotor_middle(motorSpeed_middle);
    spinMotor_right(motorSpeed_right);
    motorSerial = 0;
  }

}

/*****************************************************/
void spinMotor_left(int motorSpeed_left)
{
  if (motorSpeed_left > 0)
  {
    digitalWrite(AI1_left, HIGH);
    digitalWrite(AI2_left, LOW);
  }
  else if (motorSpeed_left < 0)
  {
    digitalWrite(AI1_left, LOW);
    digitalWrite(AI2_left, HIGH);
  }
  else
  {
    digitalWrite(AI1_left, LOW);
    digitalWrite(AI2_left, LOW);
  }
  analogWrite(PWMA, abs(motorSpeed_left));
}

void spinMotor_middle(int motorSpeed_middle)
{
  if (motorSpeed_middle > 0)
  {
    digitalWrite(BI1_middle, HIGH);
    digitalWrite(BI2_middle, LOW);
  }
  else if (motorSpeed_middle < 0)
  {
    digitalWrite(BI1_middle, LOW);
    digitalWrite(BI2_middle, HIGH);
  }
  else
  {
    digitalWrite(BI1_middle, LOW);
    digitalWrite(BI2_middle, LOW);
  }
  analogWrite(PWMB, abs(motorSpeed_middle));
}

void spinMotor_right(int motorSpeed_right)
{
  if (motorSpeed_right > 0)
  {
    digitalWrite(AI1_right, HIGH);
    digitalWrite(AI2_right, LOW);
  }
  else if (motorSpeed_right < 0)
  {
    digitalWrite(AI1_right, LOW);
    digitalWrite(AI2_right, HIGH);
  }
  else
  {
    digitalWrite(AI1_right, LOW);
    digitalWrite(AI2_right, LOW);
  }
  analogWrite(PWMA2, abs(motorSpeed_right));
}

```

# Answer
> 0 votes
ratchet freak's long answer has many good points. I would also agree with Code Gorilla's suggestion to add a constructor to the `struct`. However, once you have a constructor, it pretty much looks like a regular C++ class¹, so it would make sense to add the motor-related functions as members of the class. Thus I would start by building a class that abstracts out the details of driving the motors:

```
class Motor {
public:
    Motor(uint8_t pin_1, uint8_t pin_2, uint8_t pin_pwm)
    : pin_1(pin_1), pin_2(pin_2), pin_pwm(pin_pwm) {}

    void begin() {
        pinMode(pin_1, OUTPUT);
        pinMode(pin_2, OUTPUT);
        pinMode(pin_pwm, OUTPUT);
    }

    void spin(int speed) {
        digitalWrite(pin_1, speed > 0 ? HIGH : LOW);
        digitalWrite(pin_2, speed < 0 ? HIGH : LOW);
        analogWrite(pin_pwm, abs(speed));
    }

private:
    const uint8_t pin_1, pin_2, pin_pwm;
};

```

I have left the buttons out of the class, because you have those blue “all motors” buttons that do not fit well with the notion that each button “belongs” to a particular motor.

Then, I would use some other abstraction for representing the buttons. Maybe from a debouncing library. If button bounces are not problematic in this application, then the “abstraction” would simply be:

```
// Is that button pressed?
static inline bool pressed(uint8_t pin) {
    return digitalRead(pin) == LOW;
}

```

Of course, as an abstraction, this does not provide a lot of value. It can be seen as a small bit of “syntactic sugar” that makes writing (and reading) the rest of the code easier.

With those in place, the program would look like:

```
// Pinout.
const uint8_t left_1   = 5;
const uint8_t left_2   = 4;
const uint8_t middle_1 = 3;
const uint8_t middle_2 = 2;
const uint8_t right_1  = 14;
const uint8_t right_2  = 15;
const uint8_t all_1    = 16;
const uint8_t all_2    = 17;
const int button_count = 8;
const uint8_t buttons[button_count] = {
    left_1, left_2, middle_1, middle_2, right_1, right_2, all_1, all_2
};

// Motors.
const int SPEED = 200;
Motor motor_left(11, 12, 13);
Motor motor_middle(10, 9, 18);
Motor motor_right(6, 7, 8);

void setup() {
    motor_left.begin();
    motor_middle.begin();
    motor_right.begin();
    for (int i = 0; i < button_count; i++)
        pinMode(buttons[i], INPUT_PULLUP);
    Serial.begin(9600);
}

void loop() {
    // Read the serial command, if any.
    int serial_command = Serial.read();  // is -1 if there is no input
    bool serial_1 = serial_command == '1',  // serial request for '1'
         serial_2 = serial_command == '2';  // serial request for '2'

    // Operate the motors.
    if      (pressed(left_1))   motor_left.spin(SPEED);
    else if (pressed(left_2))   motor_left.spin(-SPEED);
    else if (pressed(middle_1)) motor_middle.spin(SPEED);
    else if (pressed(middle_2)) motor_middle.spin(-SPEED);
    else if (pressed(right_1))  motor_right.spin(SPEED);
    else if (pressed(right_2))  motor_right.spin(-SPEED);
    else if (pressed(all_1) || serial_1) {
        motor_left.spin(SPEED);
        motor_middle.spin(SPEED);
        motor_right.spin(SPEED);
        if (serial_1) delay(2500);
    } else if (pressed(all_2) || serial_2) {
        motor_left.spin(-SPEED);
        motor_middle.spin(-SPEED);
        motor_right.spin(-SPEED);
        if (serial_2) delay(2500);
    } else {
        motor_left.spin(0);
        motor_middle.spin(0);
        motor_right.spin(0);
    }
}

```

¹ The `struct` keyword in C++ actually declares a class.

# Answer
> 3 votes
```
if(digitalRead(greenLeft1) == LOW) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}
else if(digitalRead(greenLeft2) == LOW) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
    delay(200);
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}

```

Doesn't quite do what you want it to do.

Instead you want something like:

```
if(digitalRead(greenLeft1) == LOW) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);

} else if(digitalRead(greenLeft2) == LOW) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
} else {
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}

```

However because you also want a master switch and control through serial. You can pull out the tests on each button to a variable and then make the master switch override those:

```
int motor_left = 0;
if(digitalRead(greenLeft1) == LOW) {
    motor_left = 1;
} else if(digitalRead(greenLeft2) == LOW) {
    motor_left = -1;
} else {
    motor_left = 0;
}

//...

if(digitalRead(blueAll1) == LOW){
    motor_left   = 1;
    motor_center = 1;
    motor_right  = 1;
} else if(digitalRead(greenLeft2) == LOW) {
    motor_left   = -1;
    motor_center = -1;
    motor_right  = -1;
}

if(motor_left > 0) {
    motorSpeed_left = 200;
    spinMotor_left(motorSpeed_left);

} else if(motor_left < 0) {
    motorSpeed_left = -200;
    spinMotor_left(motorSpeed_left);
} else {
    motorSpeed_left = 0;
    spinMotor_left(motorSpeed_left);
}

```

Also the pin number is just and `int` so you can pull those out as a parameter as well and have only one copy of the `spinMotor` function.

```
void spinMotor(int motor_pin1, int motor_pin2, int motorSpeed)
{
  if (motorSpeed > 0)
  {
    digitalWrite(motor_pin1, HIGH);
    digitalWrite(motor_pin2, LOW);
  }
  else if (motorSpeed < 0)
  {
    digitalWrite(motor_pin1, LOW);
    digitalWrite(motor_pin2, HIGH);
  }
  else
  {
    digitalWrite(motor_pin1, LOW);
    digitalWrite(motor_pin2, LOW);
  }
  analogWrite(PWMA, abs(motorSpeed));
}

```

To reduce the number of globals you can group the state for each motor into a struct and initialize them in `init()`:

```
struct motorState {
   int motor_pin1, motor_pin2;
   int pwm_pin;
   int button1, button2;
   int direction;
   int speed;
}

motorState motor_left;
motorState motor_center;
motorState motor_right;

```

then pass the globals by pointer or ref to the functions doing the input and output.

```
void readMotorButton(motorState *motor){
    if(digitalRead(motor->button1) == LOW) {
        motor->direction = 1;
        motor->speed = 200;
    } else if(digitalRead(motor->button2) == LOW) {
        motor->direction = -1;
        motor->speed = 200;
    } else {
        motor->direction = 0;
        motor->speed = 0;
    }
}

void spinMotor(motorState *motor)
{
  if (motor->direction > 0)
  {
    digitalWrite(motor->motor_pin1, HIGH);
    digitalWrite(motor->motor_pin2, LOW);
  }
  else if (motor->direction < 0)
  {
    digitalWrite(motor->motor_pin1, LOW);
    digitalWrite(motor->motor_pin2, HIGH);
  }
  else
  {
    digitalWrite(motor->motor_pin1, LOW);
    digitalWrite(motor->motor_pin2, LOW);
  }
  analogWrite(motor->pwm_pin, abs(motor->speed));
}

```

# Answer
> 2 votes
There is a code review group on here where you will get a more generic code review if you want.

First thing I noticed is there are no comments. You have written a paragraph explaining what the code does, but that should be in the code where you will be able to read it when you find the code 12 months down the line.

Rachet Freak has covered loads of good points, but one point I would disagree with is passing globals to functions using pointers. I would use references instead, the only reason for this is IF you mess up references can't be NULL, so you don't need to check within the function to see if they are NULL. Of course it will never happen, you never pass a NULL pointer to one of these functions, but as you code grows in size the chances of you doing that will increase and should you ever write a library, the chances of someone else passing a NULL pointer to your library is very high, and then you have got "a problem in your library".

Moving on from that if the parameter's value will not be modified during the life of a function pass it in as a `const` reference. The main reason for this is it explains to the reader that the value won't change in the function, its a simple way of documenting your intention without having to write a comment. So

```
void spinMotor(int motor_pin1, int motor_pin2, int motorSpeed){...}

```

would become

```
void spinMotor(const int& motor_pin1, const int& motor_pin2, const int& motorSpeed) {...}

```

Personally I would always add a constructor to structures. This way you know that every field has the correct value to start with. (I believe the Arduino compiler will initialise everything, but not all compilers are so kind.) Also it allows you to write neater code, i.e.

```
struct motorState {
   int motor_pin1;
   int motor_pin2;
   int button1;
   int button2;
   int direction;

  // Parameterised constructor can be called either:
  //    motorState mState;
  //    motorState mState2 = motorState (2, 3, 4, 5, -1);
  motorState (const int& pin1 = 5, const int& pin2 = 6, const int& b1 = 7, const int& b2 = 8, const int& dir = 1)
  : motor_pin1(pin1)
  , motor_pin2(pin2)
  , button1(b1)
  , button2(b2)
  , direction(dir)
{}

```

}

Finally, I have always been told to never put two declarations on the same line.

```
int motor_pin1, motor_pin2;

```

There is no difference between the above and this as far as the compiler is concerned.

```
int motor_pin1;
int motor_pin2;

```

It is purely for readability you don't realise you are doing it, taking longer to read the first case than the second because your brain is more attuned to seeing a type, variable name and optional value.

```
int
motor_pin1,
motor_pin2;

```

The above is legal, but what type in `motor_pin2`? It is just a convention that is widely used and makes code easier to read, even though it is harder to write, in the same way that code has to be indented by 4 spaces on here. If it isn't indented it has the same text, but is virtually unreadable.

Finally, if you find yourself copy and pasting lines, it should probably be a function or an array or both.

---
Tags: arduino-ide, motor
---


# Question
Title: USB reset fails on arduino due because of 5v on digital pins
I have the signal channels of four 5v magnetic encoders connected directly to the digital pins of the arduino due. I am aware that this is not allowed according to the specification which says that digital pins should only sink 3.3v but I have not encountered many problems with this setup until now and the encoders only sink 20mA.

This is the setup of one of the encoders, I only encounter the following problem only if I connect more than 2 encoders in this formation

The Due resets fine when I press the reset button, but when I reconnect USB, the Due crashes and is not able to run any code (tested a blink sketch).

I cannot change any of the circuitry because it is already in multiple PCBs. Does anybody have an idea why the 5v on the 3.3v tolerant pins is causing the reset over usb to fail and how I could fix this in software? It must be fixable in software as the arduino IDE manages to upload sketches while the encoders are connected. I tried to reset over USB by connecting with 1200 baud and setting DTR but that didnt work.

Thanks so much in advance, I hope my question was clear.

edit: I am aware I am doing things wrong here and that that is whats causing the issue. The problem is we soldered 20+ of those PCBs and I cannot simply make modifications, even simple ones. I am looking for ideas on how to hotfix something in software that I messed up in hardware.

edit edit: Honestly kinda disappointed with the hostility on here, am I being downvoted simply because I made mistake with the specification and am trying to find a workaround? I dont see how that makes it a bad question.

# Answer
You're over-stressing the MCU and causing all sorts of horrible things to happen with the power rails. Of course nasty things are going to happen.

The only way to fix it is to change the circuitry. Something as simple as adding a 1kΩ resistor in series with each of the input connections could be enough to sort it out.
> 4 votes

---
Tags: power, usb, arduino-due, digital-in
---


# Question
Title: Need lot GPIO pins on arduino mega - what are restrictions?
I would like to use as much as possible GPIO pins on Arduino Mega especially with (mis)using `pinMode(x,INPUT);` and `pinMode(x,INPUT_PULLUP);` to achieve two things at the same time - drive something else by the pin weakly down or up and measure the logical level there with `digitalRead(x)` to detemine, if that "something else" is input, or outputting some logical level.

Also I need I2C, Serial over USB and nothing else.

On Arduino UNO/nano/micro/pro it works just fine for Digital pins (except D0/D1 (RX/TX), D13 (LED as strong pull-down), A4/A5 (I2C) and A6/A7 which are not digital IO). The problem is limited number of pins, so I bought **ArduinoMega**.

**The question is** \- which pins can be used that way there? So far I am aware of D0/D1 (RX/TX), D20/D21 (I2C) and D13 (LED). The rest (D2-D12, D14-D19, D22-D52 and A0-A15) seem aviable and usable. Or I am missing something else?

Are there some libraries/objects I should disable to not interfere with my script?

Thank you.

# Answer
> 3 votes
All those pins should be available. But if you want to use Pin change interrupts, you have to check which pins are usable.

---
Tags: arduino-mega, pins
---


# Question
Title: 3rd Libraries: fatal error: Something.h: File does not exist
> I created this question because I find many questions with similar problems, so I wanted to provide a reference/ more generic question for these type of problems.

For my projects I have installed 3rd party libraries by cloning from the library's git repository into the folder that `preferences.txt`'s `sketchbook.path` value exists into a folder named `libraries`. In other words if the `sketchbook.path` has the value `/home/myuser/sketchbook` I clone the repositories into the folder `/home/myuser/sketchbook/libraries`.

Then on the folder `/home/myuser/sketchbook/myexample` I store my code `myexample.ino` that needs a library with header files `Something.h`.

While I click on Arduino IDE the verify button I get the error:

```
/usr/share/arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -Wall -fno-exceptions
    -ffunction-sections -fdata-sections -mmcu=atmega328p -DF_CPU=16000000L -MMD
    -DUSB_VID=null -DUSB_PID=null -DARDUINO=105 -D__PROG_TYPES_COMPAT__
    -I/usr/share/arduino/hardware/arduino/cores/arduino
    -I/usr/share/arduino/hardware/arduino/variants/standard
    -I/usr/share/arduino/libraries/SPI
    /tmp/build6596169359663087897.tmp/LoRaSerialGateway.cpp -o
    /tmp/build6596169359663087897.tmp/LoRaSerialGateway.cpp.o
LoRaSerialGateway.ino:15:18: fatal error: Something.h:
compilation terminated.

```

So my guess is that I cannot make avr-gcc to compile using the 3rd party library. Do you know how to pass into avr-gcc the correct paths for the appropriate libraries?

# Answer
> 1 votes
Assuming you have a working library system already, i.e., there are some libraries in `.../libraries` now and they compile properly or at least the compiler are successfully finds them; and you want to add another library, say "CrashAndBurn.h" and "CrashAndBurn.cpp", you need to put those two files into a folder named `.../libraries/CrashAndBurn/`. Then in your sketch, you add an include directive `#include <CrashAndBurn.h>`.

An alternative is to put the .h and .cpp files somewhere else, such as a folder under your project folder, and modify the include directive to point to them, as `#include "libs/CrashAndBurn.h"`, where the libs folder is within the sketch folder. Or you could put them in any folder, anywhere, and write an absolute path to them: `/home/some/place/else/CrashAndBurn.h`

# Answer
> 1 votes
Sometimes you should modify a bit the library's file stricture in case of this library in order to make it avaialble I moved the code in folder `./src` **outside** to the **project's** root folder.

Also an another problem is that you may use older version of the ide. Especially this can happen in GNU/Linux if you install the arduino ide from the distribution's repositories.

---
Tags: arduino-ide, library
---


title: Program doesn't read memory well

text:
# Question
Title: Program doesn't read memory well
My program does not read the contents of the memory card, in this case the file "objects.txt". What I wanted to do was: the program reads the objects contained in the text file and allocates the table, then organizes the table alphabetically.

Something is escaping me. Another thing, how do I put a function recognizing if the user pressed a button and if pressed, the program continues?

```
#include <LiquidCrystal.h>
#include <SPI.h>
#include <SD.h>

LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// define some values used by the panel and buttons
int lcd_key     = 0;
int adc_key_in  = 0;
int x = 0;
String files, memo, memo1;
int sizef = 0;
int sizef1 = 0;
int sizef2 = 0;
int y = 0;
int z = 0;

struct objeto_celeste_s {
  char nome[20];
  float ar;
  float dec;
};
typedef struct objeto_celeste_s objeto_celeste;

char * tab1 [6];
int myCompareFunction (const void * arg1, const void * arg2) {
  return strcmp (*(char **) arg1, *(char **) arg2);
}

File root;
File file;

#define btnRIGHT  0
#define btnUP     1
#define btnDOWN   2
#define btnLEFT   3
#define btnSELECT 4
#define btnNONE   5

char * list[] = {"1.Modo Normal    ", "2.Modo Teste    ", "3.Modo GoTo     ", "4.Modo Manual  "};

// read the buttons
int read_LCD_buttons() {
  adc_key_in = analogRead(0);
  if (adc_key_in > 1000) return btnNONE;
  if (adc_key_in < 50)   return btnRIGHT;
  if (adc_key_in < 250)  return btnUP;
  if (adc_key_in < 400)  return btnDOWN;
  if (adc_key_in < 450)  return btnLEFT;
  if (adc_key_in < 650)  return btnSELECT;
  return btnNONE; // when all others fail, return this...
}

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
  Serial.println ("Welcome!");
  Serial.println ("Selecione um modo no lcd.");
  lcd.begin (16, 2);
  lcd.setCursor (0, 0);
  lcd.print ("  Selecione um");
  lcd.setCursor (0, 1);
  lcd.print ("      modo    ");
  delay (1000);
  lcd.clear ();
  lcd.setCursor(0, 0);
  lcd.print(">");
  lcd.println(list[0]);
  lcd.setCursor(0, 1);
  lcd.print (" ");
  lcd.println(list[1]);
  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    while (1);
  }
}

void loop() {
  lcd_key = read_LCD_buttons();  // read the buttons
  switch (lcd_key) {
    // depending on which button was pushed, we perform an action
    case btnRIGHT:
      break;
    case btnLEFT:
      break;
    case btnUP:
      if (x == 1) {
        x--;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[0]);
        lcd.setCursor(0, 1);
        lcd.print (" ");
        lcd.println(list[1]);
      }
      break;
      if (x == 3) {
        x--;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[2]);
        lcd.setCursor(0, 1);
        lcd.print (" ");
        lcd.println(list[3]);
      }
      break;
    case btnDOWN:
      if (x == 0) {
        x++;
        lcd.clear();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[1]);
        lcd.setCursor(0, 1);
        lcd.println("                ");
      }
      break;
      if (x == 2) {
        x++;
        lcd.clear ();
        lcd.setCursor(0, 0);
        lcd.print(">");
        lcd.println(list[3]);
        lcd.setCursor(0, 1);
        lcd.println("                ");
      }
      break;
    case btnSELECT:
      if (x == 0) {
        lcd.clear ();
        lcd.print ("Modo Normal");
        Serial.println ("Selecionou o modo normal!");
        delay (1000);
        if (SD.exists("objectos.txt")) {
          Serial.println("O ficheiro 'objetos' foi encontrado!");
          lcd.clear ();
          lcd.setCursor (0, 0);
          lcd.print ("Modo Normal");
          delay (1000);
          file = SD.open("objectos.txt", FILE_READ);
          if (file) {
            while (file.available()) {
              String line = file.readStringUntil('\n');
              sizef++;
            }
          } else {
            //se houver erro a abrir o ficheiro
            Serial.println("Erro a abrir o ficheiro 'objectos.txt'.");
          }
          objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
          Serial.print ("Contados ");
          Serial.print (sizef);
          Serial.println (" objetos no ficheiro objectos.txt.");
          if (tab == NULL) {
            lcd.clear ();
            lcd.print ("Erro a alocar memoria");
            Serial.println ("Erro a alocar memória");
            while (1) { };
          } else {
            Serial.print ("Memória alocada para ");
            Serial.print (sizef);
            Serial.println (" objectos.");
            lcd.setCursor (0, 1);
            lcd.print ("Alocados ");
            lcd.print (sizef);
            lcd.print (" obj");
          }
          file.close();
          char * line1 = (char*) malloc(15);
          file = SD.open("objectos.txt", FILE_READ);
          if (file) {
            Serial.println ("Carregando informação para a memória:");
            while (file.available()) {
              if (file.read() == '\n') {
                char * justafun = strtok (line1, " "); //divide em tokens
                while (justafun != NULL) {
                  if (y == 0) {
                    strcpy (tab[sizef2].nome, justafun);
                    Serial.print ("[");
                    Serial.print (sizef2);
                    Serial.print ("] ");
                    Serial.print(tab[sizef2].nome);
                    Serial.print (" ");
                    y++;
                  }
                  if (y == 1) {
                    tab[sizef2].ar = atof (justafun);
                    Serial.print (tab[sizef2].ar);
                    Serial.print (" ");
                    y++;
                  }
                  if (y == 2) {
                    tab[sizef2].dec = atof (justafun);
                    Serial.println (tab[sizef2].dec);
                    sizef2++;
                    y = 0;
                  }
                  justafun = strtok (NULL, " ");
                }
              }
            }
          }
          file.close ();
          delay (1500);
          lcd.clear ();
          Serial.println ("Proceda ao alinhamento manual do telescópio.");
          lcd.setCursor (0, 0);
          lcd.print ("Proceda ao ");
          lcd.setCursor (0, 1);
          lcd.print ("Alinhamento man.");
          Serial.println ("Depois de o alinhamento estar concluido, pressione o botão Select para prosseguir o programa.");
          //colocar aqui função para reconhecer quando pressiona select
          if (Serial1.available()) {
            int inByte = "V"; //Se o alinhamento está concluido, 0 para não e 1 para sim
            Serial1.write (inByte);
          }
          while (!Serial1) {
            if (Serial1.available()) {
              int inByte = "V";
              Serial1.write (inByte);
              int inByte1 = "e";
              Serial1.write (inByte1);
            }
          }
          delay (1000);
          Serial.println ("Tabela ordenada alfabeticamente:");
          qsort (tab->nome, sizef, sizeof (char *), myCompareFunction);
          for (int i = 0; i < sizef; i++)
            Serial.println (tab[i].nome);
          delay (1000);
          lcd.clear ();
          lcd.print ("Carregue Select");
          lcd.setCursor (0, 1);
          lcd.print ("Para modo manual");
          Serial.println ("Carregue em Select para ir para o modo manual e assim continuar com o programa.");
        } else {
          Serial.println ("O ficheiro 'objetos' não existe.");
          lcd.clear ();
          lcd.print ("Erro nao encontrado");
          delay (2000);
          while (1) { };
        }
      }
      if (x == 1) {
        lcd.clear ();
        lcd.print ("Modo Teste");
        Serial.println ("Selecionou o modo teste!");
        delay (2000);
        if (SD.exists("teste.txt")) {
          Serial.println("O ficheiro 'teste.txt' foi encontrado!");
          lcd.clear ();
          lcd.setCursor (0, 0);
          lcd.print ("Modo Teste");
          lcd.setCursor (0, 1);
          lcd.print ("Ficheiro encontrado");
          delay (2000);
          file = SD.open("teste.txt", FILE_READ);
          if (file) {
            while (file.available()) {//ler o ficheiro
              String line = file.readStringUntil('\n');
              sizef++;
            }
            files = "Contados " + String (sizef) + " objetos no ficheiro teste.txt.";
            Serial.println (files);
            objeto_celeste *tab = (objeto_celeste *)malloc((sizef) * sizeof(objeto_celeste));
            memo = "Alocados " + String (sizef) + " obj  ";
            memo1 = "Memória alocada para " + String (sizef) + " objetos.";
            if (tab == NULL) {
              lcd.clear ();
              lcd.print ("Erro alocar memoria");
              Serial.println ("Erro a alocar memória");
              while (1) { };
            } else {
              Serial.println (memo1);
              lcd.setCursor (0, 1);
              lcd.print (memo);
            }
            file.close();
          } else {
            //se houver erro a abrir o ficheiro
            Serial.println("Erro a abrir o ficheiro 'teste.txt'.");
          }
        } else {
          Serial.println ("O ficheiro 'teste.txt' não foi encontrado.");
          lcd.clear ();
          lcd.print ("Erro nao encontrado");
          delay (2000);
          while (1) { };
        }
      }
      break;
    case btnNONE:
      break;
  }
  delay (200);
}

```

# Answer
> 1 votes
I would say you can't add a button that restarts/continues the program. Because of all the `delay(...)` in your code. The arduino chip cant read your input and your button, while it is in a delay mode and hence no reading from the button. Read more about**non-blocking delay**

You need to keep the main `loop` method ongoing so the microcontroller-cpu can do it's work. Instead of waiting in a `delay` loop, doing nothing.

So don't use any `delay`, they are good for beginner to jump start into Arduino.

---
Tags: programming
---


title: How do I merge two programs in Arduino?

text:
# Question
Title: How do I merge two programs in Arduino?
So I have an esp8266 nodemcu which I flashed a program called Deauther 2.0. I spent the past two hours trying to merge another Sketch. Which I failed miserably.

What I am trying to achieve:

When I first power up my nodemcu it should load the Deauther program. But when I press the built in flash button it should load the second sketch.

What I have tried to fix the problem:

1. Add my own clock.cpp to the Deauther sketch and edited the top part of the sketch:

```
const int button = 0;

int temp = 0;

 void setup() {

 pinMode(button, INPUT)

 }

 void loop() {

 temp = digitalRead(button)

 if (temp == HIGH ) {

 // run the code below

}

```
2. Some other stuff which I don't want to mention.

Any ideas on how to fix this?

Thanks!

# Answer
> 2 votes
To be able to merge the sketches you must ensure that both will not try to access the same pins/resource in ways that are incompatible. For example if both need to input from serial you will need to adjust things so the input you send it will reach the correct code.

Once you have made sure of that it is often simplest to first refactor both sketches to avoid any type of delay-like code or anything that halts execution while waiting for something to happen and instead go with state-machine based that just loops constantly and uses timestamps to manage when to actually do stuff.

For example the second sketch has the format:

```
void loop(){
    //do stuff

    delay(1000);
}

```

You should refactor that to

```
unsigned long last_run = 0;

void loop(){
    unsigned long current_millis = millis();
    if(current_millis - last_run > 1000){
        last_run = current_millis;
        //do stuff that never blocks

    }
}

```

Once that is complete and you made sure there is no name conflict between the sketches for the functions/globals you can simply append the `loop()` and `setup()` functions into a new `loop()` and `setup()`

---
Tags: nodemcu
---


# Question
Title: Looking for a sensor that measures heart/pulse rate
I am looking for a sensor which is able to measure heart/pulse rate. Apart from the common pulse sensor from here, are there any others?

I have seen people recommending this as well, and it seems more accurate. Should I get the piezo vibration sensor or are there better sensors? Hoping for something that is easy to use (Like the pulse sensor where you can just place your finger onto the sensor)

Cross-post from: https://www.reddit.com/r/arduino/comments/8f051k/looking\_for\_a\_sensor\_which\_measures\_heartpulse/ and https://forum.arduino.cc/index.php?topic=543857.0

# Answer
> 3 votes
The commonly used approach is to use an infrared source and sensor pressed against the skin. Usually the finger tip is all that is needed. In addition to pulse, many have also incorporated an Oxygen measurement feature.

The 1st sensor you linked to appears to use this approach. But instead of buying a ready made sensor, many have made a project of building their own...

This project has been done and published many times on the Internet. There are well documented projects such as this one from Rutgeurs. As well as this complex one from a journal called EDN. And this one and this one from various independent hackers.

---
Tags: sensors
---


# Question
Title: "function" was not declared in this scope (called in setup)
I have this bit of code I'm trying to execute only once. but I seem to get this error every time I try to compile: "calcOppervlakte' was not declared in this scope" when it's being called in the setup.

I've looked at code examples where calling functions like this works, and I cannot wrap my head around this problem.

google isn't really helpful either since the search for something-something not declared in this scope gets me thousands of results.

```
double pi = 3.14159265359;

void setup() {
  Serial.begin(9600);
  for(int r = 1; r <11; r++){
    Serial.print(calcOppervlakte(r)); <----
  }
}

void loop() {

}

double calcOpppervlakte(float radius){
  double result = pi * pow(radius, 2);
  return result;
}

```

# Answer
The function name you're calling is **`calcOppervlakte`** but the function name in the definition is **`calcOpppervlakte`**. If you look closely you'll see there is an extra `p` in the function definition. If you change the names to match the error will be resolved.
> 4 votes

---
Tags: programming, c++, c
---


title: Unable to receive SMS on Android

text:
# Question
Title: Unable to receive SMS on Android
I have a GSM/GPRS shield for Arduino. It uses a SIM800 from SIMCOM. I've done several projects using it. Previously I used to send SMS from the same module. which were delivered appropriately. Since yesterday, whenever I am sending an SMS to my Android mobile, all what I receive is:

```
<<Content not supported>>

```

I also tried sending it to a basic mobile. It displayed:

```
Content can't be displayed

```

I tried changing the encoding using the `AT` command.

```
AT+CSCS="UCS2"
AT+CSCS="GSM"

```

It didn't work for any encoding.

The command I use to send SMS is:

```
---> AT+CMGF=1
<--- OK
---> AT+CMGS="10 digit number"
<--- >
> Hello!
^Z

```

Can someone please tell me what is going wrong? Thank you in advance!

# Answer
> 1 votes
In the SIM900 is an AT command that let you do a factory reset, your module will restart to the default values. It must be an AT command very similar to the SIM800.

The AT commando that (perhaps) will work for you is the **ATZ**, in the SIM900 works for me.

You can look over here to see what command is. Look over page 33. And be carefull, the link that I send to you is the AT command list for the SIM900, not the SIM800.

Hope you can find an answer.

---
Tags: gsm, android
---


title: Arduino AES128 - CMAC

text:
# Question
Title: Arduino AES128 - CMAC
I'm looking for ***AES128*** library with ***CMAC*** for Arduino. Help me to find one

# Answer
> 2 votes
I happen to know some libraries which use this. AES128-CMAC is for example used in the LoRaWAN MAC / driver implementation (LoRa is a low-power-wide-range radio technology). For example, the library Arduino-LMIC (**L**oRa **M**AC **i**n **C**) uses this AES-CMAC implementation (has actually 2 built-in, Ideetron is the other one):

Other stacks use the mbedtls library with only the AES and CMAC layer activated. The library, written by ARM, is entirely in C and thus easily configrable (`config.h`) and compilable for the Arduino platform:

Semetech's LoRa stack even has AES and CMAC abstracted in 4 four files:

Another good point would be to search PlatformIO's library index for "AES CMAC". Then this library comes up:

This also offers a CMAC implementation specifically designed for the Atmel AVR MCUs (Arduino Uno and likes) and partially written in Assembler. This should be best suited for you.

---
Tags: arduino-uno
---


# Question
Title: Can I use an IR distance sensor in rain?
I am planning on using 'SHARP IR Distance Sensor - GP2Y0A710K0F' in an outdoor environment. Assuming the casing I design for the sensor is waterproof, can I use this IR sensor without any trouble? If the water is interfering, what can I do to reduce that noise?

The sensor is fixed above the ground and aimed towards the ground like this.

# Answer
According to the data sheet for this device, located at Adafruit's web site, the frequency used is 870nm. If you required specific attenuation figures, that might be useful information.

Another web site suggests that thermal IR camera imaging systems (which use a different frequency IR) are attenuated by rain. Some of the IR energy is lost by absorption and some by reflection. I was hesitant to suggest that as the answer due to the different frequencies involved.

Digikey has a document covering wide use of IR sensing. Listed in the document:

The disadvantages of IR technology are:

1. Line of sight: transmitters and receivers must be almost directly aligned
2. Blocked by common materials: people, walls, plants, and other objects can block transmission
3. Short range: performance drops off with longer distances
4. Light and weather sensitive: direct sunlight, rain, fog, dust, and pollution can affect transmission
5. Speed: data rate transmission is lower than typical wired and RF transmission

Even though data transmission is not your objective, the considerations apply. A wet surface over which your sensor passes will have the signal attenuated and may also be slightly diffracted.

I found no direct reference to the magnitude of the attenuation. If your sensor is protected from water intrusion and the surface is only slightly wet, you may have minimal problems reading the distance. If the rainfall is at the level of a frog-strangler, there could be sufficient water to eliminate useful readings.

Another search resulted in a similar question on the physics stack exhange, which led to a more comprehensive answer:

There is another image on the same page, but both show that at the 870nm frequency, there is lower attenuation than much of the IR spectrum, particularly above 3000nm. The above linked document suggests that the affect of rain (water) is low at near-infrared (970-1940nm) but that's still higher than the device's 870nm figure.

For your objective, shielding the surface from rain (umbrella) or clearing the surface of standing water seems to be the best options. If those are impractical, one would have to experiment to determine how much water flow can be tolerated before the signal is lost or attenuated beyond reception limits.
> 2 votes

# Answer
the ir-sensor senses a difference in infrared. the rain will only interfere if its way warmer then the base outside temperature. this is how humans and other mammals trigger infrared sensors on outdoor garden lamps. we emit infrared because our body temp being higher than the temperature of our surroundings.

just a nice quote from this site: https://www.techwalla.com/articles/how-do-ir-sensors-work

> All objects emit light according to their temperature--this is called "black body radiation." The hotter the object, the shorter wavelength of light it emits. The Earth emits infrared light at a peak of about nine to 10 micrometers--and so do warm-blooded animals like humans. This light can be used to detect motion or warmth.
> 0 votes

---
Tags: sensors, ir
---


# Question
Title: Pro Micro recognised as Micro (win10, IDE 1.8.1)
I just got this pro-micro clone 5V and it's my first pro micro ever. After reading lots of discussions about how easy it is to brick and how it's just a smaller Leonardo, I've also found tutorials where they guide you to install custom things (sprkfun) to recognise the board, and others where it shows up as a Leonardo board.

However in my case I just plugged it in my Win10 laptop, the drivers got installed and it is automatically recognised as an Arduino Micro. Since I haven't found people having this, and since I'd like not to brick it immediately I was wondering what's the procedure between:

1. follow sparkfun's guide for pro micro and install their custom drivers
2. treat it as a Leonardo (in the IDE)
3. treat it as a standard Micro (in the IDE) since it's recognised as such

Thanks!

edit: solution: it's a **Leonardo**.

# Answer
Treat it as what it is.

What windows sees it as is just what USB reports it as. It's just a name. It has no bearing on what it is or how you program it. Select the actual board that you have in the IDE, not what Windows says it thinks it is.

As a general rule: Ignore everything Windows ever says, it's full of sh!t.
> 2 votes

---
Tags: arduino-ide, arduino-leonardo, arduino-micro, arduino-pro-micro
---


# Question
Title: Arduino MKR Zero problem with new UART comunication
I'm currently using an *Arduino MKR Zero* board and I need to add a new communication because the *Serial1* on pins 13 and 14 is already used by another device.

I've followed this tutorial from *Arduino* official website to create a new serial communication, but using the given code **I have no communication on pins 0 and 1**.

The code compiles, but it doesn't work when uploaded to the *MKR Zero* board. I've noted that *IrqHandler()* is not highlighted in my *Arduino IDE* (it remains black).

So, should I install some library?

Thank you.

# Answer
> 1 votes
When a library does not highlight, it might be that the library is not coded to be highlighted (see here).

If you installed the library yourself, you may have put it in the wrong path.

---
Tags: arduino-ide, mkr1000, arduino-zero
---


# Question
Title: How to connect/call to the PSTN network using Arduino?
For a few months I made an alarm for my house, it is very simple: it is based on magnetic sensors DC-1561 (for windows and exterior doors), a few PIR sensors for rooms, buttons, LEDs and (of course) an ArduinoNano v3. Something simple!

The question is that lately I do not spend much time in my house and I would like it when I'm away from home the alarm calls me (when is activated) to my cell phone using the public switched telephone network (PSTN) because I live in Cuba and it's the easiest way and cheaper (the GSM modems/modules are very expensive for me). I do not want to leave any message or sound record, just call me and receive the call on my cell phone, using the RJ-11 connector (in my country only 2 pins are used) to connect it with the Arduino/some\_IC.

I have been investigating since yesterday and have found quite a bit of information. The most recommended/successful that I found (remember that I want to continue using the system that I already have, I just want to add to the Arduino the ability to use the mark through the PSTN) is to use an IC (HT9200B) that is a generator of DTMF codes (as see in the figure) with serial AND parallel connection, aparently, compatible with the electronic logic of the Arduino (5V).

But of all the information that I found is to connect to this IC (HT9200B) a speaker and reproduce the DTMF codes. This is **not** what I want, what I want is to **connect directly to the phone line and be able to "call" from it**.

Anyone have any ideas, links, projects in progress, or anything that can help me?

# Answer
> 2 votes
As already written in the comments, you may use any RS232 modem you can find. They use the so-called AT commands, which is a very common way to exchange commands with this kind of peripheral. You can check on wikipedia or on google to get more information on it.

The main problem is that this kind of modems are a bit hard to find (or at least, they are a bit harder to find and a bit too expensive for my liking). That's why, for a project of mine, I wanted to switch to a cheaper alternative. Looking on the internet, a lot of people stated that it was much better to have an already approved instrument rather than designing your own. For this reason, I bought a mini-phone like this one:

You just have to open it, wire the keys (or rather, the rows and columns of the keypad) to the arduino and let it do the magic.

This solution is cheaper (I spent 4€ for this, but if you have an old phone it becomes free) than getting a RS232 modem, but needs more work on your side.

---
Tags: arduino-nano, remote-control
---


# Question
Title: Sending data to Arduino Via Nodejs: Arduino does not echo back the data
I have the following sketch that runs in a arduino UNO:

```
/*
 * Copyright 2018 Dimitrios Desyllas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

String inputString = "";         // a String to hold incoming data
bool seralReadEnded=false;

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

void loop() {
  if(seralReadEnded){
    sendDataOverSerial((byte [])inputString.c_str(),inputString.length());
    inputString="";
    seralReadEnded=false;
    delay(5000);
  }
}

String concatHex(byte value,String string){
  string+="\\x";
  if(value<16){
   string+="0";
  }
  string+=String(value,HEX);
  return string;
}

void sendDataOverSerial(byte byteArray[],size_t arrayLength){
  String returnVal="BEGIN:";
  for(int i=0;i<arrayLength;i++){
    returnVal=concatHex(byteArray[i],returnVal);
  }
  returnVal+="\n";
  Serial.println(returnVal);
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if(inChar == 0x11){
       char inChar = (char)Serial.read();
    } else if (inChar == 0x03) {
      seralReadEnded = true;
    } else {
     inputString+=inChar;
    }
  }
 }

```

And I made the following Node.js software in order to read and send data over the USB to arduino:

```
const SerialPort = require('serialport');
const Readline = require('parser-readline');
const Ready = require('parser-ready');
const Regex = require('parser-regex');
const crypto = require('crypto')

const valueIntoHex=function(value){
  switch(value){
    case 0x11:
      return "0x11";
    case 0x03:
      return "0x03";
    case 0x02:
      return "0x02";
    default:
      return value;
  }
}

/**
* Escaping NonPrintable Ascii Characters (bytes) of a buffer data
* @param <Buffer> data The data to read
*/
const formatDataForSerialSend=function(data){
  //I allocate double the length because I assume worst case scenario that all bytes to be the ones I need to escape
  const returnBuffer =  Buffer.alloc(2*data.length);
  indexToWrite=0;
  //I use indexToWrite index because during escapes the posision that I write the byte is different from the ne I read.
  for(let i=0;i<data.length;i++){
    const byte=data.readUInt8(i);

    if(byte == 0x11 || byte == 0x03 || byte == 0x02){
      console.log("Escaped Ascii: "+valueIntoHex(byte));
      indexToWrite=returnBuffer.writeUInt8(0x11,indexToWrite);
    }
    indexToWrite=returnBuffer.writeUInt8(byte,indexToWrite);
  }
  returnBuffer.writeUInt8(0x03,indexToWrite);
  //Because I do not want uneeded size of data in my buffer
  const lastIndex=returnBuffer.lastIndexOf(0x03);
  return returnBuffer.slice(0,lastIndex+1);//I want size and not the last index. (Size=lastIndex+1)
}

/**
* Application Specific send logic
* @param <Buffer> data Data te send
*/
const sendData=function(data){
  console.log("Escaping dirty Ascii");
  data=formatDataForSerialSend(data);
  console.log("SEND DATA: "+data.toString('hex'));
  port.write(data,'binary',(err)=>{
    if(err){
      console.err("Could not send data",err);
    }
  });
}

const portName = '/dev/ttyACM0';

const port = new SerialPort(portName, {baudRate: 19200});

//Look over: https://regex101.com/r/QcBTTj/1
const hexRegex=/((\\|0)(x|X)[0-9A-Fa-f]{2})+/g;
const parser = port.pipe(new Ready({ delimiter: 'BEGIN:' })).pipe(new Readline({ delimiter: '\r\n' }));

console.log("################# SEND ####################");
sendData(Buffer.from('hello','ascii'));
console.log("############# END OF SEND #################");

parser.on('data', function(input) {
    console.log("################# RECIEVE ##################");
    console.log("Message: "+input);

    const input2=input.replace(/^BEGIN:|(\r|\n|(\\|0)(x|X))/g,"");
    console.log("Sanitized Input: ",input2);

    try{
        const data=Buffer.from(input2,'hex')
        console.log("REPRINT HEX FOR VERIFICATION: "+data.toString('hex'));
        console.log("############ END RECIEVE ##############");
    } catch(e) {
        console.error(e);
    }
});

```

But for some reason I managed to make it send data but the arduino does not send them back. So I want to debug it, but I do not know how I can do that I mean over arduino code how I will launch a debugger in order to do that?

How I can at the same time look and analyze the USB traffic between an application and Arduino in order to determine the logic bug?

Also I could not distinguish why arduino does not echo back some data, if I use this code for this sketch, the node.js application reads the data fine:

```
/*
 * Copyright 2018 Dimitrios Desyllas
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction,
 * including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

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

void loop() {
  byte byteArray[]={1,10,255,3,4,2,1,55};
  for(int i=0;i<sizeof(byteArray);i++){
    Serial.print("\\x");
    if(byteArray[i]<16){Serial.print(0);}
    Serial.print(byteArray[i],HEX);
  }
  Serial.println("\n");
  delay(3000);
}

```

# Edit1

So far I modified the sketch into this:

```
String inputString = "";         // a String to hold incoming data
bool seralReadEnded=false;

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

void loop() {
  if(seralReadEnded){
    sendDataOverSerial((byte [])inputString.c_str(),inputString.length());
    inputString="";
    seralReadEnded=false;
  }
}

String concatHex(byte value,String string){
  string+="\\x";
  if(value<16){
   string+="0";
  }
  string+=String(value,HEX);
  return string;
}

void sendDataOverSerial(byte byteArray[],size_t arrayLength){
  String returnVal="BEGIN:";
  for(int i=0;i<arrayLength;i++){
    returnVal=concatHex(byteArray[i],returnVal);
  }
  returnVal+="\n";
  Serial.println(returnVal);
}

void serialEvent() {
  while (Serial.available()) {
    // get the new byte:
    char inChar = (char)Serial.read();
    if(inChar == 0x11){
       char inChar = (char)Serial.read();
    } else if (inChar == 0x03) {
      seralReadEnded = true;
    } else {
     inputString+=inChar;
    }
  }
 }

```

And I tested it by running over my GNU/Linux terminal like that:

```
screen /dev/ttyACM0 19200

```

I typed some stuff and by pressing `CTRL+C` keyboard combination I managed to get them back (Somehow gives a character `0x03` that is the `ETX` ascii character that in my case indicated the data stream).

But How I get some random binary escape them with `0x11` charactes and send into arduino via bash, as fas ad I know is that on GNU/Linux systems I can use the `/dev/random` for generating data?

# Answer
> 1 votes
There are too many `String` copies in your code. This is asking for trouble, as it can lead to memory fragmentation and, ultimately, to memory exhaustion. That's why I recommended in a comment to buffer the data in plain byte arrays.

However, it appears your Node.js script is going to do the buffering anyway (that's what the `Readline` parser does). Thus there is no point in buffering also on the Arduino, which has one million (or more) times less memory than the computer running the Node.js code. If the Arduino just outputs the bytes as it gets them, the program becomes very simple:

```
void setup()
{
    Serial.begin(19200);
    Serial.print("BEGIN:");
}

// Send a byte over the serial port, formatted in hex.
static void send_hex(uint8_t value)
{
    Serial.print("\\x");
    if (value < 16)
        Serial.print('0');
    Serial.print(value, HEX);
}

void loop()
{
    static bool escaped;  // is the next character escaped?
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\x10' && !escaped) {  // DLE (data link escape)
            escaped = true;
        } else if (c == '\x03' && !escaped) {  // ETX (end of text)
            Serial.print("\r\nBEGIN:");
        } else {
            send_hex(c);
            escaped = false;
        }
    }
}

```

Note that, upon receiving an “end of text”, the program terminates the current line (by sending "\r\n") and immediately sends the preamble for the next one ("BEGIN:"). On the receiving side, the readline parser will take care of delivering only complete lines.

If, for whatever reason, you do need to buffer inside the Arduino, then remove the `Serial.print("BEGIN:");` line from `setup()` and change the loop as follows:

```
void loop()
{
    static char buffer[1024];
    static size_t pos;    // current position in buffer
    static bool escaped;  // is the next character escaped?
    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\x10' && !escaped) {  // DLE (data link escape)
            escaped = true;
        } else if (c == '\x03' && !escaped) {  // ETX (end of text)
            Serial.print("BEGIN:");
            for (size_t i = 0; i < pos; i++)
                send_hex(buffer[i]);
            Serial.println();
            pos = 0;
        } else {
            if (pos < sizeof buffer)
                buffer[pos++] = c;
            escaped = false;
        }
    }
}

```

Note that the buffer is sized at half the RAM of your Uno. This is safe, as it is a very simple program that uses very little dynamic memory (stack only, no heap) and has no risk of fragmentation. Note also that your original program stores *both* the raw data and the formatted hex (which is 4 times larger) in memory at the same time, which means your buffering would be limited to 1/5 of the available RAM.

---
Tags: arduino-uno, usb, communication, node.js
---


# Question
Title: How reliable is Arduino Uno Serial, via USB (ATmega16U2), CRC needed?
I have a question about the reliability of Serial communication, i.e. in particular if I need to implement CRC/checksum/ECC because of bit transmission errors? I

I however think there is no general answer as there are different ways in which serial communication with the Arduino Uno's Atmega328P chip might work.

* (a) The serial communication is between two Atmega328P Chips, and using rather long wires
* (b) The serial communication is between two Atmega328P Chips, and using rather short wires
* (c) The serial communication is between one Atmega328P and the ATmega16U2, who picks up and forwards the signals via USB protocol (e.g. to a PC)

My question is with regard to the ATmega16U2. The distance (wire/line length) on the Arduino R3 board is about 2cm/1" tops, which I expect to reduce the likeliness that a signal will become corrupted. Assuming that the USB protocol which is further employed to transport the signal by itself provides by itself an ECC/CRC/checksums, I wonder if it is not rather superflous to implement a CRC when receving and sending messages via the serial communication in the case (c), while I however expect it to be *more* necessary for (b) and almost certainly necessary for (c).

Also, if this matters to respond to the question, I was wondering if the power supply (i.e. if Arduino Uno is powered by the USB provided voltage of ~4.5V or rather via an external 12V power adapter) would have an impact on the "corruptability" of the signals on the TX/RX serial lines?

# Answer
If you use the appropriate buffering of the 0/5V signal over the long wires, case A, no error detection and correction is needed. RS232, RS485, your data will be just fine (can be up to thousands of feet).

Shorter wires, from Atmega device to Atmega device, I've neved had to use anything, even at 115200 speeds, case B, case C.

16U2 to PC, that will depend on the quality of the USB cable. The +/-3V differential signal (similar to RS485 levels) is quite high speed, like 4 Mbits/second, so you want a good cable with good shielding.
> 1 votes

---
Tags: serial, atmega328, atmega16u2, reliability
---


# Question
Title: Controlling voltage and current from chip?
I'm well aware that this question perfectly showcases my spectacular ignorance, but oh well. It's a simple enough question, so here we go.

I have a 595 chip (SN74HC595) wired up to an Arduino, fed by the 5V output. After switching all the outputs on, I measured an output pin at 5.04V and 74mA.

I want to use the chip's outputs to switch transistors (P2N2222A) which will have 60 mA through them (switching common cathode RGB LEDs), so I believe I need to drop it down to around .6 to 1.2V at .6mA, right (I'm not at all sure I'm reading the datasheet right)?

So how exactly do I do that? It seems like I need to put a resistor in between the pin and the base, but don't I need to know the TOTAL resistance of the circuit? Or can I just calculate from the pin itself (I believe that would need 7K)?

Thanks in advance for your help, and please feel free to OVER-explain if you're so inclined.

**EDIT:**

**EDIT 2: Resistor values are listed wrong. R1=200, R2 & R3 = 100.**

# Answer
You're misunderstanding what you need to drive a transistor.

A transistor will allow *up to* a specific amount of current through the collector depending on the current that flows through the base. If less is needed by the load then less will flow.

Think of it like a tap. If there's not much water pressure it doesn't matter how far you turn on the tap, after a certain point the flow of water won't increase any more.

To allow 60mA through the collector you need to provide *at least* 0.6mA (assuming a *hFE* of 100) through the base. That 0.6mA will set the *upper limit* of the current to 60mA. If you provide *more* than 0.6mA then you will allow a higher *upper limit*.

The 0.6V on the base is the voltage (difference between base and emitter when wired as "common emitter") at which current will start flowing through the base. It's the same concept as the forward voltage of an LED. For switching the voltage you put on the base must be *more than* 0.6V to allow current to start flowing. Since 5V is more than 0.6V you don't need to worry about it. If you want precision in your calculations you will want to take that 0.6V into account, though.

So if you want *at least* 0.6mA from 5V with a 0.6V drop on the BE junction, you need:

```
R=V/I = (5 - 0.6) / 0.0006 = 7.3kΩ.

```

That's the *maximum* resistance you want. Anything more than that and the current through the base will limit the current through the collector to *below* the 60mA you want. So you must select some resistance that is lower than that.

What value? Well, it really doesn't matter that much. The lower the value the higher the current, but at these levels the current levels you're dealing with will be minuscule anyway.

It's common to use a 1kΩ resistor in the base for a transistor when using it as a simple switch like you are. That would give you, for each transistor:

```
I=V/R = (5 - 0.6) / 1000 = 4.4mA

```

For all 8 outputs that's a paltry 35.2mA. Far below the total the chip can provide of 70mA.

If you care about current consumption (you're running from batteries, for instance) you may want to increase to 4.7kΩ resistors to reduce the total drive current down to 7.5mA.
> 5 votes

# Answer
You are making the design more complicated than it needs to be. Use a WS2803 chip, it has 18 outputs, 0-255 PWM level programmable for each output. Got more LEDs? Use more chips. http://da-share.com/files/datasheets/WS2803.pdf

Or use WS2812B RGB LEDs, easy to wire up in a daisychain. SMD typically, and Sparkfun carries 2 thru hole variants also.
> 1 votes

---
Tags: current, voltage
---


# Question
Title: if two arduinos are connected by I2C and one of them is using an ethernet shield, does that grant both of them access to the internet?
i have two arduino mega and they send data to each other by an I2C connection. But one of those arduinos is connected to an ethernet shield which allows it to send data to a web server. Being both connected does that mean that they both can send or access the web server. Sorry if any ambiguity was found but I didnt find a better way to ask this question.

# Answer
I2C does not automatically share resources between two connected devices. You would not be able to share an Internet connection from a Mega connected via I2C to another Mega which has an Ethernet shield.

However, you **could** write code for both Megas that implements a two-way communication in which the non-shield Mega sends requests or commands to the one with the Shield, and then passes that data back to the non-shield Mega.

However, you, as the coder, would be responsible for designing such a protocol and implementing it. It would be quite a task probably.
> 5 votes

# Answer
It can but only if the one with the shield allows it (it acts like a router).

The only way for the arduino without the shield can communicate with the internet if it can send a message to the one with the shield and it will forward that message and return the replies back.
> 2 votes

---
Tags: arduino-mega, ethernet, web-server, ethernet-shield
---


# Question
Title: how to establish a connection between an arduino and a web server?
I want to establish a connection between my arduino mega ( which is connected to an ethernet shield so internet access is available) to a web server. Any idea how the code should be? I searched for it but all I found was a local host connection establishment. Thanks in advance.

# Answer
> 0 votes
The answer of this was already existing in the arduino examples which I forgot to check at first. Thanks Majenko for making me notice.

---
Tags: arduino-mega, web-server, ethernet-shield
---


title: 3 digit 7 segment display

text:
# Question
Title: 3 digit 7 segment display
I have 3 digit 7 segment display with 10 pins

I found this image pinout but it not working for me I need to know the pin out of this display

# Answer
> 1 votes
you are supposed to multiplex this display. Put a current limiting resistor between pins 10, 8 and 6 and the arduino and all the rest can be connected directly.

First pull pin 10 low and use pins 7,9,2,3,4,1 and 5 to set the segments of the first digit.

Then put 10 high and 8 low and again use pins 7,9,2,3,4,1 and 5 to set the segments of the second digit.

repeat with pin 6 pulled low.

You can test the display with a battery and resistor. Connect them in series and put positive on the lower left pin and negative on the upper left pin. That should light up the top left vertical segment on the left most digit. You may need to turn the display around.

---
Tags: pins, wires, 7-segment
---


# Question
Title: Building an adjustable low frequency PWM controller with Arduino
I am looking for a way to create an adjustable PWM controller capable of modulation frequency from 0-100 (more preferably 0-1000) Hz, duty cycle from 0-100%, and able to accept a voltage range of 5-30V DC. I have looked through Sparkfun and Adafruit for product or PWM shields capable of this and I have yet to find one. Some servo shields can be programmed down to 50Hz and arduino itself can be slowed to like 30Hz using timer0 and timer1 changes. However none of these options make it easy to vary frequency and none of them can accept much more than 6V.

I have searched far and wide and found a few interesting things:

1) http://www.instructables.com/id/The-ultimate-PWM-driver-for-many-applications/

This instructable shows an analog un-sensored PWM driver. It would get the job done here however, I need a way to read my Frequency and Duty Cycle

2) https://www.electronicsblog.net/arduino-frequency-counterduty-cycle-meter/

Here there is a way using pulsein() and other arduino functions to read both frequency and duty cycle as seen above. But then this is also assuming you're PWM voltage is 5V. So maybe you use a 5V regulator on the signal into the arduino? Would something that simple work or would it skew the signal and prevent accurate measurements?

Obviously, if anyone has a better idea I'm open to it. I've been searching for a solution for some time. The trouble really seems to be the low frequency PWM request.

# Answer
The ATmega328 in the Arduino Uno has a 16-bit timer (Timer/Counter 1) which can do PWM. It has a prescaler that can divide by 1024. The lowest frequency that it can generate is about 0.12 Hz:

```
16MHz / 1024 / 65535 / 2 = 0.1192 Hz

```

We change the PWM frequency by changing the "top" value. For higher frequencies, lower the top value, and/or pick a smaller prescaler.

(And, really, what does 0 Hz PWM even mean?!? :-)

The duty cycle can vary from 0-100%, with the resolution changing with the specific frequency you generate.

As for the high-voltage... use a motor driver, or darlington, or hexfet, or whatever...

I'm confused as to why you're reading the frequency. With the 16MHz crystal, you set it and you get what you asked for (within the crystal tolerances, temperature, etc.)

At least, that's how I think it works. Good luck!
> 4 votes

# Answer
Your question is so close to my own project, for a second I thought it was something I posted awhile back, go figure. I don't expect you to gain from my answer, me coming along to find your question some 2 years, 5 months later. It may be of help to others who pass by this way in the future. I am currently working on the exact same variable duty cycle controller and will offer up my findings.

The following programming code is the result of apx. 5 months of study into the Arduino programming as well as a long failing attempt at getting control through a series of 555 timer chip builds. I shit canned the 555 timer chip & Darlington transistor method. I thought it was too crude, and all 'engineering' schematics never allowed me to have anything more than a 50% duty cycle control. I wanted control over all PWM variables. Today I will be purchasing a metal case, or making one that can hold apx. 5-6 potentiometers allowing me to adjust every possible variable within the PWM domain of parameters (there are more variables than what I have in this code below). I will give you some details in the code first, that will give you some idea of the obsessively precise control I'm demanding from my PWM project:

Getting into the heart of the variable HIGH/LOW control. Be sure to read everything you can to understand fully why these functions are needed. Also, know that with 10 bits the 1023 value allows a resolution of .0043 volt increments (really nice):

```
void loop()
{
Potentiometer1 = analogRead(PotHzHIGH);
Potentiometer1 = map(Potentiometer1, 0, 1023, 1023, 0);
Potentiometer1 = constrain(Potentiometer1, 500, 1023);

Potentiometer2 = analogRead(PotHzLOW);
Potentiometer2 = map(Potentiometer2, 0, 1023, 1023, 0);
Potentiometer2 = constrain(Potentiometer2, 500, 1023);

Potentiometer3 = analogRead(Pot5Volts);
Potentiometer3 = map(Potentiometer3, 0, 1023, 1023, 1023); //Hold at 12Volts
Potentiometer3 = constrain(Potentiometer3, 0, 1023);
//Potentiometer3 can either be locked at 12volts with the map function, or
//you can use a Potentiometer to varry the voltage. I illistrate the
//constant at 12 volts with the map function - low/high both set to
//1023 & 1023

digitalWrite(PotHzHIGH, HIGH);
//turn it ON delayMicroseconds(PotHzHIGH);
//Keep ON for Potentiometer1=PotHzHIGH Microseconds
//1000 microseconds = 1millisecond; 1000ms = 1second

digitalWrite(PotHzLOW, LOW);
//turn it OFF delayMicroseconds(PotHzLOW); //Keep OFF for
Potentiometer2=PotHzLOW Microseconds
//1000 microseconds = 1millisecond; 1000ms = 1second;
//Largest value within the delayMicroseconds function: 16383microseconds
//Largest value when converted to milliseconds is 16.383ms, or axp. 1/20th of
//...a second

```

}

```
//other things to understand about the above program. It is possible to
//have the LOW written with: delayMicroseconds(PotHzLOW+100);
//or delayMicroseconds(PotHzLOW*1.1);
//You can add an additional potentiometer to be the multiplier of the LOW.
//these added controls prevent the LOW from ever being less than the high.
//this can come in handy if you wish to work within duty cycles that are
//between 1% & 50%. It is of interest to me because I am dealing with
//high frequencies.

```

timkasey1@gmail.com
> 0 votes

---
Tags: arduino-uno, programming, pwm, timers, frequency
---


title: Press button and Send Message Error

text:
# Question
Title: Press button and Send Message Error
The problem is that sometime I don't even need to press the button and it sent message and keep on sending continuously.

What I want to do is that once the button is pressed, sent 1 message.

I cannot figure out why it is happening. Please help me to figure out.

```
 #define CUSTOM_SETTINGS
    #define INCLUDE_GPS_SHIELD
    #define INCLUDE_SMS_SHIELD
    #define INCLUDE_VIBRATION_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>
#define SW 8

/* Define a boolean flag. */

float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  pinMode(SW, INPUT);
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();

}

void Emergency() {

      /* Send SMS. */
      if(digitalRead(SW) == 1)
      {
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Serial.println(Message);

        SMS.send("0637200721",Message);
        //Vibration.start(1000,2000);

        delay(3000);
      }
}

void loop()
{
  Emergency();

  delay(1000);
}

```

This is how I connect the button. The Grey cable is for Ground, The red is for 5V and the orange is to pin8. Between Red and Grey there is resistor.

# Answer
> -1 votes
The problem is because I didn't put the following lines and I changed to use physical push button to 1Sheeld provided button from mobile. The follwing is the working code.

```
#define CUSTOM_SETTINGS
#define INCLUDE_GPS_SHIELD
#define INCLUDE_SMS_SHIELD
#define INCLUDE_VIBRATION_SHIELD
#define INCLUDE_PUSH_BUTTON_SHIELD

/* Include 1Sheeld library.*/
#include <OneSheeld.h>
#include <string.h>

/* Define a boolean flag. */
boolean isMessageSent = false;
float lat;
float lon;
String Message;
String Message1;
String Message2;
char latitude[10];
char longitude[10];

void setup()
{
  /* Start communication.*/
  Serial.begin(9600);
  OneSheeld.begin();
  PushButton.setOnButtonStatusChange(&Emergency);
}

void loop()
{

}

void Emergency(byte isButtonPressed) {
 if(isButtonPressed)
      {
        if(!isMessageSent)
        lat = GPS.getLatitude();
        lon = GPS.getLongitude();
        Message1 = String(lat,8);
        Message2 = String(lon,8);

        Message = "I need Help! Google Maps - https://www.google.co.in/maps/place/" + Message1 + "," + Message2;
        Serial.println(Message);

        SMS.send("0637200721",Message);
        isMessageSent = true; // This line
      }
      else{
        isMessageSent = false; // This line
      }

```

---
Tags: arduino-uno, shields, button
---


# Question
Title: Should I use a loop instead of an If statement?
I have a simple sketch that tests input from 2 touch sensors and outputs to 2 relays (if a sensor is touched, trigger the respective momentary relay). It has been a bit quirky to say the least. perhaps I need to adjust delays or adjust sensitivity of the touch sensors, but I feel that maybe the coding could be more efficient. Would using a WHILE or DOWHILE loop work better than an IF statement for this? It seems like there is a timing issue between the relay and the sensor. When I hit the sensor, the relay triggers immediately, but then it doesn't shut off right away. Also if both sensors are made at the same time, I am seeing only 1 relay trigger or neither. I am trying to eliminate the code as my failure point. I have the code printing to the serial monitor to show "Sensor 1 touched" or "Sensor 2 touched", and sometimes that triggers once and sometimes it will print multiple times.

```
int touchPin1 = 2; //Touch sensor 1
int touchPin2 = 4; //Touch sensor 2
int val_1 = 0;
int val_2 = 0;
int relayPin1 = 8; //Relay 1
int relayPin2 = 9; //Relay 2

void setup()
{
  Serial.begin(9600);
  pinMode(touchPin1, INPUT);
  pinMode(touchPin2, INPUT);
  pinMode(relayPin1, OUTPUT);
  pinMode(relayPin2, OUTPUT);

}

void loop() {
  digitalWrite(relayPin1, LOW);
  digitalWrite(relayPin2, LOW);
  val_1 = digitalRead(touchPin1);
  val_2 = digitalRead(touchPin2);
  if(val_1 ==1)
  {
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
  }
  if(val_2 ==1)
  {
  Serial.println("Pad 2 Touched");
  digitalWrite(relayPin2, HIGH);
  }
  delay(100);
  //Serial.println();
}

```

Basically I am asking if there is a more efficient way to code this.

Touch Sensors: Adafruit Standalone Momentary Capacitive Touch Sensor Breakout Adafruit Part Number: 1374

Relays: SunFounder Relay Module for Arduino and Raspberry Pi 5V DC Trigger by HIGHLO (HIGH Trigger)

# Answer
What you are lacking is the `else` concept:

* If a touch pad is pressed, then
    + Turn the relay on
* **else**
    + Turn the relay off

Rather than turn the relay off *every iteration*, you only turn it off *if the touch pad is **not** pressed*.

That can be written as:

```
val_1 = digitalRead(touchPin1);

if(val_1 ==1)
{
  Serial.println("Pad 1 Touched");
  digitalWrite(relayPin1, HIGH);
} else {
  digitalWrite(relayPin1, LOW);
}

```

If you want your messages to be more meaningful and not spam, then you can remember the previous state and only do things if the state changes:

```
static uint8_t oldVal1 = LOW;

uint8_t val1 = digitaRead(touchPin1);

if (val1 != oldVal1) {
    oldVal1 = val1;
    if (val1 == HIGH) {
        Serial.println("Pad 1 Touched");
        digitalWrite(relayPin1, HIGH);
    } else {
        Serial.println("Pad 1 Released");
        digitalWrite(relayPin1, LOW);
    }
}

```
> 2 votes

---
Tags: arduino-uno, sketch, loop
---


title: comparison in a time sequence

text:
# Question
Title: comparison in a time sequence
in an Arduino sketch a user is invited to input a number representing a time in the format HH:MM, this number is to be added at the end of an ordered and limited sequence of times

--the first input (lower limit) can be any time within the 24 hours,

--the upper limit is calculated as lower\_limit+period; with period being 1,2,3,4,6,8,12 or 24 hours,

--and to be accepted, the input must verify that it is chronologically after the previous element, and that it's within the given period;

for example if first element is 20:00 and the period is 8, the upper limit will be 20+8=28 wich is 04:00; both 21:00 and 03:00 are accepted, where'is 19:00, 05:00, 09:00, 17:00, ... are rejected.

without any information on the 'day', i did not find any suitable algorithm, and none of the available Arduino libraries is useful in this case.

any link, or tip,...

# Answer
> 0 votes
Here is the basic idea and a sample implementation for solving the problem:

The problem is: Given a start time `time1` and a period `period`, each described by a pair of `(hour,minute)`, how can we check whether another time `time2` is within `time1` to `time1 + period`?

First we can see that we given a `(hour, minute)` pair we can compute the total number of minutes as `totalMinutes = 60*hour + minute`.

Then we can observe that there two distinct cases that we must check:

* the entire "time check period", that is, `time1` to `time1 + period` is within `00:00` to `24:00` without overflowing past `24:00` when we simply add the times. then, we can use a simple bounds check worded as "`time2` must be greater than `time1` and less or equal to `time1 + period` when comparing total minnutes.
* `time1 + period` overflows past `24:00`. We consider an example of `time1= 20:00` and `period = 8:00`. Thus all valid times are from `20:00` to `04:00` with an implicit "wrap around" at 24:00 to 00:00. We can see that there are now two time-intervals we must check: Everything from `20:01` to `24:00` and from `00:00` to `04:00` is valid. Thus we can derive the the bounds in minutes again. We can obtain the `04:00` by computing `20:00 + 08:00 modulo 24:00`. The C operator `%` is used to compute the residue of the division by a certain number. I.e. `28 % 24 = 4` because `28 / 24 = 1 residue 4`. This is called modulo-arithmetic.

The following C++ program demonstrates the solution:

```
#include <cstdio>

/* returns whether time2 defined by hour2:minute2 is within the period time1 = hour1:minute1 to time1 + period. */
bool is_time_within_period(
    int hour1, int minute1,
    int hour2, int minute2,
    int periodHour, int periodMinute) {

        //Reject garbage input
        if(hour1 > 24 || hour2 > 24
            || minute1 > 60 || minute2 > 60
            || periodHour > 24 || periodMinute > 60) {
                //TODO throw error message
                return false;
        }

        //Convert hours and minutes into absolute minutes. One hour is 60 minutes.
        int time1Minutes = 60 * hour1  + minute1;
        int periodMinutes = 60 * periodHour + periodMinute;
        int time2Minutes  = 60 * hour2 + minute2;

        int periodEnd = time1Minutes + periodMinutes;

        //If the start time plus the period time is over 24:00 there is a wrap-around the we need to consider.
        bool wrapAround = false;
        if( periodEnd > (24 * 60)) {
            wrapAround = true;
        }

        bool result = false;

        //printf("Wrap: %d Period end %d\n", wrapAround, periodEnd);

        if(!wrapAround) {
            //if there is no wrap-around we can just compare the total minutes against each other
            //time1 must be after time2 but before (time1 + period).
            result = time2Minutes <= (time1Minutes + periodMinutes) && time2Minutes > time1Minutes;
        } else {
            //There was a wrap around, i.e. start time + period was beyond 24:00.
            //We need to make two comparisons: is it in the time period from time1Minutes to 24:00?
            result = time1Minutes < time2Minutes && time2Minutes <= (24 * 60);

            //the result can also be okay if it from the time from 00:00 to the remaining period
            //use the module operator here. This transforms e.g. 28:00 would be reduced to 04:00. (modulo 24 hours calculated in minutes)
            int upper = (periodEnd % (24 * 60));
            //printf("Upper: %d (%02d:%02d)\n", upper, (upper / 60), upper % 60);
            result |= time2Minutes >= 0 && time2Minutes <= upper;
        }

        return result;
}

int main() {

    const int hourStart = 20;
    const int minuteStart = 0;

    const int periodHours = 8;
    const int periodMinutes = 0;

    //play around with these values
    const int compareTimeHour  = 4;
    const int compareTimeMinute = 0;

    printf("Start: %02d:%02d\n", hourStart, minuteStart);
    printf("Period: %02d:%02d\n", periodHours, periodMinutes);
    printf("Check time: %02d:%02d\n", compareTimeHour, compareTimeMinute);

    bool res = is_time_within_period(hourStart, minuteStart, compareTimeHour, compareTimeMinute, periodHours, periodMinutes);

    if(res) {
        printf("Time is within bounds\n");
    } else {
        printf("Time is not within bounds\n");
    }

    printf("Hello\n");

    return 0;
}

```

The function `is_time_within_period` has no dependencies and can thus be copy-pasted into any Arduino sketch.

Let the start time be `20:00` and the period `04:00`. Then feeding the program different times to compare against lets us see that it indeed works.

```
Start: 20:00
Period: 08:00
Check time: 20:00
Time is not within bounds

Start: 20:00
Period: 08:00
Check time: 20:01
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:00
Time is within bounds

Start: 20:00
Period: 08:00
Check time: 04:01
Time is not within bounds

```

---
Tags: arduino-uno, arduino-ide, time, algorithm
---


# Question
Title: avrdude: stk500_recv(): programmer is not responding
Arduino IDE is throwing this error when uploading sketches - **avrdude: stk500\_recv(): programmer is not responding**

The problem arose just after I uploaded a blink sketch to my Arduino Mini, which worked absolutely fine. After the successful upload I tried to upload a different sketch and got the error.

I thought I had destroyed the boot loader somehow and was about to get out the Bus Pirate for ICSP but I decided to try another Arduino Mini I had lying around (albeit from another manufacturer) and got the same error.

So I'm convinced it's a driver issue as I successfully uploaded a sketch (it still runs as we speak!) then just magically without changing **ANYTHING** I can no longer upload.

In a futile attempt to get back to work I've done the following: Switched the RX-TX lines (clearly not the issue as the first upload worked) Used a different FTDI cable used a different programmer (FTDI 5V/3.3V USB to TTL Basic FT232 FIO Programmer) (USB to TTL Serial UART RS232 Adaptor (PL2303HX) I'm fairly certain these use different drivers - FTDI and Prolific

Please help me I'm about to murder something :'(

Screencaps of error and device manager - Imgur

# Answer
> Is it this?
>
> "To upload a new sketch to the Arduino Mini, you need to press the reset button \>on the board immediately before pressing the upload button in the Arduino \>environment."
>
> https://www.arduino.cc/en/Guide/ArduinoMini

You sir, are a hero.

I don't even know how I accidentally did this sequence to upload the first sketch... Perhaps I plugged the USB to Serial UART in to the USB port and quickly pressed upload? Having got the first sketch on there really mixed me up :/

Solution:

1. Click upload sketch - It will show 'Compiling Sketch'
2. Immediately after clicking upload, hold the reset button down on the Arduino mini
3. Release the reset button when 'Compiling Sketch' turns in to 'Uploading'
> 3 votes

# Answer
Is it this?

"To upload a new sketch to the Arduino Mini, you need to press the reset button on the board immediately before pressing the upload button in the Arduino environment."

https://www.arduino.cc/en/Guide/ArduinoMini
> 4 votes

# Answer
avrdude: stk500\_recv(): programmer is not responding

I have the same problem (Arduino uno) I reset the Arduino several times, but finally i fixed the problem. so you must change the pic of the arduino and make sure it was instilled correctly on the arduino board.

hope it work...
> -1 votes

---
Tags: ftdi
---


# Question
Title: Arduino Due & Spec gas sensor - how to choose specific information from a stream of incoming bytes to store
I'm trying to build an air pollution sensor for a college project, with an Arduino Due and a series of Spec Sensors digital gas detectors. However, I'm having a little trouble getting the first one of them (Carbon Monoxide, https://www.spec-sensors.com/product/digital-co-sensor/) to behave, before I can run multiple. As they're all the same sensor setup but for different gasses, once I get the first one working, the rest should follow easily.

The code's very simple, as it uses Spec's own command system - sending the letter "c" to the sensor forces it to take one reading per second for as long as the sensor is powered, and then the serial monitor displays whatever comes back:

```
    void setup() {
      // sensor running via Serial1
      Serial.begin(9600);
      Serial1.begin(9600);
      Serial1.print("c");
    }

    void loop() {
      if(Serial1.available()!=0)
      {
        Serial.write(Serial1.read());
      }
    }

```

My problem comes with the data that's being returned. The gas reading is present, but so is a lot of superfluous information that I don't need. According to the sensor's tech document, the information returned is: serial number, reading (ppb), temperature, humidity, raw voltages, and amount of time the sensor has been running for. In the serial monitor, it looks like this:

Right now, all I want is the reading in ppb (the second value), either as the only data coming through or being stored, so that it can then be used in calculations like averages per hour. The trouble I have is that this information appears to be coming through as a stream of individual bytes, and in this format I'm having difficulty working out an effective way to specify which information I want to store, and which I want to ignore. I've been trying, for example, to come up with a way to specify that the first 14 bytes (serial number, comma, space - as this will always be the same length) should be ignored, and then the next series (up until the next comma - as this reading could be 4-6 digits) be stored as an int, or something, but I just can't seem to get anywhere no matter what I try. Does anyone have any suggestions?

# Answer
Since the length of each data varies, you should extract data using spererator like comma in the stream.

**First**, get one data line from sensor. Read the string until the "Line feed(LF)" character or "Carriage Return(CR)" character appears. located at the end of line(EOL), these two characters seperates each string by changing line. Without these two characters, the monitor shows the stream like this(no line change).

> 102617010933, 8486, 22, 35, 13464, 25716, 21962, 00, 00, 20, 06102617010933, 87216, 22, 35, 13576, 25223, 21442, 00, 00, 20, 07

So you can see there are CR, LF characters at the EOL. Utilize CR or LF as a terminator of ReadStringUntil() function. https://www.arduino.cc/en/Serial/ReadStringUntil

**Second**, parsing process. This process is extracting data you want from `strtok()` function. strtok() is from C language. It divides string by seperator characters. https://stackoverflow.com/questions/3889992/how-does-strtok-split-the-string-into-tokens-in-c?utm\_medium=organic&utm\_source=google\_rich\_qa&utm\_campaign=google\_rich\_qa

**Lastly**, utilize the data and repeat whenever sensor sends the data.

I'm not expert at coding. I haven't tested the code below. But this code would be helpful.

```
int data[12];
int isDataReceived = false;

void setup(){
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.write('c');
}

void loop(){
  while(Serial1.available()>0) {
    String inString = Serial1.readStringUntil('\n');
    char * pch = strtok(inString, ","); //Serial number would be ignored
    for(int i=0; pch != NULL; i++) {    //following data are stored in data[12] string
      pch = strtok(NULL, ",");
      data[i] = atoi(pch);
    }
    isDataReceived=true;
  }
  if(isDataReceived) {
    Serial.print("Data:");
    Serial.println(data[0]); //just example code. You may see ppb on the serial monitor.
    isDataReceived=false;
  }

}

```
> 1 votes

---
Tags: serial, sensors, arduino-due, serial-data
---


# Question
Title: when i compile this code it always 'sendCommand' was not declare in this scope..plzz help
```
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(10, 11); // RX, TX

void setup() { // Open serial communications and wait for port to open:
  Serial.begin(9600); //for monitoring purposes

  sendCommand("AT+CIFS+RST\r\n", 2000, DEBUG); // reset module
  sendCommand("AT+IPR=115200\r\n", 1000, DEBUG);
  sendCommand("AT+CWMODE=1\r\n", 1000, DEBUG); // configure as access point
  sendCommand("AT+CWJAP=\"ABCDEFG\",\"12345678\"\r\n", 3000, DEBUG); //connect to a network with name ABCDEFG with password 12345678
  delay(1000);
  sendCommand("AT+CIFSR\r\n", 1000, DEBUG); // get ip address
  sendCommand("AT+CIPSTA=\"192.168.43.16\"\r\n", 1000, DEBUG);
  sendCommand("AT+CIPMUX=1\r\n", 1000, DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,6625\r\n", 1000, DEBUG); // turn on server on port 6625
  Serial.println("Server Ready");

}

void loop() { // run over and over
  if (esp8266.available()) {
    if (esp8266.find("+IPD,0,")) {
      delay(10);
      esp8266.find(":");
      delay(10);
      char letter = esp8266.read();
      Serial.print(letter); //for monitoring purposes
      //Gets the value/char from android app
    }

String sendCommand(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command); // send the read character to the esp8266
  long int time = millis();
  while ((time + timeout) > millis()) {
    while (esp8266.available()) {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }

  if (debug) {
    Serial.print(response);
  }
  return response;
}

```

# Answer
In `loop` you have three opening braces and one closing brace. This won't end well:

```
void loop() { // run over and over
  if (esp8266.available()) {
    if (esp8266.find("+IPD,0,")) {
      delay(10);
      esp8266.find(":");
      delay(10);
      char letter = esp8266.read();
      Serial.print(letter); //for monitoring purposes
      //Gets the value/char from android app
    }

```

Two more closing braces would fix it.
> 2 votes

---
Tags: arduino-uno, serial, softwareserial
---


# Question
Title: Compiling with -flto and -nostartfiles results in no program at all
Towards developing my own bootloader I've stumbled over an issue with `avr-gcc`. I am trying to compile my code with the compiler flags

```
-flto          #to enable link time optimization
-nostartfiles  #to omit the interrupt vector table

```

My bootloader consists of multiple files which are used depending of compile flags. All the sources are being compiled and linked while the code path only leads to some portions of them. So I wanted to get rid of the dead code and `-flto` (being a newer development) creates a much smaller machine code size than `-ffunction-sections -fdata-sections` with `-Wl,--gc-sections -Wl,--print-gc-sections`.

But when it comes to further reducing the machine code size by removing the interrupt vector table using `-nostartfiles`, the complete code gets optimized away leaving me with a zero byte output.

Has anyone experienced the same issue with that compiler flag combination?

# Answer
> 1 votes
As @MaximilanGerhardt wrote in his comment. LTO was optimizing away too much of the code. Usual programs start with the interrupt vector table that in case of a regular reset or startup point to the `main` function. That is why the compiler knows that `main` has an entry point and is used. The actual program starts at the table.

Removing the interrupt vector table with `-nostartfiles` causes the compiler not to know that `main` is used at all and optimizes it away.

To give the compiler a hint `__attribute__((used))` has to be placed at all methods that have to stay and there is no code path leading to them otherwise.

---
Tags: bootloader, compile
---


title: making a LCD dice for catan

text:
# Question
Title: making a LCD dice for catan
when I go to upload the code, I get

```
 Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"
C:\Users\taran\Documents\Arduino\dice in progress\dice in progress1\diceinprogress\diceinprogress.ino:1:25: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino/"DFRkeypad.h": Invalid argument
#include <"DFRkeypad.h">
                     ^
compilation terminated.
exit status 1 Error compiling for board Arduino/Genuino Uno.

```

and the code is

```
#include <"DFRkeypad.h">
#include <LiquidCrystal.h>
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
const char* DFRkeypad::sKEY[]=                          { "---",       "Right",   "Up", "Down", "Left", "Select", "???" };
const int DFRkeypad::iARV_VALUES[DFRkeypad::eNUM_KEYS]= { 1023,        0,         143,  328,    504,     740,      -1   };
int btnSELECT;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(1, 0);
  lcd.print("Roll the dice!");
}

void loop() {
while (btnSELECT == 0){

  delay (50);
  buttonState = analogRead(btnSELECT);
}

 case btnSELECT:
     {
     lcd.print("Rolling dice");
       diceOne = random(1, 7);
       diceTwo = random(1, 7);
     break;
    }
}

```

# Answer
> 2 votes
In C/C++ you either use the `#include` pre-processor statement in the form of

```
#include "someFile.h"

```

or

```
#include <someFile.h>

```

The form

```
#include <"someFile.h">

```

is not legal. You must correct it to one of the two forms above.

The difference between those forms is explained in https://stackoverflow.com/a/77092/5296568.

---
Tags: arduino-uno, lcd
---