# Question
Title: Sending a character 'A' through blinking led
> How do i code to send a character 'A' to the arduino through a blinking led? i am doing a project about data transmission. i really need help&some guide. Material used are arduino uno r3,white led and a resistor.

MY OUPUT IN SERIAL MONITOR

Insert letter:

01000001 65 - Character A

00001010 10 - when i send/enter

CODE

```
 int LEDTrans = 13;
int timeWaitOn = 1000; //milisec (1 sec)
int timeWaitOff = 1000; // milisec (1 sec)
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);

 Serial.print("Insert letter:");
 Serial.println(" ");
}

void loop() {

digitalWrite(LEDTrans,HIGH); //turn the led on
delay(timeWaitOn); //delay in millisec (1 sec)
digitalWrite(LEDTrans,LOW); //turn the led off
delay(timeWaitOff); //wait a sec

   /*  check if data has been sent from the computer: */
  if (Serial.available()) {

     byteRead = Serial.read();
    // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
for ( uint8_t bitMask = 128; bitMask != 0; bitMask = bitMask >> 1 ) {

      if ( byteRead & bitMask ) {

    Serial.write('1');
  } else {
    Serial.write('0');
  }
}

Serial.write("    ");
Serial.println(byteRead);    //send back the actual ASCII code
}

}

```

# Answer
> 0 votes
Instead of printing '0' or '1' set the LED pin off or on, like this:

```
const int LEDTrans = 13;
const int timeWaitOn = 1000;  // millisec (1 sec)
const int timeWaitOff = 1000; // millisec (1 sec)

void setup() {
  // Turn the Serial Protocol ON
  Serial.begin(115200);
  Serial.println("Send letter:");
  pinMode (LEDTrans, OUTPUT);
}

void loop() {
  /*  check if data has been sent from the computer: */
  if (Serial.available()) {
    byte byteRead = Serial.read();
    // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
    for ( uint8_t bitMask = 128; bitMask != 0; bitMask >>= 1 ) {
      if ( byteRead & bitMask ) {
        digitalWrite(LEDTrans, HIGH); //turn the led on
        delay(timeWaitOn); //delay in millisec (1 sec)
        digitalWrite(LEDTrans, LOW); //turn the led off
      } else {
        delay(timeWaitOff); //wait a sec
      } // end of if
    } // end of for loop
  } // end of if something available
} // end of loop

```

---

> how do i count the flashes? is it based on the binary 01000001?

Here's the problem ... according to what your question seems to ask for, you are wanting an LED to flash for a 1 and be off for a zero. So the results (which my code provides) would look like this:

So, you get two flashes, the first one second after it starts, then there is a gap of 5 seconds, and then another flash. That would be 01000001.

However, how do you know when to start counting flashes? It might be:

That would be 00000001.

Or even:

That would be 10000010.

You can see, can't you, that you can't make any meaningful deduction at the receiving end about what the character is?

---

So what asynchronous serial (normal serial on an Arduino) does is have a **Start Bit** which signals when to start counting, like this:

Normally the serial port is high (continuous 1s) and then when a 0 arrives that means "start counting". So, you wait 1½ bits of time and then sample at the known baud rate. In your example, where you want 1 second per bit, the baud rate would be 1 (one bit per second). Thus, you sample every one second. Normally baud rates are somewhat faster than that, like 9600 or 115200 samples per second.

Also there is a **Stop Bit** which is always a 1. This guarantees that there will be at least a single 1 at the end of each byte, so that we can tell when the next start bit arrives.

---

There are *other ways of doing this*, for example a short pulse might represent a zero, and a longer pulse represent a one. In that case, any pulse at all could represent the start of a byte, and then you just measure how many short pulses, and how many long pulses, you get (for some definition of "short" and "long").

---
Tags: arduino-uno, led, signal-processing
---


title: Connecting two sensors with bluetooth

text:
# Question
Title: Connecting two sensors with bluetooth
I am new with Arduino. Im working in a school project, and I decided to create a glove with shock sensor for goalkeepers and need a ultrasonic sensor next to the ball, so i can know when the ball was kicked.

I need the data from both sensor.

Is this possible with only 1 arduino?, where the arduino is with the ultrasonic sensor and the shock sensor is connected with a bluetooth module to send it to the arduino.

Or, I have to use 2 arduinos?, one with with the glove and the other with the ultrasonic sensor and connect both with bluetooth?

If this is not the best way, can you help me with some ideas to do it? Thank you.

# Answer
> 0 votes
This to be possible with only 1 Arduino depends in your sensor. It is most likely not possibpe without another microcontroller (not nesessarily an Arduino) because of the following reason.

Most bluetooth modules on the market (linke the HC-05 vor HC-06) are bluetooth serial modules, meaning that they build a serial connection over bluetooth and provide the corresponding two pins (RX and TX). Yet most sensors don't implement an UART interface (the `Serial` interface in Arduino), but only give an analog or digital output voltage. With much work you might be able to tweak the firmware of the bluetooth chip for reading and sending a digital value, but this would be more work, than the price of a second microcontroller would justify.

So I would try to add a small microcontroller (like an ATTiny85) to the sensors side. It can measure the sensors output voltage and then send it via `Serial` to the bluetooth module. You might also want to use another Arduino here, though this might be an overkill. Maybe a really small version.

---

After some thinking I had the idea, that it might be possible to send an analog voltage from the sensor through a audio bluetooth module without using another Arduino. Though I'm not sure if this really would work and which module you need for that.

All in all I still would go for the extra microcontroller and serial interface bluetooth, because it is much easier for a beginner.

EDIT:

Above I mentioned using `Serial` on an ATTiny85, which is not directly possible, since it does not have a full UART hardware (but only a USI). Though you can use the standard `SoftwareSerial` library on it. If the rest of your code isn't to big, it should still fit in the small memory of the Tiny.

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


title: Turn on LEDS one after another

text:
# Question
Title: Turn on LEDS one after another
I am trying to turn on LEDs one after the other so that I can start at one end and slowly turn the LEDs until it reaches the middle of the strip. The code works coming from the end of the LED strip, but not when coming from the start of the strip. From the start of the strip, it just turns on all the LEDs up until the midpoint.

```
int midpoint = 30;
int R = 255;
int G = 0;
int B = 0;
for(int j = 0; j<midpoint; j++){
     //starting from the end, filling towards the middle
        for(int k = NUM_LEDS-j; k < NUM_LEDS; k++){
           leds[k] = CRGB (R, G, B);
        }
//there's some other code here in the interim
FastLED.show();
delay(20);
     //starting from the beginning, filling towards the middle
     //this is the section of code that doesn't work correctly
        for(int l = j - 1; l < midpoint; l++){
           leds[l] = CRGB (R, G, B);
           }
//more interim code
FastLED.show();
delay(20);
}

```

# Answer
> 2 votes
Okay so i figured it out. The problem is that the `for` loop is starting at 0 and counting all the way up to the midpoint. What I wanted is for it to light all the LEDs that are at `j` and below. So I changed it to iterate down instead of up. Here's the new loop:

```
for(int l = j; l < midpoint & l > -1; l--){
   leds[l] = CRGB (R, G, B);
}

```

The extra qualifier `l > -1` is to make sure that it doesn't try to go below `leds[0]`

---
Tags: led
---


title: Scan Bluetooth devices using HC-05

text:
# Question
Title: Scan Bluetooth devices using HC-05
Basically, I want to connect the HC-05 to a specific mobile Bluetooth(whose address is known) and when the connection is established I want to turn on a LED on the breadboard. I am totally clueless how to write the code. Can you please help me with it as it is a part of my project.

I know the various AT commands and have scanned the Bluetooth address with AT+INQ command.

# Answer
If you are using an Arduino board with HC-05 for AT commands over serial, you can follow the below flow :

1. Setup HC-05
2. Check for available nearby devices `AT+IRQ`
3. Check the response to check is the desired device is enlisted in the nearby devices
4. If device is enlisted, use `AT+BIND=<Bluetooth address>` to connect to the other device
5. Check the response of the `AT+STATE?` command until you receive “CONNECTED” (you can go for a while loop here)
6. Once the connection is successfully established here, you can send a confirmation now as per your requirement.

The above scenario is applicable only when you are sure with the Bluetooth address of the device you want to connect to. If the scenario is something different, comment and let us know with the actual requirement.
> 1 votes

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


# Question
Title: Error: "undefined reference to ..." when calling non-void class' functions from within class
I haven't used an Arduino for anything as complicated as this project before (single sketch projects so far), and am struggling getting my code to compile now that I'm creating my own libraries for the project.

I can see that it's the class' methods that return something that cause an issue, those that directly edit the classes variables instead don't appear to cause issues when compiling (i.e. void functions).

I can't share the actual code, but here's an altered and stripped down version that shows the same issue.

The sketch:

```
//Issues.ino

#include "CmdLib.cpp"

void setup() {
  //Setup USB
  Serial.begin(19200);
  Serial.flush();

  //Setup Bluetooth
  Serial0.begin(9600);
  Serial0.flush();
}

void loop(){
  CheckForPCMessages();       //Parses any messages from USB and Bluetooth
  //All the other things we need to do
}

void CheckForPCMessages(){
  CheckForMessages(&Serial);  //Check USB first
  CheckForMessages(&Serial0); //Then check Bluetooth
}

template <class T> void CheckForMessages(T *port){
  //Using function template so that works for USB and Hardware Serial
  if(port->available() != 0){
    String received_string = port->readStringUntil('\n');
    port->flush();
    Serial.print(received_string);
    Serial.println(" was received.");
    Command received_cmd(received_string);
    //Do stuff with the command (add it to a Q, etc, etc)
  }
}

```

The Header:

```
//CmdLib.h

#ifndef CmdLib_h
#define CmdLib_h

#include "Arduino.h"

enum CommandLabel{
  //Not a command
  NO_COMMAND = 0,

  //...
  //A whole bunch of other options that I can't share
  //...
};

enum CommandType{
  NA = 0,
  //...
  //A whole bunch of other options that I can't share
  //...
};

class Command{
  public:
    Command(String msg);
    String GetCmdStringFromMessageString(String full_string);
    CommandLabel GetLabelFromString(String labelstr);
    void SetLabelAndType(String labelstr);
    void SetLabel(CommandLabel label);
    void SetType(CommandLabel label);

  private:
    String _x = "";
    String _y = "";
    String _z = "";
    CommandLabel _label = NO_COMMAND;
    CommandType _type = NA;
};

#endif

```

The cpp file:

```
//CmdLib.cpp

#include "CmdLib.h"

Command::Command(String msg){
  String labelstr = Command::GetCmdStringFromMessageString(msg); //Separates label from msg
  Command::SetLabelAndType(labelstr); //Sets _label & _type vars
}

String GetCmdStringFromMessageString(String full_string){
  //Pulls out everything before first comma
  int first_comma = full_string.indexOf(',');
  String output;
  if(first_comma != -1){
    output = full_string.substring(0,first_comma);
  }
  else{
    output = full_string;
  }
  return output;
}

void Command::SetLabelAndType(String labelstr){
  CommandLabel label = GetLabelFromString(labelstr);  //Get label from string
  Command::SetLabel(label);                           //Set label
  Command::SetType(label);                            //Set type based on label
}

CommandLabel GetLabelFromString(String labelstr){
  //...
  //Cleverness to determine which to return...
  //...
  return NO_COMMAND;
}

void Command::SetLabel(CommandLabel label = NO_COMMAND){
  _label = label;
}

void Command::SetType(CommandLabel label){    //Set _type to appropriate type based upon label
  //...
  //Cleverness to determine which to return...
  //...
  _type = NA;
  return;
}

```

And here's the Error:

> sketch\CmdLib.cpp.o: In function \`Command::SetLabelAndType(String)':
>
> \[REDACTED\]/temp/arduino\_build\_557572/sketch/cmdlib.cpp:24: undefined reference to \`Command::GetLabelFromString(String)'
>
> sketch\CmdLib.cpp.o: In function \`Command::Command(String)':
>
> \[REDACTED\]/temp/arduino\_build\_557572/sketch/cmdlib.cpp:6: undefined reference to \`Command::GetCmdStringFromMessageString(String)'
>
> collect2.exe: error: ld returned 255 exit status
>
> exit status 255 Error compiling for board Fubarino Mini.

I've found previous answers where the same compile error occurred with class *variables* that were called to without being given an initial value, but can't find similar solutions for the error when created by a call to a *function*.

Any help would be greatly appreciated.

# Answer
> 1 votes
You forgot to put the function in the class:

```
CommandLabel GetLabelFromString(String labelstr){

```

should be:

```
CommandLabel Command::GetLabelFromString(String labelstr) {

```

Also, on a side note, if you *must* use `String` objects (ugh!) then *please* pass them as reference so as to avoid needless heap allocation and data copying:

```
CommandLabel Command::GetLabelFromString(String &labelstr) {

```

---
Tags: library, compilation-errors
---


# Question
Title: Analog Reference (AREF) pin on Arduino MKR1000 not working?
Has anyone successfully used the AREF pin on MKR1000?

I'm trying to use an EXTERNAL voltage reference (I need 1.5V instead of the default 5V) with:

```
analogReference(EXTERNAL)

```

But when I compile I receive the following error message:

> MKR\_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka \_eAnalogReference}' \[-fpermissive\]

In the documentation (for analogReference) I found the following:

> DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
> INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
> INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)
> INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)
> EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.

Thanks, Corrado

# Answer
The compiler error

```
MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]

```

Is actually really simple once you understand what it means.

```
analogReference(EXTERNAL);

```

The function `analogReference` takes an integer as a parameter, but you are passing it `EXTERNAL` which is an enumeration. Its probably an enumeration that uses integers for its values, but to the compiler there is a difference.

If you want to disable the warning then you can use the `-fpermissive` flag on the compile command line, this is not a good idea because it invalidates the "type-safeness" of the language for the whole program. Instead it is better to address them on a case by case basis and just cast EXTERNAL to an int.

```
analogReference((int)EXTERNAL);

```
> 1 votes

# Answer
In fact, the documentation suggests that for SAMD boards (MKR1000 is based on Zero) a different enumeration should be used where each value is prefixed with `AR_` so for example you should use `analogReference(AR_EXTERNAL);`.
> 1 votes

---
Tags: analogreference
---


# Question
Title: ESP8266: system_adc_read_fast() always gives 1024 as output
I need to use `system_adc_read_fast (uint16 *adc_addr, uint16 adc_num, uint8 adc_clk_div)` to get a sampling rate close to 100 ksps. I am able to achieve that using `adc_clk_div = 32`.

However, when I print out the values stored in `adc_addr`, I always get `1024`. Why is this?

I have a NodeMCU v3. I have connected an electret microphone to it. The +ve terminal is connected to 3.3 V through 10 kΩ; GND is connected to GND. The +ve terminal is connected to A0 on NodeMCU.

simulate this circuit – Schematic created using CircuitLab

It works fine when I use `system_adc_read()` (except the sampling rate is then 10 ksps which is not desirable).

Sketch:

```
// Expose Espressif SDK functionality - wrapped in ifdef so that it still
// compiles on other platforms
#ifdef ESP8266
    extern "C" {
        #include "user_interface.h"
    }
#endif

ADC_MODE(ADC_TOUT);

#define num_samples 512
uint16_t adc_addr[num_samples]; // point to the address of ADC continuously fast sampling output
uint16_t adc_num = num_samples; // sampling number of ADC continuously fast sampling, range [1, 65535]
uint8_t adc_clk_div = 32; // ADC working clock = 80M/adc_clk_div, range [8, 32], the recommended value is 8

int i = 0;
unsigned long start = 0;
unsigned long total = 0;
unsigned long tim = 0;

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

void loop() {
    // put your main code here, to run repeatedly:
    #ifdef ESP8266
        // Serial.println(system_get_sdk_version());

        wifi_set_opmode(NULL_MODE);
        system_soft_wdt_stop();
        ets_intr_lock( ); //close interrupt
        noInterrupts();

        start = micros();

        // Serial.println(system_adc_read());
        system_adc_read_fast(adc_addr, adc_num, adc_clk_div);

        unsigned int tot = micros() - start;

        interrupts();
        ets_intr_unlock(); //open interrupt
        system_soft_wdt_restart();

        tim += tot;
        total += num_samples * 1000000.0 / tot;
        i++;

        for (int j=0; j<adc_num;  j++) {
            Serial.println(adc_addr[j]);
        }

        if (i == 100) {
            // Serial.print("Sampling rate: ");
            // Serial.println(total / 100);
            // Serial.print("It lasted: ");
            // Serial.println(tim / 100);

            i = 0;
            tim = 0;
            total = 0;
        }
    #endif
}

```

# Answer
I created a test circuit using an AC transformer to produce a 50 cycles / second sine wave signal and tried a number of variations on the *system\_adc\_read\_fast* sample program in the Espressif SDK manual "**2C-ESP8266\_Non\_OS\_SDK\_API\_Reference\__EN**".

The ESP8266 ADC returned realistic values for *adc\_clk\_div* = 8 and 16, but, as you found, the values returned were always 1024 when I tried 32.

I found that the ADC unit was capable of performing ADC conversions in about 6-10 microseconds...

In a test program to collect data for a 40 millisecond period (ie two complete sine waves - I used a diode to chop off the negative halves) I called the *system\_adc\_read\_fast* function 40 times collecting 116 samples in each call (using "number of samples" = 116).

I collected all the readings in a two-dimensional array before printing any values because the Serial.print function causes long delays between calls to the ADC converter. The "gaps" in the chart represent the changes in the sine wave signal between successive calls to the ADC read function.
> 3 votes

---
Tags: esp8266, adc
---


title: Batteries and amps in parralel

text:
# Question
Title: Batteries and amps in parralel
So, i am about to buy a brushless motor a ESC and a 18650 batteries for my arduino.

The batteries "specs" is 3.7v and 20a, if i would to put 2 and more in parallel would i get 7.4v 20a or 7.4v 40a?

Thanks.

# Answer
In parallel you'd get 3.7V 40A

What I think you mean is in **series**. That way you get 7.4V 20A.
> 1 votes

# Answer
Series connection of battery adds voltage not current but parallel connection keeps the voltage same. Current may be increased with some condition. One things should be remembered 20 a current is huge it is not required by arduino. May be for some welding device it needs that current which can be controlled by high current mosfet
> 0 votes

---
Tags: voltage
---


title: Find Elapsed Time on Serial Plotter

text:
# Question
Title: Find Elapsed Time on Serial Plotter
How do I find out the elapsed time from the serial Plotter graph? I am plotting sensor values from the Arduino Nano and would like to know the time scale on the x-axis in order to calculate settling time of oscillations. I have tried the suggestions here but they do not seem to work in my case.

For example, in the graph below I would like to find out the time it took for the sensors to record their first movement at around point 190.

I am doing the following to print two values:

```
   //printData1();
   Serial.print(roll_err);
   Serial.print(" ");
   Serial.println(pitch_err);
   Serial.print(" ");

```

Baud Rate: 9600 Loop Time: 40ms

If my loop time is 40ms then I was thinking that the total time would be 180\*40ms. Is this reasoning correct?

Is there a better way to read the time elapsed in the serial plotter?

**EDIT: Trying to get a 10ms 'grid'**

As per the suggestion in the answer below I have tried running something similar to the following but the loop does not run at a constant time.

I tried to add `Serial.print(((millis()/10)%2)*50);` but as can be seen, the loop time is not constant.

# Answer
It depends on how precise you want your time-base to be. The plotter's x-axis is in sample-count, not time, so you have to emit samples at a fixed rate for it to have time-significance.

Your

```
loop(){
   yadda();
   zadda();
}

```

may or may not run at a constant rate, depending on what takes place in each iteration of the loop, as well as on your definition of "constant" (I don't believe I just said that...)

Even if none of your code is conditional, binary to ASCII conversion, clock and Serial interrupts, and other low-level code we don't see, may run slightly differently from iteration to iteration; e.g. the number of interrupts during any given iteration may well vary.

If you need to hold a tighter timebase, stalling at the bottom of the loop until millis() reaches (the previous millis() + an interval constant) will at least get you to within a millisecond of a fixed loop-rate. You could, of course, do the same thing with micros(), as long as you know for a fact that the loop can never take longer to execute than 1/frequency you need it to run at, and even then, it should take a fair slop-factor (that's a technical term! :) less than that, "just in case".

Update:

Though I wrote "stalling" at the end of the loop, a better technique is to call every job (in your case, 1 of them - for now ? ) as frequently as possible and let each job decide whether it needs to execute. So in your case:

```
loop {
  maybeSampleAndPlot();
  // maybeDoSomeOtherThing();  // not implemented yet...
}

maybeSampleAndPlot(){
  time = millis();
  if time - previousSampleTime >= MSEC_040
    save (time + MSEC_040) as nextSampleTime;
    sample the data;
    plot the data;
  endif
}

```
> 2 votes

---
Tags: serial, arduino-nano
---


# Question
Title: Arduino Micro interference between analog inputs
I'm building a MIDI controller with the Arduino Micro, hooking a bunch of knobs up to the analog inputs. Currently, I'm getting analog in 9 being influenced by analog in 10: `analogRead(9)` returns a number close to `analogRead(10)` and doesn't give the voltage that I'm reading with a multimeter.

What could be causing this interference?

# Answer
> 2 votes
I looked around for a while and eventually thought to put the multimeter probe on the top pin instead of on the soldered header, and got no voltage across it.

If you're experiencing a strange interference between two analog inputs, double-check your solder joints again, one of your inputs might be floating (not connected to high or ground).

---
Tags: analogread, arduino-micro
---


title: Avrdude verification error

text:
# Question
Title: Avrdude verification error
I use an Arduino UNO with IDE 1.8.5 and for the last few days it doesn't let me upload any code. When I try, it pops up with the following error:

```
avrdude: verification error, first mismatch at byte 0x0042
         0x65 != 0x8d
avrdude: verification error; content mismatch
avrdude: verification error; content mismatch

```

I really don't know what happened it used to work perfectly well. I even tried to upload blank code with nothing wired on and still the same error appears. I also tried with another USB cable, another PC, an older Arduino IDE but still nothing happens.
Any ideas ??

After checking so verbose output during compilation& upload it shows this:

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

```
C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\kat_t\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\kat_t\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\kat_t\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827 -warnings=none -build-cache C:\Users\kat_t\AppData\Local\Temp\arduino_cache_621253 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.1.1 -prefs=runtime.tools.avrdude.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2 -verbose C:\Users\kat_t\AppData\Local\Temp\untitled1895278478.tmp\sketch_may18b\sketch_may18b.ino
C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -hardware C:\Users\kat_t\AppData\Local\Arduino15\packages -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -tools C:\Users\kat_t\AppData\Local\Arduino15\packages -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\kat_t\Documents\Arduino\libraries -fqbn=arduino:avr:uno -vid-pid=0X2341_0X0043 -ide-version=10805 -build-path C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827 -warnings=none -build-cache C:\Users\kat_t\AppData\Local\Temp\arduino_cache_621253 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\arduinoOTA\1.1.1 -prefs=runtime.tools.avrdude.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2 -verbose C:\Users\kat_t\AppData\Local\Temp\untitled1895278478.tmp\sketch_may18b\sketch_may18b.ino
Using board 'uno' from platform in folder: C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21
Using core 'arduino' from platform in folder: C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21
Detecting libraries used...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "nul"
Generating function prototypes...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\preproc\ctags_target_for_gcc_minus_e.cpp"
"C:\Program Files (x86)\Arduino\tools-builder\ctags\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\preproc\ctags_target_for_gcc_minus_e.cpp"
Compiling sketch...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR   "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino" "-IC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\variants\standard" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp" -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp.o"
Compiling libraries...
Compiling core...
Using precompiled core
Linking everything together...
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827\sketch\sketch_may18b.ino.cpp.o" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/..\arduino_cache_621253\core\core_arduino_avr_uno_7e7efc521bfa236d1e5438b10f2a9ebf.a" "-LC:\Users\kat_t\AppData\Local\Temp\arduino_build_834827" -lm
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.eep"
"C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avr-gcc\4.9.2-atmel3.5.4-arduino2/bin/avr-objcopy" -O ihex -R .eeprom  "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.elf" "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex"
Sketch uses 444 bytes (1%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/bin/avrdude -CC:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf -v -patmega328p -carduino -PCOM4 -b115200 -D -Uflash:w:C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Users\kat_t\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex"
avrdude: writing flash (444 bytes):

Writing | ################################################## | 100% 0.06s

avrdude: 444 bytes of flash written
avrdude: verifying flash memory against C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:
avrdude: load data flash data from input file C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex:
avrdude: input file C:\Users\kat_t\AppData\Local\Temp\arduino_build_834827/sketch_may18b.ino.hex contains 444 bytes
avrdude: reading on-chip flash data:

An error occurred while uploading the sketch
Reading | ################################################## | 100% 0.06s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0002
         0x6b != 0x34
avrdude: verification error; content mismatch

avrdude done.  Thank you.

```

# Answer
I feel there is an issue with the bootloader that you are using with your Arduino, or maybe there is a fuse bit error.

Do you have a programmer with you, such as the usbtiny or the usbasp. IF you have another Arduino which works, than you can use it as a programmer as well. Read up about it here
https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

Connect the programmer to the Arduino Board, and your computer.

Go to tools, select the Arduino board.
Then tools\>programmers\>select the programmer you are using.
Then tools\>burn bootloader.

This will fix any fuse bit issues, while also uploading a fresh version of the Bootloader which works with your Arduino IDE.

I hope this helps.
> 1 votes

---
Tags: arduino-uno, bootloader, avrdude
---


# Question
Title: Atmel atmega32u4 not recognized when connected by usb after attempting to flash new bootloader
I am making a mechanical keyboard using Atmel's pro micro as the controller. I decided I would try to replace it's bootloader, as the one it ships with doesn't seem compatible with QMK's RESET keycode (which is supposed to put the controller into DFU mode).

Clearly I didn't know what I was doing, as the controller no longer seems to be recognized when I plug it in via USB - MicroUSB.

If I recall correctly, this is the command I used to attempt to flash the bootloader:

"sudo avrdude -p atmega32u4 -P /dev/ttyACM0 -c avr109 -U flash:w:Caterina-promicro16.hex"

At this time, it seems likely to me that the issue is that I over-wrote the bootloader (or some portion of it) and failed to replace it with an appropriate alternative. Is this correct? Is there any way to correct my error through a USB-MicroUSB connection at this point, or will I need to buy some sort of programmer? All the leds light up.

# Answer
You cannot load the bootloader over USB, that job needs to be done with an in-serial-programmer (ISP). You could have stopped the board working if you wrote the wrong fuses, e.g. different clock frequency.

Flashing the bootloader via ISP can be done with the Arduino IDE and there are lots of tutorials on the web. Try it, will probably work for you.
> 0 votes

---
Tags: bootloader, keyboard, atmega32u4, atmel
---


# Question
Title: how to use mouse.h library for arduino uno
I want to use mouse.h library with arduino but mouse.h library only for Leonardo not UNO . How to use mouse.h for UNO if not can we convert arduino UNO to Leonardo ?

# Answer
The only way to use Mouse.h on an Arduino is to use it on a compatible Arduino. You cannot "convert" an Uno into a Leonardo, since you would have to not only replace the MCU on the board (with one that is SMD only), you would have to replace the PCB itself as well. I.e., throw away the Uno and replace it with a Leonardo.

The Mouse.h (and Keyboard.h) requires an MCU with a built-in USB interface, such as the ATMega32U4 that the Leonardo has. The ATMega328p does *not* have such an interface (note: the "U" in the name kind of gives it away...).

However, all is not lost. The Uno *does* have a chip on it with a "U" in the name (as long as it's a *genuine* Arduino board and not a cheap Chinese clone with a CH340G chip). That chip, used to interface the ATMega328p to the PC through USB, can be reprogrammed to look like different devices, however doing so can break your ability to then program the Arduino itself.

You can read more about hacking your Arduino to be a mouse here.
> 0 votes

---
Tags: arduino-uno, mouse
---


# Question
Title: 4 consecutive bytes in buffer to unsigned long
I wonder if there's a smarter way to get these 4 consecutive bytes from a buffer, concatenated in a unsigned long.

```
// the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, extract the two words:

unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
Serial.print("Seconds since Jan 1 1900 = ");
Serial.println(secsSince1900);

```

Seems overkill to me, thinking these 4 bytes are already consecutive in the buffer.

Result should be unchanged i.e. having the value in a variable.

# Answer
> 0 votes
I ended up doing this:

```
unsigned long ntp_time = 0;
for (byte i = 0; i < 4; i++){
  ntp_time = ntp_time << 8 | (byte) packetBuffer[40 + i];
}

```

This is what I would have used on a high level language and my first attempt before asking — which failed because it lacked casting to byte.

I still have to understand why it failed, being `packetBuffer` declared as

```
const byte *packetBuffer

```

which to me seems addressing bytes already...

Thanks to Majenko for help, his solution still cast all buffer bytes to 4 bytes, I prefer mine that keeps down to bytes.

# Answer
> 3 votes
If they were in the same endian order as a long (little-endian on an Arduino, which they don't appear to be) you could just point to them:

```
uint32_t *l = (uint32_t *)&packetBuffer[40];

```

Then use `*l` to access the content as a long.

However since they look to be in a big-endian order it's not that simple. The simplest thing you can do is just re-combine them with bit-shifting:

```
uint32_t l = ((uint32_t)packetBuffer[40] << 24) | ((uint32_t)packetBuffer[41] << 16) |
             ((uint32_t)packetBuffer[42] << 8) | (uint32_t)packetBuffer[43];

```

# Answer
> 1 votes
An alternative is to use `union` and `struct`, and let the compiler do the work:

```
static inline uint32_t bswap32(uint32_t x)
{
        union {
                uint32_t x;
                struct {
                        uint8_t a;
                        uint8_t b;
                        uint8_t c;
                        uint8_t d;
                } s;
        } in, out;
        in.x = x;
        out.s.a = in.s.d;
        out.s.b = in.s.c;
        out.s.c = in.s.b;
        out.s.d = in.s.a;
        return out.x;
}

uint32_t sinceEpoch = bswap32(*(uint32_t*) &packetBuffer[40]);

```

Ref. http://lists.nongnu.org/archive/html/avr-gcc-list/2006-12/msg00076.html

A cleaner rewrite for the packet buffer would be:

```
static inline uint32_t bswap32(uint8_t* buf)
{
        union {
                uint32_t x;
                struct {
                        uint8_t a;
                        uint8_t b;
                        uint8_t c;
                        uint8_t d;
                } s;
        } in, out;
        out.s.a = buf[3];
        out.s.b = buf[2];
        out.s.c = buf[1];
        out.s.d = buf[0];
        return out.x;
}

uint32_t sinceEpoch = bswap32(&packetBuffer[40]);

```

Here is an AVR machine code version:

```
inline uint32_t bswap32(uint32_t value)
{
  asm volatile("mov __tmp_reg__, %A0"   "\n\t"
           "mov %A0, %D0"       "\n\t"
           "mov %D0, __tmp_reg__"   "\n\t"
           "mov __tmp_reg__, %B0"   "\n\t"
           "mov %B0, %C0"       "\n\t"
           "mov %C0, __tmp_reg__"   "\n\t"
           : "=r" (value)
           : "0" (value)
           );
  return (value);
}

```

Ref. Cosa/Types.h, https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Types.h#L553, and Cosa-NTP/NTP.cpp, https://github.com/mikaelpatel/Cosa-NTP/blob/master/NTP.cpp#L56

---
Tags: byte-order
---


# Question
Title: Running dual Adafruit GPS at 10Hz on a Teensy 3.2
Excuse the crudity of this question but I'm having quite the trouble trying to run the two **Adafruit Ultimate GPS v3** modules at **10Hz** on the **Teensy 3.2 board**. The modules are connected over the hardware serial ports 1 and 3. There is also an **IMU (MPU6050)** connected over the I2C interface.

> ## Aim:
>
> -To determine the difference between the course over ground and the body attitude (yaw) of a vehicle
>
> ## Issues:
>
> -By default, the GPS modules only run at 1Hz and at 9600 baud. I'm sending the required PMTK commands over their respective serial ports 1 and 3 to increase those to 10Hz and 115200 baud. I'm using hardware serial because the SoftwareSerial library was messing up the interrupts for the I2C interface and wasn't reliable at the baud rate required for 10Hz.
>
> -When using the TinyGPS++ library, it seems that the received chars for the GPS 1 and 2 modules were the same, which led me to believe that it wasn't behaving correctly, and I was getting no fixes. Since I also need to run a Kalman filter for each GPS module at 10Hz (which might not work at that speed on the Teensy), I switched to the NeoGPS library, which I'm told, requires much less system resources and is much faster.
>
> -The NeoGPS library also does not return any successful fix messages due to possibly being misconfigured (I'm using the default configuration files)
>
> Below is the code I'm using with the TinyGPS++ library (sans the IMU parts)
>
> With this, I'm only getting stars (\*), and the same number of received characters for both GPS 1 and 2, hence my assumption that it is faulty;

```
#include <TinyGPS++.h>

    static const uint32_t GPSBaud = 115200;

    // The TinyGPS++ object
    TinyGPSPlus gps;

    void setup()
    {
      // The serial connection to the GPS device
      #define GPS_1_Serial Serial1
      #define GPS_2_Serial Serial3
      GPS_1_Serial.begin(9600);
      GPS_1_Serial.write("$PMTK220,100*2F\r\n");
     //switch the GPS baud rate to 115200
      GPS_1_Serial.write("$PMTK251,115200*27\r\n");
     //change baud rate of serial port to 38400
      GPS_1_Serial.flush();
      delay(10);
      GPS_1_Serial.end();

      GPS_2_Serial.begin(9600);
      GPS_2_Serial.write("$PMTK220,100*2F\r\n");
     //switch the GPS baud rate to 115200
      GPS_2_Serial.write("$PMTK251,115200*27\r\n");
     //change baud rate of serial port to 38400
      GPS_2_Serial.flush();
      delay(10);
      GPS_2_Serial.end();

      Serial.begin(115200);

      while (!Serial);
      Serial.println(TinyGPSPlus::libraryVersion());
      Serial.println();
      Serial.println(F("   Fix  Date       Time     Date    Course Speed Card  Chars Sentences Checksum"));
      Serial.println(F("   Age                      Age     --- from GPS ----  RX    RX        Fail"));
      Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

    }

    void loop()
    {
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;
    //GPS________________________________________________________GPS_1___________________________________________________________________
      GPS_1_Serial.begin(GPSBaud);
      Serial.println("Listening to GPS_1");

      printDateTime(gps.date, gps.time);

      printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
      printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
      printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.deg()) : "*** ", 6);

      printInt(gps.charsProcessed(), true, 6);
      printInt(gps.sentencesWithFix(), true, 10);
      printInt(gps.failedChecksum(), true, 9);
      Serial.println();

      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial.println(F("No GPS data received: check wiring"));
      smartDelay(100);
      GPS_1_Serial.end();
    // ---------------------------------GPS_2----------------------------

      GPS_2_Serial.begin(GPSBaud);

      Serial.println("Listening to GPS_2");

      printDateTime1(gps.date, gps.time);

      printFloat1(gps.course.deg(), gps.course.isValid(), 7, 2);
      printFloat1(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
      printStr1(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.deg()) : "*** ", 6);

      printInt1(gps.charsProcessed(), true, 6);
      printInt1(gps.sentencesWithFix(), true, 10);
      printInt1(gps.failedChecksum(), true, 9);
      Serial.println();

      if (millis() > 5000 && gps.charsProcessed() < 10)
        Serial.println(F("No GPS data received: check wiring"));

      smartDelay1(100);
      GPS_2_Serial.end();

    }

    // This custom version of delay() ensures that the gps object
    // is being "fed".
    static void smartDelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (GPS_1_Serial.available())
          gps.encode(GPS_1_Serial.read());
      } while (millis() - start < ms);
    }

    static void smartDelay1(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (GPS_2_Serial.available())
          gps.encode(GPS_2_Serial.read());

      } while (millis() - start < ms);
    }

    static void printFloat(float val, bool valid, int len, int prec)
    {
      if (!valid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartDelay(0);
    }

    static void printFloat1(float val, bool valid, int len, int prec)
    {
      if (!valid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartDelay1(0);
    }

    static void printInt(unsigned long val, bool valid, int len)
    {
      char sz[32] = "*****************";
      if (valid)
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartDelay(0);
    }

    static void printInt1(unsigned long val, bool valid, int len)
    {
      char sz[32] = "*****************";
      if (valid)
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartDelay1(0);
    }

    static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
    {
      if (!d.isValid())
      {
        Serial.print(F("********** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
        Serial.print(sz);
      }

      if (!t.isValid())
      {
        Serial.print(F("******** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
        Serial.print(sz);
      }

      printInt(d.age(), d.isValid(), 5);
      smartDelay(0);
    }

    static void printDateTime1(TinyGPSDate &d, TinyGPSTime &t)
    {
      if (!d.isValid())
      {
        Serial.print(F("********** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
        Serial.print(sz);
      }

      if (!t.isValid())
      {
        Serial.print(F("******** "));
      }
      else
      {
        char sz[32];
        sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
        Serial.print(sz);
      }

      printInt(d.age(), d.isValid(), 5);
      smartDelay1(0);
    }

    static void printStr(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartDelay(0);
    }

    static void printStr1(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartDelay1(0);
    }

```

> This is the NeoGPS library version I've attempted, which does not output any indication that it is working successfully;

```
#include <NMEAGPS.h>

static const uint32_t GPSBaud = 115200;

// NMEAGPS object
NMEAGPS gps;

void setup()
{

  // The serial connection to the GPS device
  #define GPS_1_Serial Serial1
  #define GPS_2_Serial Serial3
  GPS_1_Serial.begin(9600);
  GPS_1_Serial.write("$PMTK220,100*2F\r\n");
 //switch the GPS baud rate to 115200
  GPS_1_Serial.write("$PMTK251,115200*27\r\n");
 //change baud rate of serial port to 38400
  GPS_1_Serial.flush();
  delay(10);
  GPS_1_Serial.end();
  GPS_1_Serial.begin(GPSBaud);

  GPS_2_Serial.begin(9600);
  GPS_2_Serial.write("$PMTK220,100*2F\r\n");
 //switch the GPS baud rate to 115200
  GPS_2_Serial.write("$PMTK251,115200*27\r\n");
 //change baud rate of serial port to 38400
  GPS_2_Serial.flush();
  delay(10);
  GPS_2_Serial.end();
  GPS_2_Serial.begin(GPSBaud);

  Serial.begin(115200);

  while (!Serial);
  Serial.println();
  //Serial.println(F("  Time     Date    Course Speed Card  Chars Sentences Checksum"));
  //Serial.println(F(""));
  Serial.println(F("----------------------------------------------------------------------------------------------------------------------------------------"));

}

void loop()
{

//GPS________________________________________________________GPS_1___________________________________________________________________

  Serial.println("Listening to GPS_1");
  while (gps.available(GPS_1_Serial)) {
    gps_fix fix_1 = gps.read();
    if (fix_1.valid.location){
      Serial.println("Successful Location");
    }
    if (fix_1.valid.time) {
      Serial.println("Successful Time");

    }
  }

  Serial.println();

// ---------------------------------GPS_2----------------------------

  Serial.println("Listening to GPS_2");
  while (gps.available(GPS_2_Serial)) {
    gps_fix fix_2 = gps.read();
    if (fix_2.valid.location){
      Serial.println("Successful Location");
    }
    if (fix_2.valid.time) {
      Serial.println("Successful Time");

    }
  }

}

```

I'm still a beginner when it comes to programming with an Arduino, and I appreciate any assistance to get on the right track.

Thank you for reading

Yours faithfully,

Cem Huray

# Answer
You just need two instances of the parser, too:

```
NMEAGPS gps_1, gps_2;

       ...

//___________________GPS_1______________________

  //Serial.println("Listening to GPS_1");  <-- don't print too much!
  while (gps_1.available(GPS_1_Serial)) {
    gps_fix fix_1 = gps_1.read();
          ...

//___________________GPS_2______________________

  //Serial.println("Listening to GPS_2");  <-- don't print too much!
  while (gps_2.available(GPS_2_Serial)) {
    gps_fix fix_2 = gps_2.read();
          ...

```

Also answered on the Arduino forum here.
> 0 votes

# Answer
What is processing\_style in NMEAGPS ? My understanding is there is a PS\_POLLING style that may not work well with two GPSes and PS\_INTERRUPT, that I'm not sure can handle Teensy well.

Have you tried to read directly from the Serial without any library ? When it's working, you can try to plug the library back (or parse the strings from GPS, which is quite easy).
> 0 votes

---
Tags: gps, teensy, tinygps
---


# Question
Title: How to program a Arduino Nano(Bricked) with a working arduino nano
I corrupted my bootloader on one arduino, luckily I had a spare lying around. Please help as there is not a single tutorial to help my exact state

# Answer
> 1 votes
I have a page about programming a bootloader using another Arduino.

Basically you grab the code from here and then make up wiring from the good device (which you put the sketch onto) to the device to be programmed, like this:

```
Arduino Nano        Target Nano

D10 (SS)            Reset
D11 (MOSI)          D11
D12 (MISO)          D12
D13 (SCK)           D13

Gnd                 Gnd
+5V                 +5V

```

---
Tags: arduino-nano, arduinoisp
---


# Question
Title: How to send IR data from Arduino to USB-TTL
I have a led receiver KY-022 and led emitter KY-005, I also have a PL2303 (USB-TTL). This is the code of the issuing LED:

```
#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     //Serial.print(0xa90,HEX);
     delay(40);
   }
}

```

The following is the connection scheme:

The output of the KY-022 I have connected to the pin RXD of the PL2303 which has a led that indicates that it receives data, however when using the HyperTerminal program to see the data I receive nothing appears.

I found similar information but they use another LED model, however I think it should work the same. What can I do?

I'm also testing with node js using the node js package, but in the console I only get non-readable characters, or something like this `Buffer 00 e0 e0 e0 e0` if I do not apply toString () to the data.

This is my code in node JS.

```
var SerialPort = require('serialport');
var io = require('socket.io').listen(3000);

var serialPort = new SerialPort("COM9", {
    baudRate: 9600,
    parser: new SerialPort.parsers.Readline("\n")
});

io.sockets.on('connection', function(socket){
    socket.on('message', function(msg){
        console.log(msg);
    });

    socket.on('disconnected', function(){
        console.log('disconnected');
    });
});

var clearData = "";
var readData = "";

serialPort.on('open',function(){
    console.log('open');
    serialPort.on('data', function(data){
        console.log(data);
        readData += data.toString();
        io.sockets.emit('message',data);
    });
});

```

# Answer
You are transmitting data by encoding it using one of probably many Sony Consumer Remote Control formats and expecting to decode it using one of many possible RS232 like formats. You will likely get something between nothing and random values.

Instead, consider sending data using only the RS232 protocols. This is what is done in this tutorial. It is recommended you replicate the tutorial before moving on to using a TTL to USB dongle and a computer. This should validate the transmitter is working. Note in the tutorial transmitter code example no IR remote control library is used. Only the common serial libraries.

A word regarding the tutorial. Consider using the second of the two examples in the tutorial. The first does not modulate the IR transmitter and will not work with commonly available IR receivers. The second does modulate the IR transmitter and discusses how to alter the modulation to accommodate different IR receivers.
> 3 votes

---
Tags: arduino-uno, rs232, node.js, infrared
---


# Question
Title: Clock generator up to 8 MHz using pin 3 arduino nano
I would like to generate square signal up to 8 MHz using internal timer of arduino, I have done successfully in pin 11, but i want to change it in pin 3, but still stuck. Here is the code

```
 pinMode(11,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2A0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2A = 1;

```

from this page here How can i change the pin to pin 3?

Thank you

# Answer
The MCU Timer Outputs are hardwired to specific pins. Arduino Nano (ATmega328p) pin 3 is the MCU pin PD3 and may be connected to Timer 2 output logic, OC2B with Output Compare Register 2B (OCR2B). Waveform Generator Mode and Timer Clock prescale are the same as above.

```
 pinMode(3,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2B0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2B = 1;

```

Cheers!
> 1 votes

---
Tags: programming, timers
---


title: Connect NodeMCU with USB camera

text:
# Question
Title: Connect NodeMCU with USB camera
I am trying to connect a USB camera to my NodeMCU v0.9.

* VCC Red +5V
* D- White Data
* D+ Green Data
* GND Black Ground

I dismantled the USB cable and connected the VCC cable to 5 V and the black ground cable to GND.

Now I have a DATA + and DATA - cable from the USB, which I connected to the D5/D6 GPIOs of the NodeMCU. I can now read the digital signal of the camera.

But I am not quite sure how to process the data cable's signal. I am not familiar with the USB data + / - cable concept.

Any ideas on how I can process the video image ?

# Answer
> 3 votes
You can't. It's as simple as that. To do it you require:

1. An MCU or MPU with a USB Host or OTG module built in.
2. Drivers for that module to enumerate the device
3. Drivers for the specific device you are connecting
4. Software to deal with the data provided by the device.

The ESP8266 has none of those.

Sounds to me like you want a Raspberry Pi.

---
Tags: esp8266, nodemcu, usb, camera
---


title: String to equation problem

text:
# Question
Title: String to equation problem
My project is to create a decimal adder via voice recognition. Its like a calculator that only does addition. I am using hc-06 bluetooth module to convert my voice to a string. Let's say for example, I say "21+22" then the lcd would print "21 + 22 = 43". I have no problem in displaying my voice message on the lcd. My problem is that the string can't evaluate the equation. I used toInt() but it only recognizes the first integer. Is there a code to recognize the string and convert numerical values to int separated by + then evaluate it by adding the 2 intergers?

# Answer
There is no one single function for performing a calculation from a string like you are after in C.

Instead you will have to parse and split your string up into chunks and convert the two numbers into integers (maybe confirming that there is a + between them) and perform the calculation on those two individual integers.
> 2 votes

# Answer
The standard IO library (sscanf) can help you with that:

```
String s = "21+22";
int x;
int y;
int items = sscanf(s.c_str(), "%d+%d", &x, &y);
if (items != 2) /* error handling */
int z = x + y;

```

Cheers!
> 2 votes

---
Tags: bluetooth, lcd, hc-06
---


# Question
Title: Connecting to a WNR2000v4 Netgear Router via Serial Connection with an Arduino Uno and a sketch?
I was reading in the OpenWRT wiki that you can indeed connect to the serial TTY console of an Open WRT roouter using the serial console if you're careful aabout the voltages. https://wiki.openwrt.org/doc/hardware/port.serial.cables#method\_b\_no\_physical\_changes\_to\_arduino\_board

However, I don't know anything about the voltages of my particular model of OpenWRT router a Netgear WNR2000v4. I know that it is accessible via 3 holes on the board but I know nothing of the voltages. Does anyone know or have experince with this about what voltages / wires to use to access it via the serial console?

# Answer
> 2 votes
> The WNR2000v4 serial port is at JP1: 115200 8N1 at 3.3V. Pads are, from left to right with the ethernet ports on right: \[GND\] \[Rx\] \[Tx\] \[Vcc\]

Source: https://wiki.openwrt.org/toh/netgear/wnr2000, PCB picture: https://wiki.openwrt.org/\_detail/media/netgear/wnr2000/wnr2000v1\_pcb\_detail\_small.jpg?id=toh%3Anetgear%3Awnr2000

---
Tags: arduino-uno
---


# Question
Title: C# Arduino: How to detect if the needed software is present on the computer
I have a digispark that uses trinket keyboard library to send media keys back to the computer using a rotary encoder. I currently have it configured to send normal media keys but about 2 weeks ago i started needing to change binds on what the rotary encoder does so i needed a driver of some sort. i asked and i got answers that i can't use serial ports but i can use unused keys like f13+ keys so i use the f keys now to communicate to c# software (it listens on these f keys and as soon as they are pressed depending on the configuration it does what it needs to do).
I don't think that code is needed for this demonstration but if u need it i'll be happy to edit this.

So i made the software and now comes a problem of what happens when u plug in the device that doesn't have the driver. its useless, so i need a way for the digispark to find out if there is a software that can "reprogram" what the rotary encoder does and if there isn't use the default functions(the media keys).

**Questions:**

1. How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in
2. Is there any way to add my program made in c# to the digispark, i got a usb headset and when i first plugged it in it installed its driver, so when i plug in my digispark can it load the program

**Solutions that i think may work but i have no idea how to do them:**

1. using one of these unused keys as Boolean, when its held down lets say by the c# software can the digispark using the trinket or any other compatible Tiny85 library determine if that key is pressed down or not (this may interfere with other software so i don't think its perfect solution)
2. If anyone here knows any library or custom firmware that allows the digispark(Tiny85) to communicate on serial ports that'd be pretty useful and would solve the whole question.

For the second problem: do i need any other hardware to do this as i only have a Tiny85 digispark and a rotary encoder with a breakout board

If you have a solution please provide me code or links where i may learn how to do this because as of now i have no idea how to do this, i know my way around c# but i'm a noob in arduino programming. I already asked this on stack overflow a week ago but didn't get any comments or answers. I'm sorry if this counts as a duplicate i'll remove the one on stack overflow if needed. thank you for understanding

# Answer
> 1 votes
> How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in

I can't think of any way to do that. That's like asking if a keyboard you plug into a USB port can tell if you have Photoshop installed or not.

---

> Is there any way to add my program made in c# to the digispark ...

No. The Digispark is a tiny computer based on the Attiny85 which has 8k of program memory, some of which is dedicated to a bootloader which lets you upload new code.

---

Your project is far too ambitious for the level of hardware you are proposing to use. In fact this video which I watched the other day comes to mind:

https://www.youtube.com/watch?v=s7AXskSxxMk

---

From a comment:

> the **it** refers to the digispark, when connected the digispark checks if the f17 key is pressed down and if it is that means my program is running in the background so use the functions that are compatible with the program

OK, so you want the host computer (not the Digispark) to pretend it is holding down F17, and then when the Digispark is plugged in it checks if F17 is down, and if so it knows that the desired program is running on the PC. Is that your idea?

The problem here is that the Digispark is a USB device (not a USB host). I suppose it would be possible to write a special device driver on the PC that, once the Digispark connects, would send some special code to say whether or not the program is running. However with the Digispark only having 8 KB of program memory, this extra code (on the Digispark) might be hard to fit in. Plus you would need to write your USB device driver. Plus the device driver would need to be able to query what programs are running.

I think a far simpler solution would be to have an On/Off button on the Digispark. If you plug it into a PC which has this special program running you press the button, then the Digispark sends the alternative commands to your C# program.

---
Tags: digispark, c#
---


# Question
Title: Arduino Uno with ESP8266 Wifi transceiver or ESP8266 NodeMCU board?
I already have an Arduino Uno, and I want to learn Internet-of-Things. I'm planning to use an ESP8266 since it's cheap. Should I purchase an ESP8266 Wifi transceiver module to use with my Arduino Uno or just buy an ESP8266 NodeMCU board?

Is there any advantage using an ESP8266 NodeMCU board to using my Arduino Uno with an ESP8266 Serial transceiver module?

# Answer
> 7 votes
In my opinion, it is more desirable to program the ESP8266 directly. I'm always shivering when I see a Uno (ab)using the ESP8266 as a WiFi bridge when the ESP8266 already has everything needed for the project. Of course, this is highly project specific.

Advantages of programming an ESP8266 directly:

* you learn about a new MCU and architecture (XTensa vs AVR)
* you learn to use a new Arduino Core (Arduino-ESP8266)
* ESP8266 is way more powerful than the Arduino Uno
    + 80MHz (overclockable to 160MHz) vs 16 MHz
    + ~40kB free RAM at startup vs 2 kB
    + 4 MB Flash vs 32kB
    + can use an RTOS like FreeRTOS
    + Flash can be used as filesystem (e.g. for a HTTP(S) server)
    + ==\> we can build way more complex projects
* WiFi radio and stack directly on the processor, no need to get information via a serial bridge
    + higher speed, more direct control over sockets etc.
* you can try out other frameworks and languages, such as
* easier to move to its big brother, the ESP32 (Dual-Core XTensa LX6 @ 240MHz, WiFi + BT, 4MB Flash, 520kB RAM (+4MB PSRAM optional), tons of peripherals and accelerators) for even more complex projects

Disadvantages:

* only 1 ADC input (vs. 6) with a voltage range of 0 to 1.0V (unlike the normal 5V range on the Uno)
    + remedy: external ADCs via I2C / SPI (e.g. MCP3008)
* 3.3V device, must be careful when connecting to existing 5V devices or shields
* less number of available digital GPIO pins (9 vs 13)

In summary, I think a good way of acquiring a better skillset is to try to explore and program a new board directly vs programming the old board and slapping the new one on top over serial. I hope this gave a rough overview of why an ESP8266 might be better (or worse) for a certain project.

---
Tags: arduino-uno, esp8266, iot
---


title: Decreasing a functions programming size

text:
# Question
Title: Decreasing a functions programming size
I have Arduino Code that utilizes the I2CDev library to control an MPU-6050. I am pretty new to coding and copied and pasted most of the code from examples I have found around. I am starting to run out of programming space on my Arduino, and I have found that one line of the code takes up 21%, or 6000 bytes of the programming memory. I found the function that the line related to and I have it shown below.

The link to the I2CDev libarary can be found on Github here as well: https://github.com/jrowberg/i2cdevlib

Is there a way to decrease it? Ot can someone explain to me why it is taking up so much space? Thanks!

```
uint8_t MPU6050::dmpInitialize() {
// reset device
DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
reset();
delay(30); // wait after reset

// enable sleep mode and wake cycle
/*Serial.println(F("Enabling sleep mode..."));
setSleepEnabled(true);
Serial.println(F("Enabling wake cycle..."));
setWakeCycleEnabled(true);*/

// disable sleep mode
DEBUG_PRINTLN(F("Disabling sleep mode..."));
setSleepEnabled(false);

// get MPU hardware revision
DEBUG_PRINTLN(F("Selecting user bank 16..."));
setMemoryBank(0x10, true, true);
DEBUG_PRINTLN(F("Selecting memory byte 6..."));
setMemoryStartAddress(0x06);
DEBUG_PRINTLN(F("Checking hardware revision..."));
DEBUG_PRINT(F("Revision @ user[16][6] = "));
DEBUG_PRINTLNF(readMemoryByte(), HEX);
DEBUG_PRINTLN(F("Resetting memory bank selection to 0..."));
setMemoryBank(0, false, false);

// check OTP bank valid
DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
DEBUG_PRINT(F("OTP bank is "));
DEBUG_PRINTLN(getOTPBankValid() ? F("valid!") : F("invalid!"));

// get X/Y/Z gyro offsets
DEBUG_PRINTLN(F("Reading gyro offset TC values..."));
int8_t xgOffsetTC = getXGyroOffsetTC();
int8_t ygOffsetTC = getYGyroOffsetTC();
int8_t zgOffsetTC = getZGyroOffsetTC();
DEBUG_PRINT(F("X gyro offset = "));
DEBUG_PRINTLN(xgOffsetTC);
DEBUG_PRINT(F("Y gyro offset = "));
DEBUG_PRINTLN(ygOffsetTC);
DEBUG_PRINT(F("Z gyro offset = "));
DEBUG_PRINTLN(zgOffsetTC);

// setup weird slave stuff (?)
DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
setSlaveAddress(0, 0x7F);
DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
setI2CMasterModeEnabled(false);
DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
setSlaveAddress(0, 0x68);
DEBUG_PRINTLN(F("Resetting I2C Master control..."));
resetI2CMaster();
delay(20);

// load DMP code into memory banks
DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
DEBUG_PRINTLN(F(" bytes)"));
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
    DEBUG_PRINTLN(F("Success! DMP code written and verified."));

    // write DMP configuration
    DEBUG_PRINT(F("Writing DMP configuration to MPU memory banks ("));
    DEBUG_PRINT(MPU6050_DMP_CONFIG_SIZE);
    DEBUG_PRINTLN(F(" bytes in config def)"));
    if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
        DEBUG_PRINTLN(F("Success! DMP configuration written and verified."));

        DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
        setClockSource(MPU6050_CLOCK_PLL_ZGYRO);

        DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
        setIntEnabled(0x12);

        DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
        setRate(4); // 1khz / (1 + 4) = 200 Hz

        DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
        setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);

        DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
        setDLPFMode(MPU6050_DLPF_BW_42);

        DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
        setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

        DEBUG_PRINTLN(F("Setting DMP programm start address"));
        //write start address MSB into register
        setDMPConfig1(0x03);
        //write start address LSB into register
        setDMPConfig2(0x00);

        DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
        setOTPBankValid(false);

        DEBUG_PRINTLN(F("Setting X/Y/Z gyro offset TCs to previous values..."));
        setXGyroOffsetTC(xgOffsetTC);
        setYGyroOffsetTC(ygOffsetTC);
        setZGyroOffsetTC(zgOffsetTC);

        DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero..."));
        //setXGyroOffset(0);
        //setYGyroOffset(0);
        //setZGyroOffset(0);

        DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)..."));
        uint8_t dmpUpdate[16], j;
        uint16_t pos = 0;
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Resetting FIFO..."));
        resetFIFO();

        DEBUG_PRINTLN(F("Reading FIFO count..."));
        uint16_t fifoCount = getFIFOCount();
        uint8_t fifoBuffer[128];

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
        setMotionDetectionThreshold(2);

        DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
        setZeroMotionDetectionThreshold(156);

        DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
        setMotionDetectionDuration(80);

        DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
        setZeroMotionDetectionDuration(0);

        DEBUG_PRINTLN(F("Resetting FIFO..."));
        resetFIFO();

        DEBUG_PRINTLN(F("Enabling FIFO..."));
        setFIFOEnabled(true);

        DEBUG_PRINTLN(F("Enabling DMP..."));
        setDMPEnabled(true);

        DEBUG_PRINTLN(F("Resetting DMP..."));
        resetDMP();

        DEBUG_PRINTLN(F("Writing final memory update 3/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 4/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 5/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
        while ((fifoCount = getFIFOCount()) < 3);

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);
        DEBUG_PRINTLN(F("Reading FIFO data..."));
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Reading interrupt status..."));

        DEBUG_PRINT(F("Current interrupt status="));
        DEBUG_PRINTLNF(getIntStatus(), HEX);

        DEBUG_PRINTLN(F("Reading final memory update 6/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
        while ((fifoCount = getFIFOCount()) < 3);

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);

        DEBUG_PRINTLN(F("Reading FIFO data..."));
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Reading interrupt status..."));

        DEBUG_PRINT(F("Current interrupt status="));
        DEBUG_PRINTLNF(getIntStatus(), HEX);

        DEBUG_PRINTLN(F("Writing final memory update 7/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("DMP is good to go! Finally."));

        DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
        setDMPEnabled(false);

        DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
        dmpPacketSize = 42;
        /*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) {
            return 3; // TODO: proper error code for no memory
        }*/

        DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
        resetFIFO();
        getIntStatus();
    } else {
        DEBUG_PRINTLN(F("ERROR! DMP configuration verification failed."));
        return 2; // configuration block loading failed
    }
} else {
    DEBUG_PRINTLN(F("ERROR! DMP code verification failed."));
    return 1; // main binary block loading failed
}
return 0; // success

```

}

# Answer
One line of code doesn't use 6000 bytes of memory. However if it calls a function, which otherwise would not be called, then the compiler has to include the function.

So, for example, if you have a function that takes 6000 bytes, but don't call it, then the compiler can omit the function itself.

---

Assuming DEBUG\_PRINTLN does something, then I count 2480 bytes of string literals there. Therefore your function would at the very least take up 2480 bytes. And that is called 71 times, so if DEBUG\_PRINTLN takes (say) 10 bytes to call each time, that is another 710 bytes. We are already up to 3190 bytes. Other stuff (unrelated to debugging) also probably takes quite a few bytes.

---

> I am starting to run out of programming space on my Arduino

That's not a problem until you **actually** run out of space. Who cares if you use 99% of available memory?

---

The fact that something causes a jump in memory usage is not, in itself, cause for worry. For example this sketch:

```
void setup() {
  Serial.begin(115200);
  int a;
  Serial.println (a);
}

void loop() {  }

```

Compiled for a Uno using IDE 1.6.9 I get:

```
Sketch uses 2,122 bytes (6%) of program storage space. Maximum is 32,256 bytes.

```

So, 2,122 bytes. Now change `a` to be float:

```
void setup() {
  Serial.begin(115200);
  float a;
  Serial.println (a);
}

void loop() {  }

```

Now it uses 3,668 bytes:

```
Sketch uses 3,668 bytes (11%) of program storage space. Maximum is 32,256 bytes. That's another 1,546 bytes just by changing one variable's type.

```

However it doesn't take **another** 1,546 bytes if you add a second such variable.

```
void setup() {
  Serial.begin(115200);
  float a;
  float b;
  Serial.println (a);
  Serial.println (b);
}

void loop() {  }

```

That only uses another 18 bytes:

```
Sketch uses 3,686 bytes (11%) of program storage space. Maximum is 32,256 bytes.

```

In other words, the floating-point library has now been included by the compiler. This is a once-off jump in usage. Of course, if I now do something with I2C there will be another jump as that additional library is loaded.
> 0 votes

---
Tags: i2c, mpu6050
---


# Question
Title: Read one value from continuous data stream at a lower frequency
I am working on a university final project and have run into a problem with programming Arduino, after a 3 year hiatus. I have a pressure transducer that is sending pressure data at 10Hz. I have successfully programmed my Arduino Pro Micro to read the data as it is coming in. I'm using the SoftwareSerial library to set digital pins 8 and 9 to RX and TX, respectively. As the pressure transducer is continuously streaming data values, I read each character, store them in an array, and print them to the Serial Monitor. I'm using a start and end-marker to recognize each incoming character and put them into the array. The raw data output from the transducer is in the form:

```
*000114.2927
*000114.2926
*000114.2927

```

And this is the code I am using.

```
#include <SoftwareSerial.h>
#define paroRX 8
#define paroTX 9

SoftwareSerial paroSerial(paroRX, paroTX);

const byte numChars = 16;
char paroChars[numChars];     //array to store received data
char paroToSend[numChars];      //array to transmit
boolean newParoData = false;

void setup(){
  Serial.begin(9600);     //with transmitter radio
  paroSerial.begin(9600);
}

void loop(){
  paroSerial.listen();
  readParo();      //read from Paro and store values in paroChars
  if(newParoData == true){
    for(int i=0; i<16; i++){
      paroToSend[i] = paroChars[i];
    }
    Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
    newParoData = false;
  }
}

void readParo(){
  static boolean receiveInProgress = false;
  static byte index = 0;
  char startMarker = '*';
  char endMarker = '\n';
  char pd;
  while(paroSerial.available() && newParoData == false){
    pd = paroSerial.read();
    if(receiveInProgress == true){
      if(pd != endMarker){
        paroChars[index] = pd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        paroChars[index] = '\0';      //terminate string
        receiveInProgress = false;
        index = 0;
        newParoData = true;
      }
    }else if(pd == startMarker){
      receiveInProgress = true;
    }
  }
}

```

And this is the output that I get, which is correct. I don't really want that * in front anyways.

```
000114.2927
000114.2928
000114.2927
000114.2929

```

But all of this happens at 10Hz, which means I get a constant stream of readings on the Serial Monitor. I want to slow this down to 1Hz, or just one reading per second. The obvious solution that occurred to me was to put a delay in the loop. So I tried to implement this with delay(1000) and using the millis() function as well, but I get strange readings like:

```
000114.2927
***000114
**2928
***.000114
000114.2928

```

How can I read at 1Hz from the 10Hz data stream? I want to just store one data value from the stream per second in the form of 000114.2927, then ignore the rest while the Arduino does something else.

Thanks!

# Answer
> 2 votes
You're thinking backwards. You don't want to *read* slower (which is what delay does), you want to *only send every 10th entry*.

That is, count the lines as they come in. When you hit 10 you print one and reset your count.

In other words:

```
static int count = 0;

if(newParoData == true){

  count ++;
  if (count == 10) {
      count = 0;

      // (Why copy the line just to send the copy...?)
      for(int i=0; i<16; i++){
        paroToSend[i] = paroChars[i];
      }
      Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
  }
  newParoData = false;
}

```

# Answer
> 1 votes
I would use Stream class timed functions. Serial is implementation of Stream. The property `timeout` (`setTimeout`) sets how long will the blocking functions wait for the next byte/character. Default timeuot is 1000 ms.

Timed functions of Stream are `find`, `parseInt`, `parseFloat`, `readBytes`, `readBytesUntil`, `readString` and `readStringUntil`. (Non blocking read functions are `available`, `read` and `peek`.)

# Answer
> 0 votes
Majenko’s answer is spot on: you just have to count the sentences you read and repeat one every ten sentences. And you don't need two copies of the sentence you are reading: one is enough. But I would add that you don't even need a single copy: you can just echo back the characters you read, without ever storing them, until you hit a `'*'`:

```
void loop()
{
    static uint8_t sentence_count;
    if (paroSerial.available()) {
        char c = paroSerial.read();
        if (c == '*') {
            // Increment the sentence count modulo 10.
            if (++sentence_count == 10)
                sentence_count = 0;
        } else if (sentence_count == 0) {
            // This is one sentence we have to repeat.
            Serial.write(c);
        }
    }
}

```

As a side note, if your program doesn't read input from the computer, and if it doesn't send anything to the transducer, then you may consider getting rid of `SoftwareSerial` and using only the hardware serial port:

* the receiver part of the port for reading the data from the transducer
* the emitter part to send the data to the computer.

Yes, it is perfectly fine to use the receiver and the transmitter for different links. The only caveat is that you will have to use the same port configuration on both sides: if the transducer talks at 9600 bps, then the whole port will have to run at 9600 bps.

---
Tags: softwareserial, arduino-pro-micro, serial-data
---


title: Reading several rotary encoders

text:
# Question
Title: Reading several rotary encoders
Have an upcoming project where user input will be based on spinning a large cog and I have several UNOs available

Since rotary encoders need two pins, only a Mega would be able to handle the 7-8 encoders needed. Unless theres a better method of reading them?

Is it worth using an ATTiny85 per encoder and passing all this data to a mega via 1 pin each? This way, I could extend the project beyond 7-8 later?

Or is this idea out the window, because there's a much simpler way?

# Answer
> 18 votes
Library and schematics are at https://github.com/maxgerhardt/rotary-encoder-over-mcp23017.

To read a rotary encoder (i.e., detect state changes of the knob), there are two possible implementations:

* poll the state of the two output pins and check for changes
* set up an interrupt which will be called when an output pin changes, then check for changes

Using interrupts is more efficient than always polling the pins, because an action is only executed when an actual change occurs.

Per rotary encoder you would need two pins on your microcontroller. However, we can use GPIO expanders over e.g. I2C or SPI, such as

Using a port expander over I2C has the advantage being a bus that only uses 2 pins. This means that there can be multiple (up to 127) devices on the I2C bus, and each I2C device can then e.g. provide 16 GPIO pins.

Using an ATTiny85 per encoder and possibly joining them via an I2C bus is also possible, however more expensive and more work.

I've chosen a MCP23017 here because it is interrupt-capable, has 16-bit and I had it lying around. A PCF8574 would have also worked just fine, since it has the same capabilites.

Tests were made using an MCP23017 and a KY-040.

The written library uses a modified Adafruit MCP23017 library and the Rotary library. The Rotary library also handles debouncing by using a state-machine based approach for decoding. The library is a simple header file which defines a `RotaryEncOverMCP` C++ object, with which a rotary encoder connected to an MCP23017 device can be easily described and managed. It has an example for the polling method and the interrupt method.

For 1 encoder, one can write down schematic like: (interrupt based)

Since one MCP23017 has 16 ports, we can connect up to 8 rotary encoders to one such device.

However the MCP23017 also has three address pins with which its I2C address can be selected. This means we can have 2^3 = 8 such device on the same I2C bus (i.e., connected to the same SDA and SCL lines).

Thus, with one I2C bus, which uses 2 pins, we can have a maximum of 8xMCP23017 and 64 rotary encoders (assuming no interrupts are used, which would need 1 pin for any number of rotary encoders). At the cost of 2 more pins on the microcontroller, we can create another software bit-banged I2C bus, each of which adds again a maximum of 64 rotary encoders.

Assuming D2 to D13 and A0 to A5 are free, on these 18 pins we can have 9 I2C buses with a total of 72 MCP23017 devices hosting a grand total of 576 rotary encoders. Whatever one might need that for.

I've tested this library with one rotary encoder and a MCP23017, but the code is structured in a way that adding more encoders is just adding an entry in an array.

---
Tags: arduino-uno, arduino-mega, rotary-encoder
---


# Question
Title: How to pass a static const (progmem) array to a function
I'm implementing a voice synthesizer chip. To build a phrase, I create a list of phonemes like this:

```
static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

```

And to play them I do this:

```
 for (size_t i=0; i<sizeof(heybuddy); i++){
    say(pgm_read_byte(heybuddy+i));
 }

```

So what I'd like to do is create a function where I can just pass the array to a function that can take care of the loop and do some other maintenance stuff.

```
//what I've tried:
void sayPhrase(const uint8_t *phrase){
  int open = 0;
  for (size_t i=0; i<sizeof(*phrase); i++){

      if(pgm_read_byte(*phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(*phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(*phrase+i));
    }
}

```

But when it comes to passing a static const I'm lost I've tried passing it as a reference with `*` but nothing I do seems to work - I just don't know the proper way to do this in C.

What I have compiles, but it seems to only get one phoneme and repeat it over and over. The rest are lost.

# Answer
The problem is, when you call `sizeof(*phrase)`, what is returned is 1, the size of the `uint8_t` array element, the result of your pointer de-reference. On the other hand, if you call `sizeof(phrase)` inside the function, you get the size of the pointer itself and not the size of the array, as you might expect. When you pass the array to the function via a pointer, the function has no idea if you passed the start of an array to it or merely a pointer to some `uint8_t` variable, so it can't know what the size is; context has been lost.

Instead, you should call `sizeof(phrase)` in the same scope where the array was declared and initialized and pass the result to the function, which can then use this value in the `for` loop.

```
static const uint8_t PROGMEM heybuddy[] = {
  pPA5, pHH1, pEY, pPA5,
  pBB2, pAX, pDD2, pIY, pPA5,pPA5,pPA5,
};

size_t SIZE = sizeof(heybuddy);  // this is ok since each element = 1 byte

sayPhrase(phrase, SIZE);

```

The function definition should be:

```
void sayPhrase(const uint8_t *phrase, size_t size){
  int open = 0;
  for (size_t i=0; i < size; i++){

      if(pgm_read_byte(phrase) != 4 && open == 0){
          Serial.println("mouth open");
          open = 1;
      } else if(pgm_read_byte(phrase) == 4 && open == 1){
         Serial.println("mouth closed");
         open = 0;
      }
      say(pgm_read_byte(phrase+i));
    }
}

```
> 1 votes

# Answer
I have some extensive examples of accessing PROGMEM here.

I've adapted one of the examples to show how you might do something similar to what you want:

```
const int NUMBER_OF_ELEMENTS = 10;

const char Message0000 [] PROGMEM = "Twas bryllyg, and ye slythy toves";
const char Message0001 [] PROGMEM = "Did gyre and gymble";
const char Message0002 [] PROGMEM = "in ye wabe:";
const char Message0003 [] PROGMEM = "All mimsy were ye borogoves; And ye mome raths outgrabe.";
const char Message0004 [] PROGMEM = "\"Beware the Jabberwock, my son! \n The jaws that bite, the claws that catch!";
const char Message0005 [] PROGMEM = "Beware the Jubjub bird, and shun\n The frumious Bandersnatch!\"";
const char Message0006 [] PROGMEM = "He took his ";
const char Message0007 [] PROGMEM = "vorpal sword in hand:";
const char Message0008 [] PROGMEM = "Long time the manxome foe he sought - ";
const char Message0009 [] PROGMEM = "So rested he by the Tumtum tree, \n And stood awhile in thought.";

const char * const messages[NUMBER_OF_ELEMENTS] PROGMEM =
   {
   Message0000,
   Message0001,
   Message0002,
   Message0003,
   Message0004,
   Message0005,
   Message0006,
   Message0007,
   Message0008,
   Message0009,
   };

void sayPhrase (const char * const * message)
  {
  const char * ptr = reinterpret_cast<const char *>(pgm_read_ptr (message));  // pointer to message
  Serial.println(reinterpret_cast<const __FlashStringHelper *>(ptr));    // and print it
  } // end of sayPhrase

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

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    sayPhrase (&messages [i]);

  }  // end of setup

void loop () { }

```
> 1 votes

# Answer
If you're not averse to a bit of C++:

```
void sayPhrase(const uint8_t * phrase, size_t size)
{
    bool open = false;
    for (size_t i = 0; i < size; ++i)
    {
        if(pgm_read_byte(phrase) != 4 && !open)
        {
            Serial.println("mouth open");
            open = true;
        }
        else if(pgm_read_byte(phrase) == 4 && open)
        {
            Serial.println("mouth closed");
            open = false;
        }
        say(pgm_read_byte(&phrase[i]));
    }
}

template< size_t size >
void sayPhrase(const uint8_t (&phrase)[size])
{
    sayPhrase(phrase, size);
}

```

Which can then be called directly on the array:

```
sayPhrase(heybuddy);

```

And the template will infer the array size and call the non-template function.
> 1 votes

# Answer
As others have pointed out, your problem is `sizeof`, which is calculated at compile time, not when the code is run.

You need to pass the size of the array to the function. This can be done in many ways, depending on what else you are doing.

In `c` the most common method is to use a null-terminated string, but I suspect this may not work.

You can store the size of each phrase in a separate array, and pass as a separate parameter or Pascal style as a count byte in the first element of the phrase.
> 0 votes

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