# Question
Title: Powering Arduino from 7805 voltage regulator
I am trying to build an Arduino Uno based robot. My questions are the following:

1) The motor driver also has an on-board 78M05 voltage regulator from ST electronics. I used a 9V battery to power the robot, and the 9V was connected to the input of the voltage regulator, and the +5V output I used to power the Arduino. I did so by connecting the 5V from the regulator to the 5V pin on the Arduino and the GND's together. I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

2) I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

# Answer
> 1 votes
> I read that this is not advised, and solutions ranged from making sure the 5V is regulated, to connecting a diode between +5V and Vin to using one of the ICSP pins and so on. So which is actually a good way to do this?

Nothing wrong with that as long as it is regulated 5V (which yours is). You can use either the 5V pin on the header, or the 5V pin on the ICSP connector. They are both the same. It is good practice to connect a diode between 5V and VIN to prevent current flowing backwards through the onboard regulator should something connected to VIN want to draw current.

> I later realized that the DC motors are rated for max 6V dc, and so switched the 9V battery to 4x AA batteries giving a total voltage of 6V. When I connected this to the regulator, the regulator and the Arduino still turned on, even though the data sheet says the minimum input voltage is 7V. So what is going on here? Can anyone help me understand what is happening?

A regulator has a "drop-out" voltage. That is often in the order of 1.2V for these kind of regulators (it's certainly right for the Arduino's on-board one.

You are providing less than the regulation voltage plus the drop-out voltage, so the output of the regulator will be the input voltage minus the drop-out voltage.

As long as that is above the lowest voltage the Arduino can run from at 16MHz then it will still work fine. You should be fine down to about 4V output from the regulator, and even lower if you're lucky (you may start getting stability problems though since the ATMega328P isn't rated to run at 16MHz at lower voltages).

It also means that the GPIOs on the Arduino will be running at a lower voltage as well.

---
Tags: arduino-uno, power
---


# Question
Title: Serial.parseInt value always goes back to 0
I am trying to read a value between 1000 and 2000 from my Serial Monitor and use it to drive some motors through ESC.

The code works when I use a potentiometer mapped for 1000-2000. I am now trying to use a Serial Monitor, but the "val" keeps going from the value I enter (between 1000 and 2000) and quickly returns to 0.

Why is this?

Here is the code for reference:

```
#include <Servo.h>//Using servo library to control ESC
Servo esc1; //Creating a servo class with name as esc1
Servo esc2; //Creating a servo class with name as esc2
Servo esc3; //Creating a servo class with name as esc3
Servo esc4; //Creating a servo class with name as esc4
void setup()
{
  esc1.attach(7); //Specify the esc signal pin,Here as D10
  esc2.attach(6); //Specify the esc signal pin,Here as D9
  esc3.attach(5); //Specify the esc signal pin,Here as D8
  esc4.attach(4); //Specify the esc signal pin,Here as D7
  esc1.writeMicroseconds(1000); //initialize the signal to 1000
  esc2.writeMicroseconds(1000); //initialize the signal to 1000
  esc3.writeMicroseconds(1000); //initialize the signal to 1000
  esc4.writeMicroseconds(1000); //initialize the signal to 1000
  Serial.begin(9600);
}
void loop()
{
  int val; //Creating a variable val
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while (Serial.available() > 0) {
    val = Serial.parseInt();
    Serial.println(val);
  }//Checks for a character in the serial monitor
  Serial.println(val);
  esc1.writeMicroseconds(val); //using val as the signal to esc
  esc2.writeMicroseconds(val); //using val as the signal to esc
  esc3.writeMicroseconds(val); //using val as the signal to esc
  esc4.writeMicroseconds(val); //using val as the signal to esc
}

```

# Answer
This code will work IF you set the Serial Monitor to "No Line Ending" (OSX 10.6.8. IDE Version 1.0.6.2). parseInt() doesn't like the NL + CR chars.

```
unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){
    val = Serial.parseInt();
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

```

There is another way to get the integer value using this code:

```
char inputBuffer[16];
unsigned int val;

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

void loop(){
  Serial.println("Input ESC Speed between 1000 and 2000:");
  while(Serial.available() > 0){

    // A function that reads characters from the serial port into a buffer.
    Serial.readBytes(inputBuffer, sizeof(inputBuffer));

    // Convert string to integer
    // cplusplus.com/reference/cstdlib/atoi/
    val = atoi(inputBuffer);

    // memset clears buffer and updates string length so strlen(inputBuffer) is accurate.
    memset(inputBuffer, 0, sizeof(inputBuffer));
  }
  if(val > 0){Serial.println(val);}
  delay(1000);
}

```

The Binary sketch size is 94 bytes less than the first example using parseInt. The second sketch will work with ANY Serial Monitor Line Ending settings.
> 5 votes

---
Tags: serial, servo
---


title: Interfacing Aduino Nano and RDM8800

text:
# Question
Title: Interfacing Aduino Nano and RDM8800
I'm attempting to use an Arduino Nano with the RDM8800 to read data from NFC tags. After soldering wires between the Nano and the RDM8800, I attempted to test these devices using code similar to what has been used successfully on other serial devices similar to the RDM8800. Below is the code I used to test.

Wiring:

```
Nano - RDM8800
--------------
 5V  -  5V
GND  -  GND
 D3  -  TX
 D2  -  RX

```

Tags Tested:

* NTAG 216 (ISO14443A)
* MiFare Classic 1k (ISO14443A)

Code:

```
#include <SoftwareSerial.h>

SoftwareSerial soft(2,3);

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

void loop() {
  if(soft.available() > 0) {
    String serialData = soft.readString();
    Serial.println(serialData);
    writeAck();
  }

}

void writeAck() {
  uint8_t payload[] = "ACK|0|\n";
  soft.write(payload, sizeof(payload));
}

```

I watched the serial monitor and attempted to scan two different NFC tags that matched the ISO14443A compatibility that should ship with the RDM8800, according to this article. I got no information returned on the serial monitor.

After, assuming the issue is with the firmware, I attempted to upload the firmware to the RDM8800, with no success. I installed the needed board support to the Arduino IDE, as outlined in the intro article. Not having a USB to serial tool, I used another Nano and simply bridged the connection between the GND and RST pins. I was unable to upload the firmware to the RDM8800, getting the error below each time I tried.

Error:

```
avrdude: stk500_recv(): programmer is not responding

```

I believe that it's possible that I can't upload the firmware to the RDM8800 because the setup I used with the Nano as the USB to serial tool lacked a reset button. The image in the intro article, says to connect the TX RX GND 5V and RST pins, but the image that it says shows this only shows the TX RX GND and 5V pins connected(See below).

Image:

The information that I've found on the RDM8800 and its use is very limited and so is my knowledge on this topic. I'm unsure how I should proceed right now. I believe that I'm taking the right approach to setup code to scan NFC tags, but I could be wrong there. I'm very unsure on what I'm doing in relation to the potential firmware issue. Overall, I'm simply unsure on how to proceed and I'm looking for more knowledgeable people to give me some advice on how to proceed.

Relevant Resources:
RDM8800 Itead Wiki Page
RDM8800 Data Sheet
RDM8800 Schematic
RDM8800 Introduction Article

# Answer
SoftwareSerial constructor is rx pin first then tx pin.

You have `SoftwareSerial soft(2,3);` But you said that

```
D3 - TX
D2 - RX

```

Which means soft rx is going to its rx and soft tx is going to its tx. These need to be swapped. Either swap the wires or change it to:

```
SoftwareSerial soft(3,2);

```
> 0 votes

---
Tags: arduino-nano, rfid, firmware
---


title: Measure an AA battery?

text:
# Question
Title: Measure an AA battery?
If I'm going to measure an AA battery (about 1.5 v) with a USB-powered Arduino, I will connect the battery's +ve terminal to the A0 pin. Shall I connect the -ve terminal to the gnd pin too?

# Answer
> 1 votes
Yes you could although this means you're measuring in relation to the Arduino's logic voltage, which is slightly below 5v (due to a diode's voltage drop) or the voltage of vref.

---
Tags: arduino-mega
---


# Question
Title: How can I loop for a set amount of time when a condition is met?
I'm trying to create an Arduino project with a light sensor and a buzzer. The idea is that when the sensor detects that the lights have gone off, the buzzer will sound for 5 seconds. At some point, the lights will come back on, but when they go back off, I need the buzzer to sound again.

At the moment the buzzer does sound the first time the lights are turned off but after the lights have come back on and then off again, it won't sound and I can't figure out why.

```
int lightSensor = 2;
int buzzer = 3;
long startTime,stopTime;
long myDesiredTime = 5000;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lightSensor, INPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      if(stopTime-startTime<=myDesiredTime && sensorState == 1)
      {
        runBuzzer();
        stopTime=millis();
      }
    }
  }
}

void runBuzzer()
{
  tone(buzzer, 1000); // Send 1KHz sound signal...
  delay(1000);        // ...for 1 sec
  noTone(buzzer);     // Stop sound...
  delay(1000);
}

```

# Answer
You have two major issues here:

```
void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      if(stopTime-startTime<=myDesiredTime && sensorState == 1)
      {
        runBuzzer();
        stopTime=millis();
      }
    }
  }
}

```

The first is that you never re-read sensorState. The second is that you are comparing stopTime before setting a value to it. Try re-arranging like this:

```
void loop() {
  // put your main code here, to run repeatedly:
  int sensorState = digitalRead(lightSensor);

  switch(sensorState)
  {
  case 1:
    while (sensorState == 1)
    {
      stopTime=millis();
      if(stopTime - startTime <= myDesiredTime)
      {
        runBuzzer();
      }
    sensorState = digitalRead(lightSensor);  // read sensorState again
    }
  }
}

```

---

> In your example, the buzzer does not sound when the light has been switch on and then back off again.

Good point. Well, we can simplify somewhat:

```
void loop() {

  if (digitalRead(lightSensor) == HIGH)
    {
    startTime = millis ();  // remember when we started
    while (digitalRead(lightSensor) == HIGH &&
           millis () - startTime <= myDesiredTime)
      {
      runBuzzer();
      }  // end of while switch still closed and time not up
    while (digitalRead(lightSensor) == HIGH) { } // wait for sensor go to LOW
    delay (200);  // debounce
    }    // end of switch being closed
}      // end of loop

```
> 1 votes

# Answer
Understand that your `while (sensorState == 1)` in your `switch()` is an infinite loop, with no way out (even if internally it gives the desired 5 seconds of sound).
> 0 votes

# Answer
Think of it like this. Any time you use a while loop your code has the rains until its done its job.

It's important to remember that the loop() function in Arduino should not be blocked. This line:

`while (sensorState == 1)`

will block forever. The condition is never changed from within the while loop. Theres a simple way you could fix this which would be to set `sensorState` and update it inside the while loop. But lets not do that. Because thats inefficient and you'll likely run into this problem again in more complex programs and that solution here won't still be a solution.

What you're trying to do is called concurrency. Your program should have obvious units of execution. Your two units are: "run a buzzer for 5 seconds" and "set off an event when a sensor reads true." where the first is depended on the second. So its conditional. That sounds like a job for `if`

When you code in `{` and `}` it is a block. It's not quite a context but is a distinct mode of execution.

So technically this:

```
void loop() {
    if( ... ) {
      ...
    }
    if ( ... ) {
      ...
    }
}

```

Is two modes of execution. Since loop() is executed repeatedly. With that in mind when you program you can then use a variable to control the what gets executed as needed. So:

```
void loop() {
    int sensorState = digitalRead(lightSensor);
    if( sensorState == 1 && buzzer_enabled == 0) { // set off an event when a sensor reads true.
        buzzer_enabled = 1;
        startTime = millis();
    }
    if ( buzzer_enabled == 1 ) { // run a buzzer for 5 seconds
        endTime = millis();
        if(stopTime - startTime <= myDesiredTime) {
            runBuzzer();
        } else {
            buzzer_enabled = 0;
        }
    }
}

```

We could stop here. But the use of delay is also blocking in the loop function and it is only for perception. So here's the whole thing without delays using a check against the modulus of diffTime.

```
int lightSensor = 2;
int buzzer = 3;

long startTime,stopTime;
long myDesiredTime = 5000;

bool buzzer_enabled = false;
bool buzzer_active = false;

int sensorState;
int prevSensorState = 0;

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(lightSensor, INPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
    sensorState = digitalRead(lightSensor);
    if( sensorState == 1 && prevSensorState == 0 ) { // set off an event when a sensor reads true.
        buzzer_enabled = true;
        startTime = millis();
    }
    prevSensorState = sensorState;
    if ( buzzer_enabled == true ) { // run a buzzer for 5 seconds
        stopTime = millis();
        long diffTime = stopTime - startTime;
        if( (diffTime % 2000) < 1000 ) {
            if(buzzer_active == false) {
                buzzer_active = true;
                //tone(buzzer, 1000);
            }
        } else {
            if(buzzer_active == true) {
                buzzer_active = false;
                //noTone(buzzer);
            }
        }
        if(diffTime > myDesiredTime) {
            buzzer_enabled = false;
        }
    }
}

```

No need for delay \>:3 And all for free you got a new feature which is that if you set off the event again (the light goes off) the buzzer is extended another 5 seconds. If you don't want that all you have to do is add `&& buzzer_enabled == false` to the first if.
> 0 votes

---
Tags: arduino-uno, buzzer
---


# Question
Title: Unable to upload the data on thingspeak using uno and esp8266
I am able to connect to thingspeak but now able to upload the data. here are my set of commands:

```
AT+CIPMUX=0
OK

AT+CIPSTART="TCP","184.106.153.149", 80
OK
Linked

AT+CIPSTATUS
STATUS:3
+CIPSTATUS:0,"TCP","184.106.153.149",80,0
OK

AT+CIPSEND=45
> GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60

busy s...

SEND OK

OK

```

and after some time unlink

I am giving these commands using arudino serial monitor. Please help, I have searched a many blogs, youtube videos.

# Answer
I got it working. Yo!

```
#include <SoftwareSerial.h>
#include <stdlib.h>

// LED
int ledPin = 13;
// LM35 analog input
int lm35Pin = 0;
float my_value = 22;
// replace with your channel's thingspeak API key
String apiKey = "9PJEF1EP8ZMVY5JA";

// connect 10 to TX of Serial USB
// connect 11 to RX of serial USB
SoftwareSerial ser(10, 11); // RX, TX

// this runs once
void setup() {
  // initialize the digital pin as an output.
  pinMode(ledPin, OUTPUT);

  // enable debug serial
  Serial.begin(9600);
  // enable software serial
  ser.begin(9600);

  // reset ESP8266
  ser.println("AT+RST");
}

// the loop
void loop() {

  // blink LED on board
  digitalWrite(ledPin, HIGH);
  delay(200);
  digitalWrite(ledPin, LOW);

  // read the value from LM35.
  // read 10 values for averaging.

  // convert to temp:
  // temp value is in 0-1023 range
  // LM35 outputs 10mV/degree C. ie, 1 Volt => 100 degrees C
  // So Temp = (avg_val/1023)*5 Volts * 100 degrees/Volt
  my_value++;
  float temp = my_value;

  // convert to string
  char buf[16];
  String strTemp = dtostrf(temp, 4, 1, buf);

  Serial.println(strTemp);

  // TCP connection
  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "184.106.153.149"; // api.thingspeak.com
  cmd += "\",80";
  ser.println(cmd);

  if(ser.find("Error")){
    Serial.println("AT+CIPSTART error");
    return;
  }

  // prepare GET string
  String getStr = "GET /update?api_key=";
  getStr += apiKey;
  getStr +="&field1=";
  getStr += String(strTemp);
  getStr +="&field2=";
  getStr += String(strTemp);
  getStr += "\r\n\r\n";

  // send data length
  cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  ser.println(cmd);
  Serial.println(cmd);

  if(ser.find(">")){
    ser.print(getStr);
    Serial.println(getStr);
  }
  else{
    ser.println("AT+CIPCLOSE");
    // alert user
    Serial.println("AT+CIPCLOSE");
  }

  // thingspeak needs 15 sec delay between updates
  ser.println("AT+RST");
  delay(30000);
}

```
> 0 votes

# Answer
You have a malformed HTTP request. You only have half of the first line.

A valid HTTP request would look more like this:

```
GET /update?api_key=DXDPC4MLXMXFB5TT&field1=60 HTTP/1.1
Host: api.thingspeak.com
Content-length: 0
Connection: close
<blank line>

```

Just sending "GET : ain't gonna work. For a start, the server won't know what protocol you're speaking (HTTP/1.1), nor what website it's supposed to direct the request to (Host: api.thingspeak.com). Also, the final extra blank line is *required* to finish the request.
> 0 votes

---
Tags: esp8266, uploading, thingspeak
---


# Question
Title: How to connnect Arduino to Wemos D1 (send data)?
I made a project with an **Arduino Uno**, a 16x2 LCD **display** and a DS18B20 **temperature sensor**. It shows the temperature in the display:

I want to connect it to Internet so I got a Wemos D1 Mini. It works great: it send data through my router.

But I need to connect my project with the Wemos D1 Mini:  I think that I just need to send the data (temperatures grades) from my project to Wemos so then Wemos resolve it.

How can I do it?

# Answer
> 2 votes
* A) Throw out the Arduino, and just connect your display and sensor to the WeMos directly.
* B) Connect the Arduino to the WeMos using UART, SPI or I²C and send the temperature value to the WeMos. Keep in mind that the Arduino UNO is a 5V device, and the maximum voltage for the ESP8266 is 3.3V, so you'll need a level shifter. You can send the temperature as a binary value (beware of framing errors), but the easiest way is to use a text-based protocol. Since you just have to send a single value, you can just use a single delimiter (e.g. new line). That makes it very easy to parse.

# Answer
> 1 votes
If you want to use the Wemos D1 only as a 'network adapter', put a firmware into esp8266. 'Classic' is Espressif AT firmware in esp with WiFiEsp library in your sketch. New option is WiFi Link firmmware in the esp with WiFi Link library used in your sketch.

Both libraries recommended by me (WiFiEsp and WiFiLink) have standard Arduino networking API like the Ethernet and WiFi library.

WiFi Link firmware is an Arduino sketch for the esp8266.

---
Tags: arduino-uno, wifi, lcd, nodemcu, ds18b20
---


title: Arduino ISR timing question

text:
# Question
Title: Arduino ISR timing question
Im trying to understand how the Arduino ISR keeps track of timing between pulses stored in a variable, if that variable is latter used.

Say, for example, you have a magnet mounted on a circular object, that passes a reed switch. Using this to trigger the ISR that calls a function that would have something like counts++ in it, then storing that value in a variable.

If that varible is used latter to turn on a motor, for example, according to the count capture, how does the arduino MCU know the freq or timing to output the count or pulses of the magnet passing the reed switch, at the same frequency that the counts were received? For example, a magnet mounted on a 2 inch dia shaft would turn slower past a reed switch than one mounted on a .5 inch shaft, or one could vary the speed of the magnet past the reed as they wish. So how does counter++ keep track of this freq? is it reading the attachinterupt pin (or is the function that is being called, keeping track) or does the ISR time stamp each pulse it receives and store that interval in the declared variable? so when the variable is used again, it has this interval stored in it?

To be more clear, if it takes one second for the magnet to complete one revolution, how does the MCU know it took one second and store this, along with the counts of the revolutions?

Thanks for any help

# Answer
> 1 votes
All the interrupt does is count. It has no concept of time. For instance:

```
volatile uint32_t revolutions = 0;
void count() {
    revolutions++;
}
....
attachInterrupt(0, count, FALLING);

```

will just count up 1 every time the interrupt triggers.

To be able to convert that count into something meaningful you have to manually introduce the concept of time - that is, the count of "revolutions" (for example) between two points in time. And it's up to your sketch to implement that.

The simplest way may be:

```
// For anything more than an 8 bit value on an 8 bit machine
// make a critical section to save and reset the count
cli();
uint32_t savedResolutions = revolutions;
revolutions = 0;
sei();

Serial.print(savedRevolutions);
Serial.println(F(" revolutions per second"));

// Introduce the concept of time - this will
// make it get the count once a second.
delay(1000);

```

Of course, instead of `delay()` you can use `millis()` in much the same way as the `BlinkWithoutDelay` example in the IDE.

It is possible (as long as you're not counting too fast) to incorporate the time element into the interrupt routine by keeping track of the time in a variable:

```
volatile uint32_t rps = 0;

void count() {
    static uint32_t revolutions = 0;
    static uint32_t timestamp = millis();

    revolutions++;

    if (millis() - timestamp >= 1000) {
        timestamp = millis();
        rps = revolutions;
        revolutions = 0;
    }
}
....
attachInterrupt(0, count, FALLING);

```

Then you can just reference the `rps` variable at any time to get the revolutions per second. Again it should really be queried inside a *critical section* to prevent the value being changed while you're actively reading it...

```
cli();
uint32_t myRPS = rps;
sei();

Serial.print(myRPS);
Serial.println(F(" revolutions per second"));

```

---
Tags: isr
---


# Question
Title: PWM output while using I2C with the ATTiny library
I've noticed that when using the USI interface on the ATTiny to send I2C via the methods from "Wire.h" with the ATTiny Arduino implementation included from the library manager (ATTinyCore), while `analogWrite` PWM on PB4 (Arduino pin 4, physical pin 3) works OK, it seems attempting to use it on PB1 (Arduino pin 1, physical pin 6) behaves erratically or hangs the processor.

Is this expected behavior, and is there a workaround? With the `SDA` line on PWM pin 0, physical pin 5 if that's the case it means when using the hardware USI to do I2C communications, I'm down to a single hardware PWM output, which is kind of a bummer.

# Answer
This is normal.

Timer0 is used as the clock source for the USI. It's the only internal clock source that can be used. The only other option is to use "software polled" mode where it's up to the sketch (or support library) to manually create the clock signal (less than desirable) by setting a bit in a register at the right time.

So you can only use Timer1 for your own (PWM) purposes while using the USI.
> 2 votes

---
Tags: i2c, pwm, attiny, attiny85
---


# Question
Title: Reading and comparing data from Arduino Uno EEPROM
I'm trying to read compare data from EEPROM (Arduino UNO). Reading is working fine but comparing it using the '==' operator is not working as expected.

```
//string 'True' is already stored in EEPROM

int addr = 0;
char value = EEPROM.read(addr);

Serial.println(value);// this line successfully prints the letter 'T'

// but this function is not working
if (value == "T") {
  Serial.println("foo");
}

```

# Answer
There is a HUGE difference between `"string"` and `'c' 'h' 'a' 'r'`.

You are comparing address of string `"T"` with the numerical value of character `'T'`.

The expression: `if (value == 'T')` will be much better.
> 2 votes

---
Tags: arduino-uno, eeprom
---


# Question
Title: How to get the firmware (hex) file from a .ino file containing the code
I currently have a `.ino` firmware file that I use in the Arduino IDE to program an ATmega328 micro-controller. I would like to get the file that the Arduino IDE uses to program the micro-controller.

Probably the IDE uses a hexadecimal (hex) file or something and sends it to the micro-controller through the serial.

How can I get this file being the only file that the IDE generates is the `.ino`?

# Answer
In the Preferences of the Arduino IDE; after `Show verbose output during:` check the box next to `compilation`.

Then when you compile you should get something like this at the bottom of the window:

```
...
...
"/Applications/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.elf" "/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.hex"
Sketch uses 928 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.

```

At the end of the third line from the bottom you get the `.hex` filename. In this case (on OSX) that would be `/var/folders/tp/grrlc56j3z7057f12_7f1_0r0000gn/T/arduino_build_635063/Blink.ino.hex`
> 8 votes

# Answer
You are asking how to locate the compiled hex file. It's easy! Follow these steps:

1. In the Arduino IDE select `Sketch` \> `Export Compiled Binary`. This performs a compile. Once complete, this command places a copy of the compiled `.hex` file into the directory of your sketch.
2. Then either browse to the sketch folder or in the IDE select `Sketch` \> `Show Sketch Folder`.

This generates two hex files for the target micro-controller; one with the bootloader and one without the bootloader. These hex files can be uploaded to the micro-controller using a programmer such as the Atmel Ice or AVRISPmkII.
> 9 votes

# Answer
The easiest way to get the file is:

1. Sketch \> Export Compiled Binary
2. Wait for the compilation process to finish
3. Sketch \> Show Sketch Folder

You will find an extra file in the sketch folder, which in this case will have a `.hex` extension. This is the compiled file which would normally be uploaded to the Arduino board via **Sketch \> Upload**.

Note that the "Export Compiled Binary" feature is only available from Arduino IDE 1.6.5 and newer.
> 6 votes

---
Tags: arduino-ide
---


# Question
Title: Serial Print, String And Variable On Same Line
How can I print to the serial monitor a string or just single character followed by a variable like "L 55"

# Answer
> 10 votes
```
int Var = 55;
//Do it in 2 lines e.g.
Serial.print("L ");     // String
Serial.println(Var);    // Print Variable on same line then send a line feed

```

# Answer
> 1 votes
For debug printing, you can define a macro to print both the name and value of a variable like this:

```
#define PRINTLN(var) Serial.print(#var ": "); Serial.println(var)

```

which you then use like this:

```
int x = 5;
PRINTLN(x);

// Prints 'x: 5'

```

---

Also this is nice:

```
#define PRINT(var) Serial.print(#var ":\t"); Serial.print(var); Serial.print('\t')
#define PRINTLN(var) Serial.print(#var ":\t"); Serial.println(var)

```

when used in a loop like so

```
PRINT(x);
PRINT(y);
PRINTLN(z);

```

prints an output like this:

```
x:  3   y:  0.77    z:  2
x:  3   y:  0.80    z:  2
x:  3   y:  0.83    z:  2

```

# Answer
> 1 votes
Thanks a lot for your answers. I made this ...

```
#define DEBUG  //If you comment this line, the functions below are defined as blank lines.
#ifdef DEBUG    //Macros
  #define Say(var)    Serial.print(#var"\t")   //debug print, do not need to put text in between of double quotes
  #define SayLn(var)  Serial.println(#var)  //debug print with new line
  #define VSay(var)    Serial.print(#var " =\t"); Serial.print(var);Serial.print("\t")     //variable debug print
  #define VSayLn(var)  Serial.print(#var " =\t"); Serial.println(var)  //variable debug print with new line
#else
  #define Say(...)     //now defines a blank line
  #define SayLn(...)   //now defines a blank line
  #define VSay(...)     //now defines a blank line
  #define VSayLn(...)   //now defines a blank line
#endif

```

---
Tags: serial, softwareserial
---


# Question
Title: Infinite Loop on Pin Input (Teensy 3.1)?
I have an infinite loop issue that keeps persisting in this code on my Teensy 3.1. This program is intended to take an input on Pin 0 and press the Enter key on the computer it is hooked into.

It is connected to a wire with no current but once a switch is flipped it should send a 5v Digital Signal blip to the Teensy and trigger it to run. It does function but it keeps getting caught in an infinite loop for some reason. Any help would be greatly appreciated!

```
// Global Variable
int signal_receiving_pin = 0;

void setup() {
  // Outputting for error checking
  Serial.begin(38400);

  // Readying the pin for input
  pinMode(signal_receiving_pin, INPUT);
}

void loop()
{
// If statement to check whether an input has been received
if (digitalRead(signal_receiving_pin) == HIGH)
{
  // If the signal has been detected..
  Serial.println("The signal has been received \n");
  Serial.println("Now sending the ENTER signal \n");

  // .. The ENTER key is sent to the computer
  //Keyboard.press(KEY_ENTER);
  //Keyboard.release(KEY_ENTER);

  // Waiting 1 minute before allowing more input
  //delay(60000); // Pause
}
else
{
  // If the signal is not detected..
  // it will let you know it isn't there
  Serial.println("Input not detected \n");
}
}

```

# Answer
Try using the internal Pullup/Pulldown resistor to control the input when the pin is not connected to anything. If you do not have a pullup/pulldown, then the input capacitance on the input pin circuitry can sample and hold the 5V unreliably.

```
...
void setup() {
  // Outputting for error checking
  Serial.begin(38400);

  // Readying the pin for input
  pinMode(signal_receiving_pin, INPUT_PULLDOWN);
}
...

```

You may want to uncomment the delay() or add some state logic trigger only one activation per each cycle of `signal_receiving_pin`
> 0 votes

---
Tags: teensy
---


title: Arduino 4G LTE Shield

text:
# Question
Title: Arduino 4G LTE Shield
Is there by any chance a shield that can take an 4G LTE compatible SIM card activated by a carrier and establish a connection?

# Answer
> 1 votes
Googling "4g shield arduino" gave this. It will need a 4G LTE capable SIM, but I guess "it depends" if *any* 4G LTE SIM will work..

# Answer
> 1 votes
This is a really old post but I also found this LTE shield which is much cheaper than the cooking hacks one.

Be carefully; this module is a dual band only (900/1800 MHz); no 850 or 1900 MHz.

---
Tags: shields, gsm, networking
---


# Question
Title: Read car high temperature exhaust pressure sensor
Is it possible to read the exhaust gas pressure of a turbo car with an Arduino, and then control an electric motor based on the pressure?

# Answer
> 1 votes
Yes, I don't see why it wouldn't be possible.

You would need a sturdy barometer, preferably a digital I2C one because they are typically more accurate. I recently bought this one to measure altitude: BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready.

Be careful about the temperature that the sensor will have to deal with, its maximum temperature is 85°C (185°F).

The motor, I'm assuming, would be fairly large so you would need a beefy motor driver that uses a 5 volt logic level, maybe like this one: L298 Dual H-Bridge Motor Driver.

This is a fairly difficult project, I'd say mostly because of the difficulty you would have mounting the barometer and motor. Never the less, it still is possible.

# Answer
> 0 votes
You might want to look at https://github.com/designer2k2/multidisplay they're doing exhaust gas pressure monitoring and a number of other things.

---
Tags: sensors
---


# Question
Title: Is it possible to increase the voltage on 3.3v output to 5v on an ESP board to power a DC motor?
I am trying to use an ESP32s controller connected to an RC car DC motor. I found that when using my Arduino this is easily accomplished, and I can see that my output pin produces 5v for the motor to spin. My ESP32, however, only produces 3.3v, so of course the motor does not spin. Do I need to use a motor driver board, transistors, or will the ESP32 simply not work in this scenario?

Thanks in advance.

# Answer
> 4 votes
You should not power a motor from a micro-controller, period, regardless if that is an ATmega or an ESP32.

Instead, you need to use a motor driver circuit - this isn't really so much about *voltage* amplification, as it is about *current* amplification. The actual I/O output voltage of your ESP32 is likely very close to 3.3v. If you are measuring 1.8v, that is only because you motor is loading the pin so heavily (and improperly) that the voltage sags.

Without the specs of your motor, it's not really possible to provide any specific advice. But you should seek an FET-based solution, not one based on bipolar transistors. The old bipolar L293D, L298, etc parts are horribly lossy and extremely unsuited to low voltages motors. In some low-voltage, low-current cases, the FET-based TB6612FNG can be a good solution - **but again, this depends entirely on the unstated requirements of your motor**. Typically only very lightweight or weak "RC cars" could use such drive, for more serious ones you should look at hobby-grade Electronic Speed Controller (ESC) modules, or their equivalent circuitry.

These motor driver chips will have two supply inputs. One supplies the logic and would typically share the microcontroller's supply voltage. The other supplies the motors - it might in light duty cases be whatever is supply the microcontroller's regulator, but in more power-hungry cases would often be a unique supply. Both grounds should be connected together and connected to the microcontroller's ground, but in such a way that the ground current for the motors flows directly from the power supply, and never *through* the microcontroller board.

# Answer
> 2 votes
I figured out my issue. I was only getting 1.8v output because I was testing my lead after a led light I had plugged in. Once I removed the led, my voltage went to 3.3v, which was expected.

---
Tags: arduino-motor-shield, electronics, esp32
---


# Question
Title: Getting stable measurements with the BNO055 IMU
I bought the BNO055 "smart" IMU from Adafruit, thinking it would be a simple way to get orientation data for a small mobile robot project, but I've found the thing to be very difficult to use and nearly worthless.

It's advertised as being able to auto-calibrate, and although it does attempt to do this, I've found that the calibration doesn't hold. It continuously re-calibrates itself, and either gets stuck in an error state or find a successful calibration...but then loses it after a few seconds.

Is there anything I can do to improve its stability? Does it need to be mounted inside a special grounded housing? Is there a special incantation I should utter before powering it on?

I'm reading it from an Arduino Uno via I2C, and though the wiring and programming is relatively simple, getting it calibrated and staying calibrated I've found to be nearly impossible.

Even after the "system" flag says its fully calibrated, and I have the IMU just sitting on a table, not moving, after a minute, it loses its "system" calibration. The accelerometer, gryoscope, and magnetometer usually remain calibrated, but how can I trust them if the on-board fusion algorithm is reporting it's not ready?

If the BNO055 is a lost cause, is there anything better? I've tried several MPU-\**** chips from InvenSense, but they're even worse.

# Answer
> 2 votes
Try a permanent calibration. From the Adafruit forums:

> You'd basically need to read and write data registers 55-6A. In both cases, you have to set the sensor in CONFIG\_MODE. There's more information on page 48 of the datasheet.

The magnetometer is influenced by surrounding magnetic sources like motors. You might be able to tell the extent of the effect using the following method:

> The System Calibration Status will start out at 0 and will go to 3 when the sensor is calibrated. For example, the mag calibration status will go to 3 if you do some figure 8s. If you put a piece of metal near the sensor, the calibration status will drop to 0. But when the metal is moved away, it will go back to 3. You may be able to use this value as an indicator that calibration is lost. I have found that once it's calibrated, it seems to hold calibration well.

For getting solid readings out of the gyroscope, this might be helpful advice:

> I don't worry about scaling the gyro output on a per-sample basis. I simply sum the output into a 32 bit (or larger) integer register. I do subtract-out a null value at each sample, which I will talk about later. But essentially, if you sample your gyro at 1kHz, and sum the output into an accumulator, you will see that the value of that accum at any time will be directly proportional the angle of rotation. If your rate is set for 250 deg/sec, then a rotation of 180 deg will result in approximately 23330000 in the accumulator. I call that the GYRO\_CAL number. So, at any given time the angle, in degrees, is deg = accum / GYRO\_CAL * 180.
>
> Since the gyro output is linear, the accumulator is insensitive to whether the rotation is fast or slow (as long as the max deg/sec isn't exceeded).
>
> Here is my basic routine for each gyro reading:

`void read_FIFO(){
 sample = read_value_from_FIFO(); //read the latest z-axis sample. I use the fifo, but that isn't necessary
 accum += sample - null; //add the sample to the sum and subtract the null
 if((accum > GYRO_CAL) -= GYRO_CAL*2; //roll the accumulator at +180 deg.
 if((accum < -GYRO_CAL) += GYRO_CAL*2; // roll the accumulator at -180 deg.
 angle = accum/GYRO_CAL * 180; // convert to degrees
}`

> I calculate the null at the beginning of each run. I sum 1000 readings and take the average. The gyro has to sit still for 3 or 4 seconds for this. The GYRO\_CAL value can be calculated by summing the output while you rotate the gyro by 180 deg. Or you can sum over many turns, and divide by the number of 180 deg turns for a more accurate value.
>
> You could probably use a 64-bit FP for the accumulator, but since arduino only supports 32 bit FP, I found it absolutely necessary to use a 32 bit integer to avoid roundoff and other errors.
>
> If you follow that general outline, I promise you will get rock solid performance out of the gyro. There are a few other small optimizations that I make, which I can discuss later.

---
Tags: bno055, imu
---


# Question
Title: How to input text from Serial monitor into a character array?
I'm using a Mega 2560 and Uno and want to input text to the serial monitor which can be stored in character array char in\[\]; I want array specifically as I'll be breaking each character to trigger different code for making a morse code.

```
    #include<Arduino.h>
//#include<Softwareserial.h>

int Speaker1 = 4;
int Speaker2 = 6;
int LED = 2;
int Relay = 12;
char n = '0';
char in[];
//int outPins[] = { 2, 4, 6, 8 };

void high() {

  digitalWrite(Speaker1, HIGH);
  tone(Speaker2, 800);
  digitalWrite(LED, HIGH);
  digitalWrite(Relay, HIGH);

}

void low() {

  digitalWrite(Speaker1, LOW);
  tone(Speaker2, 800);
  digitalWrite(LED, LOW);
  digitalWrite(Relay, LOW);

}

void setup() {

  Serial.begin(9600);

  pinMode(Speaker1, OUTPUT);
  pinMode(Speaker2, OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(Relay, OUTPUT);

  Serial.print("Enter your desired text: ");
  //in = Serial.readString();  /*<-------------HELP NEEDED HERE */

  for (int i = 0; i < strlen(in); i++) {

    n = in[i];

    switch (n) {

      case 'A':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'B':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'C':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'D':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'E':
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'F':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'G':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'H':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'I':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'J':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'K':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'L':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'M':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'N':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'O':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'P':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'Q':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'R':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'S':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case 'T':
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'U':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'V':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'W':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'X':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'Y':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case 'Z':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case ' ':
        delay(700);
        break;
      case '1':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '2':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '3':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '4':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;
      case '5':
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '6':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '7':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '8':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '9':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(100);
        low();
        delay(300);
        break;
      case '10':
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(100);
        high();
        delay(300);
        low();
        delay(300);
        break;

    }

  }

}

void loop() {

}

```

# Answer
I suggested in a comment you read the blog post Reading Serial on the Arduino. In this post, Majenko shows a `readline()` function that does almost exactly what you want. This function is non-blocking, which, in the embedded world, is most of the time a mandatory feature. However, in one of your comments you wrote that you want a blocking function:

> I need the program to "wait" like \[...\] `scanf`

Degrading a non-blocking function into a blocking one is as easy as wrapping the non-blocking function in a loop. Here is a code snippet for reading a CR-terminated string, which is similar to a blocking version of Majenko's `readline()`:

```
char buffer[80];
size_t pos = 0;
for (;;) {
    int c = Serial.read();
    if (c == -1) continue;   // no input
    if (c == '\r') {         // end of line
        buffer[pos] = '\0';  // terminate the string
        break;
    }
    if (pos < sizeof buffer - 1) {
        buffer[pos++] = c;
    }
}

```

That being said, I could not resist the temptation to brutally simplify your program. The key to the simplification is to consider the Morse code as a *data structure*. Then, the code for keying a string is generic: you look up each character in the code table and key it in turn. This saves the long `switch`/`case`:

```
struct code_t {
    char c;
    const char *code;
};

static const code_t morse_code[] = {
    {'A', ".-"   }, {'B', "-..." }, {'C', "-.-." }, {'D', "-.."  },
    {'E', "."    }, {'F', "..-." }, {'G', "--."  }, {'H', "...." },
    {'I', ".."   }, {'J', ".---" }, {'K', "-.-"  }, {'L', ".-.." },
    {'M', "--"   }, {'N', "-."   }, {'O', "---"  }, {'P', ".--." },
    {'Q', "--.-" }, {'R', ".-."  }, {'S', "..."  }, {'T', "-"    },
    {'U', "..-"  }, {'V', "...-" }, {'W', ".--"  }, {'X', "-..-" },
    {'Y', "-.--" }, {'Z', "--.." },
    {'1', ".----"}, {'2', "..---"}, {'3', "...--"}, {'4', "....-"},
    {'5', "....."}, {'6', "-...."}, {'7', "--..."}, {'8', "---.."},
    {'9', "----."}, {'0', "-----"},
    {' ', " "    }, {'\0', NULL}  // sentinel
};

static inline void high() { digitalWrite(LED_BUILTIN, HIGH); }
static inline void low()  { digitalWrite(LED_BUILTIN, LOW);  }

// Key a string in Morse.
void key(const char *s)
{
    for (; *s; s++) {  // *s = current letter

        // Find this letter's code.
        const code_t *p;
        for (p = morse_code; p->c; p++) {
            if (p->c == toupper(*s)) break;  // found
        }
        if (!p->c) continue;  // not found -> ignore

        // Send this code's symbols.
        for (const char *code = p->code; *code; code++) {
            if (*code != ' ')
                high();
            switch (*code) {
                case ' ': delay(100); break;
                case '.': delay(100); break;
                case '-': delay(300); break;
            }
            low();
            delay(100);
        }
        delay(200);  // inter-letter spacing = 300 ms
    }
}

void setup()
{
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    // Read a string.
    char buffer[80];
    size_t pos = 0;
    for (;;) {
        int c = Serial.read();
        if (c == -1) continue;   // no input
        if (c == '\r') {         // end of line
            buffer[pos] = '\0';  // terminate the string
            break;
        }
        if (pos < sizeof buffer - 1) {
            buffer[pos++] = c;
        }
    }

    // Key it in Morse.
    key(buffer);
}

```

Note that this program reads CR-terminated strings from the Serial port and keys them on the builtin LED. If you want your program to work on a single string, you can call `exit()` at the end of `loop()` or, alternatively, merge `loop()` into `setup()` and provide an empty `loop()`.
> 2 votes

# Answer
I don't understand exactly why your signals are much different from 'real' morse code, e.g. A is .-

Instead of calling each high and low separately like the 'a' for example:

```
  case 'A':
    high();
    delay(100);
    low();
    delay(100);
    high();
    delay(300);
    low();
    delay(300);
    break;

```

call it like this:

```
case 'A':
  send2(false, true); /* means .-
  break;

```

Than create a function send2 which sends a . and a - Something like:

```
void send2(bool b1, bool b2)
{
   send(b1);
   send(b2);
   delay(300); /* Extra wait in between characters */
}

```

For characters needing 1, 3 or 4 characters, you can make send 1, send3 and send4 accordingly.

```
void send(bool b1)
{
   digitalWrite(Speaker1, b1 ? HIGH : LOW);
   tone(Speaker2, b1 ? 800);
   digitalWrite(LED, HIGH);
   digitalWrite(Relay, HIGH);
   delay(b1 ? 300 : 100); /* Assuming HIGH needs delay of 300 and low of 100 */
}

void low() {

  digitalWrite(Speaker1, LOW);
  tone(Speaker2, 800); /* I would expect two different values for HIGH and LOW */
  digitalWrite(LED  , b1 ? HIGH : LOW);
  digitalWrite(Relay, b1 ? HIGH : LOW);
}

```
> 0 votes

---
Tags: arduino-uno, serial, communication, array, input
---


# Question
Title: Writing data to a specific address in EEPROM
I'm trying to write two strings to an Arduino Uno's EEPROM. Here, the first code block works fine: it writes string(True/False) at 'address 0'. But the second block, which writes data at 'address 5', is not working as expected.Reading data at address 5 prints a blank line. What am I missing here? Is this the correct way to write two different strings to EEPROM?

First code block:

```
int state = LOW;
char first_eeprom_value;
if (state == LOW) {
  state = HIGH;
  char example_string[4] = "True";
  first_eeprom_value = EEPROM.read(0);
  Serial.println(first_eeprom_value);
  for (int i = 0 ; i < 5 ; i++) {
    EEPROM.update(i, example_string[i]);
  }
} else {
  state = LOW;
  char example_string[5] = "False";
  first_eeprom_value = EEPROM.read(0);
  Serial.println(first_eeprom_value);
  for (int i = 0 ; i < 5; i++) {
    EEPROM.update(i, example_string[i]);
  }
}
Time = millis();

```

Second code block:

```
char first_eeprom_value1;
if (state1 == LOW) {
  state1 = HIGH;
  char example_string1[4] = "True";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 5 ; i < 11 ; i++) {
    EEPROM.update(i, example_string1[i]);
  }
} else {
  state1 = LOW;
  char example_string1[5] = "False";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 5 ; i < 11 ; i++) {
    EEPROM.update(i, example_string1[i]);
  }
}

Time = millis();

//reading data at address 5
int addr = 5;
char value = EEPROM.read(addr);
Serial.println(value);// this prints blank line

```

# Answer
You are cycling outside the string, thus creating undefined behavior.

Try replacing the second block with this:

```
char first_eeprom_value1;
if (state1 == LOW) {
  state1 = HIGH;
  char example_string1[4] = "True";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 0; i < sizeof(example_string1); i++) {
    EEPROM.update(i + 5, example_string1[i]);
  }
} else {
  state1 = LOW;
  char example_string1[5] = "False";
  first_eeprom_value1 = EEPROM.read(5);
  Serial.println(first_eeprom_value1);
  for (int i = 0; i < sizeof(example_string1); i++) {
    EEPROM.update(i + 5, example_string1[i]);
  }
}

```

Please note that this is not optimal; I suggest you to use fixed-length strings, and fill the unused spaces with blanks or 0s, so you can read back all the bytes you wrote in a safe way
> 2 votes

---
Tags: arduino-uno, eeprom, data
---


# Question
Title: Manually added boards doesn't work in 1.8.5…?
I'm trying to manually add board definitions in a boards.txt file in hardware subfolder of my sketches folder as per instructions here for instance: https://www.arduino.cc/en/Tutorial/ArduinoISP

They however do NOT show up in my board selection.

My sketches location where hardware subfolder should be placed:

Board defs:

```
~/D/Arduino ❯❯❯ cat ~/Documents/Arduino/hardware/boards.txt
##############################################################

atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)

atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.speed=57600

atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05

atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F

atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino:arduino
atmega328bb.build.variant=arduino:standard

atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.upload.tool=arduino:avrdude

```

BUT nothing show here:

I have restarted Arduino IDE.

# Answer
> 1 votes
Newer versions of the IDE (after 1.5) have a different folder structure where there is additional subfolders for maintainer and architecture.

```
<Arduino sketch folder>/hardware/<custom name>/avr/boards.txt

```

https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification

---
Tags: arduino-ide
---


# Question
Title: Recommendations for limit switches for Arduino
I'm looking for a limit switch to use with the Arduino. In my project I want to count how many times my turntable makes a full 360° rotation. An object (wheel, pipe, whatever) will be sticking out the side of the turntable and when it comes in contact with the limit switch that will be right next to the turntable, it should notify the Arduino.

Any suggestions on which limit switch I should get?

Thanks so much in advance!

# Answer
A $2 microswitch with a roller would be OK for a million revs or so.

You would put a little ramp on the diameter and use it to trigger the switch.

Non-contact magnetic or optical could be better for more cycles or faster operation.
> 6 votes

# Answer
Instead of a limit switch a hall effect sensor with a moving magnet is an optimal soltuntion since it is contact less there will be no frictional side effects on your application.

But there is one more better way to it, try to use an rotary encoder, something like a 400/600 ppr should also be fine for this, doing this way you have more positional data of the turntable,

You can calculate no of turn, arcs etc.

For eg:

1. A 400ppr would give you a resolution of 0.9 degree per pulse, and
2. 600ppr would give you 0.6degree per pulse of accuracy.

Although you can go for even higher ppr encoders but you can get these at very low cost.

Pic from: https://m.ebay.co.uk/itm/400BM-Rotary-Encoder-Module-LPD3806-360-6mm-Shaft-Arduino-Pi-Flux-Workshop-/112607725039?\_mwBanner=1

Note: Just an example, price may be different at other webites, haven't checked the price while writing this solution.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: How can I light one led from two different sensors?
I want to light **one led** with two sensors, the first one is a **PIR** and the other one is a **Photocell** sensor.

The idea is to turn on the led if the PIR sensor detects movement, and also to turn the led on if the room gets darker(detected by the photocell).

I managed to make a code, but with TWO led's, a different one for every sensor.

```
int ledPin = 13;
int ledPin1=12;
const int ldrPin = A0;
int inputPin = 2;
int pirState = LOW;
int val = 0;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(inputPin, INPUT);
  pinMode(ldrPin, INPUT);
}

void loop() {

  int ldrStatus=analogRead(ldrPin);
   if(ldrStatus<=400)
 {
    digitalWrite(ledPin, HIGH);
    delay(500);
    Serial.println("LED ON");
 }
   else digitalWrite(ledPin, LOW);
    val = digitalRead(inputPin);
      if (val == HIGH) {
        digitalWrite(ledPin1, HIGH);
          if (pirState == LOW) {
            Serial.println("Motion detected!");
            pirState = HIGH;
         }
      } else {
          delay(5000);
          digitalWrite(ledPin1, LOW);
            if (pirState == HIGH){
             Serial.println("Motion ended!");
             pirState = LOW;
           }
     }
  }

```

# Answer
> 0 votes
```
int ledPin = 13;

int ldrPin = A0;

int PIR_Pin = 2;

void setup()

{

    Serial.begin(115200);

    pinMode(ledPin, OUTPUT);

    pinMode(PIR_Pin, INPUT);

    Serial.println("Started Monitoring!");
}

void loop()
{

    boolean lightStatus = ( analogRead(ldrPin) <= 400 ) ;
    digitalWrite(ledPin,  lightStatus);

    if(lightStatus) Serial.println("Light Triggered!");

    if(digitalRead(PIR_Pin) == LOW)
    {
         Serial.println("Motion Triggered!");
         digitalWrite(ledPin, HIGH);
         delay(5000);
         digitalWrite(ledPin, LOW);
     }
}

```

~~To keep it simple serial code is removed, if needed can be added easily that should not be a big issue.~~  Still this can be done in much more efficient way. This is just one solution.

Note: haven't complied/error checked the code as i am writing this on a phone. Hope it should work as intended, errors if any, shall be minor ones. Comment below if any issues.

Update 1: added code to send triggered status over serial comm.

Update 2: corrected "Boolean" to be as "boolean"

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


# Question
Title: Char* and string conversion from an ESP8266 web server
I have the following Arduino code for configuring a wifi connection through a simple webpage:

I declare `char* ssid;`. Later I read a value from a SPIFFS config file where `q_ssid` is declared as a string and successfully populated from the file:

```
strncpy(ssid, q_ssid.c_str(), 10);

```

In the line above, I am limiting it to exactly 10 as that is the length of my wifi AP name that this connects to. If I change the initial `char*` to `char ssid[10];`, all works well, but SSIDs can have varying names, and if I do not use 10 chars, then the trailing spaces prevent connection in the statement `WiFi.begin(ssid, password);`.

On the web client handler that reads in values from the user, I use this:

```
String q_ssid = server.arg("ssid");
strncpy(ssid, q_ssid.c_str(), 10 );

```

How can I dynamically assign the size of `char* ssid;` so that it can be used with the correct number of characters for the AP name that the user has stored from the webpage?

Any help is greatly appreciated.

Thanks.

# Answer
> 1 votes
What you need to do is creating a fixed string, this can be done in two ways:

static:

```
char ssid[100];

```

Where 100 is the maximum length ever possible. Note that this will always use up 100 bytes, even if less are used (e.g. your string length is 5. dynamic:

```
char* p_ssid = malloc(100);

```

This way a pointer is created to a dynamically created string that can hold 100 characters. Disadvantage is that using malloc in a microcontroller can cause empty memory 'holes' when freeing/mallocing a lot.

With either way you can than use a normal strncpy or strcpy (in first case use &ssid to get a pointer to the ssid). Also don't forget to add 1 to the length because of the trailing \0 to denote the string is ended. Thus for storing 10 characters, you need an 11 char sized array.

---
Tags: esp8266, c-string
---


# Question
Title: avrdude: ser_open(): can't open device "\\.\COM4": Access denied
I installed the new IDE Environment 1.6.6 and I got this error when compiling a program. I am using an Arduino Uno

```
avrdude: ser_open(): can't open device "\\.\COM4": access denied

```

I need your help.

# Answer
* I think you used "Eclipse" and "Arduino" at the same time. so, I guess that a "com4 Port" conflict has occurred and the upload could not was done.

---

* restart your computer and try to open "Arduino" first and upload. not open "Eclipse" at the same time.
> 1 votes

# Answer
I had this very same issue. I solved the problem by shutting down my outside cameras. Once cameras were off (the software) the program worked. It was the camera software that was using the port.

So if you have a lot of other software or equipment running in the background this may be your problem. Just try shutting down things one at a time. That's what I did until I found that the camera software was my problem.
> 0 votes

---
Tags: arduino-uno
---


title: MATLAB+Arduino+LCD

text:
# Question
Title: MATLAB+Arduino+LCD
I am trying to send some integers to an LCD. But it is not working. I have tried in Proteus. Please help. I have uploaded MATLAB and Arduino code below.

MATLAB code:

```
clear all
clc

 answer=1; % this is where we'll store the user's answer
 arduino=serial('COM1','BaudRate',9600); % create serial communication object on port COM4

fopen(arduino); % initiate arduino communication

while answer
fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): '); % ask user to enter value for variable answer
end

fclose(arduino); % end communication with arduino

```

Arduino code:

```
#include <LiquidCrystal.h>
int matlabData;
LiquidCrystal lcd(12,11,5,4,3,2);

void setup() {
  lcd.begin(16,2);
  Serial.begin(9600);
}

void loop() {
  if(Serial.available()>0) {
    matlabData=Serial.read();
    lcd.print(matlabData);
  }
}

```

# Answer
You can use Matlab's Arduino support package, it allows you to control the Arduino directly without having to write code in the Arduino IDE. I never used it with an LCD though. Here is a link that might help.
> 1 votes

# Answer
```
while answer
  fprintf(arduino,'%s',char(answer)); % send answer variable content to arduino
  answer=input('Enter led value 1 or 2 (1=ON, 2=OFF, 0=EXIT PROGRAM): ');
  % ask user to enter value for variable answer
end

```

Is it just me or should asking the user to input something be ***before*** printing it?

Also, more importantly, isn't `fprintf(arduino, '%s', char(answer));` printing raw bytes? In which case, you would be sending 0x01/0x02. Not a great idea... In your Arduino code, print out on Serial what you are receiving, in \[hexa\]decimal, not as `char`.

```
    matlabData=Serial.read();
    Serial.print("Received: [0x");
    if(matlabData<16)Serial.write('0');
    Serial.print(matlabData, HEX);
    Serial.println("]");

```

This should give you a better idea whether you received anything, and if so, what.
> 1 votes

---
Tags: lcd, matlab
---


title: ISR vs state change detection on button

text:
# Question
Title: ISR vs state change detection on button
Hi I was wondering if a digitalRead state change detection could be saved in a variable like counter++, just like you can do with an interrupt function.

arent these two operations almost the same?

like have an external circuit with a reed closed by a magnet, to take the place of a momentary push button,

# Answer
The 2 techniques described in the question are commonly referred to as "polling" and "interrupt". Either will work. Polling is suggested for beginner programmers and when time is not important. Such as scanning an array of human controlled buttons. Whereas interrupts are usually reserved for when time is of the essence. Such as synchronizing a camera's release switch with a strobe flash.

Also, consider polling as a simple to understand, easy to test sequence of events that will always happen in the expected order. While interrupts can happen at any time and all interruptible code has to be written to tolerate being interrupted.

Often, debouncing is the more difficult problem when combining mechanical switches and microprocessors. A good fundamental exercise is to write your own debounce program. However, an Arduino debounce library is already available.
> 1 votes

# Answer
The fundamental difference between polling (`digitalRead()`) and interrupts is that of time. Yes, I know we discussed time and interrupts at length in another of your questions, but I'm not talking about recording time here.

With an interrupt you know (pretty much) *when* an input changed. With polling you can only know that it changed *sometime in the past*. An interrupt occurs at the moment an input changes state (what that change is depends on the type of interrupt). That makes it possible for your program to remember that time (by querying `millis()` for example).

With `digitalRead()` the only way you can know if an input has changed state is if you manually remember what the old state was and compare it, so all you can know is that it's changed since last time you examined the input, and if those times are far apart all you can say is "sometime in the past X milliseconds it changed state".

If your input changes *faster* than that polling time you won't know about it. For instance, if you end up polling every 10 milliseconds, and you have a pulse on your input pin that lasts 4 milliseconds (that's an eternity in microcontroller time) but occurs part way between two polls (say from 3ms to 7ms) you'll never see it.

To put it more formally, to detect a signal of frequency *f* Hz you have to sample the input at minimum *2f* Hz (or a period of *1/(2f)* seconds. This is known as the Nyquist-Shannon theorem and applies equally to both digital and analog sampling (digital sampling is merely 1-bit analog sampling).

With interrupts, since you're not sampling based on periodic checks, but instead using a hardware trigger to detect an edge (rising, falling, or changing), and assuming you have interrupts enabled at the time an edge arrives on the pin (some code disables interrupts, and interrupts can't trigger while another interrupt routine is running), you instantly know about it regardless of whatever else you are doing.

Interrupts are said to be *asynchronous*, whilst polling is known as *synchronous*.

Which method you should choose depends on many factors: the speed of your signals (pulses from sensors, buttons pressed by humans, etc), what else your program is doing, how critical it is that you detect an input state change, etc. For slow signals, like a button, polling is perfectly fine. For high speed signals, like a hall-effect sensor or a reed switch triggered by a bicycle wheel mounted magnet, interrupts are more suitable.

For some signals (especially things like revolution counters, frequency counters, etc) where you have a large number of brief pulses coming in over a period of time where all you want to do is count them, there are even better options than interrupts.

The internal timer peripherals of the chip can run in a number of modes that are designed just for this scenario. You can run a timer with the clock source as an IO pin. That means that on each incoming pulse to that IO pin the timer counts up by one. That happens completely independently of your program. You just read the current count from the timer and reset it to 0 to start counting again at a period to suit you.

Another mode is *Input Compare* mode. This combines normal interrupts with a timer. The timer runs in the background at a pre-defined rate, and as soon as a specific input changes state (each timer has specific inputs for this) the timer is frozen an interrupt is triggered. This gives highly accurate time measurement of incoming signals since it's not subject to the time taken to service the interrupt. The timer is frozen immediately and you can query that time when the system is able to service the interrupt.

There is no native support in Arduino for either of those timer modes, though, so you would have to either find an advanced library that configures the timers in that way for you, or read and understand the datasheet and manually configure the timers in the right way.
> 0 votes

---
Tags: isr
---


# Question
Title: List of sketches disappears off the bottom of my screen
v 2:1.0.5

The list of sketches disappears off the bottom of my screen and there is no scroll to reach them. This renders the IDE nearly useless.

Is there a solution?

# Answer
That issue has been fixed since the Arduino IDE 1.5.5 release, 4 years ago.

The version of the Arduino IDE you get from `apt-get install arduino` has not been able to be updated for years due to licensing issues. The versions available from various package managers may also be modified in ways that introduce new bugs. For this reason you should always install the official Arduino IDE version downloaded from: https://www.arduino.cc/en/Main/Software
> 1 votes

---
Tags: library, sketch
---


# Question
Title: SoftwareSerial + Serial.printlen() not working properly
I want to read a SMS message , find it's length and do some "substring();" operation on received SMS. My last two(2) statements do not work . How can I get correct answers? What are correct codes ?

```
#include <SoftwareSerial.h>
#include <string.h>
#include <ctype.h>
SoftwareSerial mySerial(2,3);

String TelephoneNumberText="";

void setup()
{
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);

  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);

  mySerial.println("AT+CMGF=1\r");    //Sets the GSM Module in Text Mode
  delay(500);
}

void loop()
{

 while(mySerial.available())
  {
   char s;
   s = mySerial.read();
   TelephoneNumberText = TelephoneNumberText + s;
   }

 Serial.println(TelephoneNumberText);           // this statement works

 Serial.println(TelephoneNumberText.length());  // this statement dose not works

 Serial.println(TelephoneNumberText.substring(0,3));// this statement dose not works

} // end loop

```

# Answer
Are you sure a string like this can be used?

Better anyway to not each time let a dynamic string be created, but use a fixed string e.g.

```
char TelephoneNumberText[16];

```

Set the length of the max number, and change other string functions accordingly.
> 1 votes

---
Tags: arduino-uno, programming, softwareserial, string
---


# Question
Title: Burn bootloader to Arduino Uno using ARM-USB-OCD
I have ARM-USB-OCD created by OLIMEX. I am interested in can I use this to burn a bootloader to Arduino Uno. As I know Atmega 328P can be programmed using JTAG protocol which has also ARM-USB-ODC, so if it really can anyone give the circuit or something like this. Here is my device (ARM-USB-ODC) manual.

# Answer
*Probably, but likely not easily*

To program an AVR chip you likely want to use the AVR ISP protocol, which is not JTAG, but like JTAG is a synchronous serial protocol with a clock, a data line in each direction, and one additional control pin compared to the several mode/status pins of JTAG.

According to your link, the `ARM-USB-OCD` is based on an FT2232C USB interface chip.

`avrdude` documentation indicates that this is an interface it knows how to use, though it will likely take some study to figure out how.

The final question would be wiring - you'll need to figure out which JTAG-style signal names map to which FTDI functional pins, and how those should best be connected to AVR ISP pins in a way which avrdude can use. Additionally, you'd have to make sure that any buffering between the FTDI chip and the pins is compatible with your needs, both in terms of data direction and voltage level.

Note that you can easily use any ATmega328-based Arduino as an ISP programmer for a same-voltage target - not really production worthy, but if you just need to move your project along *today* it's a handy option.
> 1 votes

---
Tags: arduino-uno, bootloader, programmer
---


# Question
Title: Problem with PCB running an Arduino program to manage a GY-521 MPU6050 accelerometer
I'm working on a project based on MPU6050 GY-521 board connected to my PCB (running with an ATMega328P). The code was developed in Arduino.

The PCB is the second version. The first one works fine with the same accelerometer.

But with the second version I'm facing problems because it doesn't work and I can't understand the cause.

I did the following tests:

1. Run the code in an Arduino Nano board connected to the GY-521 MPU6050 board. Works fine.
2. Use other PCB to dismiss possible problem while soldering process. Doesn't work.
3. Probe with other GY-521 MPU6050 board. Doesn't work.

Finally I decided to cut some parts of the code trying to understand what part of this crash. My final test makes an LED blink while the rest part of the code ran.

```
void setup() {
  Serial.begin(115200);
  Wire.begin();
#if ARDUINO >= 157
  Wire.setClock(400000UL);
#else
  TWBR = ((F_CPU / 400000UL) - 16) / 2;
#endif

  i2cData[0] = 7; // Set the sample rate to 1000Hz - 8kHz/(7+1) = 1000Hz
  i2cData[1] = 0x00; // Disable FSYNC and set 260 Hz Acc filtering, 256 Hz Gyro filtering, 8 KHz sampling
  i2cData[2] = 0x00; // Set Gyro Full Scale Range to ±250deg/s
  i2cData[3] = 0x00; // Set Accelerometer Full Scale Range to ±2g
  while (i2cWrite(0x19, i2cData, 4, false)); // Write to all four registers at once

  //line commented in the last test
  //while (i2cWrite(0x6B, 0x01, true));

  //line commented in the last test
  //while (i2cRead(0x75, i2cData, 1));
  if (i2cData[0] != 0x68) { // Read "WHO_AM_I" register
    Serial.print(F("Error reading sensor"));
    while (1);
  }

  delay(100); // Wait for sensor to stabilize

  //line commented in the last test
  //while (i2cRead(0x3B, i2cData, 6));
  accX = (int16_t)((i2cData[0] << 8) | i2cData[1]);
  accY = (int16_t)((i2cData[2] << 8) | i2cData[3]);
  accZ = (int16_t)((i2cData[4] << 8) | i2cData[5]);

  // It is then converted from radians to degrees
#ifdef RESTRICT_PITCH // Eq. 25 and 26
  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
#else // Eq. 28 and 29
  double roll  = atan(accY / sqrt(accX * accX + accZ * accZ)) * RAD_TO_DEG;
  double pitch = atan2(-accX, accZ) * RAD_TO_DEG;
#endif

  pinMode(7, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(4, OUTPUT);

}

void loop() {
  /* Update all the values */
  //line commented in the last test
  //while (i2cRead(0x3B, i2cData, 14));
  accX = (int16_t)((i2cData[0] << 8) | i2cData[1]);
  accY = (int16_t)((i2cData[2] << 8) | i2cData[3]);
  accZ = (int16_t)((i2cData[4] << 8) | i2cData[5]);
  tempRaw = (int16_t)((i2cData[6] << 8) | i2cData[7]);
  gyroX = (int16_t)((i2cData[8] << 8) | i2cData[9]);
  gyroY = (int16_t)((i2cData[10] << 8) | i2cData[11]);
  gyroZ = (int16_t)((i2cData[12] << 8) | i2cData[13]);;

  double dt = (double)(micros() - timer) / 1000000; // Calculate delta time
  timer = micros();

  // It is then converted from radians to degrees
#ifdef RESTRICT_PITCH // Eq. 25 and 26
  double roll  = atan2(accY, accZ) * RAD_TO_DEG;
  double pitch = atan(-accX / sqrt(accY * accY + accZ * accZ)) * RAD_TO_DEG;
#else // Eq. 28 and 29
  double roll  = atan(accY / sqrt(accX * accX + accZ * accZ)) * RAD_TO_DEG;
  double pitch = atan2(-accX, accZ) * RAD_TO_DEG;
#endif

  double gyroXrate = gyroX / 131.0; // Convert to deg/s
  double gyroYrate = gyroY / 131.0; // Convert to deg/s
  double gyroZrate = gyroZ / 131.0; // Convert to deg/s

#ifdef RESTRICT_PITCH
  // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees
  if ((roll < -90 && kalAngleX > 90) || (roll > 90 && kalAngleX < -90)) {
    kalmanX.setAngle(roll);
    compAngleX = roll;
    kalAngleX = roll;
    gyroXangle = roll;
  } else
    kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter

  if (abs(kalAngleX) > 90)
    gyroYrate = -gyroYrate; // Invert rate, so it fits the restriced accelerometer reading
  kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt);
#else
  // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees
  if ((pitch < -90 && kalAngleY > 90) || (pitch > 90 && kalAngleY < -90)) {
    kalmanY.setAngle(pitch);
    compAngleY = pitch;
    kalAngleY = pitch;
    gyroYangle = pitch;
  } else
    kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt); // Calculate the angle using a Kalman filter

  if (abs(kalAngleY) > 90)
    gyroXrate = -gyroXrate; // Invert rate, so it fits the restriced accelerometer reading
  kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter
#endif

  gyroXangle += gyroXrate * dt; // Calculate gyro angle without any filter
  gyroYangle += gyroYrate * dt;
  //  gyroXangle += kalmanX.getRate() * dt; // Calculate gyro angle using the unbiased rate
  //  gyroYangle += kalmanY.getRate() * dt;

  compAngleX = 0.93 * (compAngleX + gyroXrate * dt) + 0.07 * roll; // Calculate the angle using a Complimentary filter
  compAngleY = 0.93 * (compAngleY + gyroYrate * dt) + 0.07 * pitch;

  // Reset the gyro angle when it has drifted too much
  if (gyroXangle < -180 || gyroXangle > 180)
    gyroXangle = kalAngleX;
  if (gyroYangle < -180 || gyroYangle > 180)
    gyroYangle = kalAngleY;

  // leer el valor analogo que entra
  // filtrarlo
  // determinar si se enciende el led
  sensorValue = analogRead(sensorPin);
  filBattery = myFilterBattery.getFilteredValue(sensorValue);
  if (filBattery < 750) // hacer la prueba con este nuevo valor
  {
    digitalWrite(3, HIGH);
  }
  else
  {
    digitalWrite(3, LOW);
  }
  digitalWrite(5, HIGH);
  delay(500);
  digitalWrite(5, LOW);
  delay(500);
}

```

With this code the LED blinks fine, but the commented lines are critical to MPU6050 setup and operation.

If someone can help me to understand what happen to my PCB, I'll be grateful.

Thanks in advance

# Answer
> 0 votes
You have explained that PCB v1 works, and PCB v2 does not work. Therefore, it seems likely the problem is in your PCB design and not in the code.

In your code sample which blinks an LED on PCB v2, but does not communicate with the MPU6050, it seems that you have removed the I²C function calls. Therefore *if* removing those function calls is what allows your code to run, and *if* the "working" code used on PCB v1 does not run successfully on PCB v2, then it's logical that you have somehow broken your I²C bus on PCB v2.

I suggest you start by comparing your PCB v1 and v2 designs *carefully*, focussing especially on the I²C bus and the connections to the MPU6050.

---
Tags: pcb-design
---


# Question
Title: Reading Ground/Open signal wire combonations to power specific LED's - Can it be done?
This might be a super easy question to answer. I ordered an Arduino Uno anyways for the sole purpose to understand this. Would not mind getting a jump on things before it's here.

I would like to setup the Arduino Uno to be used as a gear indicator for GM transmissions (specifically right now the GM 4l60e). Below is how it currently tells the computer/cluster what gear it's in.

This uses a range switch. Basically it's a combination of 4 wires that are grounded (low) in a specific order, the computer reads it, and displays what gear the transmission is in. There are 4 signal wires - Signal A,B,C, and P. Below is how the range switch signals it:

```
Park    - A=low,  B=open, C=open, P=low
Reverse - A=low,  B=low,  C=open, P=open
Neutral - A=open, B=low,  C=open, P=low
OverDrv - A=open, B=low,  C=low,  P=open
Drive 3 - A=low,  B=low,  C=low,  P=low
Drive 2 - A=low,  B=open, C=low,  P=open
Drive 1 - A=open, B=open, C=low,  P=low

```

I am wondering what would be the best way to go about this? The Arduino would be powered on by ignition. Display would be an LED (9-12V) output from the Arduino to each gear on a floor mount shifter. Total of 7 LEDs.

Hopefully this is easy to understand what I am trying to do. Thanks!

# Answer
First of all, Arduino is a 5V device, as such to drive the 9-12V LED you will need to use one or more transistors (depending on the LEDs type, number and connection, in series or in parallel).

Also, powering the Arduino from a 9-12V is not the best option: Arduino Uno has an onboard voltage regulator, but goes up to 9V maximum and, unless you go for the original one or a reputable manufacturer (Arduino is an open source project) I wouldn't go above 6V, because non-reputable manufacturers tend to use lower specs devices, like regulators which can get too hot when powered with high voltage: consider that the regulator will have to dissipate any excess energy into heat.

Said that, and knowing nothing more than what you said about the transmission you are describing, I assume the status `open` stands for *open collector*, meaning that it is not going to draw any current, so the following circuit is what you should use:

simulate this circuit – Schematic created using CircuitLab

The diagram assumes you are using digital pins 5 to 8 of your Arduino in `INPUT` mode and the Arduino GND is at the same voltage level as the transmission: this might be a big assumption, depending on how you power your Arduino (not from a battery pack, to be clear).

When node `A` is in `open` state, the voltage on Arduino pin `5` will be 5V, or HIGH as Arduino reports it. When node `A` is in `low` state then the voltage on Arduino pin `5` will be 0V, or LOW in Arduino lingo.

Resistors from `R1` to `R4` are there to limit current drawn when the gearbox is in state `low`.

UPDATE: I'm assuming the gearbox shares the same ground and operates at 5V,a s the Arduino does. If that's not he case and the gearbox operates at an higher voltage or does not share the same ground, the circuit will not work and you risk damaging the Arduino and/or the gearbox.

You can find a simulation of the above circuit where you can play with the different pins here.

The same occurs for the other pins, so your code will have to scan the 4 pins for their state and update your display accordingly, like:

```
#define PIN_A 5
#define PIN_B 6
#define PIN_C 7
#define PIN_P 8

void setup() {
  pinMode(PIN_A, INPUT);
  pinMode(PIN_B, INPUT);
  pinMode(PIN_C, INPUT);
  pinMode(PIN_P, INPUT);
}

#define PARK 0;
#define DRIVE_1 1;
#define DRIVE_2 2;
#define DRIVE_3 3;
#define OVER_DRIVE 4;
#define REVERSE 5;
#define NEUTRAL 99;
#define UNDEFINED 255;

unsigned int gear = UNDEFINED;
void loop() {
    bool A = digitalRead(PIN_A);
    bool B = digitalRead(PIN_B);
    bool C = digitalRead(PIN_C);
    bool P = digitalRead(PIN_P);

    if (!A && B && C && !P) {
      // Park - A=low, B=open, C=open, P=low
      gear = PARK;
    } else if (!A && !B && C && P) {
      // Reverse - A=low, B=low, C=open, P=open
      gear = REVERSE;
    } else if (A && !B && C && !P) {
      // Neutral - A=open, B=low, C=open, P=low
      gear = NEUTRAL;
    } else if (A && !B && !C && P) {
      // OverDrv - A=open, B=low, C=low, P=open
      gear = OVER_DRIVE;
    } else if (!A && !B && !C && !P) {
      // Drive 3 - A=low, B=low, C=low, P=low
      gear = DRIVE_3;
    } else if (!A && B && !C && P) {
      // Drive 2 - A=low, B=open, C=low, P=open
      gear = DRIVE_2;
    } else if (A && B && !C && !P) {
      // Drive 1 - A=open, B=open, C=low, P=low
      gear = DRIVE_1;
    } else {
      // none of the above
      gear = UNDEFINED;
    }
    // update your display here
}

```

Please note the above code is NOT the most efficient, but I believe it's easier to read and understand than a version using bitwise operations to identify the possible combinations.
> 1 votes

---
Tags: programming, input, signal-processing
---


# Question
Title: using pull-up resistors with A-star 32u4 on putput pins?
Okay probably not the first time this has been asked, but really, I search all over the internet and was not able to find this. I want to drive LEDs on the output on some of my pins. Is it required to put a pull-up resistor or current limiter resistor on these? or can I just plug the LED into the output, and the other end of the LED to +vcc? Are there example schematics someplace that will show this? thoughts? suggestions? thanks.

# Answer
> 1 votes
You always should use a resistor.

Simply the following schematic should be used.

The resistor value can be calculated as follows:

(V + Vfwd = I * R) =\> R = (V + Vfwd) / I

V is 5.0 V Vfwd is the forward voltage of the LED (this differs per type/color/brand) I is normally max. around 20 mA (but can be briefly more if the LED does not continuously lights)

Normally R is between 100 and 500 R, but can differ if you want to add multiple LEDs.

simulate this circuit – Schematic created using CircuitLab

---
Tags: arduino-mini
---


title: Weird Voltage Noise

text:
# Question
Title: Weird Voltage Noise
I'm new to this forum, so hello to everyone out there.

So I have an Uno with A0 connected to the positive end of a chain of LEDs (they light up when a motion sensor goes off, clunky, but it works), and the negative end is hooked up to the GND of the analog side of the Uno. It runs the following code:

```
void setup()
{
  Serial.begin(115200);
  pinMode(A0, INPUT);
  pinMode(A1, INPUT);
}

void loop()
{

  Serial.println(printVals(A0));
}

float printVals(uint8_t pin)
{
  int sensorValue = analogRead(pin);
  float voltage = sensorValue * (5.00 / 1023.00);
  return voltage;
}

```

And when I open the Serial Plotter, I get a weird square wave for the voltage (when there is 0V on the LEDs, I used a volt meter). Out of curiosity, I added a jumper cable from A2 to +5V (the red wire in the diagram) and added plotting for A2, and this solved the problem - except now, the read on A0 is about 0.53.

Now, I'm more of a software guy, so I figure just subtract 0.53 and move on (varies only +- 0.03V), but I want to know: What in the world did that jumper cable do?

# Answer
> 1 votes
@Ferba, my chain of LEDs is actually part of a circuit board for a driveway monitor receiver. When it detects motion, the LEDs light up and the voltage measured by analogRead increases by about a volt.

Also, as it turns out, the jumper to +5v was functioning as a pull-up wire... not a good idea. It burned out the chip in the driveway monitor by backfeeding an output. In the end, I added an "\_PULLUP" after the INPUT in setup and that solved the problem.

# Answer
> 0 votes
Why are you connecting a chain of leds to a pin setted as an input and then connected to GND? I think that is like connect the pin to nothing. in the documentation of arduino they have a note about the funcion analogRead() and a fluctuation of data. https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/ i think if you need to read an input put a button (or maybe i didnt understand you scheme)

---
Tags: arduino-uno, electronics
---