# Question
Title: Storing Long numbers in arduino like phone numbers...How?
I am using 20 x 4 LCD And 3 x4 keypad I want to enter and store 3 inputs in different variables the code I am using can store 3 inputs and display it right in serial monitor example I type 5 digits using keypad it will store and display correctly in LCD and serial monitor the right value however if its more than five it has negative output and very far to what inputted. Thank you for help .The code is...

```
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
SoftwareSerial mySerial(6,5);
#include <Keypad.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
};
byte rowPins[ROWS] = {19, 18, 17, 16}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad

int count=0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

char entryStr[12];   // This can hold up to 4 digits
int i=0;

void setup()
{
    mySerial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
}

void loop(){
    long n1, n2 , n3;

    lcd.setCursor(0,0);
    lcd.print("Enter n1:   ");

    lcd.setCursor(0,1);
    n1 = GetNumber();
    Serial.println ("n1: ");
    Serial.println (n1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter  n2:   ");

    lcd.setCursor(0,1);
    n2= GetNumber();
    Serial.println ("n2: ");
    Serial.println (n2);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter n3:   ");
    lcd.setCursor(0,1);
    n3 = GetNumber();
    Serial.println ("n3: ");
    Serial.println (n3);
}

int GetNumber()
{
    long num = 0;
    char key = kpd.getKey();
    while(key != '#')
    {
        switch (key)
        {
            case NO_KEY:
            break;

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
            lcd.print(key);
            num = num * 10 + (key -'0');
            break;

            case '*':
            num = 0;
            lcd.clear();
            break;
        }
        key = kpd.getKey();
    }
    return num;
}

```

# Answer
```
int GetNumber()

```

should be changed to

```
long GetNumber()

```

It is because the function type is the type of value that returning. In this case you are returning a long so you have to change it. An int can handle a number from -32 768 to 32 767. A long on the other side can handle a number from -2,147,483,648 to 2,147,483,647.
> 1 votes

---
Tags: arduino-ide
---


title: Arduino sound equalizer

text:
# Question
Title: Arduino sound equalizer
I'm trying to build a led equalizer using arduino and I want to light up with the frequencies.

And I need a little help on how I should do it cause Im a beginner.

Should I use pulsein() or analogin pin to measure the freqeuencies?

The input will be an audio cable.

# Answer
There are three steps to doing what you want, and the Arduino is going to struggle with all of them.

First you need to sample a short block of audio into a buffer that is a power-of-two in size with at least double the number of samples that you want to have bars, and at double the frequency of the highest frequency band you are interested in.

Once you have that sample set you then need to perform a *Fast Fourier Transform (FFT)* on it. This is quite a heavy mathematical operation, but there are *integer only* implementations of it that work kind of OK on a little Arduino (though a floating point version running on a better chip with FPU, or a DSP version on a chip with a DSP, is more desirable).

Then the third step is to take the results of the FFT (or "buckets") and calculate the power magnitude of each one (basically the square root of the sum of the squares of the real and imaginary values of the bucket - just like Pythagoras with a triangle).

Finally you can plot those power values on your LED bars.
> 1 votes

# Answer
Use a MSGEQ7. This IC is a "Seven Band Graphic Equalizer".

Here is its datasheet:

https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf

This method is more efficient, accurate and easier then pulsein() or analogRead(). The IC is fairly cheap and there are many libraries for it.

https://github.com/NicoHood/MSGEQ7

Here is a nice project that I found and that uses that IC. It can be a good souce of inspiration for both your code and your electronics.

https://www.youtube.com/watch?v=InrQvtUuS2w
> 1 votes

---
Tags: arduino-uno, frequency, sound
---


# Question
Title: How to keep accurate millis() while using ADC_sleep mode?
millis() uses timer0 (linked to CPU clock) to count time, but ADC\_sleep mode stops the CPU clock, therefore millis() will drift (lag behind) after each ADC conversion performed in ADC\_sleep mode.

With the standard number of CPU cycles needed for the ADC conversion (ADC prescaler=128 multiplied by ADC clock cycles=13), and with the standard prescaler for timer0 (64), it would look like millis() loses 13.5 tics (about 0.1 ms) for every ADC conversion performed in ADC\_sleep mode.

I could update the timer0 register (TCNT0) by increasing it manually by 14 but first of all I would still have a 0.5 ticks drift (or a bit less, since the update operation would take some cycles), second I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 \> 230.

How should I proceed to use ADC\_sleep mode during ADC conversions but still keep millis() accurate?

# Answer
Rather than trying to update TCNT0, it might be better to track the number of cycles lost to ADC conversions, and in an intermediate routine – eg, `omillis()` – compensate for those cycles. *\[Edit: See better alternative, below\]*

In more detail:

• At each conversion, add about 128·13 cycles (or perhaps 128·13.5, to account for average prescaler delay) to a cycle counter:
`long lostcycles; ...; lostcycles += ADCcycles;`

• Within each `omillis()` call, say `return millis()+lostcycles/16000`

• Or perhaps say `return millis()+lostcycles>>14` to avoid wasting time on a division. This would be off by 2% on the correction, but I presume the correction is small, say 5% of total time, leading to about 0.1% error because of using a shift instead of a divide.

> Re: “I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 \> 230”

That's incorrect \[if using suggested approach\]. Even if the timer 0 overflow is handled a hundred microseconds late, it will be handled ok. \[As noted in Edgar Bonet's comment, a method that just adds to TCNT0 without checking arithmetic overflow, as in original approach, could miss a timer tick.\]

Note, the example code using `SLEEP_MODE_ADC` in the “Sleep during reading” section of ADC conversion on the Arduino on Gammon Forum suggests that one should check for the case where a timer or other interrupt occurs during an ADC conversion. While `SLEEP_MODE_ADC` stops clkI/O, clkCPU, and clkFLASH, it leaves Timer 2, WDT, and some other potential interrupt sources active.

**A better alternative:**

As Gerben points out, it's slightly cleaner to update the count variable maintained by `millis()`, rather than using an intermediate routine. For background, refer to his answer to an earlier question. Here is an adaptation \[untested\] of the idea to the current case:

```
unsigned int lostcycles=0;
...;
void accountForADC() {
  enum { ADCcycles = 13*128 + 64;  ms_cycles=16000 }; // adjust appropriately
  extern volatile unsigned long timer0_millis;
  lostcycles += ADCcycles;
  while (lostcycles >= ms_cycles) { // This loop usually runs one pass only
    byte statusReg = SREG; // Save interrupt status
    cli();                 // Turn off interrupts
    ++timer0_millis;       // Need interrupts off for atomicity
    SREG = statusReg;      // Restore old status
    lostcycles -= ms_cycles;
  }
}

```

After startup, on the tenth call to `accountForADC()` this code would add 1 to `timer0_millis` to account for a millisecond lost to ADC conversions. `lostcycles -= ms_cycles` would set `lostcycles` to 1280. After another 9 calls we again add 1 to `timer0_millis` and reduce `lostcycles`; and so forth.
> 3 votes

# Answer
I won't tell you how to do what you ask as I don't really know how to do it. But I have the gut feeling that it *can* be done. Only it would be *really, really hard*, so this brings the question: is it worth it?

To avoid posting a pure opinion-based answer, I'll try to give you some leads:

* You can set the timer 0 with single-CPU-cycle resolution simply by resetting its prescaler whenever you set a new value.
* You can make very precise delays with the `_delay_us()` function. The argument should be a compile-time constant. `_delay_us(0.125)` does exactly what it says it does.
* Beware of the prescaler of the ADC clock: it will induce some jitter on the ADC timings unless you reset it as well. AFAIK, the only way to reset that prescaler is to start the ADC conversion using some trigger source in auto-trigger mode. This may cost you a timer.
* If you miss the overflow event, you can just manually call the relevant ISR (`TIMER0_OVF_vect()`, which you declare with `ISR(TIMER0_OVF_vect);`). Sounds silly, but it works, with the only caveat that it forcibly enables interrupts upon return.

To know how many tics *exactly* you are loosing, you could spend a few evenings carefully studying the timings in the datasheet, or you could try to calibrate against a stable frequency source. I would recommend the latter.
> 1 votes

# Answer
I think you read the datasheet wrong. The conversion takes 13 ADC cycles (except for the first one), not 13.5.

Secondly; the conversion start at the next rising edge of the ADC clock, not directly. So because the prescaler is 128, it can take an additional 127 main clock cycles before the next ADC clock's rising edge. So that means and ADC conversion takes between 13 and 13.9921875 ADC clock cycles.

I'm also not sure how long it takes the uC to restart the CPU clock. So there might me more time "missed" here.

Though you must be aware that the crystal oscillator isn't that accurate to begin with.
> 1 votes

# Answer
The time to start a conversion is not fixed. From my page about timers we can see this:

> **Tip:**
>
> There is an extra time before a conversion starts. The conversion starts on the leading edge of the ADC clock, not the moment the code asks for it. In the case of a scaler of 128, there could be 127 extra (processor) clock cycles added, because the hardware has to wait for the next ADC clock cycle. This could add 7.938 µs to the conversion time.

It looks like the prescaler can be reset by writing 0 to ADEN. According to the datasheet:

> The prescaler starts counting from the moment the ADC is switched on by setting the ADEN bit in ADCSRA. The prescaler keeps running for as long as the ADEN bit is set, and is continuously reset when ADEN is low.

If you do that however then you add to the conversion time, as it will now take 25 ADC clock cycles rather than 13.

---

* As others have suggested, if accurate time is what you want, then an external clock chip could well be the answer. The chip and parts are likely to come to a dollar or so.
* An alternative would be to get an external ADC chip, thus moving the problem of noise-reduction to a chip which is (hopefully) designed to cope with it.
* ~~Another possibility would be to put an external clock input to Timer 1 and run that asynchronously. As I read the data sheet, that timer will keep running in ADC sleep mode, and thus you could use that for timing. (That wouldn't help with millis() and micros() but you could write something similar that used Timer 1).~~

*Edit* \- as Edgar Bonet pointed out, I misread the datasheet. It is Timer 2 that can do this, not Timer 1. And the pins to run the timer asynchronously are not on the PDIP chip on the Uno, and are not brought out to board pins on the Mega.
> 1 votes

---
Tags: time, millis, adc, sleep
---


# Question
Title: Any problems taking arduino(esque) devices through airport security?
I'm flying out for vacation, and I want to take some of my half-done arduino projects with me to work on. I'm concerned that aiprort security might mistake my devices for something sinister or at bare minimum 'suspicious' and be confiscated.

Has anyone ever had any negative experiences taking arduino-esque wiring projects through airport security?

# Answer
I personally haven't taken my Arduino through security, but here are a few things I'd look at before flying:

* International flights might be more secure, so keep that in mind.
* (Like already mentioned) check your bags whenever possible
* Go extra early in case you do have to explain to the TSA (or equivalent). You don't want to miss your flight!
* Take it out of your bag so it doesn't look like you're hiding anything. The more open you are about it, the less suspicious they'll be.
* Bring any original packaging for your Arduino/parts.

A few other things I've read to do:

* Take tickets if going to some event like a Maker Faire, especially if they can look it up online. If they seem skeptical, you could always pull it up on your phone.
* Don't make it look like a bomb (i.e. **don't be stupid!**)
* Don't take tools unless needed
* Be patient and calm if they stop you. You have nothing to hide from them (Right? ***Right?***)
> 2 votes

# Answer
I don't think that is a problem. I have taken my arduino several times with me when I travel by plane and have never had any problems. I have even carried an oscilloscope and I only was warned about the pointy probes. I have taken international flights with it without any problems. However, always verify the airline baggage restrictioins.
> 3 votes

# Answer
It will depend on your particular country of course. Check the rules on cabin baggage.

In Australia, Arduino boards should pose no problem. It is best to not take any batteries or tools with edges (screwdrivers) or heavy tools (wrenches). In case they do want to have a look, place the boards at the top of your bag for easy access.

I have traveled to Europe from Australia with half a suitcase full of large PCBs with no problem. The only time my bag was opened was when I was carrying a tea pot stand, which was in the shape of a tea pot. Apparently it looked like a gun.
> 2 votes

# Answer
Real world example:

I have just flown from JFK - New York to GRU - Sao Paulo (Brazil) (October 2016) with this 'RIAspire UNO R3 Master Beginner Starter Kit for Arduino DIY Discovery - 25 Sensors with RFID, Ultrasonic, Temperature, HC 05 Bluetooth, ESP8266 Wifi' on my hand luggage.

There were a lot of wires, detectors and everything.

Nothing happened.
> 1 votes

---
Tags: arduino-uno
---


title: LininoIO running "partially"

text:
# Question
Title: LininoIO running "partially"
I installed LininoIO (OS dated 02 06 2015).

Everything seems to work fine - but nothing works as expected.

I have a running Linux - but when I try to use GPIO, as described on Lilino.org -GPIO on lininoIO, I run into the first problems.

D13 doesn't exist (this should be the little red LED on board of the Yún).

Next I tested reading the analog inputs.

I can for example use `cat /sys/bus/iio/devices/iio:device0/in_voltage_A0_raw`. There are no errors, but I always get the value `0`.

Checking with `/etc/linino/test_avrdude.sh` shows:

```
Testing AVRDUDE on ATMEL 32U4 ...

avrdude: Version 6.1-20140519, compiled on Jun  2 2015 at 12:34:59
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/root/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : unknown
         Using Programmer              : linuxgpio
Can't export GPIO 11, already exported/busy?: Device or resource busy
avrdude done.  Thank you.

```

Maybe this is "by design" or another sign of an error.

By the way - when I start a serial console I get the message:

```
avr-uart: switched to uart mode: mcuio

```

Further in kernel log I found:

```
[   42.480000] fuse init (API version 7.18)
[   42.620000] spi_tty_plain spi1.0: spi_tty_probe
[   45.380000] No need to change console settings
[   49.550000] mcuio-hc 0:0.0: unexpected reply
[   49.600000] gpiochip_add: registered GPIOs 100 to 139 on device: generic
[   49.630000] mcuio adc is 0:1:1
[   49.750000] mcuio-adc 0:1.1: 6 input channels detected
[   49.910000] mcuio-hc 0:0.0: unexpected reply
[   49.970000] mcuio pwm is 0:1:2
[   49.970000] mcuio-pwm 0:1.2: 6 pwm outputs detected
[   55.790000] busybox: sending ioctl 5310 to a partition!
[   55.800000] busybox: sending ioctl 5310 to a partition!
[   55.820000] busybox: sending ioctl 5310 to a partition!
[   55.830000] busybox: sending ioctl 5310 to a partition!
[   56.290000] EXT4-fs (sda2): couldn't mount as ext3 due to feature incompatibilities
[   56.310000] EXT4-fs (sda2): couldn't mount as ext2 due to feature incompatibilities
[   56.360000] EXT4-fs (sda2): mounted filesystem with ordered data mode. Opts: (null)
[   58.520000] cfg80211: Calling CRDA for country: AT

```

It seems as if there are problems with `mcuio-hc`.

Last thing - when I ran `run-avrdude /etc/linino/bathos-one.hex` I get an error when comparing the written data (I found information that this can be ignored).

How can I fix this / find out what to fix / what's going wrong?

# Answer
finally I got it (somehow) working. After a reset and another run of run-avrdude /etc/linino/bathos-yun.hex (the first was a mistake by copy and past - not bathos-one I already ran bathos-yun before) and a reboot again I was able to read analog IO.

But still the digitals were missing. Than I found the command gpioexport an ran it. After that the correct entries (D13, D14...) were present in sys/class...

But an echo out \> D13/direction resulted in a timeout error message. Again reboot - again the Dxxx entries were gone. Another gpioexport made them appear again.

And this time not timeouts - instead I could turn on / of D13 (for test).

I guess all I have to do to make the things better is include gpioexport in "startup code" so that it runs after a reboot.
> 0 votes

# Answer
Have a look at the schematics of the YUN https://www.arduino.cc/en/uploads/Main/arduino-Yun-schematic.pdf

You will notice that most of the GPIO pins on the Atheros is not available to you. You only have access to the GPIO pins of the atmega.
> 0 votes

# Answer
LininoIO has a part which runs on the microcontroller and make the Atheros enable to use the mcu pinout as linux gpios. So you are right, you need to flash the bathos to the mcu.

In general to enable/disable lininoIO run:

```
> lininoio start
> lininoio stop

```

those commands do everything for you. have also a look here

Anyway your Linino version seems old, try to upgrade it: http://www.arduino.org/learning/tutorials/advanced-guides/how-to-upgrade-the-linino-distribution-for-arduino-yun-and-yun-mini
> 0 votes

---
Tags: arduino-yun
---


title: How to multiply strings?

text:
# Question
Title: How to multiply strings?
I want to have a line like this

```
Serial.println(count*"B");

```

So if `count=6`, it would print `BBBBBB`, etc.

Is there anything like this for arduino?

# Answer
> 1 votes
A more simple "noob" way could also be:

```
int count = 6

for(int i=0; i<count; i++)
{
  Serial.print("b");
}

Serial.println();

```

# Answer
> 3 votes
You can write a helper function to do it, like this:

```
void printRepeat (Stream & device, const char * str, unsigned int count)
  {
  while (count-- > 0)
    device.print (str);
  }   // end of printRepeat

void setup()
  {
  Serial.begin (115200);
  printRepeat (Serial, "-", 20);
  Serial.println ();
  } // end of setup

void loop()
{
  printRepeat (Serial, "Hello, World! ", 5);
  Serial.println ();
  delay (500);
} // end of loop

```

The function `printRepeat` is passed a `Stream` argument, which can be something like Serial, Serial1, a SoftwareSerial instance, and so on.

# Answer
> 2 votes
Just for fun, here is a version of Nick Gammon's answer reformulated with some C++ magic:

```
// A "repeated string" that has no use except for being printable.
class RepeatedString : public Printable
{
public:
    RepeatedString(const char * str, unsigned int count)
    : _str(str), _count(count) {}
    size_t printTo(Print& p) const
    {
        size_t sz = 0;
        for (unsigned int i = 0; i < _count; i++)
            sz += p.print(_str);
        return sz;
    }
private:
    const char * _str;
    unsigned int _count;
};

void setup()
{
    Serial.begin(115200);
    Serial.println(RepeatedString("-", 20));
}

void loop()
{
    Serial.println(RepeatedString("Hello, World! ", 5));
    delay(500);
}

```

You can `.print()` and `.println()` the `RepeatedString`s on anything that can print.

---
Tags: string
---


# Question
Title: How to count the number of button presses then play a sequence?
1. When I press the button once, sequence s1() plays.
2. When I press the button twice, sequence s2() plays.
3. When I press the button thrice, sequence s3() plays.
4. When I press the button 4 times, sequence s4() plays.

---

```
const int buttonPin = 10;
int buttonState = 0;

void setup(){
  Serial.begin(9600);
  //initialize pin 2 - 9 as output
  for(int i=2;i<=9;i++){
    pinMode(i,OUTPUT);
  }
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    s1();
    s2();
    s3();
    s4();
  }
}

void s1() {
  int i = 2 ;
  for(int z=0;z<=1;z++) {
    for(int x=i;x<=9;x++) {
      digitalWrite(i,HIGH);
      digitalWrite(x-1,LOW);
      delay(500);
      i = i + 1;
    }
    i = 2;
    if(i = 2) {
      digitalWrite(9,LOW);
    }
  }
}

void s2(){
  int y = 9;
  for(int i=0;i<=1;i++) {
    for(int x=2;x<=5;x++) {
      if(y>=1) {
        digitalWrite(x,HIGH);
        digitalWrite(y,HIGH);
        delay(500);
        y = y - 1;
      }
    }
    off();
    y = 9;
    delay(500);
  }
}

void s3() {
  for(int i=0;i<=2;i++) {
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
  }
}

void s4() {
  for(int i=0;i<=2;i++) {
    for(int x=2;x<=9;x++) {
      digitalWrite(x,HIGH);
      delay(500);
    }
    off();
    delay(500);
  }
}

void off() {
  for(int i=2;i<=9;i++) {
    digitalWrite(i,LOW);
  }
}

```

# Answer
> 1 votes
That's not that complex, please have a look at the following code: not the most elegant solution ever, but should be working (I didn't compile it as I'm currently on launch break in the office)

```
#define LONGEST_PAUSE 1000
unsigned long lastClick;
unsigned int counter;

void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    // button is pressed
    while(digitalRead(buttonPin) == HIGH)) {
      delay(1); // wait until button released
    }
    lastClick = millis();
    counter++;
  }
  if (counter > 0 && (millis() - lastClick) >= LONGEST_PAUSE) { // 1s passed since last click: let's play!
    switch(counter) {
      case 1:
        s1(); break;
      case 2:
        s2(); break;
      case 3:
        s3(); break;
      case 4:
        s4(); break;
      default:
        // what if I keep clicking?!?
    }
    counter = 0; // reset the counter
  }
}

```

# Answer
> 0 votes
I prefer you to use pinchange interrupt or simple INT0 interrupt for the buttons to count the press. Check this link.

on ISR, you can count the press.

```
int count=0;

void setup() {
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), countFn, CHANGE);
}

void loop() {
  switch(count){
      // all cases here
  }
  count=0;
  delay(2000); // this delay is important to give enough time for a number of presses for the user
}

void countFn() {
  count++;
}

```

---
Tags: led, button
---


# Question
Title: Atmega8 with Arduino bootloader - wrong serial characters
I recently flashed bootloader of Arduino to Atmega8. Unfortunately I stumbled on a problem I can't solved.

I am testing SerialEvent example on Atmega8. I modified it but started debugging it on my code (I think the same problem stops SerialEvent example from working).

I think the Atmega8 reads the characters sent through serial wrongly. That's why *SerialEvent* 'if' condition doesn't work also. Because it never gets '\n' symbol (it receives it but wrongly interprets it).

```
boolean prevState = true;
boolean OnOff = false;
boolean stringComplete = false;
String inputString = "";
String OnString = "on\n";
String OffString = "off\n";

void setup() {
    Serial.begin(1200);

    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }

    // reserve 200 bytes for the inputString
    inputString.reserve(200);

    DDRD |= 0b00001100;
    PORTD |= _BV(PD2);

    // synchronization info for RPi
    Serial.println("ARD - OK\n");
}

void loop() {
    // turn on
    if (OnOff == true && prevState == false){
        PORTD |= _BV(PD2);
        prevState = OnOff;
    }
    // turn off
    if (OnOff == false && prevState == true){
        PORTD &= ~_BV(PD2);
        prevState = OnOff;
    }

    if (stringComplete) {
        Serial.println(inputString);
        // clear the string:
        inputString = "";
        stringComplete = false;
    }
}

void serialEvent() {
    while (Serial.available()) {
         // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
        Serial.println(inputString);
        if (inChar == '\n') {
            stringComplete = true;
            Serial.println("test\n");
        }

        if (stringComplete && inputString.equals(OnString)){
            OnOff = true;
            Serial.println("Turning on.\n");
        }
        else if (stringComplete && inputString.equals(OffString)){
            OnOff = false;
            Serial.println("Turning off.\n");
        }
    }
}

```

I tested a lot of behaviors. Below I attach one of the tests from Realterm:

First I reset the board - it responded with 'ARD - OK\n' - expected behavior. Then I sent 'on\n' and it responded with two lines but the characters aren't the same as 'on\n'. Then I sent 'test123\n' but once again got wrong characters. It prints multiple lines because it sends the string in which it accumulates the data every time *SerialEvent()* is fired.

Also sending for example variabl *OnString* works ok.

I really don't know why is it acting like that... Help would be appreciated :).

# Answer
> -1 votes
You have chosen the wrong build configuration which mismatches your hardware.

An ATmega8 with an 8 MHz oscillator works just fine, but all timing aspects of your code must be complied based on knowledge of that clock rate. If they are built for 16 MHz, then everything clock related will take twice as long as intended, for example baud rates will be half of what was intended.

In the Arduino world code is built for a clock rate specified in the chosen boards.txt file entry or in a dropdown menu for recent versions and boards with multiple clock variants. So the answer is that you have chosen the wrong build configuration for your hardware.

# Answer
> 1 votes
Ok I found a solution (rather workaround).

I uploaded the same program to Arduino Uno. It worked perfectly. I transplanted the Atmega328 from Uno to breadboard. Still worked BUT the Atmega328 is using external 16Mhz crystal (which I added to the breadboard).

So what if I uploaded bootloader for 16Mhz external crystal on Atmega8? It makes it work properly.

So in short: Atmega8 with 8Mhz internal oscillator doesn't work properly. Atmega8 with 16Mhz external oscillator works properly.

Don't know why does it make it work. If anyone can think of a reason I would be glad to know it. Thanks for all your help.

---
Tags: arduino-uno, serial, bootloader
---


# Question
Title: Why is there a plastic sleeve on my HC-05 bluetooth module
I would like want to know why the bluetooth module has a plastic sleeve covering it?

Is it possible to remove it?

# Answer
It is to protect it. You should keep it so that the modules lasts longer.

If you remove it, just don't do anything stupid.
> 4 votes

# Answer
To protect it against ham fisted newbies from causing short circuits.

Yes, you can remove it, as long as you're not a ham fisted newbie that is going to cause short circuits.
> 3 votes

---
Tags: bluetooth, components
---


# Question
Title: How Bootload an Lilypad Arduino USB using Arduino UNO
I recently bought two lilypads USB, one works perfectly (it's recognized in my computer, but the other one it's never recognized, I even try in different computers and the same scenario with both devices)

So I think that maybe the second one doesn't have a bootloader installed. So I'm triying to "burn" a new bootloader. I have been triying following the guide on https://www.arduino.cc/en/Tutorial/ArduinoISP using as programmer an Arduino UNO but without luck. I ever get avrdude: Device signature = 0x000000 (retrying). Thanks for the help!

# Answer
> 2 votes
If you try uploading to a LilyPad USB with the wrong board selected, you may end up in a condition where the bootloader can no longer respond normally.

You can get the LilyPad Arduino into bootloader mode by tapping the reset button twice in under a second. Once in bootloader mode, the LED should blink at about 1Hz for about 8 seconds. My advice is to load a blank sketch (i.e., nothing in loop() or setup()) and then double tap the reset button shortly after hitting the upload button. That should restore the LilyPad USB to a working state.

# Answer
> 0 votes
The Lilypad is an official Arduino board. If you did not get it from other continents, it should have the bootloader in so don't try to burn something else. Check the traces of your Lilypad. Some short might occur because of and accidental short.

Whatever you do, DON'T TRY TO BURN SOMETHING THAT DOESN'T NEED TO BE BURNED.

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


# Question
Title: Arduino Mega 2560 and Android USB OTG serial communication
currently I am building a little project based on the Arduino Mega 2560. My goal is to send some data gathered by some sensors to an Android phone. It has to be as basic as possible. Buying new hardware is no option.

After some research, I found that it is possible to communicate via USB OTG just with Serial commands. I downloaded the an app which can do this (Serial Monitor), connected the Arduino via the USB cable to the Android. Unfortunately, it did not work.

I have an Arduino UNO, too. Connecting the UNO the same way to the phone works like a charm and does exactly what I want.

I did some more research and found nothing about that. It seems that everybody is using the Arduino Mega ADK to establish a communication between Arduino and Android. But I would like to be able to achieve this the same way it works with the UNO.

Can somebody explain me why it does not work?

**EDIT** Here is the code I have to test:

*Arduino*

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

void loop() {
  Serial.println("Test...");
  delay(2000);
}

```

For Android I use the code from this tutorial.

Any further suggestions?

# Answer
> 0 votes
So I figured it out.

It was the VendorID. I found it and noticed, that the VIDs of the UNO and Mega are different. I adjusted the code and now everything works as I expect. So, thank you Chris Startton for the correct hints.

Thank you all.

---
Tags: serial, arduino-mega, usb, android
---


title: and gate based on truth table

text:
# Question
Title: and gate based on truth table
I have to code in arduino the logic gates based on the truth table with two inputs. I searched for some examples, however all that I found is using && to compared them using only onf if else condition. What I need is to do it using all the possible cases. This is what I have, however only the last condition is working. I ask you please clarify to me what concept I am not understanding well, or what is wrong in my logic. Thank you.

```
  const int p2  = 2;  //Ground G
  const int p13 = 13; //Input A
  const int p15 = 15; //Input B

  void setup() {
    // put your setup code here, to run once:
    pinMode(p2,   OUTPUT);
    pinMode(p13,  INPUT_PULLUP);
    pinMode(p15,  INPUT_PULLUP);
  }
void loop() {
  // put your main code here, to run repeatedly:
  if ( digitalRead(p13) == 0 && digitalRead(p15) == 0 ){
    digitalWrite(p2, HIGH);
  }

  if( digitalRead(p13) == 0 && digitalRead(p15) == 1 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13) == 1 && digitalRead(p15) == 0 ) {
    digitalWrite(p2, LOW);
  }

  if( digitalRead(p13)== 1 && digitalRead(p15) == 1) {
    digitalWrite(p2, LOW);
  }

}

```

# Answer
> 1 votes
Let me give some feedback on your code, kind of a small code review:

```
const int p2  = 2;  //Ground G
const int p13 = 13; //Input A
const int p15 = 15; //Input B

```

This is useless. The purpose of creating these constants is to give them meaningful names, and `p2` is no more meaningful than just `2`. You can remove these definitions and replace in the following `p2` with `2`, etc. Or you could find better names:

```
const int inputA_pin = 13;
const int inputB_pin = 15;
const int output_pin = 2;

```

Notice that the comments that you put next to the constants are not needed anymore, as the names are now explicit enough.

```
void setup() {
    // put your setup code here, to run once:

```

This comment is useless, better remove it. It is in BareMinimum.ino so that you know what to put there, but now that you have done it, no need to keep the comment.

```
if (digitalRead(p13) == 0 && digitalRead(p15) == 0) {
    digitalWrite(p2, HIGH);
}

```

I assume you are using negative logic: the user presses a button, and makes the input LOW, to mean TRUE. If this is the case, you are not being clear enough about it. You should at least have a comment to make this explicit, e.g.:

```
int inputA = !digitalRead(inputA_pin);  // negative logic

```

where `!` is the NOT logic operator.

Otherwise your program seems fine. If it does not work, check your wirings. John Burger's suggestions on how to make it better are very sound, and you should probably follow them. But I would like to show you *another* way of writing this that could be relevant to your course: you can implement the truth table as an actual table, i.e. a C++ array. Here is my version:

```
const int inputA_pin = 13;
const int inputB_pin = 15;
const int output_pin = 2;

const bool truth_table[2][2] = {
            /* false  true  */
/* false */  { false, false },
/* true  */  { false, true  }
};

void setup() {
    pinMode(inputA_pin, INPUT_PULLUP);
    pinMode(inputB_pin, INPUT_PULLUP);
    pinMode(output_pin, OUTPUT);
}

void loop() {
    int inputA = !digitalRead(inputA_pin);  // negative logic
    int inputB = !digitalRead(inputB_pin);  // ditto
    int output = truth_table[inputA][inputB];
    digitalWrite(output_pin, output);
}

```

Notice that this uses the equivalence between false/true and 0/1.

In the case of the AND gate, this looks just like a silly classroom exercise. However, for a complex gate with four inputs or more, and a non-trivial truth-table, this technique may be the most straightforward implementation.

---

**Addendum** – You wrote in a comment:

> Not clear how your truth table works.

You are probably confused by the fact that I laid out the table in compact form, with the first input in the row headings (comments on the left edge) and the second input in the column headings (comments at the top), just like a traditional multiplication table. Incidentally, it happens to be a 2×2 multiplication table.

I could have used the more common “flat” layout, where each combination of inputs is represented as one line of the table:

```
const bool truth_table[] = {
    /*   A     B     output  */
    /*-----------------------*/
    /* false false */ false,
    /* false true  */ false,
    /* true  false */ false,
    /* true  true  */ true
};

```

But then, since it's now a 1D table, the table index has to be computed from both inputs, as each input provides one bit of the index:

```
int output = truth_table[inputA<<1 | inputB];

```

This is actually how I would do it if I had to simulate a gate with more than two inputs. I've used this technique to make a 2-bit Gray code adder (4 inputs, 2 outputs) which, with a little bit of optimization, boils down to

```
for (;;) PORTB = truth_table[PINB & 0x0f];

```

# Answer
> 3 votes
Your whole code can be replaced with one line:

```
digitalWrite(output_pin, digitalRead(inputA_pin) && digitalRead(inputB_pin));

```

That is, write out the results of a boolean AND on the state of the two inputs.

# Answer
> 0 votes
Your question title says "and", which means that if `input1` is `HIGH` ***AND*** `input2` is `HIGH`, then `output` should be `HIGH`. Your first line has

```
(...==0 && ...=0) digitalWrite(..., HIGH);

```

Surely these should be `==1`?

Another thing is that every line of code in your program is re-reading the inputs. You should read them *once*, then decode the meaning behind them. So:

```
int input1 = digitalRead(p13);
int input2 = digitalRead(p15);

if (input1==1 && input2==1) {
    digitalWrite(p2, HIGH);
} // if
else if (input1==0 && input2==0) {
    digitalWrite(p2, LOW);
} // else if
else if ...

```

But note that the last three options are all the same: the code simply writes `LOW`. So you can combine all the last three cases into one step.

In other words, there's a single special case (both inputs `==1`), and an everything-else case. In this code, I only read the inputs once, since I'm only looking for the special case. If it doesn't exist, then I simply do the alternative:

```
if (digitalRead(p13)==1 && digitalRead(p15)==1) {
    digitalWrite(p2, HIGH);
} // if
else {
    digitalWrite(p2, LOW);
} // else

```

---
Tags: programming
---


title: Supply 5V to Arduino

text:
# Question
Title: Supply 5V to Arduino
I am building a quadrocopter with an Arduino Uno as control unit. I know I can supply 5 volts to the 5V pin, but my ESCs produce 5.5 volts, which I measured with my multimeter. Will this voltage drop to 5 volts when I connect the Arduino and if not are 5.5 volts to the 5V pin a problem?

Edit:

My Arduino was running well for a couple of days on this setup with 5.5 volts to the 5V pin but died yesterday. By dying I mean the ATmega doesn't execute any code anymore, the L LED doesn't blink, and even a loopback test fails, which is a sign of a defective USB connector. But I am faced with the same challenge. Should I run my Arduino on 14.4 Volts from my 3S LIPO to Vin or supply 5.5 volts to the Vin pin?

Actually I just realised when I measure the voltage from the ESCs they deliver 9 point something volts for half a second when connecting the multimeter, I guess this voltage spike killed the Arduino.

# Answer
I'm going to assume you are using the UNO model - or any other board based around the Atmega328p.

According to the datasheet the voltage limits are 1.8v to 5.5, with an absolute maximum of 6v. You should be fine - but if you are able to get the voltage down closer to 5 volts, I would recommend doing that instead.
> 1 votes

# Answer
Most Arduinos won't mind 5.5v if your are sure that is the max. The ATmega328 is design to be used from 2.7V to 5.5V so that is the very max. No, the voltage will not drop down to 5V when you connect it to the Arduino but I believe you are quite safe with 5.5V. Just don't make a short because you'll be pushing your ATmega328 to it's designed max. You might wanna look at the datasheet for it. All it specs are in there.
> 1 votes

# Answer
You're better off applying that 5.5V to the Vin pin. You may end up with slightly less than 5V at the Arduino, but it'll tolerate that much better than going above 5.5V on the 5V rail.
> 1 votes

# Answer
> Actually I just realised when i measure the voltage from the escs they deliver 9 point something volts for half a secound when connecting the multimeter ...

Yes, that won't be good for it. I suggest a LDO (low dropout) 5V voltage regulator. Something with a 0.5V dropout will get rid of that extra 0.5V and also handle the initial spike.
> 1 votes

# Answer
Okay - it looks like that voltage spike might be the cause of death for your board. As an answer to your question though - I would recommend applying the 14.4 volts to vin, as 5.5 volts is not enough (the regulator needs 6 volts as a minimum, and the absolute maximum is 20 volts). Just make sure you apply the 14.4 volts to the *vin* pin and **NOT** the *5v* pin, as that would kill the board.

Please tell us how it worked out - good luck!
> 1 votes

---
Tags: arduino-uno, voltage-level
---


title: I2C on non I2C pins, possible?

text:
# Question
Title: I2C on non I2C pins, possible?
I have 2 I2C devices that uses the same address. One of them is the DS3231 RTC. I use this library for the DS3231. I dont want to mess with the other one cause it is way more complicated then this one.:

```
#include <DS3231.h>

```

http://www.rinkydinkelectronics.com/library.php?id=73

Then, there is an object declaration for the real time clock:

```
DS3231  rtc(SDA, SCL);

```

I wounder if I can change that to:

```
DS3231  rtc(A0, A1);

```

I've seen the library but I haven't understand it yet (duh... I'm so stupid!). But is it possible to use an other pair of pins for I2C communication.

Note that I've already tried to use the soft I2C library but I really want to avoid it because it is just too much. If it is the final solution then so be it.

# Answer
> 2 votes
You can change the address of the GY-521 by pulling the AD0 pin to Vcc. After that the address will be 0x69 instead of 0x68.

# Answer
> 1 votes
Ok, so I've realise that the anwser was somewhat on the page of the library (that I completly ignored). I can change the pins like I did because the library uses a "TWI-/I2C-like protocol".

> The library has not been tested in combination with the Wire library and I have no idea if they can share pins. Do not send me any questions about this. If you experience problems with pin-sharing you can move the DS3231/DS3232 SDA and SCL pins to any available pins on your development board. This library will in this case fall back to a software-based, TWI-/I2C-like protocol which will require exclusive access to the pins used.

---
Tags: arduino-uno, i2c, pins, communication, port-mapping
---


# Question
Title: GSM and Bluetooth modules on 1 Arduino Uno board
I couldn't find anything on this topic.

**Task:** to connect sensors to Arduino board via Bluetooth module, process the received data and then send the data to server via GSM module.

**Question:** Is it possible to connect both of these modules to 1 Arduino board? If I'm not wrong, Arduino Uno has only one pair of Rx Tx pins, while for these two modules each has its own pairs on Rx Tx pins.

I need to know this before ordering them. So, please help

# Answer
> 1 votes
Take a look at the `SoftwareSerial` library which allows other pins to be used for Serial at speeds \<= `57600`

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

---
Tags: arduino-uno, bluetooth, pins, gsm, wires
---


# Question
Title: Why is Serial.begin(9600) interfering with my multiplexor functioning?
I have an Uno hooked up to a sparkfun 8 channel multiplexer (https://learn.sparkfun.com/tutorials/multiplexer-breakout-hookup-guide). I have it wired up like this:

```
Arduino0 --> S0
Arduino1 --> S1
Arduino2 --> S2
Arduino3 --> Z
Arduino 5v --> VCC
Arduino GND --> GND

```

I'm running a simple code to blink two different LED's, one attached to Y7, and one attached to Y6.

```
//Define MUX pins
int pin0 = 0;
int pin1 = 1;
int pin2 = 2;
int zOutPut1 = 3;

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

    // Set controll pins
    pinMode(pin0, OUTPUT);
    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(zOutPut1, OUTPUT);
}

void loop() {
    samplerStarter();
}

void samplerStarter() {
    sample(1); // Takes sample for 5 min
    delay(1000);
    sample(2);
    delay(1000);
}

void sample(int noidNum){
    //MUX 1
    if(noidNum == 1) {
        digitalWrite(pin0, HIGH);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y7
    }
    else if (noidNum == 2) {
        digitalWrite(pin0, LOW);
        digitalWrite(pin1, HIGH);
        digitalWrite(pin2, HIGH);
        digitalWrite(zOutPut1, HIGH); //Y6
    }
    delay(500);

    //Set everythign back to Low
    digitalWrite(pin0, LOW);
    digitalWrite(pin1, LOW);
    digitalWrite(pin2, LOW);
    digitalWrite(zOutPut1, LOW);

    delay(500);
}

```

But when I run this code, only the first LED attached to Y7 blinks. But if I remove the `Serial.begin(9600)` line:

```
//Serial.begin(9600);

```

Everything works fine. So I have no idea why this one line dealing with Serial Communication is affecting my multiplexor.

# Answer
(Digital) Pins 0 and 1 are used by the hardware serial port you initialize with Serial.begin() on a classic Arduino like an Uno.

With this type of board it is generally best not to use those for any other purpose; if you do, you have to accept that you cannot use the hardware serial for input or debug/status output.

Even if you don't want to use serial during the operation of the your creation, having those pins connected to other functions can interefere with uploading sketches via the bootloader, or else the act of uploading a sketch can misoperate the functions connected to those pins.
> 3 votes

---
Tags: arduino-uno, serial, multiplexer
---


title: Does a GPS need a sim card?

text:
# Question
Title: Does a GPS need a sim card?
I am trying to use a NEO-6M GPS to datalog my current position on a Micro SD card with the help of an Arduino Pro Mini. It doesn't transmit anything. So do I need a SIM card?

> Caution:
>
> 1. The GPS tracker must be worked with a SIM card which may cost data and SMS fee.
> 2. No annual authorization fee for the first year. The coming annual fee details, please visit our company website.

# Answer
For use as a GPS device, the NEO-6M doesn't need a SIM card. For use as part of a tracker that sends SMS / GSM messages, ie, that uses the cell telephone system to send messages, you need a SIM card. The SIM card is used to authenticate your system to the phone system.

See examples at "arduino gps and sms where are you arduino" (bigdanzblog.wordpress.com) and "vehicle tracking system using arduino gps and gsm" at circuitdigest.com.
> 3 votes

---
Tags: gps
---


# Question
Title: Arduino/ESP8266 no SPI data coming from MCP3008
I'm using an ESP8266 (NodeMCU Dev Kit v1) to read analog data via an MCP3008 ADC chip.

However I'm receiving only zeros when I know non-zero data should be present. I'm using the following code, which works perfectly when using the MCP3008 with my Arduino UNO. Using verbose mode on compilation, I can confirm that when compiling for the ESP8266, that is indeed linking the ESP8266 SPI library.

Am I missing something here in the code?

```
#include <SPI.h>

#define CS_PIN 15 // Use 10 when compiling for Arduino

int adcRead(int channel) {
  if ((channel > 7) || (channel < 0)) {
    return -1;
  }

  digitalWrite(CS_PIN, LOW);

  SPI.transfer(1);
  uint8_t r1 = SPI.transfer((channel + 8) << 4);
  uint8_t r2 = SPI.transfer(0);

  digitalWrite(CS_PIN, HIGH);

  return ((r1 & 3) << 8) + r2;
}

void setup() {
  SPI.begin();
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(SPI_MODE0);
  SPI.setFrequency(1000000); // 1 MHz -- remove line when running on Arduino UNO
  Serial.begin(9600);
  digitalWrite(CS_PIN, HIGH);
}

void loop() {
  Serial.println(adcRead(0));
  delay(50);
}

```

In terms of wiring, I have the following

```
MCP3008   ESP8266
V_DD      3v3
V_REF     3v3
AGND      GND
CLK       GPIO14 (D5)
D_OUT     GPIO12 (D6)
D_IN      GPIO13 (D7)
CS        GPIO15 (D8)
DGND      GND

```

# Answer
> 1 votes
I was having trouble with this code and setup with the Adafruit Feather HUZZAH ESP8266.

# Solution

In addition to adding the `pinMode(CS_PIN, OUTPUT);` to `setup()`, I also dropped the frequency to something much lower. In my case, dropping the frequency to 10000 gave me good readings.

---
Tags: esp8266, spi, adc, nodemcu
---


# Question
Title: How to detect Genuino 101 from inside the code?
I am using a custom library for Arduino Mega which uses AES library for AES-128 encryption.

However, when I try to use that library in Intel Genuino 101 development board, it shows compilation error which is because the assembly language written in AES library was compatible with Atmel devices only.

And my question is whether there is a way, my code can automatically detect the GENUINO board by writing some sort of signature verification of this board and hence I can exclude the encryption part if it can successfully detect GENUINO 101.

For any queries, feel free to bug me, thanks.

# Answer
> 1 votes
Arduino defines some macros so you can use conditional compilation. For example these are from boards.txt:

* use `ARDUINO_AVR_PROMICRO` if it's specific for board variant
* use `ARDUINO_ARCH_AVR` if it's specific for Arduino with AVR

Also avr-gcc defines macros according to cpu settings (this should be similar for other platforms too):

* use `__AVR_ATmega32U4__` if it's specific for only one MCU
* use `__AVR__` if it's compatible with all AVR based MCUs

And code examples:

```
#if defined(__AVR_ATmega88__) || defined(__AVR_ATmega168__) || defined(__AVR_ATmega328__)
// something for ATmegaXX8 family...
#else
// ...
#endif

#ifdef __AVR__
// Code related to AVR
#else
// Code for other architectures
#endif

```

More about predefined macros in avr-gcc.

---
Tags: arduino-mega, core-libraries, arduino-galileo, avr-gcc
---


# Question
Title: Comparing time_t values within an if statement
I am using an UNO with a RTC to control a light board. I'm using a simple control structure to decide when to turn things off and on. It's my understanding that a `time_t` value is just a number (number of seconds since 1970), and that I should be able to compare these `time_t` values as I would any integer- in this case comparing two `time_t` values to see which one is larger.

```
#include <Wire.h> // Needed for I2C protocol (RTC uses I2C)
#include "RTClib.h" //Good Library for RTC functions
#include <Time.h> // Needed for time_t variables and tmElements

RTC_DS3231 rtcVM; // From the RTClib library for use with an DS3231 RTC. Creates an object called rtcVM

DateTime nowVM; // Declare a Date Time object that will be used to hold the current time
time_t nowUniVM;// Declare a time_t object (Unix time) which is a float value (good for straight comparisons) to hold current time
time_t starter;// Declare a time_t object for the start time (time_t)
tmElements_t MagStart; // Declare a tmElement_t object to manually input the start Time

//FILL OUT START TIME AND DATE FOR FIRST SAMPLE (NO LEADIN ZEROS--"8" not "08")
byte startHour = 17;
byte startMin = 58;
byte startSec = 0;

byte startDay = 12;
byte startMonth = 10;
int twoDigYear = 16; // Enter last two digits of year

byte startYear = twoDigYear + 30 ; // This is a little confusing. This is the year offset from 1970 (AKA 2016 should be input as 46. Or just add 30 to last two digits).

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

  Wire.begin();
  rtcVM.begin();

  // Creates a tmElement by putting together all of Maggies Start Time and Dates
  MagStart.Hour=startHour;
  MagStart.Minute = startMin;
  MagStart.Second = startSec;
  MagStart.Day = startDay;
  MagStart.Month = startMonth;
  MagStart.Year = startYear;

  // Takes the tmElement and converts it to a time_t variable. Which can now be compared to the current (now) unix time
  starter = makeTime(MagStart);

  // Start message
  Serial.println("Start time is: ");
  Serial.print(hour(starter));
  Serial.print(":");
  Serial.print(minute(starter));
  Serial.print(":");
  Serial.print(second(starter));
  Serial.print(" ");
  Serial.print(month(starter));
  Serial.print("/");
  Serial.print(day(starter));
  Serial.print("/");
  Serial.println(year(starter));
  Serial.println("****************************");
}

void loop() {
  nowVM = rtcVM.now(); // get current time and hold in "nowVM"
  time_t nowUniVM = nowVM.unixtime(); // Calculate current time in Unix time

  samplerStarter();

  // RTC Get and Display
  DateTime now = rtcVM.now();// Getting the current Time and storing it into a DateTime object

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(' ');
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();
  delay(3000);

  //Use these 2 to check the numerical values for comparisons
  Serial.println(starter);
  Serial.println(nowUniVM);
}

void samplerStarter() {
  if (starter < nowUniVM) {
    //if (1 < 2) {
    Serial.println("Start Time");
   }
}

```

I've included my entire test code here, but it's the last if statement that puzzles me. The idea behind that last statement is that it should print out "Start Time" when the start time is reached. The statement works if I compare something simple like (1 \< 2), and the statement gets printed. So I assumed it would work if I did the same thing but with two different `time_t` values.

But if I input an appropriate start time under the "Fill Out Start Time" section, the print statement is not triggered when the start time comes to pass (AKA- when the start time (starter) is less than the current time (`nowUniVM`).

Is there something about time\_t values that does not allow them to be compared like this? Or is there something in the way I'm creating my values that is messing up the comparisons?

My output to the serial monitor shows the actual `time_t` values, and they look like normal integers to me when they print out, so I'm not sure whats going on here. Why doesn't that last if statement print out when the start time is reached?

# Answer
You have *two* variables called `nowUniVM`. The fist one is a global declared at the top of your program, and implicitly initialized to zero by the compiler. Since you never update it, it is always zero. The second one is local to `loop()`: it shadows the global variable inside `loop()` and is updated periodically.

The function `samplerStarter()` only sees the global variable, which is zero. Thus, the comparison boils down to

```
if (starter < 0)

```

But since `time_t` is an unsigned type, the test can never be true.
> 2 votes

---
Tags: arduino-uno, timers, time, rtc
---


# Question
Title: How to repair or work around a damaged usb port on the Arduino?
While unplugging the usb cable from the Arduino, the plastic piece in the center of the port (the part that separates the pins) broke off and lodged into the end of the usb cable. I didn't notice that it broke off and when I plugged the cable back into the Arduino it bent one of the pins back onto itself.

How would you go about repairing this?

If I fail to repair it is there an alternate method to programming the board?

# Answer
You would need to replace the whole socket in order to repair it. For that you would need:

* Soldering iron
* Solder sucker
* Solder wick
* Patience and experience

Or you just connect an FT232 breakout board to TX, RX and RESET as if you were making a breadboard arduino and program the board through that.
> 1 votes

# Answer
You could try bending the pin back, removing the white part from your cable, and gluing it back in.

Second option is to replace the USB socket on the Arduino board. You might be able to salvage a socket from some old electronics you still have lying around.

Third option is to cut one end of a spare USB cable, and solder the 4 wires inside the cable directly to the corresponding pads on the bottom of the broken socket. Add some glue to provide some strain-relieve to the cable.

Fourth option is an external USB to serial converter, like @Majenko suggested.
> 1 votes

# Answer
I would suggest to actually remove the whole thing and resolder it. There are many tutorials out there is you're new to soldering. This way, it is less probable that it creates a short or data loss during compilation.

If you don't want to solder, then you might be able to use an FTDI connector. FT232s are quite cheap.

Tx \> Rx

Rx \> Tx

Reset \> Reset

Vcc \> Vcc

GND \> GND
> 1 votes

---
Tags: arduino-uno, usb
---


# Question
Title: The best signal source for a path-finding robot
Newbe question - I'm thinking of creating a simple robot that heads to a signal source.

Ie, when you press a button on some remote control - the robot will head towards its source.

What would be the best choice of signal? A strength of a wifi, sound?

AD

# Answer
> 1 votes
IR sensor in combination with an ultrasonic distance sensor would work great.

You can mimic a radar with an IR sensor so that it can detect from where the IR source from your remote is comming from. Then from there, process the angles and make you robot go towards it.

The ultrasonic distance sensor can be used a "fail" prevention system. In the sense that if it detects an object in front of the robot, it will stop, go around it and then continue towards the target

# Answer
> 1 votes
I like @Canadiancyborg's IR solution, but the same theory can be applied to any other emitter, and RF emitters may be preferable to an IR emitter since IR light can be blocked by intermediate objects. Also an omnidirectional RF transmitter is easier to arrange than an omnidirectional IR transmitter.

The basic theory is that you need to work out which direction a signal is coming from. In order to do that you need to "look around you" and find at which angle the signal is strongest.

A highly directional receiver (parabolic dish, IR receiver with lens, etc) will allow you to sense the signal strongest when the receiver is pointing directly at the source. By then rotating the receiver (either on its own independent rotational system, such as a servo motor, or by rotating the entire robot using the wheels) you can "lock on" to the direction where the signal is strongest and drive towards it.

---
Tags: robotics
---


# Question
Title: Arduino Uno Wifi Module ESP8266 AT Command Test error
When i Connected Rx\>Rx (Rx Of module To Pin 0 Of Arduino) And Tx\>Tx ( Tx Of Module To Pin 1 Of Arduino), The AT Command Test shows The Following error With Scrambled Words, but when I Connect Rx\>Tx (Rx Of Module To Pin 1 Of Arduino) And Tx\>Rx(Tx Of Module To Pin 0 Of The arduino), The AT Command Test Shows a Blank Screen. I Connected VCC, CHPD and RST Of Module to 3v Of Arduino and GND Of Module To GND Of Arduino. So How Do I Connect Arduino To Wifi Module which passes the at command test, Btw i Have an Intermediate, ie Motor Shield, I Connected Motor Sheild To Arduino And Then I connected Wifi Module To Motor Shield. Listen So I need To Connect Wifi Module To Arduino, such that there isnt any error. what do i do?

# Answer
> 2 votes
The first connection you made between arduino and esp which resulted in some random data means both are communicating whereas the second connection where the screen shows blank means communication hasnt been established on account of incorrect wiring. So your first connection tx\>tx and rx\>rx is **correct**.

The only two area which you need to check is the baud rate and the mode of return. Some Esps work at 115200 with mode carriage return. So you can try different combinations of baud rate and mode to check which one does your Esp support.

---
Tags: arduino-uno, esp8266, wifi, interrupt, testing
---


title: Attiny85 code on Attiny84

text:
# Question
Title: Attiny85 code on Attiny84
I made OLED timer/watch using Attiny85, but as internal clock isnt accurate i need external crystal. On Attiny85 im short on pins so i am switching to Attiny84 but i have problems to compile/upload same code to Attiny84. Even if i stay on Attiny84 8mhz internal clock as on Attiny85 i still cant compile. Im using Arduino UNO as ISP.

Error what i have:

```
WDT_Time.cpp: In function 'void setup_watchdog(uint8_t)':
WDT_Time.cpp:272: error: 'WDTCR' was not declared in this scope
WDTCR |= (1 << WDCE) | (1 << WDE);
^
In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\io.h:99:0,
             from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\avr\pgmspace.h:88,
             from C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:28,
             from WDT_Time.cpp:12:
WDT_Time.cpp:276: error: 'PCIE' was not declared in this scope
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
              ^
WDT_Time.cpp:276:3: note: in expansion of macro 'sbi'
   sbi(GIMSK, PCIE); // Turn on Pin Change interrupts (Tell Attiny85 we want to use pin change interrupts (can be any pin))
   ^
WDT_Time.cpp:277: error: 'PCMSK' was not declared in this scope
   sbi(PCMSK, PCINT3);
       ^
WDT_Time.cpp:277:3: note: in expansion of macro 'sbi'
   sbi(PCMSK, PCINT3);
   ^
'WDTCR' was not declared in this scope

```

# Answer
> 5 votes
There are slight differences between registers, register names and registers bit names:

* `WDTCR` is named `WDTCSR`
* `PCIE` doesn't exist in `GIMSK` as there are two IO ports, so there are two pin change channels: `PCIE0` and `PCIE1`
* and `PCMSK` is similar to `PCIE`. There'll be two of them too.

Basically you have to look into both datasheets and compare what you are using and check if it's correct.

---
Tags: arduino-uno, timers, attiny
---


# Question
Title: Help managing the fallout from timer0 mode and prescaler change on ATMega2560 without modifying wiring.c
For a driving application I need the PWM mode to be phase correct and the prescaler to be 1. The issue is that the board I am working with has the load hooked up to a PWM pin reliant on timer0. The firmware running on this board makes use of the `delay()`, `delayMicroseconds()`, and `millis()` functions from wiring.c. The goal is to make the timer0 change, shown below, and then make small modifications where the firmware calls the wiring.c timing functions. My approach was to find a scaling factor to be applied to the call of these functions. The scaling factor I came to was **32.12549**, calculated by taking the wiring.c expected timer0 behavior: **prescaler=64** and **TOV0 flag every 256 counts**, and comparing it to the actual values after my change: **prescaler=1** and **TOV0 flag every 510 counts**

**Calculation:** 64\*256/510=32.12549

**Timer0 change:**

```
// Set timer0 to phase correct PWM
TCCR0A = TCCR0A & 0b11111100 | 0x01;

// Set prescaler for timer0 to 1
TCCR0B = TCCR0B & 0b11111000 | 0x01;

```

The other timers are all configured in phase correct PWM mode, with a prescaler of 1.

...When I apply this scaling factor to a value returned from millis() to keep time it works well. For example the two pieces of code below proved to be equivalent through the timer0 change:

**Use of `millis()` before timer0 change:**

```
//current time
long unsigned now = millis();

//delay for 1 second
while(millis() - now < 1000){}

```

**Use of `millis()` after timer0 change:**

```
//current time
long unsigned now = millis();

//delay for 1 second, with x32.125 scaling coefficient
while(millis() - now < 32125){}

```

**The two snippets of code above both delayed for 1 second**

Now comes the problem: when I try to apply that same scaling factor to `delay()` or `delayMicroseconds()` it seems to give unreasonable delays...

**Use of `delayMicroseconds()` before timer0 change:**

```
// wait 1.5ms for mux to switch
delayMicroseconds(1500);

```

...this delays for 1.5ms

**Use of `delayMicroseconds()` after timer0 change:**

```
// wait 1.5ms for mux to switch, with x32.125 scaling coefficient
delayMicroseconds(48188);

```

...this delays for ~20ms.

Assuming this is still linearly scalable: if 48188 -\> 20ms, therefore 1.5ms -\> 3614

But when the following code is used...

```
// wait 1.5ms for mux to switch, scaled
delayMicroseconds(3614);

```

...this delays for ~4.5ms

Why is it that `delayMicroseconds()` and `delay()` cannot be linearly scaled to account for a timer0 change? Furthermore, is there any simple modification to how these functions are called or utilized that can account for the effect of changing timer0?

# Answer
## The millis() roll over

By making Timer 0 faster, your `millis()` will roll over much more often than normal: every 37.1 hours instead of every 49.7 days. Thus, when you “scale” `millis()`, you should be careful to do it in a rollover-safe way. From the code you show, it appears that you are doing *exactly the right thing*. Well done! Don't change anything. Don't be tempted to scale the value returned by `millis()`.

## The overflow in delayMicroseconds()

As this function just burns cycles in a busy loop, it is not affected by your configuration of Timer 0. You can just use it as is, with no scaling. Beware however that it's argument should always be smaller than 16384 (on a 16 MHz board). Otherwise it will overflow when it is multiplied by 4 in order to get a loop count.

For example, when you call `delayMicroseconds(48188);`, the function computes the number of loop iterations to make as

48188 × 4 − 5 = 61675 (modulo 216)

Then, it burns about 15 ms of CPU time (0.25 µs per iteration), which is close to the 20 ms you see. For the difference, see below.

## The cycles burned by the Timer 0 ISR

This ISR, which keeps the millis() counter updated, is supposed to run every 1024 µs. Each time it runs it burns a few cycles, but it's usually not a big deal. With your new timer configuration, it is now running far more often: every 31.875 µs.

From the numbers you give in the question, I would say the ISR is eating about 20% of your CPU power: when you call `delayMicroseconds(3614);`, that function burns 3614 µs of CPU time, yet you measure a delay of about 4500 µs. The difference is taken by the Timer 0 ISR.

## Use another timer for millis()

If you can spare a timer, you could both restore the normal behavior of `millis()` and avoid wasting so much CPU in the Timer 0 ISR:

* configure Timer 0 to *not* trigger interrupts
* configure your spare timer just like the Arduino core would normally configure Timer 0
* write an overflow ISR for your spare timer that just calls the Timer 0 overflow ISR.

This way your spare timer is basically replacing Timer 0. Example using Timer 2:

```
// This Timer 2 overflow ISR simply forwards the call to the Timer 0
// overflow ISR from Arduino core.
ISR(TIMER0_OVF_vect);
ISR(TIMER2_OVF_vect, ISR_NAKED) {
    TIMER0_OVF_vect();
    asm volatile("reti");

    // Alternatively, just:
    // asm volatile("jmp __vector_16");
}

void setup()
{
    // Set timer0 to phase correct PWM
    TCCR0A = (TCCR0A & 0b11111100) | 0x01;

    // Set prescaler for timer0 to 1
    TCCR0B = (TCCR0B & 0b11111000) | 0x01;

    // Disable Timer 0 interrupts.
    TIMSK0 = 0;

    // Configure Timer 2 to replace Timer 0.
    TCCR2A = _BV(WGM20)   // fast PWM, TOP = 0xff
           | _BV(WGM21);  // ditto
    TCCR2B = _BV(CS22);   // clock at F_CPU / 64
    TIMSK2 = _BV(TOIE2);  // enable overflow interrupt

    pinMode(LED_BUILTIN, OUTPUT);
}

void loop()
{
    // Blink the LED at 1 Hz.
    uint32_t now = millis();
    static uint32_t last_toggle;
    if (now - last_toggle >= 500) {
        last_toggle += 500;
        digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    }
}

```

I wrote a “naked” ISR to avoid having plenty of CPU registers saved and restored *twice* (once by each ISR in the call chain), but then I had to put the return instruction explicitly in assembly (`ret` and `reti` would be equivalent in this instance). The version with `jmp` is slightly more efficient, but you have to know the “real” name of the ISR, which is MCU-dependent (`__vector_16` on an Uno).

Notice that with this technique `micros()` will not work, as it reads TCNT0 directly. And `delay()` will not work either because it relies on `micros()`.
> 2 votes

---
Tags: pwm, timers
---


title: How to represent -1 as a byte

text:
# Question
Title: How to represent -1 as a byte
I want to initialize the value of byte to -1. When I just use `byte num = -1` the value ends up being a decimal 255. I've also tried `int8_t number = -1` and then `byte num = number` but this didn't work either.

# Answer
> 6 votes
A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.

Depending on the range of your numbers you could use a `char` (-128 to +127) or an `int` (-32768 to +32767).

# Answer
> 4 votes
Simply -1 can't be a byte. A byte is a number from 0-255. -1 is below 0. The Arduino reference defines a byte as "A byte stores an 8-bit unsigned number, from 0 to 255.".

# Answer
> -1 votes
As the other two users have already mentioned: A byte can only store a number between 0-255, which obviously means that -1 can't be stores as a byte.

I suggest storing it as a positive number, and then when you want to use it just multiply it by -1, which will turn it into a negative one.

***Example to convert positive number as a byte to a negative number:***

```
    negativeNumber = positiveNumberStoredAsByte * -1

```

---
Tags: arduino-uno
---


# Question
Title: Serial loop stopped after a while, I don't know why
I am very new to Arduino. I wrote a program in order to read some registers in a I2C device. I receive HEX datas.

So the Arduino LEONARDO is connected to the external board using the 2-wires-bus. Then informations are sent to my computer by using Serial.println.

My problem is my Arduino stops working after a while, maybe 25 or 30 loops. Sometimes I loose communication and I have to reboot the Arduino.

I guess it's an overflow issue or I'm loosing connection randomly :

```
int dt = 500;
int dt2 = 1000; // used for delay duration
#include "Wire.h"
#include <Process.h>
#define pot_address 0x25 // each I2C object has a unique bus address, the MCP40

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

}

void loop() {
  // put your main code here, to run repeatedly:

  Wire.beginTransmission(pot_address);
  Wire.write(0); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
  byte b = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(1); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte c = Wire.read();

   Wire.beginTransmission(pot_address);
  Wire.write(2); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte d = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(3); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte e = Wire.read();

  Wire.beginTransmission(pot_address);
  Wire.write(4); //
   Wire.endTransmission();
  Wire.requestFrom(pot_address,8);
 byte f = Wire.read();

  Serial.print("b");
  Serial.println(b, HEX);
  Serial.println("-");
  Serial.print("c");
  Serial.println(c, HEX);
  Serial.println("-");
  Serial.print("d");
  Serial.println(d, HEX);
  Serial.println("-");
  Serial.print("e");
  Serial.println(e, HEX);
  Serial.println("-");
  Serial.print("f");
  Serial.println(f, HEX);
  Serial.println("-");

 delay(dt2);

}

```

# Answer
Add:

```
while(!Serial) ;

```

I'll make sure the Leonardo is in sync with the Serial communication.

It is the case because the Leonardo is USB native thus the Serial communication works differently.
> 1 votes

---
Tags: serial
---


title: Use photocell as digital input

text:
# Question
Title: Use photocell as digital input
I need to use multiple photocells as input, but its more than the amount of analog pins that my arduino has.

I'm wondering if theres any way to use a photocell as a digital input, with the photocell triggering at a specific set threshold of light.

It doesn't seem quite possible but I thought I'd ask.

# Answer
**Yes**, you can use LDRs(photocells) as an indirect digital input.

You can design a **voltage divider circuit**, which incorporates your LDR and gives LOW or HIGH digital readings based on your **pre-calibrated threshold light values**.

Your voltage divider circuit must reach a specific voltage for your wanted light threshold to give you a HIGH reading.

---

The following are the voltage thresholds guaranteed to be read as HIGH.

> When a pin is configured as an INPUT with pinMode(), and read with digitalRead(), the Arduino (Atmega) will report HIGH if:
>
> ```
> a voltage greater than 3 volts is present at the pin (5V boards);
> a voltage greater than 2 volts is present at the pin (3.3V boards);
>
> ```

Source of Quote
> 1 votes

# Answer
I see two possible options for achieving what you want:

## Voltage divider

This is the solution proposed by William Roy: you make a voltage divider circuit and check whether it gives a voltage above the threshold of the digital input. For example:

```
+5V ---+
       |
       R
       |
       +--- digital input
       |
      LDR
       |
GND ---+

```

There are a couple of issues with this approach though:

1. Every digital input is fitted with a Schmitt trigger which makes it hysteretic, meaning the voltage threshold for switching from `LOW` to `HIGH` is higher than the threshold for switching from `HIGH` to `LOW`. If the pin voltage is between the two thresholds, it will read either `HIGH` or `LOW`, as determined by the history of that voltage. Depending on your application, this may not be a problem, and may even be desirable. But if you want, as you wrote in your question, “a specific set threshold of light”, it sure will be problematic.
2. You do not know what those threshold voltages are. The datasheet of the ATmega328P (the main chip of the Uno) states that they should “typically” be around 2.1 and 2.6 V, but it only guarantees that the low threshold should be no less than 1.5 V and the high threshold no more than 3 V. For any input voltage between 1.5 and 3 V (which is a very significant range), the chip manufacturer doesn't guarantee what the pin will read.

The first issue can be solved by using a write-before-read protocol: first you set the pin to OUTPUT LOW, which will force the input Schmitt trigger to the LOW state. Then you set it to INPUT and take a reading. This way you will read HIGH if *and only if* the pin voltage is above the high threshold. The low threshold becomes irrelevant. Example code:

```
/*
 * Read the given pin avoiding the input hysteresis.
 *
 * Returns HIGH if the pin voltage is above the upper (LOW to HIGH)
 * threshold, LOW otherwise.
 *
 * WARNING: The pin is set to OUTPUT LOW for a very short time.
 */
int anhystereticRead(uint8_t pin) {
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    pinMode(pin, INPUT);
    return digitalRead(pin);
}

```

The second point can be solved by calibrating your input using a trimpot instead of a resistor. You would adjust the pot until the threshold is exactly what you want. Using fixed resistors instead of a pot will make it very difficult to achieve your “specific set threshold of light”, unless you can live with a very rough precision.

## Capacitive measurement

The second option is use the LDR as the resistor in an RC circuit, and measure the charging time of the circuit, like this:

```
digital output --- LDR ---+--- digital input
                          |
                      capacitor
                          |
                         GND

```

Starting with a discharged capacitor, you set the output to `HIGH` and measure how long it takes for the input to read `HIGH`. This time is typically something like 0.73 *R* *C*, where *R* is the resistance of the LDR and *C* the capacitance of the capacitor. The exact numerical factor is not know, as it depends on the high threshold voltage of the digital pin.

For details and example code, you could check the Capacitance Meter and RC Time Constants Arduino tutorial, or search the Web for “Arduino capacitance meter”. You will find material about how to measure an unknown capacitance using a know resistance, but you can use the same technique to measure an unknown resistance using a known capacitance. And you should replace the waiting loop:

```
while (analogRead(input) < THRESHOLD) {}  // wait

```

by a similar loop using the digital input threshold:

```
while (digitalRead(input) == LOW) {}  // wait

```

The interesting thing about this technique is that you do not need a trimpot to set the illuminance threshold: you will *measure* the charging time and set the threshold in software. Also, this technique is not affected by the input hysteresis. The main drawback is that the measurement takes longer than the voltage divider technique.

**Edit**: I found a blog post describing this exact method in greater detail: Measuring resistance or voltage with 1 digital I/O, by Moser.
> 1 votes

# Answer
**LDR in a Wheatstone bridge + OpAmp as a comparator**

For more (temperature...) stability of your LDR threshold it could be better to use a wheatstone bridge instead of a simple voltage divider.

Then you can send the output of your wheatstone (or your divider) to a simple OpAmp comparator circuit that will output High or Low, which you can plug in any digital port.

To know more on Wheatstone and OpAmp: (you can use directly the last schema by plugging the output of the Opamp to the digital pin of your arduino (instead of sending it to the transistor)

http://www.electronics-tutorials.ws/blog/wheatstone-bridge.html

Hope that can help,

Gaetan

---
> 0 votes

---
Tags: arduino-uno, digital-analog-conversion
---


title: Amplified piezo sensor wiring problem

text:
# Question
Title: Amplified piezo sensor wiring problem
I am trying to amplify the signal from an Adafruit Small enclosed piezo. The piezo is working using the Arduino Knock example but I want to increase the sensitivity using an amplifier. The wiring shown below does not work using the Knock sketch and I am assuming it is a problem with the wetware and the wiring(NOOB here). Any advice in amplifying the piezo is appreciated.

# Answer
> 1 votes
You don't seem to understand how to wire an OP-AMP. Here is a quick tutorial on their basics:

https://www.youtube.com/watch?v=kqCV-HGJc6A

The thing is that you are missing a LOT of resistors. An usual OP-AMP circuit contains many resistors to determine the amount of amplification and more...

The tutorial explains quite well what resistor and where do you need to put them in order for your circuit.

---
Tags: arduino-uno, analog-sampling, piezo
---


# Question
Title: Cast from uint8_t* to char - loses precision
I am trying to decode a received (via websocket) message (JSON) on my ESP8266.

The websocket library provides the data as uint8\_t. The JSON library only understands char arrays. As far as I know uint8\_t is basically char.

**I am getting this error:** cast from 'uint8\_t\* {aka unsigned char\*}' to 'char' loses precision \[-fpermissive\]

The websocket-function provides the payload as uint8\_t:

```
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length)

```

The JSON Decoder wants a char arr, as provides in the sample:

```
char json[] =
"{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}";

```

**How to "convert" the uint8\_t to char\[\]?**

Here is my full code:

```
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <WebSocketsServer.h>

WebSocketsServer webSocket = WebSocketsServer(81);
StaticJsonBuffer<200> jsonBuffer;

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

    switch(type) {
        case WStype_DISCONNECTED:
            Serial.printf("[%u] Disconnected!\n", num);
            break;
        case WStype_CONNECTED:
            {
                IPAddress ip = webSocket.remoteIP(num);
                Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

        // send message to client
        webSocket.sendTXT(num, "Connected");
            }
            break;
        case WStype_TEXT:
        {
            Serial.printf("[%u] get Text: %s\n", num, payload);
            JsonObject& root = jsonBuffer.parseObject((char)payload);
            // send message to client
            // webSocket.sendTXT(num, "message here");

            // send data to all connected clients
            // webSocket.broadcastTXT("message here");
        }
            break;
        case WStype_BIN:
            Serial.printf("[%u] get binary length: %u\n", num, length);
            hexdump(payload, length);

            // send message to client
            // webSocket.sendBIN(num, payload, length);
            break;
    }

}

void setup()
{
  Serial.begin(115200);
  Serial.println();
  IPAddress ip(192, 168, 178, 51);
  IPAddress gateway(192, 168, 178, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  WiFi.begin("MyWifi!", "passpasspass");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
  webSocket.begin();
  webSocket.onEvent(webSocketEvent);
}

void loop() {
   webSocket.loop();
  }

```

# Answer
Well, you are trying to cast `pointer to uint8_t` to one character, so it warns you about that. If you cast it to `pointer to char`, it should work:

```
JsonObject& root = jsonBuffer.parseObject((char *)payload);

```
> 1 votes

---
Tags: esp8266
---


title: avr-gcc -D is ignored

text:
# Question
Title: avr-gcc -D is ignored
Im trying to use XCode to compile avr program with arduino libs but seems like something wrong with my Makefile because it throws me warnings like

```
# warning "F_CPU not defined for <util/delay.h>"

```

but I use -D on CC and CXX which should define stuff I thought, here is my Makefile:

```
TARGET              = firmware
MCU                 = atmega32u4
F_CPU               = 16000000L
USB_VID             = 0x2a03
USB_PID             = 0x8036
USB_PRODUCT         = "USB Device"
USB_MANUFACTURER    = "Unknown"
ARDUINO_VERSION     = 107010

CC   =
CXX  = avr-g++
AR   = avr-ar
COPY = avr-objcopy
SIZE = avr-size
DUDE = avrdude

CFLAGS = -c -g -Os -w -ffunction-sections -fdata-sections -MMD -mmcu=$(MCU) -DF_CPU=$(F_CPU) -DARDUINO=$(ARDUINO_VERSION) -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=$(USB_VID) -DUSB_PID=$(USB_PID) -DUSB_MANUFACTURER=$(USB_MANUFACTURER) -DUSB_PRODUCT=$(USB_PRODUCT)

CXXFLAGS = -c -g -Os -w -fno-exceptions -fno-threadsafe-statics -MMD -mmcu=$(MCU) -DF_CPU=$(F_CPU) -DARDUINO=$(ARDUINO_VERSION) -DARDUINO_AVR_LEONARDO -DARDUINO_ARCH_AVR -DUSB_VID=$(USB_VID) -DUSB_PID=$(USB_PID) -DUSB_MANUFACTURER=$(USB_MANUFACTURER) -DUSB_PRODUCT=$(USB_PRODUCT)
all: compile

compile:

    $(shell $(CXX) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo src/program.cpp -o build/program.cpp.o)

    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/hooks.c -o build/hooks.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/WInterrupts.c -o build/WInterrupts.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring.c -o build/wiring.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_analog.c -o build/wiring_analog.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_digital.c -o build/wiring_digital.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_pulse.c -o build/wiring_pulse.c.o)
    $(shell $(CC) $(CFLAGS) -I arduino -I arduino/variants/leonardo arduino/wiring_shift.c -o build/wiring_shift.c.o)

    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/abi.cpp -o build/abi.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/CDC.cpp -o build/CDC.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial.cpp -o build/HardwareSerial.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial0.cpp -o build/HardwareSerial0.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial1.cpp -o build/HardwareSerial1.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial2.cpp -o build/HardwareSerial2.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HardwareSerial3.cpp -o build/HardwareSerial3.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/HID.cpp -o build/HID.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/IPAddress.cpp -o build/IPAddress.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/main.cpp -o build/main.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/new.cpp -o build/new.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Print.cpp -o build/Print.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Stream.cpp -o build/Stream.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/Tone.cpp -o build/Tone.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/USBCore.cpp -o build/USBCore.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/WMath.cpp -o build/WMath.cpp.o)
    $(shell $(CPP) $(CPPFLAGS) -I arduino -I arduino/variants/leonardo arduino/WString.cpp -o build/WString.cpp.o)

    $(shell $(AR) rcs build/core.a build/hooks.c.o)
    $(shell $(AR) rcs build/core.a build/WInterrupts.c.o)
    $(shell $(AR) rcs build/core.a build/wiring.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_analog.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_digital.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_pulse.c.o)
    $(shell $(AR) rcs build/core.a build/wiring_shift.c.o)
    $(shell $(AR) rcs build/core.a build/abi.cpp.o)
    $(shell $(AR) rcs build/core.a build/CDC.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial0.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial1.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial2.cpp.o)
    $(shell $(AR) rcs build/core.a build/HardwareSerial3.cpp.o)
    $(shell $(AR) rcs build/core.a build/HID.cpp.o)
    $(shell $(AR) rcs build/core.a build/IPAddress.cpp.o)
    $(shell $(AR) rcs build/core.a build/main.cpp.o)
    $(shell $(AR) rcs build/core.a build/new.cpp.o)
    $(shell $(AR) rcs build/core.a build/Print.cpp.o)
    $(shell $(AR) rcs build/core.a build/Stream.cpp.o)
    $(shell $(AR) rcs build/core.a build/Tone.cpp.o)
    $(shell $(AR) rcs build/core.a build/USBCore.cpp.o)
    $(shell $(AR) rcs build/core.a build/WMath.cpp.o)
    $(shell $(AR) rcs build/core.a build/WString.cpp.o)

    $(shell $(CC) -w -Os -Wl,--gc-sections -mmcu=$(MCU) -o build/program.cpp.elf build/program.cpp.o build/core.a -Lbuild -lm)

    $(shell $(COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 build/program.cpp.elf build/program.cpp.eep)
    $(shell $(COPY) -O ihex -R .eeprom build/program.cpp.elf build/program.cpp.hex)

$(TARGET).bin: compile

    $(shell $(COPY) -O binary build/program.cpp.elf $(TARGET).bin)

clean:

```

# Answer
You are using `$(CPPFLAGS)` for `*.cpp` files but only `$(CXXFLAGS)` are defined.

This should be obvious from command line (if you enable showing executed commands for `make`)

And also:

* `CC =`
* using `$(CPP)` again only `$(CXX)` is defined

And don't forget Makefile needs tabs for indenting target commands (here you have four spaces, but it might be just replaced by SE)
> 2 votes

---
Tags: avr, compile, avr-toolchain, command-line, avr-gcc
---


# Question
Title: keypad storing problem any idea store more than 11 numbers like phone number
```
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>

SoftwareSerial mySerial(6,5);
int table[]={0,0,0};

#include <Keypad.h>
#include <Wire.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
const byte ROWS = 4; //four rows
const byte COLS = 3; //three columns

char keys[ROWS][COLS] = {
    {'1','2','3'},
    {'4','5','6'},
    {'7','8','9'},
    {'*','0','#'}
};
byte rowPins[ROWS] = {2, 3, 17, 16}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {15, 14, 13}; //connect to the column pinouts of the keypad
int count=0;
Keypad kpd = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
char entryStr[13];   // This can hold up to 4 digits
int i=0;
***char n1, n2 , n3;
char buf [15] ;// i put here***

void setup()
{
    Wire.begin();
    mySerial.begin(9600);
    Serial.begin(9600);
    lcd.begin(20, 4);
    ask();
}

void loop()
{
    Wire.requestFrom(2, 3);    // request 6 bytes from slave device #2
    for (int i = 0; i < 3; i++)
    {
        int c = Wire.read(); // receive a byte as character
        Serial.print(c);
        table[i] = c;
        Serial.print('\t');
        // print the character
    }
    Serial.print('\n');
    Serial.print(table[0]);
    Serial.print('\t');
    Serial.print(table[1]);
    Serial.print('\t');
    Serial.print(table[2]);
    Serial.print('\n');

    //if(table[0]<=8)
    //{
    //Serial.print("Flame Detected!");
    //Serial.println("Level1");
}

void ask()
{
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no1.:");
    lcd.setCursor(0,1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n1 = GetNumber(buf, sizeof (buf) - 1);

    Serial.print(n1);

    delay(1);

    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Enter no2.:");
    lcd.setCursor(0, 1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1, 2);
    n2 = GetNumber(buf, sizeof (buf) - 1);

    Serial.println(n2);
    delay(1);
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Enter no3.:");
    lcd.setCursor(0,1);
    lcd.print("(starts with 0)");
    lcd.setCursor(1,2);
    n3 = GetNumber(buf, sizeof (buf) - 1);

    Serial.println (n3);
    delay(1);
    Serial.println (n1);
    Serial.println (n2);
    Serial.println (n3);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("list of numbers ");
    lcd.setCursor(0, 1);
    lcd.print("will be shown press");
    lcd.setCursor(1, 2);
    lcd.print("reset if wrong");

    delay(7000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("Numbers Stored:");
    lcd.setCursor(0, 1);
    lcd.print("no1.:0");
    lcd.print(n1);
    lcd.setCursor(1, 2);
    lcd.print("no2.:0");
    lcd.print(n2);
    lcd.setCursor(2, 3);
    lcd.print("no3.:0");
    lcd.print(n3);
}

void GetNumber(char * result, const int maxLength)
{
    char key = kpd.getKey();
    int i = 0;   // how far through buffer we are
    while (key != '#')
    {
        switch (key)
        {
            case NO_KEY:
                break;

            case '0': case '1': case '2': case '3': case '4':
            case '5': case '6': case '7': case '8': case '9':
                lcd.print(key);
                if (i < maxLength)
                {
                    result [i++] = key;
                    result [i] = 0;  // terminating null
                }
                break;

            case '*':  // backspace
                if (i > 0)
                {
                    i--;
                    result [i] = 0;  // terminating null
                }
                break;
        }

        key = kpd.getKey();
    }
} // end of GetNumber

```

I changed it..it gave me this error

# Answer
> ```
>  long GetNumber()
>
> ```

A `long` type (on this platform) can go up to 2^31 (that is 2,147,483,648). Large 10-digit numbers (ie. starting with "9") will not fit.

You could work with a 10-character string (or longer) instead of a long.

---

Make GetNumber deal with strings, like this:

```
void GetNumber(char * result, const int maxLength)
{
  char key = kpd.getKey();
  int i = 0;   // how far through buffer we are
  while (key != '#')
  {
    switch (key)
    {
      case NO_KEY:
        break;

      case '0' ... '9':
        lcd.print(key);
        if (i < maxLength)
          {
          result [i++] = key;
          result [i] = 0;  // terminating null
          }
        break;

      case '*':  // backspace
        if (i > 0)
          {
          i--;
          result [i] = 0;  // terminating null
          }

        break;
    }

    key = kpd.getKey();
  }
} // end of GetNumber

```

---

Now, to call GetNumber supply a char buffer and the maximum length (allowing for the 0x00 needed to terminate a string), like this:

```
  char buf [15];
  GetNumber (buf, sizeof (buf) - 1);

```
> 1 votes

# Answer
Use a string or a char. They store their numbers a character per character and not a huge number. A long can hold a max of around 2 000 000 000.

For example, 123 declared as an lon would be litteraly, mathematicly 123 (as 100 + 20 + 3). On the other side, a char will consider it as 1,2,3. It can store higher digits number.
> 0 votes

---
Tags: arduino-ide
---


# Question
Title: Interfacing key-pad with arduino with 7 segment display
I have the following components:

* Arduino Mega
* 7-segment display
* 12-digit key-pad

For my project, I would like to display on the 7-segment display the number that the user presses on the keypad.

# Answer
Try this: please note that you have to fill in the last function in order to get an int value from your keypad. The 7-segments part of the code should be fine.

```
const int segment[7] = {2,3,4,5,6,7,8}; //pins for each segment

const int nums[10][7] = //declaring array
{
  {1,1,1,1,1,1,0}, //0
  {0,1,1,0,0,0,0}, //1
  {1,1,0,1,0,0,1}, //2
  {1,1,1,1,0,0,1}, //3
  {0,1,1,0,0,1,1}, //4
  {1,0,1,1,0,1,1}, //5
  {1,0,1,1,1,1,1}, //6
  {1,1,1,0,0,0,0}, //7
  {1,1,1,1,1,1,1}, //8
  {1,1,1,0,0,1,1}  //9
};

void setup() {
  for(int i=2; i<=8; i++) //shorcut for declaring a buch of pin modes
  {
    pinMode(i, OUTPUT);
  }
}

//=======================================================================

void loop() {
  number(keypadInput);
}

//=======================================================================

void number(int num) //num is the number to display
{
  for(int i=0; i<7; i++)
  {
    digitalWrite(segment[i], nums[num][i]);
  }
}

int (keypadInput)
{
  //code for getting the input of your keypad
}

```
> 1 votes

---
Tags: arduino-mega, keyboard, 7-segment
---