title: making a digital dice

text:
# Question
Title: making a digital dice
i'm trying to make a digital dice to play catan with, here's what i have so far

```
#include <LiquidCrystal.h>
#include <DFR_LCD_Keypad.h>

// this is factory config shield initialisation
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// initialise the keypad
DFR_LCD_Keypad keypad(A0, &lcd);
int lcd_key     = 0;
int abc_key_in;
int read_LCD_buttons;
int  diceOne;
int  diceTwo;
#define btnSELECT 4
int read_LCD_buttons()
{
  abc_key_in = analogRead(0);
if (abc_key_in < 790) return btnSELECT;}
const int button = 4;
const int BUTTON4LOW = 400;
const int BUTTON4HIGH = 650;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i
}

void loop() {
  int reading =  analogRead (A0);

  lcd_key = read_LCD_buttons();

 if (reading<BUTTON4LOW && reading<BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

  if (diceOne + diceTwo == 7) {
    lcd.clear();
    lcd.setCursor(7, 0);
    lcd.print("7");
    lcd.setCursor(3, 1);
    lcd.print("The pirate");

      if (diceOne + diceTwo == 3,2,1,5,4,6) {
          lcd.clear();
          lcd.setCursor(7, 0);
          lcd.print("fish");
      }
      }
  }
}
}

```

and im running into a error code saying

```
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons'
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'int read_LCD_buttons()':
demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void setup()':
demo_simple:28: error: 'i' was not declared in this scope
   i
   ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void loop()':
demo_simple:34: error: 'read_LCD_buttons' cannot be used as a function
   lcd_key = read_LCD_buttons();
                              ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: At global scope:
demo_simple:58: error: expected declaration before '}' token
 }
 ^
exit status 1
'int read_LCD_buttons()' redeclared as different kind of symbol

```

# Answer
You have

```
int read_LCD_buttons;

int read_LCD_buttons()
{
//..
}

```

You can't have a variable `int read_LCD_buttons` at the same time as a function called `read_LCD_buttons` -- this identifier is already taken. It looks however like you're not assigning or reading anything from this variable, so it probably never should have existed in the first place -- deletion is the solution.

In the case that you wanted to write a function prototype (which you by the way don't have to write in the Arduino IDE because it autogenerates them), the correct form would have been

```
int read_LCD_buttons();

```

i.e., the exact same prototype ended by a `;`.

In `setup()` you have a random `i` which doesn't belong there.

```
void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i //delete this line
}

```

Finally, you have a mismatch of opening and closing curly braces. Always format your code correctly, so that these errors are more easily spotted! You have one final `}` too much.

```
void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");

      if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
        lcd.clear();
        lcd.setCursor(7, 0);
        lcd.print("fish");
      }
    }
  }
}
} //This } is too much!

```

Then you'll also see that the third `if` statment which checks for a sum is actually within another expression where it was asserted that the sum is already 7. Then the inner `if` can never become true. You probably meant to move the `if` to the outer part, i.e. write

```
void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");
    }
    //the line below is still wrong
    if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("fish");
    }
  }
}

```

Next, this expression makes no sense.

```
if (diceOne + diceTwo == 3,2,1,5,4,6)

```

I think you meant that "if the sum of diceOne and diceTwo are equal to either 3, 2, 1, 5, 4, or 6 (i.e. within 1 and 6 inclusive), then do something.

Using multiple or statments this would be expressed as

```
if ((diceOne + diceTwo == 3) || (diceOne + diceTwo == 2) || (diceOne + diceTwo == 1) || (diceOne + diceTwo == 5) ||(diceOne + diceTwo == 4) || (diceOne + diceTwo == 6))

```

Or using the simpler interval check, assuming both numbers are positive and greater than 1.

```
if( diceOne + diceTwo <= 6)

```

Also this expression is suspect

```
if (reading<BUTTON4LOW && reading<BUTTON4HIGH)

```

When you have a LOW and a HIGH boundary and you want to check if `reading` is between these, you would write it as "if reading is greater than the lower boundary and less than the higher boundary", i.e.,

```
if (reading > BUTTON4LOW && reading < BUTTON4HIGH)

```
> 2 votes

---
Tags: arduino-uno
---


title: sbi() and cli() implementation

text:
# Question
Title: sbi() and cli() implementation
I've often seen `cli()` and `sbi()` in Arduino code. I usually don't mind them as I know what they do (clear or set the bit given as second argument in the register of the microcontroller given as first). I've always thought that those functions where only a clear way to perform simple bit manipulation, which can be quite error-prone. Something like that: `#define cli(reg,bit) (*reg &= ~(1 << bit)` and `#define sbi(reg,bit) (*reg |= (1 << bit))`.

Then I found out that the actual implementation is as follows:

```
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

```

It's quite like I used to think... but with two extra macros. I looked for them in the Arduino libraries:

```
#define _BV(bit) (1 << (bit))

```

and

```
#define _SFR_BYTE(sfr) _MMIO_BYTE(_SFR_ADDR(sfr))

```

which contains

```
#define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr))

```

and

```
#if _SFR_ASM_COMPAT
#if (__SFR_OFFSET == 0x20)
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)
#elif !defined(__ASSEMBLER__)
#define _SFR_ADDR(sfr) (_SFR_IO_REG_P(sfr) ? (_SFR_IO_ADDR(sfr) + 0x20) : _SFR_MEM_ADDR(sfr))
#endif
#else  /* !_SFR_ASM_COMPAT */
#define _SFR_ADDR(sfr) _SFR_MEM_ADDR(sfr)

```

Further research took me to definitions I couldn't understand (for example because they are explained in comments using a lot of acronyms I don't know). So I have the following questions:

* Why is `sfr` casted to `*(volatile uint8_t *)`?
* What do the acronyms used in that code mean? (`ASM`, `SFR`, `MMIO`)
* Under what circumstances is `__ASSEMBLER__` defined, and where (in which file)?
* Why can't we simply write `#define cli(reg,bit) (*reg &= ~(1 << bit)` and `#define sbi(reg,bit) (*reg |= (1 << bit))`?

# Answer
> 4 votes
> Why is sfr casted to \*(volatile uint8\_t \*)?

Because you want the *content* (the first `*`) of a memory address that you specify, and you need it volatile so it doesn't cache it. Oh, and it's an 8-bit value.

> What do the acronyms used in that code mean? (ASM, SFR, MMIO)

ASseMbly, Special Function Register and Memory Mapped Input/Output

* ASM means assembly language.
* A Special Function Register is something like DDRB.
* Memory Mapped IO is a way of interacting with peripherals by reading from and writing to locations in the normal memory address space.

> Under what circumstances is `__ASSEMBLER__` defined, and where (in which file)?

It is defined by the compiler when you are compiling an assembly file.

> Why can't we simply write `#define cli(reg,bit) (reg &= ~(1 << bit)` and `#define sbi(reg,bit) (reg |= (1 << bit))`?

Because `reg` is just an address. You need to convert that into a variable in memory that you can reliably access (hence the *volatile*). Further to that, not all chips use MMIO for all peripherals - some can be accessed by more efficient IO instructions. That said, in many cases yes you can just use simpler code. After all, things like `DDRB |= 0x04` works fine. It all depends on how the value to pass as `reg` is defined originally. By forcing a specific `volatile` cast you can ensure that whatever way it was defined (with or without volatile, etc) it will work.

# Answer
> 4 votes
On Atmel (now Microchip) AVR microcontrollers, the sbi, cbi, sbis, and sbic assembly language instructions can only address the 32 IO ports at addresses between 0x20 and 0x3f. The Atmega168 and 328 (used in Arduinos prior to the Leonardo) has WAY more than 32 IO registers, so only a subset of them can be addressed by sbi and cbi (the AVR instruction set was nailed down YEARS ago, when 32 IO registers seemed like more than enough).

As a result, operations that set or clear a single bit in those 32 IO registers can be performed by a single instruction which executes in two clock cycles, but the same operations on the remaining IO registers require a full-blown load-operate-store sequence that takes at least three cycles to execute.

From what I recall, AVRlibC had multiple macros that did almost the same thing, but had different use cases:

* One would compile to the fastest and most efficient instruction(s) available for that particular IO address.
* One would always compile to sbi/cbi, and would throw a compiler error if you tried to access a register outside of 0x20-0x3f
* One would ALWAYS compile to the load-act-store sequence, without regard to whether or not it could have used sbi/cbi instead.
* One would always compile to the load-act-store sequence, but would throw a compiler error if you tried using it on an address between 0x20 and 0x3f.

Basically, the choice enabled you to decide between optimized (but variable) performance, uniformly-slow (but deterministic) execution time, or the fastest-possible (but deterministic-at-compile-time) variant \[which required that the programmer be aware of whether the register in question was within or above 0x20-0x3f\].

---
Tags: c++, avr
---


# Question
Title: 360 degree motion of servo with position control
Is there any way I can control the position of servo by changing the value of potentiometer for using it for 360 deg motion?

# Answer
> 0 votes
A pot doesn't spin all the way around, so you could map hi/lo values, but you can't run more than one lap with it. You could add a button that silences the pot input, so that you can hold the button and dial back the pot, releasing the button to continue turning the servo with the pot. In that case, you use relative values between samples to turn the servo instead of simply feeding it the ADC value.

A rotary encoder is probably a better fit though, since it can spin 360 just like the servo. You would still want to "gear down" the encoder if you're micro-stepping, so that say, 4 turns of the encoder yields 1 turn of the servo. This allows full 360 and as much arbitrary precision as your project needs.

---
Tags: arduino-uno, servo
---


title: HC-06 Bluethoot communication

text:
# Question
Title: HC-06 Bluethoot communication
During this week i purchased two hc-06 bluethoot module for arduino with the purpose of maintain a stable bluethoot connection between two arduino devices. Most people use hc-05 and hc-06 togheter so my question is if i can make a connection without hc-05 module.

# Answer
> 1 votes
No.

What you have is two slave devices and you need a master in order to initiate the Bluetooth communication with the slave. So, either you need two HC-05 Or 1\* HC-05 and 1\* HC-06.

# Answer
> 0 votes
You have purchased two slave modules (HC-06). Actually, you have to use a master module (HC-05) in order to initiate the Bluetooth communication.

Therefore, the answer to your question is NO , can not make a connection without HC-05 module, unless you provide any other master module.

---
Tags: arduino-uno, bluetooth
---


# Question
Title: Breaking out of a while loop using IR remote for neopixel
I've been piecing together various lighting effects. I am wanting to have each lighting effect loop until another button is pressed to trigger another lighting effect.

I've come to a bit of standstill at the moment. I've created a loop that doesn't seem to end. I've had a look around but I can't work out how to fix my code. Sorry in advanced, I'm new to using arduinos but if anyone could help out, it would be much appreciated. Thanks!

```
//www.elegoo.com
//2016.12.9

#include "IRremote.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(20, PIN, NEO_GRB + NEO_KHZ800);

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
int Remote = 0;

/*-----( Function )-----*/
void translateIR() // takes action based on IR code received

// describing Remote IR codes

{

  switch(results.value)

  {
  case 0xFFA25D: Serial.println("POWER");
  ArrowRight(strip.Color(25, 0, 0), 100); //Red
  ArrowRight(strip.Color(0, 0, 25), 100); //Blue
//  Remote = 0xFFA25D;
  break;

  case 0xFFE21D: Serial.println("FUNC/STOP");
  ArrowLeft(strip.Color(25, 0, 0), 100); // Red
  ArrowLeft(strip.Color(0, 0, 25), 100); // Blue
//  Remote = 0xFFE21D;
  break;

  case 0xFF629D: Serial.println("VOL+"); break;
  case 0xFF22DD: Serial.println("FAST BACK");    break;
  case 0xFF02FD: Serial.println("PAUSE");    break;
  case 0xFFC23D: Serial.println("FAST FORWARD");   break;
  case 0xFFE01F: Serial.println("DOWN");    break;
  case 0xFFA857: Serial.println("VOL-");    break;
  case 0xFF906F: Serial.println("UP");    break;
  case 0xFF9867: Serial.println("EQ");    break;
  case 0xFFB04F: Serial.println("ST/REPT");    break;
  case 0xFF6897: Serial.println("0");    break;
  case 0xFF30CF: Serial.println("1");    break;
  case 0xFF18E7: Serial.println("2");    break;
  case 0xFF7A85: Serial.println("3");    break;
  case 0xFF10EF: Serial.println("4");    break;
  case 0xFF38C7: Serial.println("5");    break;
  case 0xFF5AA5: Serial.println("6");    break;
  case 0xFF42BD: Serial.println("7");    break;
  case 0xFF4AB5: Serial.println("8");    break;
  case 0xFF52AD: Serial.println("9");    break;
  case 0xFFFFFFFF: Serial.println(" REPEAT");break;

  default:
    Serial.println(" other button   ");

  }// End Case

  delay(0); // Do not get immediate repeat

} //END translateIR
void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  strip.begin();
  strip.show();
  Remote = 0;

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}/* --(end main loop )-- */

void ArrowRight(uint32_t c, uint8_t wait) {
  while (Remote = 0xFFA25D) {
    for (uint16_t i = strip.numPixels()/2; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
    }
    for (uint16_t i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(wait);
  }
}

void ArrowLeft(uint32_t c, uint8_t wait) {
  while (Remote = 0xFFE21D) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2-1; i + 1 > 0 ; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
    }
    for (uint16_t i = strip.numPixels(); i + 1 > 0 ; i--) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(wait);
  }
}

```

# Answer
> 1 votes
There are a few causes for eternal loops and other things that will go wrong in your code.

As ChrisL noted above you are assigning a value to Remote in the while condition which is almost certainly not what you wanted to do. On the plus side, every C/C++ programmer ever has also made that same mistake at some time or another.

Now if you change it to `while (Remote == 0xcFFE21D)` it still won't work, because Remote is always 0. You have commented out the lines that set Remote, but they are after the call to the function. To be honest since you know the value before you call the function (because of the switch statement) you don't need to check the value within the function so you could remove the while loop all together. If you intention is to call this function repeatedly until a different button is pressed on the remote, the way you are doing it won't work. you need to store the last button pressed value and then pass that into the switch statement. When a different button is pressed update the 'last button pressed' value.

You for loop conditions need looking at. I don't think that the number of lights in the strip is going to change while the program is running. If that's true then your are wasting processor instructions by doing `strip.numPixels()/2-1` you might want to look at setting global values in setup.

Also the for loops might benefit from using `i >= 0` because then you don't need to do `i+1` every loop.

---
Tags: led, ir, neopixel, loop
---


title: Two SD card interfaces on one ESP8266?

text:
# Question
Title: Two SD card interfaces on one ESP8266?
I know it's possible to hook up multiple SPI devices, but how can one access the second drive from a sketch?

Looking at the SDWebServer.ino example, my doubt is with the `SD.begin(SS);` part. If I call `begin()` again with the other CS pin, it seems that I would lose a reference to my first volume, or maybe it won't work at all. I would instantiate another `SD` instance, but the sketch never seems to instantiate that object, it first appears in `setup()` with `SD.begin(SS);`

If I copy the lib (sd.h+sd.cpp) and replace all literal instances of `SD` with `SD2`, can I then include and use `SD2` just like the original (provided the different `.begin(pin)`)? Is there a less hacky way of using two SD cards in ESP8266 Arduino?

In case anyone's wondering, it's for a crypto project where one card will contain one-time-pads of plaintext length and the other contains the XOR'd ciphertext, both are fed by wifi upload, and the max file size must be bigger than SPIFFS, so I really need two SD cards...

# Answer
> 1 votes
Not possible without changing the library code. Because the current library code is written intended for only one SD card, ie not intended for multiple SD cards because it will be complicated to do so. The SPI library also uses FatFS library, which is a bottleneck in this scenario.

**Worth a try.**

sdfatlib is library written for Arduino. I have never used it, but you can give a try on ESP.

Let us know if it works.

# Answer
> 0 votes
You should (I have not tested it) be able to do it if the library is well coded and doesn't use global variables and you do something like this:

```
// Don't know what the class name is so replace TYPE with what it should be.
TYPE SDCardOne;
TYPE SDCardTwo;

SDCardOne.begin(CS1);
SDCardTwo.begin(CS2);
....

```

---
Tags: esp8266, spi, sd-card
---


# Question
Title: Need help with an Arduino project using a RTC and LEDs
I need some help with a project I am doing involving the DS1307 RTC. I am trying to make what is essentially a way to mins quickly check the time which involves nine LEDs slowly lighting up every 10 so that I can quickly check time but looking at it. : So far I've tried TimeAlarms but I can't figure out how to do this. I have a Arduino Uno by the way.

Can someone possibly help?

# Answer
Use the SQW pin on the DS3231 or DS1307 to create 1sec pulse, read it on your Arduino. There are very good libraries are available (like RTClib from adafruit).
> 1 votes

---
Tags: arduino-uno, programming, rtc
---


# Question
Title: Issue in long ON OFF timer using millis()
I have 3 components: a relay and two LEDs...I want two timers using Arduino... In timer one, relay should be off on; one LED is off; and other is on...In second timer, relay is off; one led is on; other is off... This is my Code:

```
//const unsigned long onTime = (2 *3600000); // 2 Hours in miliseconds;
const unsigned long onTime = (3 *1000); // 3 seconds;
//const unsigned long onTime = (5 *60000); // 15 minutes;

//const unsigned long offTime = (0.5 *3600000); // 1/2 Hours in miliseconds;
const unsigned long offTime = (2 *1000); // 1 seconds;
//const unsigned long offTime = (5 *60000); // 5 minutes;

const unsigned long start_delay = (5 *60000);  // 5 minute in miliseconds

// Tracks the last time event fired
unsigned long previousMillis=0;

// Interval is how long we wait
int interval = onTime;

// Used to track if relay should be on or off
boolean relayState = true;

void setup()
{
  pinMode(13, OUTPUT); //Relay
  pinMode(3, OUTPUT); //LED Green for ON
  pinMode(4, OUTPUT); //LED Red for OFF

  digitalWrite(13, LOW);   // Relay Off
  digitalWrite(3, LOW);    // Green LED off
  digitalWrite(4, LOW);    // Red LED OFF

  //delay (start_delay);  // wait for 5 minute
}
void loop()
{
  if (relayState == true)
  {
    // Relay ON
    digitalWrite(13, HIGH);   // Relay ON
    digitalWrite(3, HIGH);    // Green LED ON
    digitalWrite(4, LOW);    // Red LED OFF
  }
  if (relayState == false)
  {
    // Relay OFF
    digitalWrite(13, LOW);   // Relay Off
    digitalWrite(3, LOW);    // Green LED Off
    digitalWrite(4, HIGH);    // Red LED On
  }

  // Grab snapshot of current time, this keeps all timing
  long currentMillis = millis();

  // Compare to previous capture to see if enough time has passed
  if ((unsigned long)(currentMillis - previousMillis) >= interval)
  {
    // Change wait interval, based on current relay state
    if (relayState)
    {
      // Relay is currently on, set time to stay off
      interval = offTime;
    }
    else
    {
      // Relay is currently off, set time to stay on
      interval = onTime;
    }
    // Toggle the relay's state
    relayState = !(relayState);
    // Save the current time to compare "later"
    previousMillis = currentMillis;
  }
}

```

Now issue is; when I make timer for seconds like OnTime is 3 second and offTime is 1 second... It works perfect... But timer for hours or minutes does not simply works... it does not switch state from on to off... It constantly remains on... What could be the problem... Thanks!

# Answer
You declare interval as an integer, while onTime and offTime are `unsigned long`.

Change `int interval = onTime;` to `unsigned long interval = onTime;`

The maximum value of `int` is only 32767 (215-1), which is only 33 seconds.

An `unsigned long` can be as high as 4294967296 (232-1). Which is around 49.7 days worth of milliseconds.
> 4 votes

# Answer
You should not depend on millis() function for long time delays, use an extra rtc chip(DS3231/DS1307) instead.

Theoretically millis() function should produce 1 millisecond time frame, but it is not exactly that. There will always be a difference; and if you multiply that small time difference with a big number, then there will be a significant delay.
> 0 votes

---
Tags: arduino-uno, timers, millis
---


# Question
Title: Response from ESP8266 is returning unknown characters
I'm working on a project with Arduino UNO that needs connection with a cloud server, that is why I'm using ESP8266 module.

I'm already connecting to wi-fi and making GET and POST request but my problem is get the response from these requests.

Here is my code:

```
/* Doing all these steps to make the request
AT+RST
AT+CWMODE=1
AT+CWJAP="MyNetwork","MyPassword"
AT+CIPMUX=1
AT+CIPSTART=0,"TCP","myserver.com.br",80
AT+CIPSEND=0,270
*/

String data = "data=example";

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
comando += "User-Agent: Arduino/1.0\r\n";
comando += "Connection: Close\r\n";
comando += "Content-Type: application/x-www-form-urlencoded;\r\n";
comando += "Content-Length: " + String(data.length()) + "\r\n\r\n";
comando += data;

esp8266.println(command);

delay(2000);

String response;

while(esp8266.available()) {
  response += esp8266.readStringUntil('\r');
}

Serial.print("Request response: ");
Serial.println(response);

```

When I run this code the only response I can get is something like:

```
Recv 270 bxt⸮⸮C⸮
SEND OK

+IPD,0.569:HTTP/1.0 200 OK

```

But I was expecting a JSON.

Can someone tell me what I am doing wrong and how can I resolve it?

---

Edit.

Ok, after Code Gorilla helps me (Thank you so much) and a lot of research what I did was program Arduino UNO to send some commands that I invented to serial and program ESP8266 to read the serial and, depending of the command that it reads, do requests and stuff.

ESP8266 is a lot easyer to make requests and have a lot of others possibilities, like HTTPS requests, that you can't do using AT Commands.

When I create this ask I didn't know that I could program directly in ESP8266, but when Code Gorilla told me about it and helps me with some articles I could finally continue with my project.

# Answer
> 1 votes
```
String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
...
esp8266.println(command);

```

I suspect this is just a typo because it shouldn't compile. But you are adding all the HTTP headers to **commando** not **command**.

Usually the ? means that the character is unprintable. So to help diagnose the issue display the integer value for each character that is returned. Something **LIKE** this (I've never used a `String` before so length() might not be right)

```
Serial.print("Request response: ");
Serial.println(response);
for (int index = 0; index < response.length(); ++index)
{
   Serial.print (response[index]);
   Serial.print (" ");
}

```

If you want to program the ESP directly then have a look at these guides, they should give you the general idea. Its usually as easy as programming an UNO once you are setup.

http://www.whatimade.today/esp8266-easiest-way-to-program-so-far/ https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide https://www.hackster.io/harshmangukiya/how-to-program-esp8266-with-arduino-uno-efb05f

---
Tags: arduino-uno, esp8266, http
---


# Question
Title: Program an Arduino Uno with an Atmel ICE
When I connected my atmel ice to my arduino uno everything went okay. Then I tried debugWIRE and since then I can't connect to my ATMEGA328p. I get the error `Failed to enter programming mode. ispEnterProgMode: Error status received: Got 0xc0, expected 0x00 (Command has failed to execute on the tool)` I think one of the fuse bits is wrong but can't connect to the ATMEGA328p to change them. Does anyone have a idea what to do?

# Answer
Your Ardunino is stuck in debugWIRE (The debug wire fuse is set). Here is a tutorial on how to get it back to programming mode.

In the tutorial I am using the AVR Dragon with AS6, but the process is the same with Atmel ICE and AS7.

You have to be in Debug Mode to disable debugWIRE. While in debug, Click Debug\>Disable Debug Wire and Close.
> 1 votes

---
Tags: atmel-studio
---


title: Optimal and Safe Water Pump Control

text:
# Question
Title: Optimal and Safe Water Pump Control
I'm using an Arduino Micro, a 12 V water pump, and a print relay to water a plant.

A water level switch monitors the the water tank to make sure the water pump does not run dry.

I tried different watering times and figured that when using longer watering times of 90,000 milliseconds and longer, the relay sometimes does not switch correctly and the pumps keeps running. I'm not sure if my code is optimal for that kind of purpose:

```
const int Power_Water = 3; // Pin to turn the Pump On and Off via relay
const int Watering_Time = 90000; // Time the water's supposed to run
const int Water_Tank = 10; // Water Level Switch

void setup() {
  Serial.begin(9600);
  pinMode(Power_Water,OUTPUT); // Pin that triggers the Relay as Output
  pinMode (Water_Tank,INPUT_PULLUP); // Pin of Water_Level Sensor as internal pullup
}

void loop () {
  unsigned long watering_Start = millis();

  while (millis() - watering_Start <= Watering_Time && (digitalRead (Water_Tank) == LOW)) {
    digitalWrite(Power_Water,HIGH); // Water Pump goes ON
    Serial.println(millis() - watering_Start);
  }

  if (millis() - watering_Start > Watering_Time || (digitalRead (Water_Tank) == HIGH)) {
    Serial.println("Pump OFF");
    digitalWrite(Power_Water,LOW);// Water Pump OFF
   }
   delay(100000000); // example "sleep" time the system is not supposed to water
}

```

Any suggestions are appreciated.

I changed

```
const int Power_Water = 3; // Pin to turn the Pump On and Off via relay
const long Watering_Time = 90000; // Time the water's supposed to run
const long Water_Tank = 10; // Water Level Switch

void setup() {
  Serial.begin(9600);
  pinMode(Power_Water,OUTPUT); // Pin that triggers the Relay as Output
  pinMode (Water_Tank,INPUT_PULLUP); // Pin of Water_Level Sensor as internal pullup
}

void loop () {
  unsigned long watering_Start = millis();
  digitalWrite(Power_Water,HIGH);
  while (digitalRead(Power_Water) == HIGH) {
    Serial.println(millis() - watering_Start);
    if (millis() - watering_Start > Watering_Time || (digitalRead (Water_Tank) == HIGH)) {
      Serial.println("Pump OFF");
      digitalWrite(Power_Water,LOW);
    }
  }
  delay(100000000); // example "sleep" time the system is not supposed to water
}

```

# Answer
That delay statement totally defeats the purposes of your millis code. If you want to enforce a minimum off time then you'll have to do that with millis as well. Using millis in this way requires that you allow the loop function to repeat many thousands of times per second. As written you only allow the loop function to run through once every eleven and a half days.
> 1 votes

---
Tags: relay, loop
---


# Question
Title: Serial.write(buf, len) error. How to remove an error and pass an array of bytes?
```
int angleServo1,angleServo2 = 0;
const int axisX=A0; // ось Х подключена к A0
const int axisY=A1; // ось Y подключена к A1
int valX, valY = 0; // переменные для хранения значений осей
int datos[3];
#include <SPI.h>

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

void loop()
 {
      valX = analogRead(axisX); // значение оси Х
      valY = analogRead(axisY); // значение оси Y
      // масштабируем значение к интервалу 0-180
      angleServo1=map(valX,0,800,100,-100);
      angleServo2=map(valY,0,810,100,-100);

       datos[0] = angleServo1;
       datos[1] = angleServo2;
       Serial.write(datos, sizeof(datos));
       delay(100);
}

```

error: no matching function for call to 'HardwareSerial::write(int \[3\], unsigned int)'

how to remove an error and pass an array of bytes?

# Answer
> 2 votes
You want to send data to computer processing or print them for user to read? Functions `write` send raw data. To print the data to Serial monitor `print` and `println` functions are used.

There are two `write` functions. First sends one byte. Second sends array of bytes. There is no write function to send array of ints. You could cast the array of ints to array of bytes to send the array as raw bytes for processing on the receiving side. But then you first should perhaps send to the receiving side some control data about the data package.

```
  Serial.write((byte*) datos, sizeof(datos));

```

If you want to print numbers to Serial Monitor, the `print` functions have variants which take a number and convert it to string. But there is no `print` function to print an array of numbers. You must print them one by one in a for loop. And put some separator between them (coma, space, new line).

---
Tags: serial
---


# Question
Title: How to transmit string data using the rc-switch library?
I am using the rc-switch library for sending and receiving data. In rcswitch library, there is no method to send string data. I am using below method to send the string message in char buffer.

```
send_string("Hello World!");
---------------------------

void send_string(const char *str)
{
int i = 0;

for (char *p = str; *p; p++ ) {
mySwitch.send((i<<8) + *p, 16);
i++;
}
mySwitch.send((i<<8) + 255, 16);
}

```

And I am receiving is using this **Serial.print((char)mySwitch.getReceivedValue());** build in method. But I am getting this message.

```
H
H
H
e
e
e
l
l
l
l
l
l
o
o
o

W
W
W
o
o
o
l
l
l
d
d
d
!
!
!

```

Now how can I get my original message?

# Answer
The communication protocol used by this library is unreliable. Thus, each code word is sent multiple times, 10 times by default. One solution around this problem is to send a “byte number” along with each byte you transmit. You would then transmit 16-bit words, where the MSB (most significant byte) is the byte number, and the LSB is the actual byte you want to transmit. Something like this:

```
int i = 0;
for (char *p = str; *p; p++) {
    mySwitch.send((i<<8) + *p, 16);
    i++;
}

```

Oh, wait! That's exactly what you are already doing! So it appears that you are already aware of this issue and you have even implemented a solution. How come you are asking this question then?

OK, I'll assume in the following that you just forgot to tells us that the code snippet above is not from you, and that you didn't even understand what it is doing. And you also forgot to provide a link to the source of that code. Please, next time read How do I ask a good question? before asking, and provide all the relevant information right in the question.

So now the problem is in the reading side. You have to use those byte numbers to remove the duplicates. One (untested) solution could look like this:

```
// Return a received byte, or -1 if none is available.
int receivedValue()
{
    if (!mySwitch.available())  // no byte available
        return -1;
    static uint8_t last_byte_number = 0xff;
    uint16_t code = mySwitch.getReceivedValue();
    uint8_t this_byte_number = code >> 8;
    if (last_byte_number == this_byte_number)  // this is a duplicate
        return -1;
    last_byte_number = this_byte_number;
    return code & 0xff;  // LSB is the byte to return
}

```

And you could use it to print the data on the serial monitor like this:

```
int c = receivedValue();
if (c != -1)  // if we really got a new byte
    Serial.write(c);

```
> 1 votes

---
Tags: esp8266, arduino-ide, library, string, buffer
---


# Question
Title: Arduino Modbus Master code to read data using arduino uno from EB meter
I am using DC energy meter as slave.When I am testing DC energy meter using Modbus tester tool,its showing value from 1 to 24 register.I am using my own atmega328P with on board RS485 as a master device.I have connected A,B from slave to mater board.Now,I want to read slave outputs using my master.For that I have written below mentioned code.when I am serially printing array,its showing 00000000000000000000000000000000769.I am not getting full data on my master.

```
#include <ModbusRtu.h>

// data array for modbus network sharing
uint16_t au16data[64];
uint8_t u8state;

int i;

/**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
Modbus master(0,0,1); // this is master and RS-232 or USB-FTDI

/**
 * This is an structe which contains a query to an slave device
 */
modbus_t telegram;

unsigned long u32wait;

void setup() {
  master.begin( 9600 ); // baud-rate at 19200
  master.setTimeOut( 2000 ); // if there is no answer in 2000 ms, roll over
  u32wait = millis() + 1000;
  u8state = 0;
}

void loop() {
  switch( u8state ) {
  case 0:
    if (millis() > u32wait) u8state++; // wait state
    break;
  case 1:
    telegram.u8id = 1; // slave address
    telegram.u8fct = 3; // function code (this one is registers read)
    telegram.u16RegAdd = 1; // start address in slave
    telegram.u16CoilsNo = 24; // number of elements (coils or registers) to read
    telegram.au16reg = au16data; // pointer to a memory array in the Arduino

    master.query( telegram ); // send query (only once)
    u8state++;
    break;
  case 2:
    master.poll(); // check incoming messages
    if (master.getState() == COM_IDLE) {
      u8state = 0;
      u32wait = millis() + 100;
    }
    break;
  }
 //au16data[4] = analogRead( 0 );

 for(i=0;i<=64;i++)
 {
  Serial.print(au16data[i]);
 }
 Serial.println("\n");
 Serial.println("\n");
 delay(1000);
 }

```

# Answer
> 0 votes
The response is received when ModbusRtu library object is again in the `IDLE` state after a request was sent. In your code based on the example from the library, the response is ready in state `2` which follows state `1` where the request was sent. If in state `2` when the `master` object state changes to IDLE, you can use the response in array `au16data`.

---
Tags: arduino-uno, modbus
---


title: 4WD rover not moving

text:
# Question
Title: 4WD rover not moving
I am trying to make a 4WD vehicle. I have uploaded the code, all connections are OK and I have used L298N and HC-05. But when running the Bluetooth app, the motors do not rotate. I tried with both an Uno and a Nano and nothing happens. Could anyone help me spot the errors?

I used this code in Arduino Uno:

```
#include <SoftwareSerial.h>

SoftwareSerial BT(0, 1); //TX, RX respetively
String readvoice;

void setup() {
  BT.begin(9600);
  Serial.begin(9600);
  pinMode(4, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
}
//-----------------------------------------------------------------------//
void loop() {
  while (BT.available()) {  //Check if there is an available byte to read
    delay(10);              //Delay added to make thing stable
    char c = BT.read();     //Conduct a serial read
    readvoice += c; //build the string- "forward", "reverse", "left" and "right"
  }
  if (readvoice.length() > 0) {
    Serial.println(readvoice);

    if (readvoice == "*forward#")
    {
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*back#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
      delay(100);
    }
    else if (readvoice == "*left#")
    {
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(800);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*right#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(800);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*stop#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*keep watch in all direction#")
    {
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(100);
    }
    else if (readvoice == "*show me Garba#")
    {
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);

      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(400);
      digitalWrite(3, HIGH);
      digitalWrite(4, HIGH);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
      delay(600);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, LOW);
      delay(500);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, HIGH);
      delay(500);
    }
    readvoice = ""; //Reset the variable
  }
}

```

This is the wiring diagram of the rover:

# Answer
> 2 votes
If you have the wiring right, which you have probably checked 100 times by now, then its probably the fact that you aren't supplying enough current to break the stall of the motor. Search the web for the motor's datasheet and look up the "Stall current" then see if you are supplying enough current.

Have you checked the motor without the gearbox attached, if that's possible?

The motor will have both voltage and current requirements. You are using a 6V motor but we also need to know the running current and stall current so you can workout if your batteries are capable of supplying that. Are you trying to run one motor or 4? Get one motor working first and then move up to 4 when you need to supply 4 times the power.

Also can I just check that you have the batteries in series (to give you 7.4V). This probably isn't enough if the motors require exactly 6v because of the 2V drop through the IC.

Measure the voltage into the bridge and into the motor, as shown in the web page. Also measuring the current would help, but you will have to search to see how best to do that.

---
Tags: arduino-uno, arduino-nano
---


title: Arduino Mega RS485

text:
# Question
Title: Arduino Mega RS485
I am following the instructions from this page to set up RS485 communication between two Arduinos.

https://arduino-info.wikispaces.com/SoftwareSerialRS485Example

My wiring varies slightly from the demo in that;

DI (data in)is Pin 18 (11 in the example) RO (receive out) is pin 19 (10 in the example) DE (data enable) and RE (receive enable) jumpered together and to pin 5

When I use the script, I can see the built in LED go dark when sending, but I don't get the echo back, nor do I see the LED on the remote blink for the receive.

Is there a fundamental problem with the pins I am using on the MEGA, or am I having difficulty with the script?

Thanks!

# Answer
I don't know what is wrong with your setup, but I suggest you start by testing with a simpler program.

Below is a program that simply copies bytes from the USB link (the bytes coming from the Arduino's serial monitor) to the RS-485 bus, or the other way around depending on a `#define`. Both Arduinos should be connected as follows:

```
Arduino     transceiver
--------------------------------
GND         GND
5V          VCC
TX1 (18)    DI (driver input)
RX1 (19)    RO (receiver output)

```

Additionally, connect:

* on the sending side:
    + the USB plug to your computer
    + the transceiver's DE (driver output enable) and RE (receiver output enable) to the Arduino 5V
* on the receiving side:
    + the transceiver's DE and RE to the Arduino GND

Make sure both Arduinos are powered and share a common ground. Optionally, you can connect the receiving Arduino to your computer, if you can manage to tell the USB links apart.

Then load the program below to both of them. Make sure you comment-out the line `#define SENDER` before programming the receiver.

```
// The "sender" copies bytes from the USB link (Serial) to the RS-485
// bus (Serial1). The receiver copies them the other way around.
// Comment-out this line for the receiver.
#define SENDER

#ifdef SENDER
HardwareSerial &inputStream  = Serial;
HardwareSerial &outputStream = Serial1;
#else
HardwareSerial &inputStream  = Serial1;
HardwareSerial &outputStream = Serial;
#endif

void setup()
{
    inputStream.begin(9600);
    outputStream.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);  // used to show activity
}

void loop()
{
    // Copy input stream to output stream.
    if (inputStream.available()) {
        digitalWrite(LED_BUILTIN, HIGH);
        outputStream.write(inputStream.read());
        outputStream.flush();
        digitalWrite(LED_BUILTIN, LOW);
    }
}

```

Now you can test sending strings through the serial monitor and seeing whether both LEDs blink. If you connect both Arduinos to your computer, you could use a terminal emulator (screen, putty, minicom... depending on your OS) to get the characters back from the receiving Arduino.

If all that fails, get a scope and look at all the signals along the path.
> 1 votes

---
Tags: arduino-mega, rs485
---


title: Wemos D1 doesnt drive Relay

text:
# Question
Title: Wemos D1 doesnt drive Relay
I recently bought a Wemos D1 board and tried to connect a relay and test its connection.

I got an example server from here and executed. I connected D5 to a Relay's data and 5v and GND from Wemos board.

But this does not change the state of relay, it always remains high. I connected a LED for D5, it works perfectly with client's response.

Then I powered relay using an external 5v and ground connection, but the same result.

I have checked for possible solution, but coulnt find an answer.

The relay I am using is this one

# Answer
> 3 votes
The board which you are using is operating on 3v3. Even if you try to run the relay using the D5 or any other pin on the board, you may not be able to run it successfully at all times. In this case, you can go for either MOSFETs or Pull-up resistors so that you can hold the voltage to 5V for triggering the relay. I would personally suggest to go for a PNP type.

As requested by Sachith, here is the circuit suggested for the problem stated. Just note that the voltage source should be `+5 V` (which is `+1 V` in the schematic). Also, the MOSFET is not the specific one, it is just for the schematic purpose.

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-uno, esp8266, power, relay
---


# Question
Title: Bluetooth Modules not communicating correctly
I plug in BT rx to digital 11, BT tx to digital 10 and then 5v and ground from the HC-05 to the arduino. I then upload this code to the HC-05 that is set as a master.

```
#include <SoftwareSerial.h>

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

void setup() {
  Serial.begin(57600);
  mySerial.begin(9600);
}

void loop() { // run over and over
  Serial.println(mySerial.read());
  delay(2000);
}

```

I then upload this code to the arduino with the HC-05 that is set as a slave:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10,11); // RX , TX

void setup() {
  // put your setup code here, to run once:
  mySerial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  mySerial.write("100");
  delay(2000);
}

```

The issue is that I never receive "100" on the serial monitor, I only ever receive 49 and occasionally 48. When I changed it from "100" to "10" same thing happened. Any help would be appreciated.

# Answer
SoftwareSerial.read() returns a single character as an integer. When you print an integer the print() functions convert it to a human readable format.

You want to covert (cast) the output of read() to the char type. Either:

```
void loop() {
  char c;
  c = mySerial.read(); // store the result in a temporary variable c
  Serial.println(c);
  delay(2000);
}

```

or

```
void loop() {
  Serial.println((char)mySerial.read()); // cast the type to char befor printing.
  delay(2000);
}

```

However since only one character at a time is being read your output will be one character per line (assuming no data loss due to the delay):

```
1
0
0

```
> 1 votes

# Answer
"You are getting 49 and 48 occasionally"?

I would expect you to get 49, 48, 48, 49, 48, 48 ...

49 is '1' in ASCII and guess what 48 means :)

This is because you are writing and reading bytes not characters. There is a very subtle difference.

change you receiver to this and it should make more sense.

```
void loop() { // run over and over
  const char letter = (char)mySerial.read(); // Turn the byte into an ASCII letter.
  Serial.println(letter);
  delay(2000);
}

```

It may all still go wrong, if you read \<32 or \>126 but ...

Here is an ASCII table to help: ASCII Table
> 1 votes

# Answer
You should change the TX and the RX pins on the arduino board and pin it on to another pin other than the TXD and RXD as the are hardware pins....
> -1 votes

---
Tags: arduino-uno, bluetooth, softwareserial, hc-05, hc-06
---


# Question
Title: minimal code for multiple buttons de-bouncing
i have 4 buttons attached to 4 pins configured as inputs with internal pull-up activated...

is this function sufficient to get a debounced state of the pressed button?

```
byte buttonPressed(){
  byte btn = 0;
  if (digitalRead(30)==LOW) btn = 1; else
  if (digitalRead(9)==LOW) btn = 2; else
  if (digitalRead(31)==LOW) btn = 3; else
  if (digitalRead(8)==LOW) btn = 4;
  delay(20);
  return btn;
}

```

any strictly necessary improvements are welcome...

# Answer
> 3 votes
Yes, your code should work as the most basic debouncing, although the debouncing time may be a little bit short. Note however that, in many instances, one would like to have a little more that the most basic. One may also want:

* *deglitching*: when the button is held down, your hand may make the contacts move a little bit, making spikes in the reading that are not associated with a real change in the button position; you don't want those spikes to read as "released and pressed again"
* *edge detection*: many times you are more interested in the button press event than in knowing whether the button is down or up; this can be handled by another function, but it can be convenient to integrate it with the debouncing
* *non blocking operation*: your program may have better things to do than wasting CPU cycles inside `delay()`.

Those are the reasons most debouncing codes are significantly more complex. But it's often worth it.

---

**Edit 1**: In view of the comments, some clarification seems to be needed. There are two kinds of glitches a mechanical button can experience:

1. when the button is mechanically changing position, i.e. it is being depressed or released; this is called a *bounce*
2. when the button is being held down, especially if the pressure on the button is low and the finger applying that pressure is somewhat shaky.

Most debouncing libraries you can find actually address both kinds of glitches. Thus, they do *more* than just debouncing, they do what I called “deglitching”. The previous answers implicitly assume that a proper debouncing code *must* address both kinds.

The code posted in the question only addresses the first kind of glitches, i.e. the *bounces* in the strict sense. That's why I wrote that it does the “most basic debouncing”. It is however susceptible to the second kind of glitches. So yes, with this code glitches can persist even after debouncing.

**Edit 2**: As an example, consider the Bounce 2 library. It provides edge detection, non blocking operation and, in the default configuration, full deglitching. However, it can be configured to use an alternative debounce algorithm called “Lock-out interval”, which is more responsive but does not protect against the “type 2” glitches mentioned above: it “does not cancel noise”, as the documentation puts it.

# Answer
> 0 votes
No. Actually it just checks each button one by one. In addition only the last button is checked since it overwrites the btn variable.

The simplest way to use debouncing button 1 is:

```
byte buttonPressed()
{
    byte btn = 0;

    byte btn1Before = digitalRead(30);
    delay(50); // Wait 50 ms, or 100 depending on your debouncing time
    byte btn1After = digitalRead(30);

    if ((btn1Before == LOW) && (btn1After == LOW))
    {
        btn = 1;
    }
}

```

You have to do similar as the others. You can use only one delay (just add 4 before and after variables and check them.

```
byte buttonPressed()
{
    byte btn = 0;

    byte btn1Before = digitalRead(30);
    byte btn2Before = digitalRead( 9);
    byte btn3Before = digitalRead(31);
    byte btn4Before = digitalRead( 8);

    delay(50); // Wait 50 ms, or 100 depending on your debouncing time

    byte btn1After = digitalRead(30);
    byte btn2After = digitalRead( 9);
    byte btn3After = digitalRead(31);
    byte btn4After = digitalRead( 8);

    if ((btn1Before == LOW) && (btn1After == LOW))
    {
       btn = 1;
    }
    else if ((btn2Before == LOW) && (btn2After == LOW))
    {
       btn = 2;
    }
    else if ((btn3Before == LOW) && (btn3After == LOW))
    {
       btn = 3;
    }
    else if ((btn4Before == LOW) && (btn4After == LOW))
    {
       btn = 4;
    }

    return btn;
}

```

Note that this way the program will be unresponsive for 50 ms. If you do not want this, you have to use millis, but this makes it more complex. Check the debouncing example on the Arduino site.

# Answer
> 0 votes
No - simply `delay()`ing after reading the button doesn't tell you whether the button is still bouncing or, more importantly, what its final state is. Debouncing requires you to know that the button

* changed state;
* has stopped changing state;
* what state it has settled into.

You'll need to notice the current state doesn't match the last debounced state you saw; then either test it frequently until it doesn't change state again for some number of tests, or simply wait the known maximum time it takes to settle; then read, store, and return the final state.

# Answer
> 0 votes
While @MichelKeijzers answer is a nice solution for simple querying in the main loop. This is not practicable for interrupts. Interrupts can block the entire MCU and interrupting an interrupt routinte can cause serious problems.

Depending on your requirements I'd suggest to take a look at using capacitors and resistors for debouncing. With that you achieve simpler code and no need for dealing with hardware issues in software. Of course at the expense of additional parts in your hardware setup.

If your MCU for example is using a pin as interrupt, that interrupt would be called only once as opposed to bouncing one.

---
Tags: debounce
---


title: Line following robot problems

text:
# Question
Title: Line following robot problems
I am making line following robot using Arduino Uno but every time I connect everything together and upload the code and put the sensors on the line the motor does not work can anyone help me?

I use an L298n motor and Arduino Uno. This is the circuit diagram i am using:

And this is the code:

```
// First the line following (IR) sensors
const int irLeft = 2; //Left line sensor is on pin A2
const int irRight = 3; //Right line sensor is on pin A3

//Motor A (Right)
int enableA = 11;
int pinA1 = 10;
int pinA2 = 9;

//Motor B (Left)
int enableB = 7;
int pinB1 = 6;
int pinB2 = 5;
//Define Run variable
boolean run;
void setup() {
pinMode(enableA, OUTPUT);
pinMode(pinA1, OUTPUT);
pinMode(pinA2, OUTPUT);
pinMode(enableB, OUTPUT);
pinMode(pinB1, OUTPUT);
pinMode(pinB2, OUTPUT);
}
void loop(){
  int valleft= analogRead(irLeft);
   int leftsensor = analogRead(A2);  //in the side of motor B
  int rightsensor = analogRead(A3);  //in the side of motor A

   if ((leftsensor >= 700) && (rightsensor >= 700))
     forward();
        else if((leftsensor <= 150) && (rightsensor <= 150))
     backward();
     else if((leftsensor <= 150) && (rightsensor >= 700))
     turnright();
     else if((leftsensor >= 700) && (rightsensor <= 150))
     turnleft();
}
//Motors Foward
void forward(){
  digitalWrite(pinA1,HIGH);
  digitalWrite(pinA2,LOW);
  digitalWrite(pinB1,HIGH);
  digitalWrite(pinB2,LOW);
}
// Motors Backward
void backward(){
  digitalWrite(pinA1,LOW);
  digitalWrite(pinA2,HIGH);
  digitalWrite(pinB1,LOW);
  digitalWrite(pinB2,HIGH);
}
// turn left
void turnleft(){
  digitalWrite(pinA1,HIGH);
  digitalWrite(pinA2,LOW);
  digitalWrite(pinB1,LOW);
  digitalWrite(pinB2,HIGH);
}
// turn right
void turnright(){
  digitalWrite(pinA1,LOW);
  digitalWrite(pinA2,HIGH);
  digitalWrite(pinB1,HIGH);
  digitalWrite(pinB2,LOW);
}

```

# Answer
> 1 votes
Wire, write and debug just one part of your project at a time.

* Can you just run a motor?
* Can you run it in either direction?
* Can this code do the same for *either* motor?
* Can you run two motors?
* Can you set either of them to run forward, reverse, or to stop, independently of each other?

Then the sensors (forget the motors for now):

* Can you read the right sensor and detect light or dark?
* Can you adapt the code to read either sensor?

Then using the above pieces and knowledge:

* Can you make one of the motors run or stop in response to one of the sensors?

Now you have enough pieces - *known working!* \- to reassemble them into a device that uses sensors and motors to navigate. If it fails at this point, there's a whole lot you *don't have to debug*, and you can concentrate on whatever you haven't tested yet - your navigation algorithm, any rewiring you've done since you tested each part, and whether you've included the final known-working pieces from your tests, e.g., you used all of the latest and greatest bits of code you developed above.

---
Tags: robotics
---


title: DLHR differential pressure sensor SPI

text:
# Question
Title: DLHR differential pressure sensor SPI
I am new to using SPI with an Arduino. But I'm trying to wrap my head around the "coding protocols"/syntax of the Arduino IDE code. I understand the basics of how SPI works conceptually, just not how to actually use it with an Arduino Mega 2560. Most examples on YouTube are about how to play with LEDs and the examples on the Arduino blogs are very specific for two specific examples. Analog reading is incredibly easy (which is what I am used to doing).

I have an AllSensors DLHR-L05D 18 bit differential pressure sensor (SPI, not I2C) \[Datasheet: https://www.allsensors.com/cad/DS-0350\_Rev\_B.PDF\]. Page 5 has the commands needed. From my understanding, I need to somehow send from the Arduino to the sensor a "start" sequence (0xAA) and a "read" (0xF0 and 0x00) sequence, but I'm not sure what that looks like when coding it.

Any and all advice/direction on how to "code up" this SPI device would be greatly appreciated!

# Answer
> 0 votes
Turns out, someone actually has a specific library to handle the I2C for this sensor, which helps tremendously: https://github.com/jeremycole/AllSensors\_DLHR

---
Tags: arduino-mega, arduino-ide, sensors, spi
---


title: Minimum value of a pull-down resistor

text:
# Question
Title: Minimum value of a pull-down resistor
I've just started working with the Arduino UNO SMD edition and I'm also quiet new to electronics in general. Recently I wanted to try out this tutorial https://www.arduino.cc/en/Tutorial/Button and I ran into a problem with the pull-down resistor. In the tutorial they recommend a 10kOhm resistor but I've got only 460Ohms laying around. Obviously I could link dozens of them in series but I was wondering if it is possible to replace this 10k resistor with 460 Ohms. Would that be enough? I'm assuming, that the 5V Output can supply up to 500mA (datasheet) and the ground can take up to 500mA. Following Ohms Law I = U/R given 460Ohms there should be a current of 11mA flowing. Is it correct that the ground can take this amount of current?

Hope you can answer my question and may point out mistakes i made.

Greetings Tmirror

# Answer
Why are you messing with pulldown resistors at all? Use the internal pullup resistor instead. Connect your button between the pin and Gnd so the pin goes low when pressed.

Here's a simple code example:

```
byte inputPin = 2;

void setup(){
    pinMode (inputPin, INPUT_PULLUP); // turns on internal pullup
    Serial.begin(9600);
}

void loop(){
    if (digitalRead(inputPin) == LOW){
        Serial.print ("button pressed");
    }

    else {
        Serial.print ("button open");
    }

    delay(200);  // limits reading to 5 times a second to avoid flooding the PC with messages

}

```
> 0 votes

---
Tags: arduino-uno, resistor
---


title: Error compiling to teensy 3.6

text:
# Question
Title: Error compiling to teensy 3.6
**Problem:**

In short, the Arduino IDE won't compile a sketch for the Teensy 3.6. It gives the error:

```
exec: "A:\\arduino-1.8.5\\hardware\\teensy/../tools/teensy_post_compile": file does not exist
Error compiling for board Teensy 3.6.

```

**What I have tried**

-Re-installing teensyduino (And yes, I have it installed, along with a compatible Arduino IDE (version 1.8.5))

-completely wiping the IDE and re-installing

-using a different USB cable

**Other information**

The OS I'm using is Windows 10

A broken Teensy is not out of the question, as I have been doing some soldering on it and I may have slipped or something, although I don't think that's the problem

Thanks in advance.

# Answer
I found a fix, it's not elegant or easy to use, but it works.

**Steps to take**

-Install a fresh version of teensyduino

-Make a copy of `[arduino directory]/hardware/tools` and save it anywhere as a backup (sometimes weird, buggy things happen)

-Make a copy of `teensy.exe` from the `tools` folder, and put it in the same directory as `arduino.exe`

-every time you run `arduino.exe` (don't double-click on a `.ino` file), first start `teensy.exe` and everything *should* work.

Sometimes, the `tools` directory gets deleted (It just seems a bit buggy), if that happens copy the backup and paste it where it should be (`[arduino directory]/hardware/tools`)

Also occasionally `teensy.exe` gets deleted, so make sure to have a backup of that as well.
> 0 votes

---
Tags: arduino-ide, teensy
---


title: const char* to double

text:
# Question
Title: const char* to double
I'm trying to use an if statement to check when the time goes past a specific point and run a specific function. To do this I'm looking to convert time into a double and running something along the lines of `if(timeCurrent >= 8.30)`. I seem to however have an issue with the conversion part, normally I'm aware the standard practice in C++ would be to do the following:

```
DateTime now = rtc.now();
static char buffer[80];

sprintf(buffer, "%02d.%02d", now.hour(), now.minute());
String str(buffer);
double timeCurrent = strtod(str);

```

However, this doesn't work for Arduino. What can be done to create the same desired function?

# Answer
> 3 votes
Don't do that. Converting a time to `double` is highly inefficient. Moreover, your approach suffers from a rollover issue every 24h.

If you just want to compare the time of day with 8:30, you can do it in a very straightforward way:

```
if (now.hour() > 8 || (now.hour() == 8 && now.minute() >= 30))

```

If the long `if` annoys you, you can put the comparison logic inside a `static inline` function. If you really want to combine hour and minute into a single number, then convert to an integer rather than a double:

```
if (now.hour() * 100 + now.minute() >= 830)

```

This can be made more efficient if you think in binary rather than decimal: you can build a 16-bit number with one byte holding the hours and the other byte holding the minutes:

```
if ((now.hour() << 8) | now.minute() >= (8 << 8) | 30)

```

Again, you may encapsulate the `((a)<<8|(b))` in a macro or static inline function if it helps with readability. If you want to compare to an absolute time, your best option is to build a `DateTime` object representing the deadline, and compare with `now` as:

```
// Assume timeout should be today at 8:30.
DateTime timeout(now.year(), now.month(), now.day(), 8, 30, 0);
if (now.secondstime() >= timeout.secondstime())

```

Here the `secondstime()` method is used to convert the `DateTime` into a scalar number (a 32-bit integer of type `time_t`) that can be easily compared and is far more efficient than using floats.

---
Tags: arduino-uno, c++
---


# Question
Title: Code throwing errors after an IDE update
I'm really new to coding for arduino. My current project is a monitor for my terrarium using an arduino UNO board, a DHT11 and a DS3231 RTC, displaying Temperature(from both DHT (in the terrarium) and the RTC (outside)) as well as time and humidity.

The code was functional, but recently the IDE said there were some updates (which I ran) and now it won't verify. All this code was basically obtained through examples for the hardware I'm using. Can someone please point me to what I need to correct?

The code as is ....

```
#include <DS3231.h>

#include <dht11.h>

#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
DS3231  rtc(SDA, SCL);
dht11 DHT;                        //Note:DHT on behalf of the temperature         and humidity sensor
const int dht11_data = 6;
int temp=0;
int hum=0;

#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
                              // Convert normal decimal numbers to binary   coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
                              // Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)

{
  return( (val/16*10) + (val%16) );
}

void setup()
{
  Wire.begin();
                              // set the initial time here:
  // DS3231 seconds, minutes, hours, day, date, month, year
  // setDS3231time(30,42,21,4,26,11,14);
  rtc.begin();                    //Initialize the rtc object
  lcd.begin(16,2);                //Initialize LCD display
  lcd.print("Terrarium ");        //Splash Screen text line 1
  lcd.setCursor(0,1);             //Set Cursor Position for second line of Splash screen
  lcd.print("Monitor 1.3");       //Splash screen text line 2
  delay(3000);                    //Delay 3 seconds on Splash screen
  lcd.clear();                    //Clear LCD
}

void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
dayOfMonth, byte month, byte year)

{
  // sets time and date data to DS3231
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0);                  // set next input to start at the seconds register
  Wire.write(decToBcd(second));   // set seconds
  Wire.write(decToBcd(minute));   // set minutes
  Wire.write(decToBcd(hour));     // set hours
  Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
  Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
  Wire.write(decToBcd(month));    // set month
  Wire.write(decToBcd(year));     // set year (0 to 99)
  Wire.endTransmission();
}

void readDS3231time(byte *second,byte *minute,byte *hour,byte     *dayOfWeek,byte *dayOfMonth,byte *month,byte *year)

{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
                              // request seven bytes of data from DS3231       starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}
void displayTime()
{
  DHT.read(dht11_data);
  temp=DHT.temperature;
  hum=DHT.humidity;

  lcd.clear();                    //clear display

  lcd.print("rH=");               //Display text rH= on LCD
  lcd.print(hum);                 //Display relative humidiy reading from    DHT11
  lcd.print("%");                 //Display Percent sign

  lcd.setCursor(9,0) ;            //set cursor position
  lcd.print("Ti=");               //display"Ti="
  lcd.print(temp);                //Displays temperature reading from     DHT11, designated is Internal Temperature
  lcd.write(0xDF);                //Display custom characters '°'
  lcd.print("C");                 //Display text "C" to designate Celsius     units

  byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;

                              // retrieve data from DS3231
  readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,  &year);
                              // send it to the serial monitor

  lcd.setCursor(0,1);
  lcd.print(hour, DEC);           //Displays hours value on LCD
                               // convert the byte variable to a decimal number when displayed
  lcd.print(":");                 //Displays ":" between hours and minutes
  if (minute<10)
  {
    lcd.print("0");
  }
  lcd.print(minute, DEC);         //Displays Minutes value on the LCD
  lcd.setCursor(9,1);
  lcd.print ("Te:");              //Displays text "Te:" on LCD
  lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

}
void loop()
{
  displayTime();                  // display the real-time clock data on the Serial Monitor,
  delay(1000);                    // every second
}

```

and the errors it is throwing are:

```
> > Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"
>
> Terrarium_Monitor_1.3:8: error: no matching function for call to
> 'DS3231::DS3231(const uint8_t&, const uint8_t&)'
>
>  DS3231  rtc(SDA, SCL);
>
>                      ^
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:8:21: note:
> candidates are:
>
> In file included from F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino:1:0:
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
> note: DS3231::DS3231()
>
>    DS3231();
>
>    ^
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:64:3:
> note:   candidate expects 0 arguments, 2 provided
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note: constexpr DS3231::DS3231(const DS3231&)
>
>  class DS3231 {
>
>        ^
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note:   candidate expects 1 argument, 2 provided
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note: constexpr DS3231::DS3231(DS3231&&)
>
> C:\Users\Ursinos\Documents\Arduino\libraries\DS3231/DS3231.h:60:7:
> note:   candidate expects 1 argument, 2 provided
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
>    'void setup()':
>
> Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named
> 'begin'
>
>    rtc.begin();                    //Initialize the rtc object
>
>        ^
>
> F:\Arduino Kit Stuff\my
> sketches\Terrarium_Monitor_1.3\Terrarium_Monitor_1.3.ino: In function
> 'void displayTime()':
>
> Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named
> 'getTemp'
>
>    lcd.print(rtc.getTemp());       //Displays Temperature from DS3231
> designated as "External Temperature"
>
>                  ^
>
> Multiple libraries were found for "LiquidCrystal.h"  Used: E:\Program
> Files (x86)\Arduino\libraries\LiquidCrystal  Not used:
> C:\Users\Ursinos\Documents\Arduino\libraries\arduino_136712 exit
> status 1 no matching function for call to 'DS3231::DS3231(const
> uint8_t&, const uint8_t&)'
>
> This report would have more information with "Show verbose output
> during compilation" option enabled in File -> Preferences.

```

As I said, I was working when I uploaded it to my arduino on last changes a week ago (and it's still running on the board right now), but after doing the updates to the libraries and whatnot, it's now throwing all these errors. I know the code isn't very elegant, I'm still learning. Please help

edit: After altering the line as advised in the answers, I now get the following errors.

```
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Uno"

F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void setup()':

Terrarium_Monitor_1.3:34: error: 'class DS3231' has no member named 'begin'

   rtc.begin();                    //Initialize the rtc object

       ^

F:\Arduino Kit Stuff\my sketches\Terrarium_Monitor_1.3  \Terrarium_Monitor_1.3.ino: In function 'void displayTime()':

Terrarium_Monitor_1.3:112: error: 'class DS3231' has no member named 'getTemp'

 lcd.print(rtc.getTemp());       //Displays Temperature from DS3231 designated as "External Temperature"

             ^

Multiple libraries were found for "LiquidCrystal.h"
 Used: E:\Program Files (x86)\Arduino\libraries\LiquidCrystal
 Not used: C:\Users\Ursinos\Documents\Arduino\libraries   \arduino_136712
exit status 1
'class DS3231' has no member named 'begin'

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

```

Could this have anything to do with my Arduino IDE being version 1.8.3 instead of the newest version?

# Answer
> 0 votes
I found this online but I can not verify it.

http://www.instructables.com/topics/no-matching-function-for-call-to-DS3231DS3231const/

The relevant part for you I think is:

> I don't know where you get the syntax
>
> DS3231 rtc (SDA, SCL);
>
> My copy of the DS3231 library says you need only DS3231 rtc; //no arguments. BUT you need the Wire library.

So change your code and make sure you have the Wire library.

# Answer
> 2 votes
Alright, so I figured it out by *gasp* going and reading the documentation for the DS3231 library I'm using.

It seems when the library updated, one of the keywords changed.

so, after removing the (SDA, SCL) from the one line, I had to remove the line

```
rtc.begin();

```

and change

```
lcd.print(rtc.getTemp());

```

to

```
lcd.print(rtc.getTemperature());

```

thanks for the help :D

---
Tags: arduino-uno
---


# Question
Title: Using attachInterrupt() to make a reset button for my code?
I have used `attachInterrupt()` to reset my program to the beginning. It actually interrupts while running the 3 states as shown below inside of the `if` statement but when I press the actual button it does not exit, it goes to the function and continuing to the next state. It only works (means exiting/resetting) after all three states have executed completely.

```
if(buttoncount<2){
  originalstate();
  alertstate();
  evacuationstate();

```

I would like to make a button to stop the program while running in the middle and start again.

Code:

```
// Declaring pins

// Input pins
const int sensor1button_pin = 6;
const int sensor2button_pin = 3;
const int sensor3button_pin = 4;
const int sensor4button_pin = 5;
const int sensor5button_pin = 2;
const int sensor6button_pin = 15;
const int sensor7button_pin = 15;

// Output pins
const int led1_pin = 8;
const int led2_pin = 9;
const int led3_pin = 10;
const int led4_pin = 11;
const int buzzerpin = 15;

// Initialy buzzer at false mode
boolean flag1;
boolean flag2;
int flag3 ;

// for leds
int ledState1 = LOW;   // Original
int ledState2 = LOW;   // Alert
int ledState3 = LOW;   // Evacuate
int ledState4 = LOW;   // Isolate

// Buttons
int button1_state = LOW;
int button2_state = LOW;
int button3_state = LOW;
int button4_state = LOW;
int button6_state = LOW;
int button7_state = LOW;
int button5_state = LOW;

// Other variables
int buttoncount = 0;
int reset_switch=0;

void setup() {
  // INPUT pins
  pinMode(sensor1button_pin, INPUT);
  pinMode(sensor2button_pin, INPUT);
  pinMode(sensor3button_pin, INPUT);
  pinMode(sensor4button_pin, INPUT);

  pinMode(sensor5button_pin, INPUT_PULLUP);

  attachInterrupt(digitalPinToInterrupt(sensor5button_pin), clearreset, CHANGE);

  pinMode(sensor6button_pin, INPUT);
  pinMode(sensor7button_pin, INPUT);

  // OUTPUT pins
  pinMode(buzzerpin, OUTPUT);
  pinMode(led1_pin, OUTPUT);
  pinMode(led2_pin, OUTPUT);
  pinMode(led3_pin, OUTPUT);
  pinMode(led4_pin, OUTPUT);

  Serial.begin(9600);
}

void loop() {
  button1_state = digitalRead (sensor1button_pin);
  button2_state = digitalRead (sensor2button_pin);
  button3_state = digitalRead (sensor3button_pin);
  button4_state = digitalRead (sensor4button_pin);
  button5_state = digitalRead (sensor5button_pin);
  button6_state = digitalRead (sensor6button_pin);
  button7_state = digitalRead (sensor7button_pin);

  Serial.println(digitalRead (sensor5button_pin));

  if( button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    delay(280);
    buttoncount = buttoncount + 1;
  }

  if (button1_state == HIGH || button2_state == HIGH || button3_state == HIGH || button4_state == HIGH) {
    if(buttoncount<2){
      originalstate();
      alertstate();
      evacuationstate();
    }
  }
}

// LED lighting arrangements
void originalstate() {
  digitalWrite(led1_pin, HIGH);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void alertstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, HIGH);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void evacuationstate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, HIGH);
  digitalWrite(led4_pin, LOW);
  delay(1500);
}

void isolatestate() {
  digitalWrite(led1_pin, LOW);
  digitalWrite(led2_pin, LOW);
  digitalWrite(led3_pin, LOW);
  digitalWrite(led4_pin, HIGH);
}

// Clear or reset back to the begin

void clearreset() {
 button1_state = LOW;
 button2_state = LOW;
 button3_state = LOW;
 button4_state = LOW;
 button5_state = LOW;
 button6_state = LOW;
 button7_state = LOW;

 digitalWrite(led1_pin, LOW);
 digitalWrite(led2_pin, LOW);
 digitalWrite(led3_pin, LOW);

 buttoncount = 0;
 exit;
}

```

# Answer
> 1 votes
You need non-blocking code in combination with a finite state machine: 1. **Non-blocking code:** You should not use `delay()`, since it is just busy waiting. Instead use the `millis()` function to measure the time distance between the last execution of the code part and the current time. If it has reached a certain level (like 1500ms), execute the code and save the current time in a timestamp as a reference for the next execution. Refer to the `BlinkWithoutDelay` example of the Arduino IDE. There are also many tutorials for that on the internet, so I will not explain this further here. 2. **Finite state machine:** Here your `loop()` function contains of a `switch` statement with a (mostly numerical) state variable as parameter. Every case contains only the code for its special case. To get from one state to another you would just change the state variable to the corresponding value. You can also do this in an ISR (if you set the state variable as `volatile`). If you non-blocking code as described above, the `loop()` function is executed very fast, so that the change of the state variable inside the ISR takes effect almost immediately (delay will not be sensable by a human). Something like this:

```
volatile int state=0;

void isr_function(){
    state++;
    if(state>1) state=0;
}

void loop(){
    switch(state){
        case 0: // state 0
            do_something();
            break;
        case 1: // state 1
            do_another_thing();
            break;
    }
}

```

Note: Depending in your target you may want to add code for button debouncing, so that one button press is really sensed as one press, not more. This is relevant most times you have non-blocking code. Debouncing has been described many times in the internet, so just Google it

# Answer
> 1 votes
You should enable verbose compilation in the IDE. You will then have a chance to see this compiler warning:

```
warning: statement is a reference, not call, to function ‘exit’
  exit;
      ^
warning: statement has no effect

```

Naming a function without calling it is a way to get a pointer to the function. It's equivalent to `&exit`. But since you do nothing with that pointer, the statement has no effect, and that's exactly what the compiler is warning you about.

You presumably want to *call* the `exit()` function, like in:

```
exit(0);

```

**Edit**: That being said, `exit()` is probably *not* what you want. This function just stops your program by putting it in an infinite loop. If you want it to restart from scratch, you can first declare

```
extern "C" void __init();

```

then, instead of `exit(0);` call `__init();`. This will send your program to the beginning of the initialization code from the C runtime, which is responsible of resetting the stack and initializing the memory (.data and .bss sections). Note that this is *not* equivalent to a hardware reset because:

* doing this does not run the bootloader
* more importantly, it doesn't reset the IO registers of the peripherals to their default reset state.

# Answer
> 0 votes
> ... .any way, I can interrupt the program while running and change to any other function of the program. such as when we press the reset button it goes to reset, if we press a push button it goes to some any other function.

Interrupt will not help you achieve your requirement. You want to 'reset the state' of your running sketch. But after the interrupt the MCU returns in the code where it was before interrupt and continues.

You should implement the 'reset of the state' in your algorithm. In a loop of a non-blocking sketch you can check the button and if it is pressed, then 'reset the state' of the sketch.

---
Tags: arduino-uno, interrupt, button, reset
---


# Question
Title: How to stop sending the last received char of UART echo function?
I developed a code for uart based ISR with linear buffers, the problem is that it keep sending the last received char in Arduino IDE.

Here's the application code:

```
#include "uart_new.h"

void setup() {
uart_init_new(103);
DDRB = 0xff;
}

void loop() {
uint16_t c;
c = get_char();
if (c & NO_DATA)
{
  PORTB |= (1<<PB5);
  _delay_ms(500);
  PORTB &= ~(1<<PB5);
  _delay_ms(500);
}
else
{
  put_char(c);
}
}

```

The header file:

```
#ifndef uart_new_H_
#define uart_new_H_

#define NO_DATA     0x0100
#define Buf_OF      0x0200
#define FR_Er       0x0400
#define DOR_Er      0x0800
#define PARTY_Er    0x1000

#define buf_s 32
#define buf_mask Buf_s - 1
#define baud_rate 9600

void uart_init_new(uint16_t ubrr);
void put_char(uint8_t data);
uint16_t get_char(void);
void put_s(uint8_t *str);

#endif // uart_new_H_

```

The source code:

```
#include <avr/io.h>
#include <Arduino.h>
#include "uart_new.h"

/*******************************************
If you want to prevent reading a string
backwards then you need FIFO implementation
*******************************************/

static volatile uint8_t rx_buf[32],tx_buf[32];
static volatile uint8_t rx_p,tx_p,rx_cnt,tx_cnt;
static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

void uart_init_new(uint16_t ubrr)
{
    rx_p=0,tx_p=0,rx_cnt=0,tx_cnt=0;
    UBRR0H = (uint8_t)(ubrr>>8);
    UBRR0L = (uint8_t)ubrr;
    UCSR0B = (1<<RXEN0)|(1<<TXEN0)|(1<<RXCIE0); //Enable Rx and Tx & Receive interrupt
    UCSR0C = (1<<USBS0)|(3<<UCSZ00);            //Set frame format: 8data, 2stop bit
}

uint16_t get_char(void)
{
    if (rx_cnt == 0)
        return NO_DATA;
    else if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
}

void put_char(uint8_t data)
{
    if (tx_cnt < 32)                        // start count the input data
        tx_buf[tx_cnt++] = data;            // 1st input location tx_cnt

        UCSR0B |= (1<<UDRIE0);
}

void put_s(uint8_t *str)
{
    while (*str)
        put_char(*str++);
}

ISR(USART_RX_vect)
{
    if (rx_cnt < 32)                        // start count the received data
        rx_buf[rx_cnt++]=UDR0;              // 1st output location rx_cnt
    else
        rx_cnt = 0;                         // when the counter reached max value, reset it, overwrite everything

if (!(UCSR0A & (1<<RXC0)))
        UCSR0B &= ~(1<<UDRIE0);
}
ISR(USART_UDRE_vect)
{
    uint8_t i;
    if (tx_p < tx_cnt)                      // check if pointer < counted data
        UDR0 = tx_buf[tx_p++];
        else
        {
            for (i=0;i<tx_cnt;i++)
                tx_buf[i]=0;
            tx_p = 0;                       // when the pointer reach max value, reset it
            tx_cnt= 0;                      // also reset counter for new transmission
            UCSR0B &= ~(1<<UDRIE0);         // disable empty data register interrupt
        }
}

```

If the there's a received char, then ISR is executed, the function exit the LED blink loop, but when the receive stops and there're no more data it doesn't return the blink state and keeps sending the last received char. How to solve this problem?

# Answer
> 2 votes
There are many, many problems with this code. The most fundamental flaw is that it uses linear buffers, where you should be using circular buffers instead. I'll come to this later. Now, if we look at the details, in the header file:

```
#define Buf_OF      0x0200

```

This, and a few other macros, serve no purpose. Do not put "TODO" items in the code: put them in a TODO file, or as comments. Strive to always have your code in a clean state. More so when you post it in a public place.

```
#define buf_mask Buf_s - 1

```

This is presumably intended to be used as a bit mask, but it will not work reliably. For example, if you try to complement the mask as `~buf_mask`, the preprocessor will expand that to `~Buf_s - 1`, and the compiler will interpret it as `(~Buf_s) - 1`, which is **not** what you want. You should always parenthesize any expression you use in a macro, as

```
#define buf_mask (Buf_s - 1)

```

Later,

```
void put_s(uint8_t *str);

```

If you want to be able to issue calls like `put_s("Hello!");`, then you should declare the function as:

```
void put_s(const char *str);

```

Now, in the implementation, you have:

```
static volatile uint8_t rx_errors,tx_sBuf,rx_sBuf;

```

All those are unused. Remove them. Again, this is supposed to be a program, not a TODO list.

Later,

```
uint16_t get_char(void)
{
    if (rx_cnt == 0)
        return NO_DATA;
    else if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
}

```

The compiler should have warned you about this: what if both conditions are false? In this case the function will return by reaching its end, with no specified return value. This is undefined behavior. You should probably return `NO_DATA` in this case. But then, that's what you should return every time you are not returning valid data, so the function can be simply written as:

```
uint16_t get_char(void)
{
    if (rx_p < rx_cnt)
        return rx_buf[rx_p++];
    else
        return NO_DATA;
}

```

Later, in `ISR(USART_RX_vect)`,

```
if (rx_cnt < 32)
    rx_buf[rx_cnt++]=UDR0;
else
    rx_cnt = 0;

```

If you set `rx_cnt` to zero without updating `rx_p`, then the subsequent characters that you will put in the buffer will be ignored by `get_char()` until you fill the buffer up to `rx_p`. Thus you presumably want to set `rx_p` to zero also. And if you do this at the start if the ISR, you ensure that *at least* the current character is not lost:

```
// when the counter reached max value, reset the buffer
if (rx_cnt >= 32) {
    rx_p = 0;
    rx_cnt = 0;
}
rx_buf[rx_cnt++]=UDR0;

```

Further in the ISR:

```
if (!(UCSR0A & (1<<RXC0)))
    UCSR0B &= ~(1<<UDRIE0);

```

This makes no sense: if you have no pending character in the *receive* register (which you should not have, as you have just read that register), then you disable the ISR that serves the *transmitter*. The transmitter and the receiver should be able to work independently: remove those lines.

Then, in `ISR(USART_UDRE_vect)`:

```
for (i=0;i<tx_cnt;i++)
    tx_buf[i]=0;

```

This serves no purpose. If you handle your buffers properly, you should *never* access uninitialized data in them. Thus you will never read the zeroes you are writing here. Again, remove those lines.

If you implement all the fixes above, you should end up with a code that “kind of” works. There are still a couple of issues though:

**Race conditions**

If `get_char()` gets interrupted by `ISR(USART_RX_vect)`, you can get what is known as a “race condition”, which can lead to incoherent behavior or data corruption. For example, testing `rx_p<rx_cnt` is not atomic: the CPU has to read `rx_cnt` from RAM, then read `rx_p`, then compare them. If the interrupt fires between the two memory reads, the ISR can set both values to zero, then the test will compare the old `rx_cnt` with the new `rx_p` (which is now zero) and incorrectly assume there is valid data to be returned.

There are other places where this can byte you. For example, `rx_p++` is not atomic either, it's a read-modify-write sequence that can very well be interrupted in the middle. And there are similar issues if `put_char()` gets interrupted by `ISR(USART_UDRE_vect)`.

The fix for these issues is to disable interrupts while you are in the “critical sections” that access data shared with the ISRs. This can be done using `noInterrupts()`/`interrupts()` pairs or, if you prefer the avr-libc style, with atomically executed code blocks. For example:

```
#include <util/atomic.h>

uint16_t get_char(void)
{
    uint16_t result = NO_DATA;
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        if (rx_p < rx_cnt)
            result = rx_buf[rx_p++];
    }
    return result;
}

```

A similar protection is needed in `put_char()`.

**Linear buffers**

This is the main flaw, because it will require you to rethink a significant part of your code. Imagine what can happen if the UART transmitter lags slightly behind your program calling `put_char()`. Say you reach `tx_p` = 30 and `tx_cnt` = 32. Then your buffer has 30 “empty” cells (from 0 to 29 the space is available, as that data has already been sent) and two cells with bytes pending to be sent (at positions 30 and 31). If you call now `put_char()` to send an extra byte, that byte will be lost (because `tx_cnt<32` is false). This is unacceptable: you should not loose data when the buffer is almost empty!

The solution is to put the extra byte at position 0, the next one at position 1, etc. But this creates a complication: now the pending bytes are at positions 30, 31, 0, 1... At this point your buffer becomes a circular buffer. It's not a big deal, but you **must** read about the subject before you try to implement it.

Note that the same issue applies to the receive buffer: both buffers should be made circular.

---
Tags: avr, uart, isr, loop
---


# Question
Title: Data transfer to and from Arduino to Raspberry Pi
I am trying to transmit MPU6050 accelerometer data + data from 3 potentiometers from Arduino to Raspberry Pi. I do post processing here (on Raspberry Pi) and then transfer the data back to Arduino to move actuators. However my problem is that when I try to write the processed data back to Arduino, I see that even the stream of incoming data from Arduino starts getting corrupted and everything becomes really slow . Even If I just read serial data from Arduino, things are slower if than if I do the processing on Arduino directly. Also, the accelerometer data seems to become unresponsive i.e. its value doesn't change if I move the accelerometer. Everything just works fine if all the processing is done on Arduino. I don't know what is going wrong. Below are my Arduino and Python functions / codes.

**Arduino Code:**

```
void send_rec_data(){

    Serial.print(Kp);
    Serial.print(",");
    Serial.print(Kd);
    Serial.print(",");
    Serial.print(Ki);
    Serial.print(",");
    Serial.println(Theta_x);

    delay(20);

  if (Serial.available()>0){ // Read data sent by Raspberry Pi / Piserial

    str_data = Serial.readString();

    int firstCommaIndex = str_data.indexOf(',');

    cmd = str_data.substring(0, firstCommaIndex); // This stores the Scaled output from the Raspberry Pi

    param1 = str_data.substring(firstCommaIndex+1); // This stores the error from the Raspberry Pi to decide motor roattion direction

    Output = cmd.toFloat(); my_error = param1.toFloat(); // Change the outputs from string to float

    blink_led(); // Blink LEDS if data is received from Raspberry Pi

  }

}

```

**Python Code:**

```
while 1:

    data = cont.get_serial_data(arduino)

    time.sleep(0.02)

    if data is not None:

        Kp, Kd, Ki, Theta_x = data

        print(" \n Arduino sent Kp = ", Kp , "Kd = ",Kd , "Ki = ", Ki, "Theta_x = ", Theta_x)

        cont.set_tunings(Kp, Kd, 0)

        Output_scaled = cont.Compute_PID_Output(Input = Theta_x) # Compute the output of PID Algorithm

        ff = str(Output_scaled)+','+str(cont.error)

        arduino.write(ff.encode())

        print("\n Computed data sent TO ARDUINO Output_scaled = ", Output_scaled, "Error = ", cont.error)

arduino.close()

```

I have spent quiet sometime to resolve the issue byputting delays, flushing buffer but nothing has worked so far. Can someone please help.

Thanks.

# Answer
Thank you every one. I read through this forum and it also says the same things which you guys also suggested. I did the same thing and now everything is fast.

```
Serial.readString()

```

is indeed the problem.
> 0 votes

# Answer
Ok, without rewriting all your code, one thing I'm seeing here is a lot of *sloooow* string functions.

Pythons print function is extremely slow, for example. You should insert some timers in your code and see how long everything's taking. I think you will be surprised.

For a real-time application, which it sounds like this is, you need to be very careful and use timeouts and non-blocking code to make sure that everything doesn't grind to a halt unexpectedly.

You really need to re-write all this code, but I'll point out a few specific problems.

```
delay(20);
if (Serial.available()>0){
   ...
}

```

This is sloppy. If your python code does not process and return data before the 20ms elapses everything is going to go out of sync.

```
str_data = Serial.readString();

```

A look at the documentation reveals that this will only return on timeout, so this is guaranteed to block for 1s (I think that's the default), so there's another show-stopper problem. See this question for more info.

```
cmd = str_data.substring(0, firstCommaIndex);

```

This is also not sufficient. There is no synchronization between the pi and the arduino, so you have no guarantee that you won't get half of a previous transmission tacked onto the front of your data string (or worse). You need to make your own buffer and parse for the datastring. Or do some careful buffer clearing and use generous timeouts.

So TLDR; here's what you want to do (assuming you want to block while this exchange happens)

1. Clear the arduino receive buffer.
2. Send data packet from arduino.
3. Start receiving. Add received bytes to a char buffer.
4. Continuously search that buffer for your complete data packet.
5. Timeout after x ms. Handle the lack of returned data somehow.
6. If you do find the complete data packet, then process it.

On the Pi:

1. Poll for serial data. Add it to a buffer as it comes in.
2. Start deleting the oldest characters from the buffer if it's longer than 2x the longest data packet
3. Continuously search the buffer for your data packet. If you find it then continue below.
4. delete the data packet from the receive buffer.
5. process the data.
6. Send out return data packet to arduino.
> 1 votes

---
Tags: accelerometer
---