# Question
Title: compilation error when changing variable from char to String
I have a code with these two lines:

```
  char handshakecode = "S"; // Capital S
  char receive;

```

The lines of code are placed in a separate `void`, and not `setup` or `loop`. When i change the two variables from `char` to `String` i get a error(complete error at bottom) when compiling to the arduino or verifying the code.

```
  String handshakecode = "S"; // Capital S
  String receive;

```

When i snippes out partial code for just that particular `void`, it compiles fine, so it must be in combination with the rest of the code, which i have left out from this post at the moment.

Is this a known error or am I doing something wrong?

> In function 'global constructors keyed to 65535\_0\_WFS\_v0.3.ino.cpp.o':
>
> lto1.exe: internal compiler error: Segmentation fault
>
> Please submit a full bug report,
>
> with preprocessed source if appropriate.
>
> See http://gcc.gnu.org/bugs.html for instructions.
>
> lto-wrapper.exe: fatal error: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE\_1.8.15.0\_x86\__mdqgnx93n4wtt\hardware\tools\avr/bin/avr-gcc returned 1 exit status
>
> compilation terminated.
>
> c:/program files/windowsapps/arduinollc.arduinoide\_1.8.15.0\_x86\__mdqgnx93n4wtt/hardware/tools/avr/bin/../lib/gcc/avr/5.4.0/../../../../avr/bin/ld.exe: error: lto-wrapper failed
>
> collect2.exe: error: ld returned 1 exit status
>
> exit status 1 Error compiling for board Arduino/Genuino Mega or Mega 2560.

# Answer
This bug is specific to the 5.4.0-atmel3.6.1-arduino2 version of avr-gcc used by Arduino AVR Boards 1.6.22 and newer. It has been reported here:

https://github.com/arduino/Arduino/issues/7949

Here's the workaround:

1. Tools \> Board \> Boards Manager
2. Wait for downloads to finish.
3. When you move the mouse pointer over "Arduino AVR Boards", you will see a "Select version" dropdown menu appear. Select "1.6.21".
4. Click "Install".
5. Wait for installation to finish.
6. Click "Close".

Due to a bug, this workaround doesn't work with Arduino IDE 1.8.6, but it will work with any other version of the Arduino IDE.

If you have **File \> Preferences \> Check for updates on startup** checked, the Arduino IDE may occasionally notify you that a new version of Arduino AVR Boards is available, you'll need to refrain from updating back to the new Arduino AVR Boards version, otherwise you'll be back to seeing the segmentation fault error again.
> 1 votes

---
Tags: compilation-errors, avr-gcc
---


title: Wemos D1 mini fatal exception

text:
# Question
Title: Wemos D1 mini fatal exception
I'm trying to flash a Wemos D1 mini ESP8266 board with the blink sketch, but get an error. The built in LED turns off when flashing starts.

```
Sketch uses 247872 bytes (23%) of program storage space. Maximum is 1044464 bytes.
Global variables use 28000 bytes (34%) of dynamic memory, leaving 53920 bytes for local variables. Maximum is 81920 bytes.
warning: serialport_set_baudrate: baud rate 921600 may not work
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

```

I tried changing the programming speed to most of the other options.

If I open the serial monitor and set the baud rate to `74880`, I get the following message repeatedly.

```
Fatal exception (0):
epc1=0x400cd530, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

```

Is the board dead, or is there a way of reflashing it without using the serial port?

# Answer
Flashing with the serial port is the only practical option. The flash chip can be removed, and it can be flashed off board, but that isn't practical.

Has the board ever worked? Have you used other RSP8266 boards before or is this the first you have? Do you have a different USB cable you can try? Marginal power can cause unpredictable operation.
> 1 votes

---
Tags: esp8266
---


# Question
Title: Connect Arduino Uno to server using oneM2M platform
I have an Arduino Uno that doesn't have any Wi-Fi. After putting the sensor there, I've found out that it is quiet impossible to connect to localhost for oneM2M platform.

Is there any possibility that I can connect to localhost using just the blue cable below which will also being used for uploading the code? Any help will be much appreciated!

# Answer
You can not do it without a special software running on the computer. I mean special as in someone will need to write it since there likely isn't something available that you can find.

The most practical solution is to either use an ethernet shield on the Uno. Or use a board like the Wemos D1 Mini (an ESP8266 based board) that can do Wifi. It can run under the Arduino platform. And they are dirt cheap.

https://wiki.wemos.cc/products:d1:d1\_mini

https://wiki.wemos.cc/doku.php

https://wiki.wemos.cc/products:d1\_mini\_shields:dht\_shield
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How are errors (not related to syntax) managed in arduino and in the AVR architecture in general?
I was just curious about how the AVR architecture manages errors that would cause a regular desktop program to crash. I'm talking about logical errors for example math problems that are undefined. Such as division by 0 and getting a square root of a negative number. At first I was expecting that by giving an error to the AVR chip it will just return 0. But I ran this program:

```
void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

```

and got this output:

```
4294967295
0

```

After this I got really confused. Why would the `result` variable take the maximum value of an `unsigned long`? Since I declared an `int` the micro controller must have dedicated 2 bytes of dynamic memory to this variable but apparently it somehow managed to get additional 2 bytes to store the data. Could this mean that the AVR chip can corrupt data in other memory locations while allocating new data for the variable that just was fed a undefined in to it? Okay maybe the AVR chip just sets any mathematical nonsense to 4294967295. But no in the example of getting the square root of -10 we see that the value became 0. Although this is probably a function processed by some library so maybe there is some kind of protection against these errors. Also, I tried to run the program above but with a `byte` variable for the `result` instead of `int`.

```
void setup() {
Serial.begin(9600);
}
void loop(){
int x = 0;
int p = 50;
int result;
result = p/x;
Serial.println(result);
result = sqrt(-10);
delay(1000);
Serial.println(result);
delay(10000);
}

```

And the result was the same. So, is there some kind of documentation about error management in AVR since this is important to know while development.

P.S. Everything was run on a real Atmega 328p chip on an arduino nano.

# Answer
> 8 votes
The simple answer is: they are not handled at all.

According to the C and C++ standards, what you are invoking is called *undefined behavior*, meaning anything can happen. In practical terms, it means that the compiler can do its optimizations *assuming* you will never invoke undefined behavior, and completely disregard what could happen if the assumption does not hold. The generated code could be completely broken, it won't be the compiler's fault.

The AVR architecture cannot do divisions, nor floating point math. Thus all the errors you have here happen at the software level. Note that `sqrt(-10)` is *not* an error (it's NaN, which is correctly handled by the avr-libc), but converting that to an int (which you do when you assign it to `result`) is an error.

If you really want to know the details of what happens with each of these errors, there is only one option: you have to disassemble the executable program and read the assembly listing.

# Answer
> 1 votes
**About the number 4294967295**

To my surprise, the sketch produces indeed the number 4294967295. That is not okay.
It turns out that the compiler knows the numbers and tries to do the math itself (instead of runtime).

At runtime, the `50 / 0` results into a signed integer of -1.
When a byte is used, the `50 / 0` results into 255.
The result of that calculation is a variable with only 1's. That is 0xFFFF for a 16-bits variable. That results into 65535 for a unsigned integer and -1 for a signed integer and 255 for a unsigned byte.

So far, that is okay. It makes sense.

However, when the compiler tries to do the math itself with `50 / 0`, it turns the result into a 32-bit variable of 0xFFFFFFFF. The compiler does not put the math into the binary result, but calls the Serial.println() directly with a 32-bit unsigned long of 0xFFFFFFFF, which is 4294967295.

The reason is not the variable type of the variable '`result`', but the division with '`p/x`'. The compiler thinks it is better to make a 32-bit integer when the math is done with two 16-bit integers.

I think that when the compiler optimizes, the result should be same as a runtime calculation.
There is an interesting discussion below this answer. @EdgarBonet calls the compiler behaviour weird but not a bug.

Below is a test sketch that produces 4294967295 with Arduino 1.8.7 for an Arduino Uno:

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

void loop(){
  int x = 0;
  int p = 50;
  int result;
  result = p/x;
  Serial.println(result);
  delay(5000);
}

```

The code outputs normal results when 'x' or 'p' is calculated, for example the result from a function, or when one of the three variables is made volatile.

---
Tags: arduino-ide, avr, mathematics, error
---


# Question
Title: How to build a wireless pump controller using arduino and esps?
I want to have automatic control for my pump, wirelessly.

A transmitter unit fitted in the water tank would sense the water level and transmit the data to a receiver unit attached to the pump starter to turn it off/on.

Also an override unit would allow me to turn the pump on/off according to my will and will also display the water level.

How do I write the code for the wireless transmission part ?

# Answer
> 2 votes
First of all I would recommend to play around with Web Server example to understand how the server hosting works. Also, the ip adders is assigned randomly to the ESP so you definitely need to write a rule in your WiFi router in order to assign a static ip to the ESP. But you can try to use mDNS to assign a name to your esp. For example http://pump.local/path. You can find some instructions here. If you are looking for simplicity you can use Blynk. It is a fully automated and free service that allows you to control you ESP from anywhere where there is a internet connection. And it also can display different variables such as the water level in your case.

---
Tags: arduino-uno, esp8266, nodemcu, wireless
---


# Question
Title: Anomalous behaviour of ADC, digitalWrite and floating point operations
I'm trying to analyse mic (A0) input, calculate certain spectral lines with Goertzel algorithm to detect a number encoded by DTFM and display it with 8x8 matrix display (max7219 driver).

The code works perfectly fine without a display sending the result to serial, however when I added a display, strange things started to happen.

* if `goertzel(..)` is called before `displayDigit` the display doesn't show anything
* if `displayDigit` is called first the output of `goertzel(..)` is a complete mess
* if I comment out 1 line in `goertzel(..)` which is `amp = sqrt(re * re + im * im); // [1]` the display works (but it doesn't make sense)

I'm using Arduino UNO, ADC in free-run mode.

The code below:

```
/**
 * 8x8 LED matrix display with MAX7219 driver
 * +5V, GND, CLK (8 pin), CS (9 pin), DIN (10 pin)
 */
#include <binary.h>
#include <LedControl.h>

#include "font8x8.h"

#define N           256
#define IX_LEN      8
#define THRESHOLD   20

/* Display PINs */
#define CLK     13//8
#define CS      12 //9
#define DIN     8 //10

LedControl matrix = LedControl(DIN, CLK, CS, 1);
int8_t lastDetectedDigit = -1;
int8_t currentDigit = -1;
uint32_t lastDetectedMillis = 0;

const int adc_channel = 0;

volatile uint16_t samples[N];
volatile uint16_t samplePos = 0;

float spectrum[IX_LEN] = {0,0,0,0,0,0,0,0};

// Frequences [697.0, 770.0, 852.0, 941.0, 1209.0, 1336.0, 1477.0, 1633.0]
// Corresponding spectrum indexes [18, 20, 22, 25, 32, 35, 39, 43]

// Calculated for 9615Hz 256 samples
const float cos_t[IX_LEN] = {
  0.9039892931234433, 0.881921264348355, 0.8577286100002721, 0.8175848131515837,
  0.7071067811865476, 0.6531728429537769, 0.5758081914178454, 0.49289819222978415
  };

const float sin_t[IX_LEN] = {
  0.4275550934302821, 0.47139673682599764, 0.5141027441932217, 0.5758081914178453,
  0.7071067811865475, 0.7572088465064845, 0.8175848131515837, 0.8700869911087113
  };

const char table[4][4] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
};

const uint8_t char_indexes[4][4] = {
  {0, 1, 2, 12},
  {3, 4, 5, 13},
  {6, 7, 8, 14},
  {10, 9, 11, 15}
};

void initADC() {
  // Init ADC; f = ( 16MHz/prescaler ) / 13 cycles/conversion
  ADMUX  = adc_channel; // Channel sel, right-adj, use AREF pin
  ADCSRA = _BV(ADEN)  | // ADC enable
           _BV(ADSC)  | // ADC start
           _BV(ADATE) | // Auto trigger
           _BV(ADIE)  | // Interrupt enable
           _BV(ADPS2) | _BV(ADPS1) | _BV(ADPS0); // 128:1 / 13 = 9615 Hz
//  ADCSRB = _BV(ADTS2) | _BV(ADTS0);              // Timer/Counter1 Compare Match B
  ADCSRB = 0; // Free-run mode
  DIDR0  = _BV(adc_channel); // Turn off digital input for ADC pin
}

void goertzel(volatile uint16_t *samples, float *spectrum) {
  float v[N + 2];
  float re, im, amp;

  for (uint8_t k = 0; k < IX_LEN; k++) {
    float a = 2. * cos_t[k];
    v[0] = v[1] = .0;
    for (uint16_t i = 2; i < N + 2; i++) {
      v[i] = float(samples[i - 2]) + a * v[i - 1] - v[i - 2];
    }
    re = cos_t[k] * v[N + 1] - v[N];
    im = sin_t[k] * v[N + 1];
    amp = sqrt(re * re + im * im); // [1]
    spectrum[k] = amp;
  }
}

float avg(float *a, uint16_t len) {
  float result = .0;
  for (uint16_t i = 0; i < len; i++) {
    result += a[i];
  }
  return result / len;
}

int8_t get_single_index_above_threshold(float *a, uint16_t len, float threshold) {

  if (threshold < THRESHOLD) {
    return -1;
  }

  int8_t ix = -1;
  for (uint16_t i = 0; i < len; i++) {
    if (a[i] > threshold) {
      if (ix == -1) {
        ix = i;
      } else {
        return -1;
      }
    }
  }
  return ix;
}

char detect_digit(float *spectrum) {
  float avg_row = avg(spectrum, 4);
  float avg_col = avg(&spectrum[4], 4);
  int8_t row = get_single_index_above_threshold(spectrum, 4, avg_row);
  int8_t col = get_single_index_above_threshold(&spectrum[4], 4, avg_col);

  if (row != -1 && col != -1) {
    return table[row][col];
  } else {
    return 0;
  }
}

void displayDigit(uint8_t c) {
  if (currentDigit == c) {
    return;
  }

  for (uint8_t i = 0; i < 8; i++) {
    matrix.setColumn(0, 7 - i, IMAGES[c][i]);
  }
  currentDigit = c;
}

void setup() {
  cli();
  initADC();
  sei();

  matrix.shutdown(0, false);
  matrix.setIntensity(0, 2);

  Serial.begin(115200);

}

unsigned long z = 0;

void loop() {
  while(ADCSRA & _BV(ADIE)); // Wait for audio sampling to finish

  goertzel(samples, spectrum);
  samplePos = 0;

//  if (z % 25 == 0) {
    displayDigit(2);

    for (int i = 0; i < IX_LEN; i++) {
      Serial.print(spectrum[i]);
      Serial.print("\t");
    }
    Serial.println();
    char digit = detect_digit(spectrum);
    Serial.println(digit);
//  }
  z++;

  ADCSRA |= _BV(ADIE);       // Resume sampling interrupt
}

ISR(ADC_vect) {
  uint16_t sample = ADC;

  samples[samplePos++] = sample;

  if(samplePos >= N) {
    ADCSRA &= ~_BV(ADIE); // Buffer full, interrupt off
  }
}

```

`font8x8.h`:

```
const byte IMAGES[16][8] = {
{
  B00001000,
  B00011000,
  B00001000,
  B00001000,
  B00001000,
  B00001000,
  B00001000,
  B00011100
},{
  B00111100,
  B01000010,
  B01000010,
  B00000100,
  B00011000,
  B00100000,
  B01000000,
  B01111110
},{
  B00111100,
  B01000010,
  B00000010,
  B00000100,
  B00000100,
  B01000010,
  B01000010,
  B00111100
},{
  B00010100,
  B00100100,
  B00100100,
  B01000100,
  B01111110,
  B00000100,
  B00000100,
  B00000100
},{
  B00111110,
  B01000000,
  B01000000,
  B01111100,
  B00000010,
  B00000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000010,
  B01000000,
  B01111100,
  B01000010,
  B01000010,
  B01000010,
  B00111100
},{
  B00111110,
  B01000010,
  B00000100,
  B00000100,
  B00001000,
  B00001000,
  B00010000,
  B00010000
},{
  B00111100,
  B01000010,
  B01000010,
  B00111100,
  B01000010,
  B01000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000010,
  B01000010,
  B01000010,
  B00111110,
  B00000010,
  B01000010,
  B00111100
},{
  B00111100,
  B01000110,
  B01001010,
  B01010010,
  B01010010,
  B01010010,
  B01100010,
  B00111100
},{
  B00000000,
  B01010100,
  B00111000,
  B01111100,
  B00111000,
  B01010100,
  B00000000,
  B00000000
},{
  B00101000,
  B00101000,
  B11111110,
  B00101000,
  B11111110,
  B00101000,
  B00101000,
  B00000000
},{
  B00011100,
  B00100010,
  B00100010,
  B01000010,
  B01111110,
  B01000010,
  B01000010,
  B01000010
},{
  B01111100,
  B01000010,
  B01000010,
  B01111100,
  B01000010,
  B01000010,
  B01000010,
  B01111100
},{
  B00111100,
  B01000010,
  B01000000,
  B01000000,
  B01000000,
  B01000000,
  B01000010,
  B00111100
},{
  B01111000,
  B01000100,
  B01000110,
  B01000010,
  B01000010,
  B01000010,
  B01000010,
  B01111100
}};

```

I use `LedControl.h` library but inside is uses only digitalWrite, no timing, interrupts.

Can somebody explain what is the problem?

**UPD** This is what IDE tells me about the sizes:

```
Sketch uses 5602 bytes (17%) of program storage space. Maximum is 32256 bytes.
Global variables use 1048 bytes (51%) of dynamic memory, leaving 1000 bytes for local variables. Maximum is 2048 bytes.

```

This is LedControl library I'm using

# Answer
From your recent edit:

> Global variables use 1048 bytes (51%) of dynamic memory, leaving 1000 bytes for local variables. Maximum is 2048 bytes.

Your `goertzel()` function defines this

```
float v[N + 2];

```

where `N` is 256. This alone takes 258×4 = 1032 bytes of stack and you only have 1000 bytes available. Then, as I suspected, you are smashing the stack against the .bss section, effectively overwriting some of your global variables with the local ones.

It is hard to predict what can happen in such circumstances. The program is corrupting its memory: you can only expect it to act erratically.
> 2 votes

---
Tags: arduino-uno, adc, float
---


# Question
Title: Triggering a soft reset (Arduino Leonardo)
I want to trigger a soft reset on my Arduino Leonardo, and after some searching settled on using the watchdog timer, as it seemed to be the easiest and cleanest way to do it.

However, I don't think it works as it should. It seems to work fine on the following example:

```
#include <avr/wdt.h>

int outputPin = LED_BUILTIN;

void setup() {
  MCUSR = 0;
  wdt_disable();
  pinMode(outputPin, OUTPUT);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(500);
  digitalWrite(outputPin, HIGH);
  delay(500);
  digitalWrite(outputPin, LOW);
  delay(1000);
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

```

The LED blinks continuously,.

But for the following example:

```
#include <avr/wdt.h>

void setup() {
  MCUSR = 0;
  wdt_disable();
  Serial.begin(9600);
  while (!Serial);
  Serial.println("Hello");
}

void loop() {
  wdt_enable(WDTO_15MS);
  while (true) {}
}

```

"Hello" only gets printed once (where I would expect it to arrive continuously).

I tried increasing the watchdog timeout to 2 seconds, but that didn't solve the issue.

# Answer
> 1 votes
So it turns out my code was working correctly, the watchdog performed the reset as it should, the problem was only that I needed to relaunch the serial monitor after each reset.

---
Tags: timers, arduino-leonardo, reset
---


title: expected unqualified id before token

text:
# Question
Title: expected unqualified id before token
here is the code.

PROBLEM:- if I use for the loop the error comes "expected unqualified-id before for .......but if I use the void loop instead of for loop...the code is run without any error. Meanwhile, I needed for loop .

```
long int Distance = 0;  // Record the number of steps we've taken
//LOW LOGIC MOVEMENT BACKWARD and GEARS MOVE clocwise
// PIN 18 FOR DIRECTIRON
// PIN 19 FOR STEP  INPUT
int y= 10^-6;
long int k;
long int h= 1600;
void setup() {
Serial.begin(9600);
  pinMode(18, OUTPUT);
  pinMode(19, OUTPUT);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  digitalWrite(18,LOW);
  digitalWrite(19, LOW);
 digitalWrite(14, LOW);
 digitalWrite(15, LOW);
}
for ( k=0; k<=h; k++)
{
  //if we are at the end of our move
  digitalWrite(19, HIGH);
  delayMicroseconds(100);
  digitalWrite(19, LOW);
  delayMicroseconds(100);
  Distance = Distance + 1;   // record this step
  //k=Distance;
//   Check to see
  if (Distance ==h)
 {
   // We are! Reverse direction (invert DIR signal)
   if (digitalRead(18) == LOW)
    {
     digitalWrite(18, HIGH);
   }
   else
   {
     digitalWrite(18, LOW);
   }
//    Reset our distance back to zero since we're
 //   starting a new move
   Distance = 0;
  //   Now pause for half a second
    delay(1000);
  }
  }
}

```

# Answer
> 1 votes
It looks like you intended the for-loop to run to completion once. If that is correct, just include it and its entire block of code within and at the end of the setup() function. You will still need to provide a loop() function but it can be empty:

```
void loop(){
   ;
}

```

If, instead, you wanted the for() loop to be run repeatedly, enclose it in the loop() function:

```
void loop(){
   for ( k=0; k<=h; k++ )
   {
   ...
   }
}

```

The setup() function runs once after a power up or reset. The loop function then gets called repeatedly, forever. Put your functional code in whichever one fits your purpose.

The reason for the error message is that, as you've written the for-loop, it is outside of a function, but executable code (as opposed to defining global variables) is only valid within a function.

# Answer
> 0 votes
You need the `void loop()` function on your sketch. This function gets called directly after the setup. If it's not there, then the program cannot compile. You cannot put any execution code (means code other than declarations and such) outside of a function.

Depending on what exactly you want to achieve, you have 2 options:

1. If you want the program to only run once and then stop until the next reset, you can put your code inside the `setup()` function and leave the `void loop()` function empty ( with this: `void loop(){ }` ).
2. If you want the program to repeat itself indefinitely after the for loop, you can put the code inside the `void loop()` function.

Whatever you choose, you need the `void loop()` function.

Note: The `void loop()` function is part of the Arduino world. In general all programs for microcontroller in C/C++ have a function called `main()`. It is the function, that starts the execution of the program. Without it no program would actually run. The Arduino framework wraps this `main()` function up and gives you directly one function to execute the initialization code (`void setup()`) and one function, that runs after that and loops indefinitely (`void loop()`). This infinite loop is an important thing, because the microcontroller has no OS or such that he can return to. If you don't have an infinite loop there, the execution can go on to the next address in the program, where you don't know what it contains.

---

Also the line `int y= 10^-6;` does not, what you might think it does. In C/C++ the `^` is not the power function, but will do a bitwise OR operation. You will have to use a function for this, for example the `pow(value1, value2)` function. You can use google to find one of the many examples, how to use it.

And in the same line, (I assume as above) you want to tell Arduino to put a value much smaller than 1 (a value between 0 and 1) into an integer variable. It will contain `0`. `int` means integer and cannot hold decimal numbers (number with something after the decimal point). It can hold numbers like -1,0,1,2,3 in the range from -32768 to 32767 (because it is 16 bits wide on the Arduino UNO and Mega). You will have to use the `float` type for this.

---
Tags: arduino-mega
---


title: Disconnect Ethernet Shield

text:
# Question
Title: Disconnect Ethernet Shield
I'm trying to use the Ethernet Shield and the EasyVR (voice recognition) together. The Ethernet shield uses the same pins that the EasyVR, but the easyVR works fine if I don't call Ethernet.begin(). Is there a way to disconnect the ethernet shield in order to be able to use the EasyVR again?

I haven't seen any method like "release" or "disconnect" in the Ethernet's class.

Thanks!

# Answer
You have correctly determined the root of the problem, both shields are trying to use the same pins. To work around this we need to know which pins are being used, and for what.

The **Ethernet Shield** documentation reveals the following:

> The Arduino board communicates with the shield using the SPI bus. This is on digital pins 11, 12, and 13 on the Uno and pins 50, 51, and 52 on the Mega. On both boards, pin 10 is used as SS. On the Mega, the hardware SS pin, 53, is not used to select the Ethernet controller chip, but it must be kept as an output or the SPI interface won't work.

https://www.arduino.cc/en/Reference/Ethernet

The documentation for Sparkfun's EasyVR library isn't as explicit, but one of the examples gives us another clue:

```
#if defined(__SAMD21G18A__)
  // Shield Jumper on HW (for Zero, use Programming Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_MONITOR
#elif defined(SERIAL_PORT_USBVIRTUAL)
  // Shield Jumper on HW (for Leonardo and Due, use Native Port)
  #define port SERIAL_PORT_HARDWARE
  #define pcSerial SERIAL_PORT_USBVIRTUAL
#else
  // Shield Jumper on SW (using pins 12/13 or 8/9 as RX/TX)
  #include "SoftwareSerial.h"
  SoftwareSerial port(12, 13);
  #define pcSerial SERIAL_PORT_MONITOR
#endif

#include "EasyVR.h"

EasyVR easyvr(port);

```

EasyVR-Arduino/examples/TestEasyVR/TestEasyVR.ino

This block of code is determining how to set up the serial communication. The first two if statements are for different boards, but the third one sets up the software serial connection... and it says there are two options, pins 12/13 OR 8/9! If there are two options, there must be a way to switch it on the board itself.

And sure enough! Check out that white box labeled "SW Serial Pins". Jackpot!

Here's what the manual has to say:

> On the bottom side of the board there are two SMD resistors that you can move to select the two pins of Arduino that the EasyVR will be connected to when in Software Serial mode (Mode Jumper on SW).
>
> * RX – Software Serial Receiver pin
>     + D12 – Use digital pin 12 as serial receiver (default)
>     + D8 – Use digital pin 8 as serial receiver
> * TX – Software Serial Transmitter pin
>     + D13 – Use digital pin 13 as serial transmitter (default)
>     + D9 – Use digital pin 9 as serial transmitter
>
> The choice of pins 12-13 is maintained for backward compatibility with the previous hardware revisions of the EasyVR Shield. However those pins may also be used for the SPI interface, so another choice of pins 8- 9 is provided. If you want to use different pins make sure the receiver pin supports change interrupts.
> 3 votes

---
Tags: arduino-uno, shields, ethernet
---


title: Sanity check for dual IR LED circuit

text:
# Question
Title: Sanity check for dual IR LED circuit
If the intent is to drive the two LED's with 200-400mA (using PWM @ 38Hz), is there anything wrong with this solution?

Perhaps this is a better solution, as it ensures the current is exactly the same for the two LED's (so that they are not out of phase with each other):

# Answer
I would use a single transistor rated at minimum 1A continuous (a MOSFET by choice), and have both LEDs switched in parallel with their own resistor. By having them in series as in your second schematic you are limiting the input voltage to a minimum of *2×Vf* which could be as high as 5.2V, and thus more than your power source can provide.

simulate this circuit – Schematic created using CircuitLab

This gives the same result as your first circuit, but only uses one transistor for the switching. You can add more LED+Resistor pairs in parallel as you like as long as the total current is below that which the chosen MOSFET can handle.

You should rate the MOSFET to handle the maximum continuous current, not the pulse current, in case the output of the Arduino should be set continuously HIGH instead of sending PWM.

You should also note that the *pulse* current of an LED is usually rated at 1% duty cycle.

Also note that as the voltage of your power source drops, so will the voltage across the resistors, and thus the current flowing through them (and your LEDs) making the LEDs dim. It may be beneficial to first pass your battery power through a high-efficiency 3.3V switch-mode regulator to keep the voltage stable whilst wasting the minimum amount of power in the regulation.
> 1 votes

---
Tags: led, ir, teensy, transistor, resistor
---


# Question
Title: Creation of multiple power cells to be controlled by Arduino
I'm fairly new to the Arduino world, but have a history of good working knowledge of computers and software (I'm a software engineer), but I've only had the opportunity so far to create a few simple successful play-around projects.

I've decided to embark on a fairly ambitious project to build my son a ride on battery powered car for Christmas and trying to put all the pieces together.

An integral part of this plan is to develop what I call a couple of 'Power cells', which is simply a battery enclosure that has:

**Updated:**

1. An input from the Arduino to control the motor speed/voltage.
2. An input from either the Arduino or forward reverse switch to control the direction of polarity (make motor spin forwards or backwards)
3. Has a output to power the motor: 20V, drawing about 1-1.5 Amps
4. Has a output to power the 9x 12V LED lights on it, about upto 50W total (the LED lights will be controlled by the Arduino outside of the power bank, seeing there are a few of them).

I've drawn up a schematic that works with the components I've bought to help put the system together and was wondering if I am missing anything, critical or not?

Info about the battery I'm using can be found here: Aldi Xfinity 20V Li-Ion Battery teardown.

**More Specifically:**

* Are there any errors with the cabling, I'm assuming no additional earth is required in a DC Circuit.
* What size cables will i need to adequately service my power requirements?
* Would I be able to control the reverse polarity switch directly from the Arduino? As I would like to also trigger a beeper when it is switched in reverse mode. Keep in mind the arduino would need to control 2-4 power cells.
* I assume the controlling the potentiometer from the arduino I would need to use junction boxes between the arduino and the power cells to distribute the signal across each power cell, would this be the best way to do this?
* The Li-Ion Battery also seems to have T output pin, i assume this is temperature monitoring, is there a way to utilize this input into the arduino for safety monitoring?
* I was thinking of splitting the lighting power load between 2 power banks, would this be recommended / possible? (left power cell would power left side leds and right power bank would power right cell leds, with the exception of them both powering the center led).
* Are there any additional safety precautions I should be following, especially working with a Li-Ion battery, ie. Fuse etc ?

I'm planning to make 2x of these Power cells to put in the car (each powers its own motor) (with the ability to add another 2 down the track).

Would really appreciate your feedback (please let me know if this is not the right place to ask this sort of question).

# Answer
OK. Looks much better now. And I see one problem. It seems that the normal way to do the speed control is with a pot. A variable voltage at the input depending on the rotation. The Arduino low end designs have an analog out capability but it really is not analog. It is a pulse width variable signal that produces an on percentage between 0 volts and the CPU positive supply voltage. The boards do not have a real digital to analog converter. (maybe some higher end boards but not boards based on the Uno CPU.

It may still work but you need to integrate the pulse output and produce a real analog output voltage. A resistor on the output connected to a capacitor to ground will do the integration and filter out the pulses.

See http://www.ontrak.net/pwm.htm for more details.

The problem you might encounter is to much loading on the capacitor by the pot input circuit. Without more details about the module I couldn't say. The signal can be buffered with an amplifier but that adds to the complexity. Still would be doable though.

Or you can add a real digital to analog converter to the Arduino board. That would be my preference rather than having to add a buffer amplifier if a simple RC circuit wasn't good enough.

Do you have a link for that board?

From the picture of the linked speed module. It uses a LM324 opamp to generate the PWM signal. I did a quick look and found a typical circuit.

http://www.pcsilencioso.com/cpemma/graphics/erg\_pwm\_sch.gif

Typical but not the exact one. It is much as I expected. And if you did the RC only filtering then it may just work. The opamp input would not be too much loading on the capacitor. The concern that I have is that the 5 volt maximum from the Arduino may not be high enough to turn the motor on at its maximum value.
> 2 votes

---
Tags: power, motor, battery, speed
---


# Question
Title: Controlling LED and Button with single pin
I am trying to use an ATTINY85/Ardunio Uno to turn an LED on and listen to a button input. I don't mind if the LED turns on when the button is used.

I am have found this thread from a couple of years ago however it doesn't seem to work at low voltage (3V) due ending up with floating pins due to the forward voltage of the LED. I was wondering if anyone had a soltion or if they could check to see if my solution would be suitable.

Many Thanks

simulate this circuit – Schematic created using CircuitLab

# Answer
> 2 votes
I think this is what you want...

simulate this circuit – Schematic created using CircuitLab

To check for button, set pin to INPUT and enable pullup. If pin is LOW, then the button is pushed.

To light LED, set pin to OUTPUT and LOW.

---
Tags: led, attiny, button
---


# Question
Title: How to avoid Multiple definition of 'Blynk' error?
By including

```
 #include <BlynkSimpleEsp8266.h>

```

Blynk library (https://github.com/blynkkk/blynk-library) from more than 1 module/cpp file, "Multiple definition of \`Blynk’" error is thrown at compile time. The header file contains following:

```
static WiFiClient _blynkWifiClient;
static BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);

```

How can I get the Blynk declarations into a second or third module, without multiple definitions error? Editing the header/library file/s is not an option!

By the question in How to create global variables/includes/functions for use in multiple source files it is still not clear what a working solution is...

# Answer
The Blynk "simple" header files are not ready to be included into multiple cpp files. They are meant to be included only in the main ino file. The reason is that the variable allocations are in headers file, which is bad practice for C and C++. The h files should contain only declarations. The right way would have

```
extern BlynkWifi Blynk;

```

and the lines which are now in the h file should go in a cpp file. Then every cpp file that includes the .h will know about the variables but the variables would be allocated only once.

The fix is to change the library or to copy the BlynkSimpleEsp8266.h include to your project as for example MyBlynk.h and change the Blynk variable in MyBlynk.h to `extern` and add a MyBlynk.cpp file with variables allocation

```
#include "MyBlynk.h"

WiFiClient _blynkWifiClient;
BlynkArduinoClient _blynkTransport(_blynkWifiClient);
BlynkWifi Blynk(_blynkTransport);

```
> 4 votes

---
Tags: c++, esp8266
---


# Question
Title: Why do I get “ stray '#' in program ” error?
I am making an Arduino program with SIM800L module and would like to check credit status of the SIM card. When I manually enter the command: AT+CUSD=1,"\*123#" into Serial Monitor, it works fine.

But in the Arduino (1.8.7) I am receiving an error `stray "#" in program`

when compiling this line of sketch: `SIM800.print("AT+CUSD=1,"*123#"\r");`

I am not experienced enough to fix this problem. Could somebody help me, please?

Thank you. Marko

# Answer
> 3 votes
Use the escape backslash to get a double quote in a text. See: https://en.cppreference.com/w/cpp/language/escape

Is the `*123$` between double quotes?

```
Serial.println("Hello");
Serial.println("I said: Hello to you");
Serial.println("I said: \"Hello\" to you");
Serial.println("AT+CUSD=1,\"*123#\"\r");
Serial.println("AT+CUSD=1,\"*123#\"");

```

I think the carriage return `\r` at the end is not needed when the `println` is used. The `println` adds a linefeed `\n` by the way.

---
Tags: arduino-ide
---


title: Make a float using integers

text:
# Question
Title: Make a float using integers
I want to make a floating point number that has only one decimal point. I have separate integers for both side. Ex:

`int n1 = 8;`

`int n2 = 2;`

I want to make 8.2 as float value using separate integers. Please give me a solution.

# Answer
> 4 votes
Seems too simple:

```
float x = n1 + n2 * 0.1;

```

Is there a trick?

**Edit**: The method proposed by Michel Keijzers, namely

```
float x = n1 + n2 / 10.0;

```

(I removed the redundant casts) can be slightly more accurate, but takes longer to compute, because division is significantly slower than multiplication on the Uno. Computing `n2/10.0` always yields the correctly rounded result, namely the float that best approximates the exact mathematical result. On the other hand, `n2*0.1` involves *two* rounding operations: one at compile time, in the representation of 0.1 (which is not an exact float), another at run time, which rounds the result of the multiplication. If `n2` is between 0 and 8, you end up getting the correctly rounded result anyway, just as with `n2/10.0`. However, if `n2` is 9, then

* `n2*0.1` yields 0.900000035762786865234375 (error ≈ 3.6e-8)
* `n2/10.0` yields 0.89999997615814208984375 (error ≈ -2.4e-8)

The former carries a rounding error 1.5 larger than the latter.

# Answer
> 2 votes
```
float x = (float) n1 + (float) (n2 / 10.0);

```

This works only if the value of n2 has 1 digit. Otherwise the following make it smaller until n2 gets below 1.0:

```
float x = (float) n1;

float f2 = (float) n2;
while (f2 >= 1.0)
{
   f2 /= 10.0;
}
x = n1 + f2;

```

---
Tags: arduino-uno, variables, float
---


# Question
Title: How to retain the on state of the LED and buzzer if the sensor is triggered?
I'm working on a project which is likely an earthquake alarm. The sketch that I got from the internet does not retain the "on" state of the indicators(LED and buzzer)when it is triggered. I want to modify the sketch that it makes the LED and buzzer retains their "on" state when the sensor(accelerometer) is triggered. Could someone help me ?

Here is the code:

```
#include <Wire.h>
#include <MPU6050.h>

#define minval -5
#define maxval 3

MPU6050 mpu;

void setup()
{
  Serial.begin(115200);
  pinMode(7,OUTPUT);
  pinMode(8,OUTPUT);

  delay (2000);

  // Initialize MPU6050
  Serial.println("Initialize MPU6050");

  while(!mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
  {
    Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
    delay(500);
  }

  mpu.setThreshold(3);
  // Check settings
  checkSettings();
}

void checkSettings()
{
  Serial.println();
  Serial.print(" * Sleep Mode:        ");
  Serial.println(mpu.getSleepEnabled() ? "Enabled" : "Disabled");
  Serial.print(" * Clock Source:      ");
  switch(mpu.getClockSource())
  {
    case MPU6050_CLOCK_KEEP_RESET:
      Serial.println("Stops the clock and keeps the timing generator in reset");
      break;
    case MPU6050_CLOCK_EXTERNAL_19MHZ:
      Serial.println("PLL with external 19.2MHz reference");
      break;
    case MPU6050_CLOCK_EXTERNAL_32KHZ:
      Serial.println("PLL with external 32.768kHz reference");
      break;
    case MPU6050_CLOCK_PLL_ZGYRO:
      Serial.println("PLL with Z axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_YGYRO:
      Serial.println("PLL with Y axis gyroscope reference");
      break;
    case MPU6050_CLOCK_PLL_XGYRO:
      Serial.println("PLL with X axis gyroscope reference");
      break;
    case MPU6050_CLOCK_INTERNAL_8MHZ:
      Serial.println("Internal 8MHz oscillator");
      break;
  }

  Serial.print(" * Gyroscope:         ");
  switch(mpu.getScale())
  {
    case MPU6050_SCALE_2000DPS:
      Serial.println("2000 dps");
      break;
    case MPU6050_SCALE_1000DPS:
      Serial.println("1000 dps");
      break;
    case MPU6050_SCALE_500DPS:
       Serial.println("500 dps");
       break;
    case MPU6050_SCALE_250DPS:
       Serial.println("250 dps");
       break;
  }

  Serial.print(" * Gyroscope offsets: ");
  Serial.print(mpu.getGyroOffsetX());
  Serial.print(" / ");
  Serial.print(mpu.getGyroOffsetY());
  Serial.print(" / ");
  Serial.println(mpu.getGyroOffsetZ());
  Serial.println();
}

void loop()
{
  Vector rawGyro = mpu.readRawGyro();
  Vector normGyro = mpu.readNormalizeGyro();
  Serial.print(" Xraw = ");
  Serial.print(rawGyro.XAxis);
  Serial.print(" Yraw = ");
  Serial.print(rawGyro.YAxis);
  Serial.print(" Zraw = ");
  Serial.println(rawGyro.ZAxis);

  if (normGyro.XAxis > maxval ||
      normGyro.XAxis < minval &&
      normGyro.YAxis > maxval ||
      normGyro.YAxis  < minval &&
      normGyro.ZAxis > maxval ||
      normGyro.ZAxis  < minval)
  {
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    digitalWrite(7,HIGH);
    digitalWrite(8,HIGH);
    delay(300);
    delay (1000);
  }
  else
  {
    digitalWrite(7,LOW);
    digitalWrite(8,LOW);
  }
  Serial.print(" Xnorm = ");
  Serial.print(normGyro.XAxis);
  Serial.print(" Ynorm = ");
  Serial.print(normGyro.YAxis);
  Serial.print(" Znorm = ");
  Serial.println(normGyro.ZAxis);
  delay(10);
}

```

# Answer
* Define a (boolean: bool) variable, set it to false initially.
* When the sensor is activated, set the variable to true.
* Define something that should be able to disactivate the buzzer/LEDs. And if that happens, set the variable to FALSE. Maybe this is a reset button ?
* Than based on this variable set the buzzer and LEDs on or off.

So you get something like a global variable

```
bool alarmTriggered;

```

In setup:

```
alarmTriggered = false;

```

In loop:

```
if (AreSensorsTriggered(...)) // Create your own function
{
   alarmTriggered = true;
}
else if (IsResetButtonPressed(...)) // Create your own function
{
   alarmTriggered = false;
}

SetBuzzer(alarmTriggered); // Create a function that enables/disables buzzer
SetLEDs(alarmTriggered); // Create a function that enabled/disables LEDs

```
> 0 votes

---
Tags: arduino-uno, mpu6050
---


# Question
Title: How to define and use a list/array of chars using `Serial.print`
I wish to define a list of months names and access it when printing a report.

Array was defined as follows:

`const char months []=
{'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'};`

```
for (int i=0; i<=11; i++) {

                                 Serial.print(months[i]);
                        }

```

**Tries:**

I was looking for help under `Arrays` in Arduino documentation didn't give, as far as I found, any explanation for such case, but arrays of `int`

Appreciate any help.

# Answer
You are almost there:

* Use a char\* instead of char, a char can only contain one character
* Use " instead of ' (Thanks Juraj)

Then you get:

```
const char* months[] =
 {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

```
> 6 votes

---
Tags: string
---


title: Using analog in to read a push button

text:
# Question
Title: Using analog in to read a push button
I'm working on a project in which I use a lot of the pins on the Arduino; I have run out of most of the pins and and I need to read the value of a push button.

Is it possible to read the value of the switch in the analog in pins on the board??

If so how can I implement this?

# Answer
> 1 votes
> Is it possible to read the value of the switch in the analog in pins on the board??

Yes. Analog input pins are also digital IO pins. You can use them exactly the same way as all the other pins on the board.

# Answer
> 2 votes
On ATmega640/ATmega1280/ATmega1281/ATmega2560/ATmega2561 devices (with Arduino Mega using an ATmega640 or 2560), the analog input pins have their analog capabilities in addition to standard digital capabilities. They can be used to read or write digital values, like other digital pins on the device.

On ATmega48A/PA/88A/PA/168A/PA/328/P devices (with Arduino Uno using an ATmega168- or 328-family device) analog inputs A0 ... A5 have standard digital capabilities, but A6 and A7 do not. A6 and A7 on an Uno or Nano is limited to analog input. However, you can use a circuit like the following to multiplex several buttons. With this circuit attached to A6, you would get 1 V at A6 when you press S1; 2 V when you press S2; 3 V when you press S3; and so forth. You get 0 V at A6 when all the switches are open.

One would first use a fast analog read (about 13 μs) to decide if any switch is pressed; for example, if the first reading is above 1/2 V. In some systems, a fast reading may be good enough by itself to decode switch number; if not, take a second reading via ordinary analog read. In any case, given an analog reading `ar`, and letting `CPS` be the expected step in counts from one switch to the next (in this case either 256/5 or 1024/5 depending upon use of 8 or 10 bits of readings), compute switch number via something like `s = (ar+CPS/2)/CPS;`.

# Answer
> 1 votes
Same things happens with me.

Here, it's my code. It's works for me.

```
const int kPinBtn = A0;  // Push-Button connected to Analog pin A0
const int kPinLED = 13;  // LED connected to to Digital Pin 13

void setup()
{
  pinMode(kPinBtn, OUTPUT); // Generally, in push-button we take INPUT as a parameter but here we take OUTPUT because ANALOG PIN

  digitalWrite(kPinBtn, HIGH); // Make button condition HIGH

  pinMode(kPinLED, OUPUT);
}

void loop()
{
  // Now, normal push-button operation, LED blink when we press push button

  if(digitalRead(kPinBtn) == LOW)  // If button pressed
  {
    digitalWrite(kPinLED, HIGH);   // Blink LED
  }
  else digitalWrite(kPinLED, LOW); // Else LED is off
}

```

# Answer
> 1 votes
> Is it possible to read the value of the switch in the analog in pins on the board??

As other answers say, you can use digitalRead on most Analogue pins. But to answer the question, yes you can read analogue input, which is useful on pins like A6/A7 which cannot be used as digital pins.

You should connect the pin with a pull up resistor - for arduino pins A0-A5 (depending on board, i'm referring to a Nano) this can be done internally using:

```
pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5

```

If you are working on pins A6/A7 you cannot access the internal pull-up resistor, so you need to add your own to prevent a floating input. A 10K resistor should go between the input pin and VCC.

Lastly, an example of reading the input:

```
const int buttonPin = A7;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

void loop() {
  // read the state of the pushbutton value:
  buttonState = analogRead(buttonPin);

  Serial.println(buttonState);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState > 512) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

```

---
Tags: arduino-mega, programming, analogread
---


# Question
Title: How to manage variable I2C read lengths requiring address incrementation (Wire/I2C/EEPROM IC emulation)
The question is about how to have information/control of a variable length read for an Arduino acting as a slave device.

The concrete context is that I want to emulate an EEPROM IC. A byte write to the EEPROM's address sets the internal EEPROM address to start reading from. The subsequent read from the EEPROM's address, will start returning bytes from that internal address which is incremented for each byte read.

"Wire.onRequest(requestEvent);" allows us to set up a handler, but it seems to be called only once on the start of the read.

In the handler it is possible to provide a reply of multiple bytes. However I did not find the documentation allowing to know how many bytes were effectively sent to the master.

I got the initial code from the arduino forum . I've adapted it to this:

```
#include <Wire.h>
//#define DEBUG
byte XEEPROM[256] = {
  0x5D, 0x26, 0x31, 0x91, 0x3e, 0x12, 0x8e, 0x70, 0xa5, 0x57, 0x3d, 0xed, 0x91, 0x99, 0xb4, 0x11,
  0x38, 0xde, 0x1b, 0xd6, 0x4c, 0xd9, 0xf5, 0x13, 0x23, 0x94, 0xb8, 0x3d, 0x9c, 0xb0, 0xc4, 0x54,
  0xf0, 0x69, 0xca, 0xb3, 0x28, 0x84, 0xa5, 0xc1, 0x80, 0x53, 0x69, 0x0c, 0x38, 0x4f, 0x0c, 0x74,
  0xa1, 0x5b, 0x8c, 0x71, 0x34, 0x30, 0x38, 0x30, 0x30, 0x38, 0x31, 0x35, 0x33, 0x31, 0x30, 0x35,
  0x00, 0x12, 0x5a, 0x1e, 0xbd, 0x9e, 0x00, 0x00, 0x02, 0x82, 0x30, 0xaa, 0x10, 0xb7, 0x7f, 0x8d,
  0x0a, 0xcb, 0x2e, 0xc1, 0xeb, 0x52, 0x20, 0xdc, 0x00, 0x03, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x97, 0x55, 0x57, 0xfc, 0x00, 0x00, 0x00, 0x00, 0x47, 0x4d, 0x54, 0x00, 0x42, 0x53, 0x54, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x05, 0x00, 0x02, 0x03, 0x05, 0x00, 0x01,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc4, 0xff, 0xff, 0xff,
  0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
  0x68, 0xaa, 0xdd, 0x02, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x01, 0x04, 0x46, 0x45,
  0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x01, 0x04, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69,
  0x12, 0x03, 0x46, 0x45, 0x8f, 0x8f, 0x78, 0x56, 0xbb, 0x69, 0x02, 0x02, 0x46, 0x45, 0x8f, 0x8f,
  0x78, 0x56, 0xbb, 0x69, 0x12, 0x02, 0x84, 0x79, 0x80, 0x00, 0x00, 0x00, 0x16, 0x01, 0x00, 0x00
};
static volatile byte rQ;

void setup()
{
 Wire.begin(0x50);
 Wire.onReceive(receiveEvent);
 Wire.onRequest(requestEvent);
 Serial.begin(115200);
 Serial.println("I2C EEPROM EMULATION\n");
}

void loop()
{
}

void requestEvent(){
  //Wire.write(XEEPROM[rQ]); // Just 1
  Wire.write(XEEPROM+rQ,6); /// More than 1
  #ifdef DEBUG
  Serial.print("ADR:");
  Serial.print(rQ,HEX);
  Serial.print("R:");
  Serial.print(XEEPROM[rQ],HEX);  // print the character
  Serial.println();
  #endif
  rQ++; // Increment should depend on number of reads - not sure how to detect that.
}

void receiveEvent(int iData){
    rQ = Wire.read();
    Serial.print("ADR:");
    Serial.print(rQ,HEX);
    bool dwHeader=false;
    // loop through all but the last
    while(1 < Wire.available())
    {
      if(!dwHeader) {
          dwHeader=true;
          Serial.print("DATAW:");
      }
      XEEPROM[rQ]=Wire.read();;
      Serial.print(XEEPROM[rQ],HEX);  // print the character
    }
    Serial.println(); // new line
}

```

The question is about requestEvent and specifically:

```
void requestEvent(){
  //Wire.write(XEEPROM[rQ]); // Just 1
  Wire.write(XEEPROM+rQ,6); /// More than 1
  rQ++; // Increment should depend on number of reads - not sure how to
}

```

I would like to send one at a time, or at least be able to increment rQ according to the number of bytes effectively sent.

If you want to look at a datasheet, you can look at the AT24C02 datasheet. With regards to the incrementing internal EEPROM address, the EEPROM specification says:

> **CURRENT ADDRESS READ**: The internal data word address counter maintains the last address accessed during the last read or write operation, incremented by one. This address stays valid between operations as long as the chip power is maintained. The address “roll over” during read is from the last byte of the last memory page to the first byte of the first page. The address “roll over” during write is from the last byte of the current page to the first byte of the same page.

This is why the Arduino code emulating the EEPROM should know exactly how many bytes were read.

Thanks.

# Answer
> 1 votes
Note, that I haven't tested the code below, since I currently don't have enough time for it. But it may help you to get, what you want to do.

The way the I2C interface works is, that after each byte read from the slave, the master will answer with ACK or NACK, depending on if he wants to read more data or not. So the slave doesn't know beforehand, how many bytes the master wants to read.

But you can change the `Wire` library, to call the `onRequest` callback for every single byte, instead of every request. The important code lies in the path of your Arduino installation at `hardware/arduino/avr/libraries/Wire/src/utility/twi.c` at line 575 (I refer to my installation of version 1.8.5; might be slightly different for you):

```
case TW_ST_SLA_ACK:          // addressed, returned ack
case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
      // enter slave transmitter mode
      twi_state = TWI_STX;
      // ready the tx buffer index for iteration
      twi_txBufferIndex = 0;
      // set tx buffer length to be zero, to verify if user changes it
      twi_txBufferLength = 0;
      // request for txBuffer to be filled and length to be set
      // note: user must call twi_transmit(bytes, length) to do this
      twi_onSlaveTransmit();
      // if they didn't change buffer & length, initialize it
      if(0 == twi_txBufferLength){
        twi_txBufferLength = 1;
        twi_txBuffer[0] = 0x00;
      }
      // transmit first byte from buffer, fall
case TW_ST_DATA_ACK: // byte sent, ack returned
      // copy data to output register
      TWDR = twi_txBuffer[twi_txBufferIndex++];
      // if there is more to send, ack, otherwise nack
      if(twi_txBufferIndex < twi_txBufferLength){
        twi_reply(1);
      }else{
        twi_reply(0);
      }
      break;

```

When receiving a request with correct address, the first `case` will be executed (of course after other stuff with receiving address and sending ACK). The `twi_onSlaveTransmit()` function will execute the `onRequest` callback. When that is done, the code falls directly into the next `case` statement, which sends the first byte. When the slave receives an ACK after that byte, it should come back to this `case` and send another byte.

We can now put the buffer filling code into the second `case` statement, so that the callback will be executed for every requested byte. In this case we also need to change the `if` statement after that, so that it only triggers and sends NACK, if the user didn't write a byte in the callback. The original library seems to write at minimum 1 byte (even it nothing is in the buffer; it is set to zero). So we will also do this by setting a flag in the first `case` statement. The code now looks like this:

```
case TW_ST_SLA_ACK:          // addressed, returned ack
case TW_ST_ARB_LOST_SLA_ACK: // arbitration lost, returned ack
      // enter slave transmitter mode
      twi_state = TWI_STX;
      twi_slave_transmit_first_byte = 1;
      // transmit first byte from buffer, fall
case TW_ST_DATA_ACK: // byte sent, ack returned
      // ready the tx buffer index for iteration
      twi_txBufferIndex = 0;
      // set tx buffer length to be zero, to verify if user changes it
      twi_txBufferLength = 0;
      // request for txBuffer to be filled and length to be set
      // note: user must call twi_transmit(bytes, length) to do this
      twi_onSlaveTransmit();
      if(twi_slave_transmit_first_byte == 1){
          twi_slave_transmit_first_byte = 0;
          // if they didn't change buffer & length, initialize it
          if(0 == twi_txBufferLength){
            twi_txBufferLength = 1;
            twi_txBuffer[0] = 0x00;
          }
      }
      // copy data to output register
      TWDR = twi_txBuffer[twi_txBufferIndex++];
      // if there is more to send, ack, otherwise nack
      if(twi_txBufferIndex < twi_txBufferLength){
        twi_reply(1);
      }else{
        twi_reply(0);
      }
      break;

```

And we have to add the flag declaration at the top of the file (where all the other static volatile variables are defined) as static volatile:

```
static volatile uint8_t twi_slave_transmit_first_byte = 0;

```

In the `onRequest` callback you can now write a single byte to the buffer and incrementing your counter.

---

I think, that should work. If someone knows better, please correct me.

# Answer
> 0 votes
This is exactly what I stumbled upon when trying to create a I2C slave with a memory-based interface.

You are right, the `requestEvent` callback is called only once. So you have to prepare it beforehand. What is positive, however, is that the `write` function will discard all the unused bytes.

So, what can you do? Well, first of all a sum up of the I2C "messages". You, as a master, can

* Send a "write" command, with a payload
* Send a "read" command, with no payload, and the slave will reply with bytes as long as you continue to send ACKs

In my mind there were two different approaches:

* The "write" command should contain the initial register and the number of registers to read; this approach, however, complicates distinguishing between a "read from EEPROM" and "write to EEPROM" commands
* The write command should send only the initial register for reading from EEPROM, and the initial register + content to be written for writing to EEPROM.

In my project I chose the second approach. For this reason, when the master writes something on the I2C bus, the first byte of the payload is the register number, and then if there is no other data the slave prepares for sending the contents of the register and the next ones, while if there is any data this is treated as a write command.

The only problem with this approach is that the slave has to prepare a buffer, and the buffer size limits the maximum number of registers returned. I set this limit to 8 in my code; if the master asks for more than only 0s are returned.

Here is the library I wrote for this project.

File I2CInterface.h:

```
#ifndef I2CINTERFACE_H
#define I2CINTERFACE_H

#include <stdint.h>

class I2CInterface
{
  public:
    static I2CInterface instance;

  public:
    void start();

  private:
    I2CInterface();

    static void requestEvent();
    static void receiveEvent(int howMany);
    void resetSendingBuffer();

  private:
    static const uint8_t Address = 0x46;

    static const uint8_t MaxBufferLength = 8; // (max) 8 byte
    uint8_t sendingBuffer[MaxBufferLength];
};

#endif // I2CINTERFACE_H

```

File I2CInterface.cpp

```
#include <Arduino.h>
#include <Wire.h>
#include "I2CInterface.h"

I2CInterface I2CInterface::instance;

I2CInterface::I2CInterface()
{

}

void I2CInterface::start()
{
  Wire.begin(Address);
  Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);
  resetSendingBuffer();
}

void I2CInterface::requestEvent()
{
  Wire.write(instance.sendingBuffer, MaxBufferLength);
  instance.resetSendingBuffer();
}

void I2CInterface::receiveEvent(int howMany)
{
  if (howMany <= 0)
    return;
  else if (howMany == 1)
  { // Reading request
    uint8_t regist = Wire.read();
    for (uint8_t i = 0; i < MaxBufferLength; i++)
      instance.sendingBuffer[i] = Configuration.getRegister(regist++);
  }
  else
  { // Writing request
    uint8_t regist = Wire.read();
    while (Wire.available())
    {
      Configuration.setRegister(regist++, Wire.read());
    }
    instance.resetSendingBuffer();
  }
}

void I2CInterface::resetSendingBuffer()
{
  for (uint8_t i = 0; i < MaxBufferLength; i++)
    sendingBuffer[i] = 0x00;
}

```

Please note that the `Configuration.getRegister` and `Configuration.setRegister` are the functions I used to get and set some registers; you can substitute them with a direct EEPROM access or your own functions.

You just need to add, in your main file,

```
#include "I2CInterface.h"
...

void setup()
{
  ...
  I2CInterface::instance.start();
  ...
}

```

---
Tags: i2c, eeprom
---


title: LED intensity on digital pins

text:
# Question
Title: LED intensity on digital pins
I am using an Arduino UNO.

On any digital/analog pin, if an LED (with resistor) is connected and we use digitalWrite(pin,HIGH) the LED lights up rather dimly.

On the other hand, if we use pinMode(pin,OUTPUT) and then use digitalWrite, the LED lights up to maximum intensity.

I checked that in both cases, the voltage on the pin is 5V. Any explanation for this ? Thanks.

# Answer
> 4 votes
This is due to a specific feature of the AVR microcontrollers, where the same register (`PORTB`, `PORTC` or `PORTD`) is used for controlling both the output value of the pin and its optional internal pullup resistor. The command `digitalWrite(pin,HIGH)` sets to 1 the bit of this register corresponding to the selected pin.

* If the pin is set to `INPUT` (which is the default), the effect of `digitalWrite(pin,HIGH)` is to turn on the internal pullup.
* If the pin is set to `OUTPUT`, the same command sets the output to `HIGH`.

The internal pullup is about 30 kΩ, which lets flow a very small current through the LED. You may notice that the voltage at the pin is 5 V if nothing is connected to it, but significantly less when the LED is connected. Notice also that the preferred way of enabling the pullup is `pinMode(pin,INPUT_PULLUP)`.

---
Tags: arduino-uno, led
---


# Question
Title: Can I operate an arduino that has a file uploaded on it, without having the file myself?
I've been a massive idiot and accidentally deleted the sketch I need for a project at university, and I didn't create any backups. The sketch is already uploaded into the arduino, which operates using the serial monitor; when "1" is entered it does one thing, when "2" is entered it does another thing and so on. My question is: can I still use the serial monitor to operate the arduino without having the original sketch?

Any help would be appreciated, thank you.

# Answer
Of course you can. The serial monitor has nothing to do with the sketch - it's just a very primitive serial interface program.

You don't even need the serial monitor. You can use any serial interface program ("terminal emulator") such as Teraterm, Putty, Hyperterminal, etc.
> 4 votes

---
Tags: serial, arduino-ide
---


title: How to stop a linear actuator?

text:
# Question
Title: How to stop a linear actuator?
I wrote code but the motor does not stop, it keeps moving. Can anyone send code so that I can stop the motor after my code shown below?

```
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
  pinMode(forwards, OUTPUT);//set relay as an output
  pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {
 digitalWrite(forwards, LOW);
 digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
 delay(20000); // wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
 delay(2000);// wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
 delay(20000);// wait 2 seconds

 digitalWrite(forwards, HIGH);
 digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
 delay(2000);// wait 2 seconds
}

```

# Answer
> 0 votes
There's multiple things you can do. Here's some examples.

1: Move code out of `loop()` and into`setup()`:

```
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds
}

void loop() {
}

```

2: Stop `loop()` from looping:

```
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    while (1); // Stop here and do nothing forever
}

```

3: Set a "I have done it" flag:

```
const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin
bool complete = false;

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {
    if (!complete) {
        digitalWrite(forwards, LOW);
        digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
        delay(20000); // wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
        delay(20000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        complete = true;
    }
}

```

Each has benefits and drawbacks. Which is right for you depends on what you are actually trying to achieve.

---
Tags: arduino-uno, motor
---


title: ESP32 stops looping after 2 loops

text:
# Question
Title: ESP32 stops looping after 2 loops
My code: https://pastebin.com/UmdK33U2

I made a menu so I can send commands. First I connect to the wifi and then I send the command to send a request.

Then when it detects the key datos(); goes true, so the loop detects that and it starts sending requests. After 2 requests it just doesnt continue.

What I can do?

Btw im using a ESP32.

Thank you!

```
boolean datos = false;

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "ssid";
const char* password = "pass";

//removed the password and ssid for security, it was there before.
void setup() {
  pinMode(2, OUTPUT);
  Serial.begin(115200);

  while (!Serial)
    ;
  Serial.println("===================================================");
  Serial.println("Welcome to the menu, choose what do you want to do:");
  Serial.println("1º Connect to the Wifi | W");
  Serial.println("2º Scan Wifi | S");
  Serial.println("3º Send data to Website | D");
  Serial.println("===================================================");
  Serial.println("Made by Francine and Javi.");
  Serial.println("===================================================");
}

void scanwifi() {
  int n = WiFi.scanNetworks();
  Serial.println("===================================================");
  Serial.println("Scan have been finished.");
  Serial.println("===================================================");
  if (n == 0) {
    Serial.println("===================================================");
    Serial.println("No networks have been found.");
    Serial.println("===================================================");
  } else {
    Serial.print(n); // imprimir en el puerto serial el # de redes encontradas
    Serial.println(" networks have been found.");
    for (int i = 0; i < n; ++i) {
      // SSID: Nombre de la red; RSSI: Potencia de la red en dBm
      Serial.print(i + 1); //iniciamos en la red # 1...
      Serial.print(": ");
      Serial.print(WiFi.SSID(i)); //Imprime el nombre de la red
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i)); //Imprime la potencia de la señal en dBm
      Serial.print(")");
      byte encryption = WiFi.encryptionType(i); // en la variable encryption, guardamos el tipo de encriptación de la red
      Serial.print(" Encryption Type: ");
      Serial.println(encryption, HEX); // imprimimos el tipo de encriptación: 2: WPA, 5: WEP, etc.
      delay(10);
    }
  }
}

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

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);

    Serial.println("Connecting to WiFi..");
  }

  Serial.println("Connected to the WiFi network");
  delay(1000);
  setup();
}

void loop() {
  if (Serial.available()) {
    char ch = Serial.read();
    if (ch == 'w' || ch == 'W') {
      conectarsealwifi();
    }
    if (ch == 'S' || ch == 's') {
      scanwifi();
    }
    if (ch == 'd' || ch == 'D') {
      datos = true;
      Serial.println(datos);
    }
    if (datos == true) { // si esta habilitado el sending de datos haz
      //randomN = random(200);
      if (WiFi.status() == WL_CONNECTED) {
        digitalWrite(2, HIGH);
        HTTPClient http;

        http.begin("removedtheurl"); //Specify the URL
        int httpCode = http.GET();                            //Make the request

        if (httpCode > 0) { //Check for the returning code

          String payload = http.getString();
          Serial.println(httpCode);
          Serial.println(payload);
          Serial.println("===================================================");

        } else {
          Serial.println(
              "Error on HTTP request, reminder maybe its cloudflare shit.");
        }
        http.end(); //Free the resources
        digitalWrite(2, LOW);
      }
      delay(2000);

    } else {

    }
  }
}

```

# Answer
You send from Serial Monitor a character followed by a new line character. This two characters are available. Nothing more to enter the `if (Serial.available()) {` block.
> 0 votes

---
Tags: esp32, loop
---


title: Ultrasonic sensor showing weird reading

text:
# Question
Title: Ultrasonic sensor showing weird reading
When i run a test code in Newping library for ultrasonic sensor SR04 then in works properly but when i run the actual code for obstacle avoiding robot then it shows 0 cm everytime. This means that wiring is correct but there is something wrong in my code below

```
#include <NewPing.h>
#include <AFMotor.h> //import your motor shield library

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

AF_DCMotor motor1(1, MOTOR12_64KHZ); // set up motors.
AF_DCMotor motor2(2, MOTOR12_8KHZ);

int distance;

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

void loop() {
  delay(50);
  distance = sonar.ping_cm(); // start the scan
  delay(20);
  if (distance < 2) {
   Serial.println("Close Obstacle detected!" );
   Serial.println("Obstacle Details:");
   Serial.print("Distance From Robot is " );
   Serial.print(distance);
   Serial.print( " CM!");// print out the distance in centimeters.
   delay(10);
   Serial.println (" The obstacle is declared a threat due to close distance. ");
   Serial.println (" Turning !");
   motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
   motor2.run(BACKWARD);

}
  else {
   Serial.println("No obstacle detected. going forward");
   delay(15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
   motor2.run(FORWARD);
  }
}

```

Test code for sensor which worked:-

```
#include <NewPing.h>

#define TRIGGER_PIN  12
#define ECHO_PIN     11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
  delay(50);
  Serial.print("Ping: ");
  Serial.print(sonar.ping_cm());
  Serial.println("cm");
}

```

Tell me whats wrong here

Motor Shield used below Wiring of sensor is connected to Arduino below the shield

# Answer
> 0 votes
Try with

```
unsigned int distance;

```

Instead of

```
int distance;

```

It could also be the motor shield that is using the same pins as your ultrasonic sensor.

---
Tags: arduino-uno, sensors, code-review
---


title: SD Card Read/Write Arduino Mega Fail

text:
# Question
Title: SD Card Read/Write Arduino Mega Fail
I have an Arduino Mega 2560 where I have used a MicroSD Card Module to Read/Write Data on the Micro SD Card. I have tried using the Example in the Arduino IDE but the data is not being written or read by Arduino to the SD Card Module. The connections with the module is exactly how it is described in the Sketch. I have attached pictures of the Connection and the module I use for the same.

The Example sketch for the SD Card Read/Write is also attached.

If there is a problem that you can notice, please let me know what the problem is and if it can be solved.

Thank you in advance.

```
/*
SD card read/write

This example shows how to read and write data to and from an SD card file
The circuit:
* SD card attached to SPI bus as follows:
** MOSI - pin 11
** MISO - pin 12
** CLK - pin 13
** CS - pin 4 (for MKRZero SD: SDCARD_SS_PIN)

created   Nov 2010
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe

This example code is in the public domain.

*/

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

 File myFile;

 void setup() {
 // Open serial communications and wait for port to open:
  Serial.begin(9600);
     while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

 Serial.print("Initializing SD card...");

 if (!SD.begin(4)) {
 Serial.println("initialization failed!");
 return;
  }

  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
   myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
    if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
     } else {
     // if the file didn't open, print an error:
     Serial.println("error opening test.txt");
   }

    // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
   Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
     while (myFile.available()) {
     Serial.write(myFile.read());
     }
    // close the file:
    myFile.close();
     } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
     }
    }

    void loop() {
   // nothing happens after setup
     }

```

Connection with Arduino SD Card Module

# Answer
> 1 votes
The SPI wiring described in the SD card example sketch is for Uno. On Mega the SPI pins are 50 MISO, 51 MOSI and 52 CLK.

---
Tags: sd-card, arduino-ide
---


title: strtok keep original char

text:
# Question
Title: strtok keep original char
I want to make a vocab program for an arduino. The vocabs are saved in a char array seperated with an '/'. Now I want to split a random picked char and split it at the '/' so I can save it into two variables. But if I do it with strtok the original string gets sacrificed. If now the same vocab comes again...

I hope you can help me, but if you think a other way to do it would be better I'm open for suggestions. Here's my code

```
long random1, random2, random3, random4;
int lengtharray = 5;
char* vocab1;
char* vocab2;
char* vocab3;
char* vocab4;
char* german1;
char* english1;
char vocabs[5][16] = {"Apfel/apple","er/he","Zoo/zoo","sie/she","Hallo/hello"};

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

void loop() {
randomSeed(analogRead(0));
random1 = random(0,lengtharray);
randomSeed(analogRead(0));
random2 = random(0,lengtharray);
while(random2 == random1){
    randomSeed(analogRead(0));
    random2 = random(0,lengtharray);
}
randomSeed(analogRead(0));
random3 = random(0,lengtharray);
while(random3 == random1 || random3 == random2){
    randomSeed(analogRead(0));
    random3 = random(0,lengtharray);
}
randomSeed(analogRead(0));
random4 = random(0,lengtharray);
while(random4 == random1 || random4 == random2 || random4 == random3){
    randomSeed(analogRead(0));
    random4 = random(0,lengtharray);
}

vocab1 = vocabs[random1];
vocab2 = vocabs[random2];
vocab3 = vocabs[random3];
vocab4 = vocabs[random4];

Serial.println(vocab1);
Serial.println(vocab2);
Serial.println(vocab3);
Serial.println(vocab4);
Serial.println("//");
delay(1000);

german1 = strtok(vocab1,"/");
english1 = strtok(NULL,"/");
Serial.println(german1);
Serial.println(english1);
}

```

# Answer
Personally I would take a completely different tack. I'd store the word pairs as separate items within a struct:

```
struct wordpair {
    const char *german;
    const char *english;
};

struct wordpair pairs[] = {
    { "Apfel", "apple" },
    { "er", "he" },
    { "Zoo", "zoo" },
    { "sie", "she" },
    { "Hallo", "hello" },
};

#define NWORDS (sizeof(pairs) / sizeof(pairs[0]))

```

Now you have instant access to the words. For example:

```
pairs[3].german

```

is `"sie"`, and

```
pairs[3].english

```

is `"she"`.

You don't need to waste time splitting words up, since they are already split up. You don't need to worry about words getting corrupted, because you're never writing anything to the words. Indeed, if you tried to, because they are tagged as `const`, the compiler should complain.

So:

```
struct wordpair *vocab1 = &pairs[random1];

Serial.println(vocab1->german);

```

The macro `NWORDS` gives you the size of the array for easy reference.
> 0 votes

# Answer
Make a buffer large enough to hold the largest of the word-pairs. Copy the selected pair into the buffer and run strtok() in that buffer. Strtok will damage the buffer contents but that is a throw-away; the original word-pair string is still unchanged.
> 1 votes

---
Tags: programming
---


# Question
Title: Initialize and read from a PROGMEM array of pointers to PROGMEM arrays
I'm working on a project for the arduino uno for which I need multiple constant arrays of bytes. Such an array is initialized like so:

```
const byte charR[] PROGMEM = {
  B01111111,//top half
  B01111111,
  B01000100,
  B01000110,
  B01101111,
  B00111001,
  B00000000,
  B01111000,//bottom half
  B01111000,
  B00000000,
  B00000000,
  B01111000,
  B01111000,
  B00000000
};

```

This array represents the capital letter R. I read the nth byte of this array like so:

```
nth_byte = pgm_read_word(charR+n);

```

This is all fine and good so far, but now I need to take it a step further. I need to create the array message\[\]. I need to use message\[\] to read byte arrays in a certain sequence. For instance:

```
message[] = {
  charR,
  chare,
  charp,
  charl,
  chary,
  charspace,
  charp,
  charl,
  chare,
  chara,
  chars,
  chare
};

```

Each entry in message\[\] refers to a byte array that represents a character. Notice how multiples appear. This is kind of like a 2-D array, but I want to save progmem by only defining each character once.

How do I properly initialize message\[\]? Will I need to use pointers for this? How do I properly get the array size or yth byte of the xth entry in message\[\]?

# Answer
> 2 votes
`const byte* const message[] PROGMEM =`

to use an item, load it in RAM

`strcpy_P(buffer, (byte*)pgm_read_word(&(message[i])));`

source Arduino reference - PROGMEM

---
Tags: array, pointer, progmem, constants
---


# Question
Title: Look for Master and Slave code with error for a Arduino Mege
I am building a a-10c Sim. So I need lots of input and outputs. Each Arduino has 54 digital i/o and 16 analog inputs in each. As I need more I just add another arduino mega 2560.

I want to thank in advance Im am very new at his, and would welcome any help.

Regards,

Gary Im am a dyslexic so pls excuse the spelling or bed sentences

# Answer
I am not sure that I understand what you are planning to build. From the Internet I see that a "10c Sim" is a flight simulation program. Therefore I assume you plan to build some hardware, like flight stick and throttle, to provide the necessary input to the PC on which this sim program runs.

The number of digital i/o and analog inputs you mention is not true for "each Arduino" but only for an Arduino Mega.

To expand the number of i/o pins you could add another Arduino, but this makes the programming (much) more complicated. You could set them up as master and slave, where the master tells the slave which output to perform and the slave tells the master which input came in. Or you can split-up the total system into two subsystems where each Arduino has his own responsibilities to handle it's part of the system. In order not to lose many i/o pins to the connection between both Arduino's, the connection between the two Arduino's has to be serial.

But there are better possibilities to extend the number of i/o-pins. IC's (chips) exist wit a serial input and a number of (parallel) i/o pins. A special case of this are the IC's working with I2C as the serial connection. Look at Google for "i2c port expander".
> 2 votes

---
Tags: arduino-uno, arduino-mega
---


title: problem related to arduino

text:
# Question
Title: problem related to arduino
first of all, I am not very good at English. if I have done a mistake during describe the problem apologize me. I want to combine both ultrasonic sensor code and mpu6050 sensor. can anyone tell me how to combine both codes in one code?

```
#include <Wire.h>
//I2C communication library for MPU6050
#include <I2Cdev.h>
//MPU6050 interfacing library
#include <MPU6050_6Axis_MotionApps20.h>
//Processing incoming serial data
#include <CmdMessenger.h>
//Contain definition of maximum limits of various data type
#include <limits.h>

//Creating MPU6050 Object
MPU6050 mpu(0x68);
//Messenger object
CmdMessenger Messenger_Handler = CmdMessenger(Serial);

///////////////////////////////////////////////////////////////////////////////////////
//DMP options
//Set true if DMP init was successful
bool dmpReady = false;
//Holds actual interrupt status byte from MPU
uint8_t mpuIntStatus;
//return status after each device operation
uint8_t devStatus;
//Expected DMP paclet size
uint16_t packetSize;
//count of all bytes currently in FIFO
uint16_t fifoCount;
//FIFO storate buffer
uint8_t fifoBuffer[64];

#define OUTPUT_READABLE_QUATERNION
////////////////////////////////////////////////////////////////////////////////////////////////

//orientation/motion vars
Quaternion q;
VectorInt16 aa;
VectorInt16 aaReal;
VectorInt16 aaWorld;
VectorFloat gravity;

//Euler angle container
float euler[3];

//yaw/pitch/roll container and gravity vector
float ypr[3];

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool mpuInterrupt = false;     // indicates whether MPU interrupt pin has gone high
void dmpDataReady() {
    mpuInterrupt = true;
}

/////////////////////////////////////////////////////////////////
//Motor Pin definition
//Left Motor pins

#define A_1 3
#define B_1 4

//PWM 1 pin number
#define PWM_1 6

//Right Motor
#define A_2 4
#define B_2 5

//PWM 2 pin number
#define PWM_2 5

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Ultrasonic pins definition
const int echo = 24, Trig = 23;
long duration, cm;

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////////////////////
//Motor speed from PC
//Motor left and right speed
float motor_left_speed = 0;
float motor_right_speed = 0;
/////////////////////////////////////////////////////////////////

//Setup serial, encoders, ultrasonic, MPU6050 and Reset functions
void setup()
{

  //Init Serial port with 115200 baud rate
  Serial.begin(115200);

  //Setup Motors
  SetupMotors();
  //Setup Ultrasonic
  SetupUltrasonic();
  //Setup MPU 6050
  Setup_MPU6050();

  //Set up Messenger
//  Messenger_Handler.attach(OnMssageCompleted);

}

void SetupMotors()
{

 //Left motor
 pinMode(A_1,OUTPUT);
 pinMode(B_1,OUTPUT);

 //Right Motor
 pinMode(A_2,OUTPUT);
 pinMode(B_2,OUTPUT);

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup UltrasonicsSensor() function
void SetupUltrasonic()
{
 pinMode(Trig, OUTPUT);
 pinMode(echo, INPUT);

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup MPU6050 function

void Setup_MPU6050()
{

    Wire.begin();
   // initialize device
    Serial.println("Initializing I2C devices...");
    mpu.initialize();

    // verify connection
    Serial.println("Testing device connections...");
    Serial.println(mpu.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");

    //Initialize DMP in MPU 6050
    Setup_MPU6050_DMP();

}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Setup MPU 6050 DMP
void Setup_MPU6050_DMP()
{

     //DMP Initialization

   devStatus = mpu.dmpInitialize();

   mpu.setXGyroOffset(220);
   mpu.setXGyroOffset(76);
   mpu.setXGyroOffset(-85);
   mpu.setXGyroOffset(1788);

   if(devStatus == 0){
         Serial.println(F("Enabling DMP..."));
        mpu.setDMPEnabled(true);
    //mpu.setDMPEnabled(true);

//    pinMode(PUSH2,INPUT_PULLUP);
//    attachInterrupt(PUSH2, dmpDataReady, RISING);

    mpuIntStatus = mpu.getIntStatus();

    dmpReady = true;

    packetSize = mpu.dmpGetFIFOPacketSize();

   }else{

     ;
     }
}

void loop() {

 //Read from Serial port
    Read_From_Serial();

    //Send ultrasonic values through serial port
    Update_Ultra_Sonic();

    //Send MPU 6050 values through serial port
    Update_MPU6050();

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Read from Serial Function

void Read_From_Serial()

{
   while(Serial.available() > 0)
    {

       int data = Serial.read();
//       Messenger_Handler.process(data);

    }

}

void Update_Ultra_Sonic()
{
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);
  // The echo pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  duration = pulseIn(echo, HIGH);

  //Sending through serial port
  Serial.print("u");
  Serial.print("\t");
  Serial.print(cm);
  Serial.print("\n");

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Update MPU6050

void Update_MPU6050()
{

  int16_t ax, ay, az;
  int16_t gx, gy, gz;

    ///Update values from DMP for getting rotation vector
    Update_MPU6050_DMP();

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Update MPU6050 DMP functions

void Update_MPU6050_DMP()
{

 //DMP Processing
 // if programming failed, don't try to do anything
    if (!dmpReady) return;

     // wait for MPU interrupt or extra packet(s) available
    while (!mpuInterrupt && fifoCount < packetSize) {

        ;

          }

// reset interrupt flag and get INT_STATUS byte
    mpuInterrupt = false;
    mpuIntStatus = mpu.getIntStatus();

    //get current FIFO count
    fifoCount = mpu.getFIFOCount();

    // check for overflow (this should never happen unless our code is too inefficient)
    if ((mpuIntStatus & 0x10) || fifoCount > 512) {
        // reset so we can continue cleanly
        mpu.resetFIFO();
    }

// otherwise, check for DMP data ready interrupt (this should happen frequently)
else if (mpuIntStatus & 0x02) {
        // wait for correct available data length, should be a VERY short wait
        while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

        // read a packet from FIFO
        mpu.getFIFOBytes(fifoBuffer, packetSize);

        // track FIFO count here in case there is > 1 packet available
        // (this lets us immediately read more without waiting for an interrupt)
        fifoCount -= packetSize;

        #ifdef OUTPUT_READABLE_QUATERNION
            // display quaternion values in easy matrix form: w x y z
            mpu.dmpGetQuaternion(&q, fifoBuffer);

            Serial.print("i");Serial.print("\t");
            Serial.print(q.x); Serial.print("\t");
            Serial.print(q.y); Serial.print("\t");
            Serial.print(q.z); Serial.print("\t");
            Serial.print(q.w);
            Serial.print("\n");

        #endif

        #ifdef OUTPUT_READABLE_EULER
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetEuler(euler, &q);
            Serial.print("euler\t");
            Serial.print(euler[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(euler[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(euler[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            Serial.print("ypr\t");
            Serial.print(ypr[0] * 180/M_PI);
            Serial.print("\t");
            Serial.print(ypr[1] * 180/M_PI);
            Serial.print("\t");
            Serial.println(ypr[2] * 180/M_PI);
        #endif

        #ifdef OUTPUT_READABLE_REALACCEL
            // display real acceleration, adjusted to remove gravity
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            Serial.print("areal\t");
            Serial.print(aaReal.x);
            Serial.print("\t");
            Serial.print(aaReal.y);
            Serial.print("\t");
            Serial.println(aaReal.z);
        #endif

        #ifdef OUTPUT_READABLE_WORLDACCEL
            // display initial world-frame acceleration, adjusted to remove gravity
            // and rotated based on known orientation from quaternion
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetAccel(&aa, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetLinearAccel(&aaReal, &aa, &gravity);
            mpu.dmpGetLinearAccelInWorld(&aaWorld, &aaReal, &q);
            Serial.print("aworld\t");
            Serial.print(aaWorld.x);
            Serial.print("\t");
            Serial.print(aaWorld.y);
            Serial.print("\t");
            Serial.println(aaWorld.z);
        #endif

        #ifdef OUTPUT_TEAPOT
            // display quaternion values in InvenSense Teapot demo format:
            teapotPacket[2] = fifoBuffer[0];
            teapotPacket[3] = fifoBuffer[1];
            teapotPacket[4] = fifoBuffer[4];
            teapotPacket[5] = fifoBuffer[5];
            teapotPacket[6] = fifoBuffer[8];
            teapotPacket[7] = fifoBuffer[9];
            teapotPacket[8] = fifoBuffer[12];
            teapotPacket[9] = fifoBuffer[13];
            Serial.write(teapotPacket, 14);
            teapotPacket[11]++; // packetCount, loops at 0xFF on purpose
        #endif

    }

}

```

# Answer
In the function `Update_Ultra_Sonic()` you do the measurement and save the result in the variable `duration`. Then you print the variable `cm`, but you haven't calculated the value for this variable yet. You have to calculate the number of cm from the echos `duration` and save the result in `cm`. When you don't do this, the variable stays at zero.
> 0 votes

---
Tags: arduino-uno, arduino-mega
---


# Question
Title: AtTiny85 and MMA8452Q accelerometer cannot connect using i2c
I am trying to connect the MMA8452Q with AtTiny85 using the TinyWireM library. I made the proper hardware setup with pull-ups on SCL and SDA pins - tested it on Arduino Uno and it works, however when i connect the Tiny I cannot even get the handshake. The following code produces output `13` instead of `42` (0x2A)

**HARDWARE SETUP**

MMA8452 Breakout ------------AtTiny85

3.3V -------voltage regulator------ 5V

SDA -----------^^(330)^^----------- PB0 (on attiny programmer marked as 5)

SCL -----------^^(330)^^----------- PB3 (on attiny programmer marked as 2)

GND --------------------------------- GND

(I also tried different pins with no luck)

**CODE**

```
//---bluetooth console communication stuff---//
#include <SoftwareSerial.h>
#define rxPin 1 //not important - needed for initialization
#define txPin A2
SoftwareSerial blueTooth(rxPin, txPin);
//      ---     //

#include "TinyWireM.h" // Used for I2C

// The SparkFun breakout board defaults to 1, set to 0 if SA0 jumper on the bottom of the board is set
#define MMA8452_ADDRESS 0x1D  // 0x1D if SA0 is high, 0x1C if low

#define WHO_AM_I   0x0D

void setup() {

  blueTooth.begin(9600);
  delay(1000);
  TinyWireM.begin(); //Join the bus as a master
  delay(1000);
 }

void loop() {
   byte c =0;
   c = readRegister(WHO_AM_I);
   blueTooth.println(c);
   delay(1000);
  }

 // Read a single byte from addressToRead and return it as a byte
byte readRegister(byte addressToRead) {
  TinyWireM.beginTransmission(MMA8452_ADDRESS);
  TinyWireM.send(addressToRead);
  TinyWireM.endTransmission(); //endTransmission but keep the connection active

  TinyWireM.requestFrom(MMA8452_ADDRESS, 1); //Ask for 1 byte, once done, bus is released by default

  while(!TinyWireM.available()) ; //Wait for the data to come back
  return TinyWireM.receive(); //Return this one byte
}

```

Would anyone know how to get it right?

# Answer
> 1 votes
On an ATtiny85 pin 5 (PB0) is SDA and pin 7 (PB2) is SCL for the I2C interface. You're using the wrong pin for SCL.

Additionally, your pull-up resistors are too strong. Somewhere between 4.7K Ohm and 10K Ohm are recommended for pull-up's on the SDA and SCL lines.

# Answer
> 0 votes
> using the TinyWireM library.

Make sure the i2c actually works. Arduino libraries are generally of poor quality and just because someone wrote it doesn't mean it actually works. Get a logic analyzer or scope on the bus and see what's going on.

Once you can confirm that, get a datasheet for the 8452 and see how it works and code to it.

---
Tags: i2c, attiny, accelerometer
---