# Question
Title: Voltage divider arduino 5v and Ethernet board 3.3
I have an `Arduino Nano 5v` module and I just received an Ethernet Interface Board - `ENC28J60` that runs at `3.3v`. (https://www.sparkfun.com/products/765)

Might sound a dumb question but I will power the Ethernet board from a Voltage regulator that can deliver 3.3v but then I have to connect via `SPI` to my Arduino controller. I guess I can't connect my Arduino pins directly to the Ethernet board right? because HIGH in the pin will be 5v instead of 3.3v.

> Do I need to add a Voltage divider for those pins connections? And in case I need to what resistance values are the right ones to use?

Thanks

# Answer
From experience with 3.3v ESP8266es with 5v Arduinos, only the signals *to* the 3.3v device need to be converted (5v high -\> 3.3v high). A 3.3v level *to* the Arduino is high enough for 5v logic to still read it as HIGH. That means you can get away with just a voltage divider on each of the Arduino -\> ENC28J60 pins.
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Disable Reset when Com Port Connected/Disconnected
I've noticed that when I open and close the com port my Arduino is connected to, the device resets. This makes the program run the setup profile again and it loses the previous variable states. Is there any way to prevent this?

# Answer
If you review the Uno schematic, you can see the circuitry that enables an automatic reset when serial communication starts. The circuitry is intended to allow easy program downloading.

There are two or three ways to prevent that reset: add a 10 μF capacitor from ground to reset; use a much-lower resistance for the pullup on reset; cut a trace from the serial-interface pin (eg CTS) that pulls reset.

The first method is relatively easy to implement, and easy to remove whenever you want to install a new program.

References: Disabling AutoReset On SerialConnection and ArduinoISP on Uno requires 10uF cap -- WHY?, both at Arduino.cc.
> 6 votes

---
Tags: arduino-uno, reset
---


title: Adding null character to char array

text:
# Question
Title: Adding null character to char array
I have this code written and functioning that will write out the chars in `cmd` to a serial port for an input of ASCII text representing byte values.

```
void SendCTRL (String &input)
{
  //Adjust Data
  const char *hin = input.c_str();    // Get character array
  int clen = input.length()/2;
  unsigned char cmd[clen+1]; // Leave a byte for null terminator
  for (int i=0; i < 2*clen; i+=2)
  {
    cmd[i/2] = dehex(hin[i])<<4 | dehex(hin[i+1]);
  }

  //Send Data
  cmd[clen] = 0;                     // Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  for (int i=0; i< clen; i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

```

As the majority of the byte values fed are constant, I'm trying to create similar output for the following code when I feed the function below only the byte values that change frequently:

```
void Create_Message(int Address, int Data)
{
  //Adjust Data
  Address--;
  byte SvAdd = 1;
  byte FuCode = 6;
  byte AddHi = Address>>8;
  byte AddLo = Address;
  byte DatHi = Data>>8;
  byte DatLo = Data;
  byte AdDa[] = {SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo};
  unsigned int crc=CRC(AdDa,sizeof(AdDa)/sizeof(AdDa[0]));
  byte CrcHi = crc & 0xFF;
  byte CrcLo = crc >> 8;
  /*U8 Slave Address, U8, Function Code, U16 Address, U16 Data, U16 CRC
  * to
  *[U8 Address Split High, U8 Address Split Low, U8 Data Split High, U8 Data Split Low, U8 Function Code]
  */

  //Send Data
  unsigned char cmd[9]={SvAdd,FuCode,AddHi,AddLo,DatHi,DatLo,CrcHi,CrcLo};
  cmd[8]=0; //Null-byte terminator
  digitalWrite(SSerialTxControl, RS485Transmit);  // Enable RS485 Transmit
  lcd.setCursor(0, 1);
  for (int i=0; i< sizeof(cmd)/sizeof(cmd[0]); i++)
  {
    RS485Serial.write(cmd[i]);   // Send string someplace
  }
  digitalWrite(SSerialTxControl, RS485Receive);  // Disable RS485 Transmit
}

```

I'm reading the Values written by RS485.write() and, in both cases, the data is good. However, for the 2nd section of code, the Arduino seems to write out the null-byte while it does not write the byte out in the 1st block. If I remove the allocation for the null-byte in the second code, it does not get a response from my device.

I'm guessing that the issue is that I am not setting my null-byte terminator correctly or otherwise missing something (I'm pretty new here XD )

**Update: it seems like using `sizeof(cmd)/sizeof(cmd[0])` to determine the send length interfered with data transmission when I set this to a constant the code works just fine.**

# Answer
In the second code example, the value of `sizeof(cmd)/sizeof(cmd[0])` is 9, due to the declaration `unsigned char cmd[9] ...`

Thus, the `for` loop will write out 9 bytes, with indices 0, 1, ... 8. Due to `cmd[8]=0;` earlier in the code, the last byte will be zero. To prevent that, one might instead use the expression `sizeof(cmd)/sizeof(cmd[0])-1` in the `for` loop:

```
for (int i=0; i< sizeof(cmd)/sizeof(cmd[0])-1; i++)
   RS485Serial.write(cmd[i]);

```

Note, this doesn't explain why it should be so that “If I remove the allocation for the null-byte in the second code, it does not get a response from my device”, although practically anything can happen if you say `cmd[8]=0;` after allocating only 8 bytes of storage.
> 1 votes

# Answer
In addition to James's answer, to print (or send) a null terminated string you do not have to know the length of the string. Just print the characters till you find the null. So this code works better.

```
for (int i=0; cmd[i] != 0; i++)
{
    RS485Serial.write(cmd[i]);   // Send string someplace
}

//or

int i=0;
while(cmd[i] != 0)
{
    RS485Serial.write(cmd[i++]);   // Send string someplace
}

```
> 0 votes

---
Tags: arduino-uno, communication, softwareserial
---


title: Error in IR receiver project

text:
# Question
Title: Error in IR receiver project
I'm trying to receive remote information with an IR receiver and this is my code:

```
#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
}

void loop() {
  if (irrecv.decode(&results)) {
    Serial.println(results.value, HEX);
    irrecv.resume(); // Receive the next value
  }
  delay(100);
}

```

I tried to upload this to Arduino and it says:

```
exit status 1
redefinition of 'int RECV_PIN'

```

How can I fix this?

# Answer
Apparently the name `RECV_PIN` is used somewhere else, presumably in `IRRemote.h` -- although not in any version of it I can find. Anyway, just change the name of `RECV_PIN` to something which doesn't conflict.

For example:

```
int MY_RECV_PIN = 11;
IRrecv irrecv(MY_RECV_PIN);

```
> 2 votes

---
Tags: arduino-uno, arduino-ide, ir, code-optimization, ch340
---


# Question
Title: I want to build a radar alert system with Arduino
I'm new to all this. I bought an Arduino Uno recently and an Ultrasonic distance sensor. My mom's cats keep walking down into the basement and doing their... business. Anyhow, I want to create a radar system which detects movement past this door. I'd like to have an alert sent to my computer or Android. Is this within a basic Arduino level? Other than the Arduino what else might I need?

# Answer
> 2 votes
I think that's quite possible. As mentioned, not technically radar. I don't know if cats could hear it, but then if it scares them off, job done, right?

I don't know if sending the alert to a PC would help or not - you might just consider an audible alarm using a cheap 8-ohm speaker. Otherwise, USB, bluetooth, wifi, or SMS for notification. A PC or phone (on all the time) to receive the data. Some thought about what you will do with it.

As a deterrent, a water pistol is ideal, you'd need a motor - solenoid? - to fire the water pistol. Harmless, but very distasteful to cats.

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

Update: Inspired by @SDSolar, I checked it out - yes, cats can hear that frequency.

> Cats have excellent hearing and can detect an extremely broad range of frequencies. They can hear higher-pitched sounds than humans or most dogs, detecting frequencies from 55 Hz up to 79 kHz.

(from https://en.wikipedia.org/wiki/Hearing\_range#Cats )

This means they will probably learn to associate the sound with the water pistol (yes, cats CAN be trained, if they are motivated). This means if you remove your device, they will probably come back, but if you leave the sensor (active), but remove the water, then it will continue to work!

# Answer
> 2 votes
I'm not convinced an ultrasound detector will detect a cat. They're fluffy and (usually) soft, so the ultrasound might not bounce off.

Instead I suggest you just try a gadget that annoys cats and keeps them out of the area. It's an ultrasound emitter, and the noise is **claimed** to be objectionable to cats. I've seen them sold in gardening stores, for keeping cats away from the bird table:

Opinions on cat scarers

# Answer
> 2 votes
Ultrasonic sensors can only measure the distance to the nearest object in their cone. Are you sure you can detect a "small" thing like a cat?

I think the only feasable way is to use optical recognition (motion sensor with a camera - even a webcam - and a board like a raspberry pi).

# Answer
> 1 votes
As a project building a cat detector sounds interesting, but as a cat owner I can promise you that if you actually go through with it the cats will see it, play with it and trash it within 5 minutes. If it is successful and you do manage to scare them out of the basement they are just going to find somewhere else to 'do their business' and that could be in your bed.

However, your sensor will need to scan a large field of potentially rapidly moving objects. A beam wouldn't be suitable because they could step over or under it. I think PIR would be best for this task, but PIR sensors might not be sensitive enough to detect the little darlings.

Another idea maybe a gas sensor based project to provide an audible warning when a human enters the area that there are 'landmines' in the proximity and extreme caution needs to be used, if you know what I mean :)

# Answer
> 1 votes
ANSWER BASED ON YOUR TITLE:

Here is a microwave RADAR motion-sensing module that you might find useful. You could mount it right by the stairs.

http://www.ebay.com/itm/262662221979

LFS-DC04 2.7GHz Microwave Radar Module DC 5V 360 Degree High Level Signal New

## Product Introduction:

```
1.Model:LFS-DC04
2.Frequency:2.7GHz
3.Size:40*22mm
4.Input Voltage:DC 5V
5.Output Type:level signal output
6.Connection Method:VCC,GND connect with positive negative input, OUT,GND signal connect with output
7.Installation Height:1-3.5m
8.Sensing Ditance:5-8m
9.Delay Time:30s(quick testing mode is 4s)
10.Sensing Angle:360 degree
11.$1.59 price via the slow boat

```

---

ANSWER BASED ON YOUR TEXT:

Ultrasonic can work - you will want to position it so your software can tell whether there is a cat/no cat, like pointing it across a step. With no cat it would give a reliable distance reading from something on the other side of the step. With the cat in the way, that reading would change.

Yes, this is in the realm of Arduino, for sure.

Here is a Google search to get you started:

https://www.google.com/search?q=arduino+with+ultrasonic+sensor

To tell the difference between a cat an a human you would want a second sensor, above the cat's height, also.

Or you could use a DS3231 RTC module to decide when it is night-time so you wouldn't need to discriminate between cats and people at all.

# Answer
> 1 votes
Or there's an off-the-shelf solution: Innotek ssscat is a bottle of compressed air and a motion detector. The spray is harmless but it sounds like a hiss, which is Cat for GTFOuttaHere!

---
Tags: arduino-uno, sensors, project
---


# Question
Title: fatal error: avr/io.h: No such file or directory
I'm compiling a project on Due that was working correclty using UNO. I get this error : **'avr/io.h: No such file or directory'**. Searching across the web, it seams I'm not the only one to get that error when using Arduino Due but didn't clearly figured out why it appears.

Of course, the file is present where it should be, I verified ..\Arduino\hardware\tools\avr\avr\include\avr\io.h

I opened it and see something like that :

```
...

#if defined (__AVR_AT94K__)
#  include <avr/ioat94k.h>
#elif defined (__AVR_AT43USB320__)
#  include <avr/io43u32x.h>
#elif defined (__AVR_AT43USB355__)
#  include <avr/io43u35x.h>
#elif defined (__AVR_AT76C711__)
#  include <avr/io76c711.h>
#elif defined (__AVR_AT86RF401__)
#  include <avr/io86r401.h>
#elif defined (__AVR_AT90PWM1__)
#  include <avr/io90pwm1.h>
#elif defined (__AVR_AT90PWM2__)
#  include <avr/io90pwmx.h>
#elif defined (__AVR_AT90PWM2B__)
#  include <avr/io90pwm2b.h>
#elif defined (__AVR_AT90PWM3__)
#  include <avr/io90pwmx.h>
#elif defined (__AVR_AT90PWM3B__)
#  include <avr/io90pwm3b.h>
#elif defined (__AVR_AT90PWM216__)
#  include <avr/io90pwm216.h>
#elif defined (__AVR_AT90PWM316__)
#  include <avr/io90pwm316.h>
#elif defined (__AVR_AT90PWM161__)
#  include <avr/io90pwm161.h>
#elif defined (__AVR_AT90PWM81__)
#  include <avr/io90pwm81.h>

...

```

so I suppose that a line referring to my card is missing or something like that ?

I'm using Arduino 1.6.12

# Answer
> 4 votes
The Due is SAM architecture. avr/io.h is specific to the AVR architecture of the Uno's microcontroller. The compiler will not look in the avr tools folder for that file and even if it did it wouldn't help because that file is not compatible with the SAM architecture.

This error indicates that part of the code you're attempting to compile (probably a library) is AVR specific. You will need to either port that code to the SAM architecture or find an alternative that is already compatible with Due.

---
Tags: arduino-due, compile
---


title: What's wrong with my code?

text:
# Question
Title: What's wrong with my code?
I was trying to do a LED display that turns on a LED at pin 13 that goes on then turns off after a delay then the next pin (which is pin 12 counting down) will turn on and then turn off.

I also put in a potentiometer that can change the delay to make it faster or slower.

Here's the code:

```
float pinOn = 13;
int outMin = 0;
int outMax = 13;
float delayNum = 1000;

void setup () {
  for (int i=outMin; i<=outMax; i++) {
  pinMode(i, OUTPUT); }
  Serial.begin(9600);
}

void loop () {
  // Reads Potentiometer -- sets delay relative to the Potentiometer input
  int sensorValue = analogRead(A0);
  delayNum = sensorValue;
  // Turns on the Pin designated by 'pinOn'
  digitalWrite(pinOn, HIGH);
  delay(delayNum);
  digitalWrite(pinOn, LOW);
  // Checks if 'pinOn' is 0 which then resets it back to 13 if not 0 then counts down
  if (pinOn = 0) {
    pinOn + 13;
  } else {
    pinOn - 1;
  }
}

```

All it does is turn on pin 13 for a moment then permanently turns on pin 1 and 0 and it gets stuck like that.

# Answer
> 2 votes
`if (pinOn = 0)` is doing an assignment (single =) not a comparison (double ==), so `pinOn` is begin set to `0` each time through the loop. The result of an assignment is the value being assigned. So it's the same as `if ( 0 )`, which is false.

Now, on to the two branches. `pinOn + 13` is a statement and the result is not being assigned to anything. You need an equals sign somewhere:

```
if (pinOn == 0) { // == means "is equal to"
  pinOn += 13; // same as pinOn = pinOn + 13
}
else {
  pinOn -= 1;
}

```

---
Tags: arduino-uno
---


# Question
Title: I want to make a counter but i don't know what i'm missing or am doing wrong
this is the code i made but it gives me an error about te } and also i need to know how to make delays with this

```
int ledPin = 4;
int buttonPin=2;
int buttonState = 0;         // variable for reading the pushbutton status

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

void loop()
{
  if (buttonPin=(LOW);
 {
 Serial.println("someone pressed it");
}
  else
  {
    Serial.println("nothing");
  }
}

```

thanks for helping!

# Answer
> 1 votes
You forgot bracket here

```
if (buttonPin=(LOW);

```

Should be

```
if (digitalRead(buttonPin)==(LOW)){

```

To make a delay of 0.5 seconds for example:

```
delay(500);

```

---
Tags: button
---


# Question
Title: analogRead seems to freeze some seconds the program
I have the following code that reads a `RFID` reader, it was working perfect without any dealy and then I try to an analog read from a potentiometer using `analogRead`.

The analog read works fine but then when I hover the card over the `RFID` it takes about 7 seconds or so to go into the line where I turn on a `LED`.

Im sure Im doing something wrong with `analogReader` because this is the first time I use it.

> I really appreciate any help

```
    #include <MicroView.h>

    MicroViewWidget *widget;        // create widget pointer

    #define MAX_BITS 100                 // max number of bits
    #define WEIGAND_WAIT_TIME  3000      // time to wait for another weigand pulse.

    unsigned char databits[MAX_BITS];    // stores all of the data bits
    unsigned char bitCount;              // number of bits currently captured
    unsigned char flagDone;              // goes low when data is currently being captured
    unsigned int weigand_counter;        // countdown until we assume there are no more bits

    unsigned long facilityCode=0;        // decoded facility code
    unsigned long cardCode=0;            // decoded card code

    int sensorPin = A1;    // select the input pin for the potentiometer
    int sensorValue = 0;  // variable to store the value coming from the sensor

    // interrupt that happens when INTO goes low (0 bit)
    void ISR_INT0()
    {

      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;

    }

    // interrupt that happens when INT1 goes low (1 bit)
    void ISR_INT1()
    {

      databits[bitCount] = 1;
      bitCount++;
      flagDone = 0;
      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void setup()
    {

      pinMode(2, INPUT_PULLUP);     // DATA0 (INT0)
      pinMode(3, INPUT_PULLUP);     // DATA1 (INT1)
      pinMode(5, OUTPUT);           // LED

      Serial.begin(9600);

      // binds the ISR functions to the falling edge of INTO and INT1
      attachInterrupt(0, ISR_INT0, FALLING);
      attachInterrupt(1, ISR_INT1, FALLING);

      digitalWrite(sensorPin, HIGH);      // Internal Pull-up
      pinMode(sensorPin, INPUT);          // make pin as INPUT

      uView.begin();                      // start MicroView
      uView.clear(PAGE);                  // clear page
       uView.setCursor(5,0);
      uView.print("TEST");
       uView.setCursor(0,20);
       uView.print("RFID READ");
      widget = new MicroViewSlider(0, 35, 0, 1024);    // make widget as Slider
      //widget2 = new MicroViewSlider(0, 20, 0, 1024, WIDGETSTYLE1);    // make widget as Silder STYLE1
      uView.display();                    // display the content in the screen buffer

      weigand_counter = WEIGAND_WAIT_TIME;
    }

    void loop()
    {

      // This waits to make sure that there have been no more data pulses before processing data
      if (!flagDone) {
        if (--weigand_counter == 0)
          flagDone = 1;
      }

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//
      sensorValue = analogRead(sensorPin);    // read sensorPin
      widget->setValue(sensorValue);          // set value of sensorPin to widget
      //widget2->setValue(sensorValue);         // set value of sensorPin to widget
      uView.display();

//****** THIS IS THE NEW CODE THAT FREEZE FOR ABOUT 7 SECONDS THE PROGRAM ***//

      // if we have bits and we the weigand counter went out
      if (bitCount > 0 && flagDone) {
        unsigned char i;

        Serial.print("Read ");
        Serial.print(bitCount);
        Serial.print(" bits. ");

        if (bitCount == 32){

          // **** AFTER 7 SECONDS I GET INTO THIS CODE ****///

          uView.clear(PAGE);      // clear the page buffer
          uView.setCursor(0,0);

          digitalWrite(5, HIGH);

        }

         // cleanup and get ready for the next card
         bitCount = 0;
         facilityCode = 0;
         cardCode = 0;
         for (i=0; i<MAX_BITS; i++)
         {
           databits[i] = 0;
         }
      }
    }

```

# Answer
> 1 votes
`analogRead()` is fine, it takes only about 110 µs, but there are several other issues with your code that you should fix:

1. Any variable that is shared between interrupt code and normal code should be declared `volatile` in order to prevent the compiler to do some unsafe optimizations.
2. Any such variable that is more than one byte in size should be accessed from the main program with interrupts disabled.
3. You should take care of not writing into `databits[]` past the end of the array.
4. Counting loop iterations is a very bad way of measuring elapsed time, as the counting speed will change whenever you change your loop code. Use `micros()` instead.

There is also an issue with how you use `flagDone`. You set it to 1, then you call `analogRead()`, `MicroViewSlider::setValue()` and `uView.display()`, then you read it back. What if your ISR has set it back to 0 in the meantime? I suspect this is the main cause of the problem you see.

I suggest you use `flagDone` to inhibit the ISRs: the main loop sets it to `true` to tell the ISRs “Let's say we are done with this card. Please do not touch anything while I process the already received information.” And later it sets it to `false` meaning “You can proceed reading bits now.”

Given the above considerations, I would try something along these lines:

```
volatile bool flagDone;     // if we are done, pause the reading
volatile uint8_t bitCount;  // number of bits received so far
volatile uint32_t rxTime;   // last time we got a bit

// Interrupt that happens when INTO goes low (0 bit).
void ISR_INT0()
{
    if (!flagDone && bitCount < MAX_BITS) {
        rxTime = micros();
        databits[bitCount++] = 0;
    }
}

// Same thing, but writes 1 instead of 0 into databits[].
void ISR_INT0() { ... }

void loop()
{
    // Safely read rxTime.
    noInterrupts();
    uint32_t rxTimeCopy = rxTime;
    interrupts();

    if (bitCount > 0 && micros() - rxTimeCopy >= WEIGAND_WAIT_TIME) {
        // Assume we are done reading this card.
        flagDone = true;

        // Do whatever with databits[].
        // ...

        // Get ready for the next card.
        bitCount = 0;
        flagDone = false;  // do this last: it re-enables the ISR
    }
}

```

---
Tags: arduino-uno, analogread
---


title: TLS Client ESP8266

text:
# Question
Title: TLS Client ESP8266
My ESP8266 collects data and sends it to a webserver over HTTP. I would like to use TLS for this but I cannot figure out how to get ESP8266 running on the Arduino framework to use this.

My curent code is based on `ESP8266HTTPClient` and when searching the ESP8266 pages on GitHub 50% of the information tells me that it's impossible to use HTTPS and the other half of the info tells me it's possible but not documented with `WiFiClientSecure` but that looks like a whole different way of communicating HTTP..

Link: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/WiFiClientSecure.h

```
void senddata() {
  String testdata = "{\"tickle\": {\"id\": " + String (package.id) + ",\"value1\": " + String (package.value1) + ",\"value2\": " + String (package.value2) + "}}";
  Serial.println("Starting the journey to Salador..");
  http.begin("https://myserver/_db/Salador/upload");
  http.addHeader("Content-Type", "application/json");
  int httpCode = http.POST(testdata);
  if(httpCode > 0) {
      Serial.println("[HTTP] POST... code: ");
      Serial.println(httpCode);

  }
  else {
      Serial.println("[HTTP] POST... failed, error: ");
      Serial.println(http.errorToString(httpCode));
  }
  http.end();
}

```

# Answer
> 1 votes
I don't think you can easily mix the HTTP wrapper and the WiFiClientSecure. At the moment if you want to do HTTPS you have to do the HTTP portion of the transaction manually by sending the individual headers and then the body, then parsing the response yourself.

It's not that hard, and the example you point to shows you how it can be done - print the headers and body to the client, then read the data back looking for specific things (like a blank line to separate headers from body, etc).

---

Although: I do see this clue in the BasicHttpClient.ino example:

```
// configure traged server and url
//http.begin("https://192.168.1.12/test.html", "7a 9c f4 db 40 d3 62 5a 6e 21 bc 5c cc 66 c8 3e a1 45 59 38"); //HTTPS

```

So maybe if you know the fingerprint of your HTTPS server you can connect directly with HTTPS. How you get that fingerprint though is not something I know yet.

---
Tags: esp8266, http
---


# Question
Title: can I give the 9v input power for arduino mega 2560 using vin pin?
I am using Arduino mega 2560. I have some doubts about powering my microcontroller. Can I use the 9v battery to power my arduino through the VIN terminal? I have uploaded an image. Check whether it is a correct method or not?

# Answer
> 3 votes
Yes!

> The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may become unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.
>
> The power pins are as follows:
> \- Vin. The input voltage to the board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.

https://www.arduino.cc/en/Main/ArduinoBoardMega2560

Vin is the same as the external positive power input.

---
Tags: arduino-mega
---


# Question
Title: Running out of pins in a 4x7-segment display clock
I've been playing around with the 7-segment displays and so far I've only been able to make 1 working display hooked up to a potentiometer that changes the number on the display with a switch that turns it into a counting-up timer

My main goal is to make a Clock but that uses 4 7-segment displays and I've already used up 7 pins for 1 display so now I either need to make more pins (I'm using Arduino Uno which has 14 Digital pins + 6 if you use the Analog In pins) or use the 7-segment decoders

if I use the 7 segment decoder that will take up 4 per display which totals up to 16 which is well in range the required amount of Pins

so can someone teach me what is easier to do:

Making more pins using the 8-bit shift registers or Use the 7-segment decoders to make space

and if you think one is easier can you tell me how to use them because I have no idea and I've been tinkering with the decoder for the past hour or two (btw the 7-segment displays are all Common Anode)

# Answer
> 2 votes
The basic idea is this:

First, connect segment A of each display together, and all the segment Bs together, and all the segment Cs and so on. Each "group" is driven by one pin on the Arduino. For this you will need seven pins.

Your displays will have either a common anode or common cathode - perhaps you have that connected straight to +5v or straight to ground currently. Instead, you connect the "common" pin from each display to a spare pin on your Arduino - so using another four pins.

Remember the resistors too.

Now, you can light up any segment on any display, by setting the appropriate segment pin and the appropriate common pin to the right values.

Make sense?

---
Tags: arduino-uno
---


# Question
Title: What is the best way/module to talk to an Arduino from far away (WIFI)?
I am new to Arduino and IoT. I plan to build a product that I will connect to an app and they have to be able to communicate from a very far distance (kilometers).

Bluetooth is not a good option then (because the distance is too far). So would Wifi work? I read something about a module called esp8266 that might be what I am searching for.

# Answer
> 0 votes
Esp8266 range is about 400m. So if you have your mobile within 400m then you may be able to communicate. But for long distance communication I would not prefer but if you have any Internet connection available nearby esp then you may be able to transmit your messages via it. Well for long distance communication I would prefer you to use any GSM shield in which you need to plug in a sim card and it can be used upto when you have coverage in that area.

# Answer
> 1 votes
The simplest option is to use GSM for the communication. Range isn't an issue, since point A isn't communicating with point B, instead point A and point B are both communicating via third party communication subsystem C which has a much greater coverage than anything you could build yourself.

I use GSM modules for communication with agricultural monitoring and control systems at remote locations. It works well, and you're pretty much guaranteed to have a signal.

For those times when GSM isn't a possibility (no signal, or the customer doesn't want the subscription cost) you really need *line of sight* between the two locations. Then you can use a highly directional antenna (e.g., parabolic dish or Yagi array) to extend any other suitable wireless communication signal over a long range (WiFi can reach tens of kilometres with parabolic dishes) and there are companies that specialise in that kind of equipment (such as this one that claims 8 mile range \- of course you need two of them, one for each end of the link). Of course, with some skill and determination it's possible to get incredibly long distances from WiFi. Not for your average user though...

# Answer
> 0 votes
**LoRa** is apparently the most popular low-speed, low-power, wide-area network at the moment.

Many people use LoRa for direct point-to-point links around a kilometer. Other people use LoRa for "last mile" wireless links as part of a **LoRaWAN** to some gateway hard-wired to the internet, much like a Wifi access point -- except trading off data rates in order to get longer wireless range than WiFi.

details:

---
Tags: bluetooth, wifi, wireless
---


title: Grab keys from an ordinary USB keyboard

text:
# Question
Title: Grab keys from an ordinary USB keyboard
**Arduino USB**

I want to write an Arduino Sketch (if there is no other possibility it can also be plain c) , to grab keyboard inputs from my ordinary USB keyboard. Preferably without expensive hardware, but as mentioned, if there is no other possibility, this will do it too.

Is this possible with V-USB? I looked a their website, but it seems like this only supports being slave and to imitate a keyboard.

# Answer
As suggested in the comments, you have two options:

As suggested by Majenko, you can use the Arduino USB Host Shield:

Alternatively you could use a PS2 keyboard instead (as suggested by Gerben). Arduino already has a library to handle PS2 keyboards, so the implementation of it would be easy. For reference (and example program) playground.arduino.cc/Main/PS2Keyboard

If you do not have access to a PS2 keyboard or just want to use a USB keyboard, Gerben further suggests that most USB keyboards can be converted to PS2 keyboards with an adapter:

The keyboard must be able to support both formats (USB & PS2).

The following webpage shows the connections needed to go from USB to PS2: USB to PS/2 adapter pinout
> 3 votes

# Answer
I am able to use this library: https://github.com/techpaul/PS2KeyAdvanced and USB's data +/- connected to pins 2+3 of an arduino to read keys on standard keyboards.

```
keyboard.begin( 3, 2); // D3= data+, D2= data-

```

A standard keyboard is one which doesn't need a driver to work on any computer. I'd tried several libraries, serial keyboard adapters, and ps2/usb converters, and this method works best. Since the ps2-USB converter is just a physical pin change with no logic, standard USB keyboards just magically with with the PS2 libraries; even caps lock and what not...
> 2 votes

---
Tags: usb, atmega328, datalogging, keyboard
---


title: More than 500 pins

text:
# Question
Title: More than 500 pins
For a project I need 400-1000 pins controlled by one arduino. Each pin should work similar as arduino pin, so something like 5V, 90mA. Is using dozens of shift registers a good idea? And what power source should I connect? My idea is following:

So one shift register requires 3 input pins to control it, and if one shift register has 12 output pins, I can connect 4 more shift registers to one shift register. Is it a good idea and will it work?

# Answer
> 4 votes
You don't connect shift registers as a tree. That would be awfully slow. Instead, you connect them as chains. Shift registers are meant to be chained by connecting the serial out of one register to the serial in of the next one, while both registers share the latch and clock lines. You can chain as many as you want this way: a chain of four 8-bit shift registers behaves like a single 32-bit shift register. See for example this Arduino tutorial on the 595 to see how the chaining works.

There is an issue, however, in making long chains: whenever you want to change the state of one single output you have to shift the whole chain again. And the longer the chain the longer it takes. Thus it is more efficient to put in a single chain outputs that you will likely want to change together, and use independent chains for outputs that are most likely going to change at different times.

As for the wiring, you need three Arduino pins to drive one chain of registers: data, clock and latch. But you can share the data and latch pins between many chains, as long as you have a dedicated clock pin for each chain. You should then be able to drive *n* independent chains using *n* \+ 2 Arduino outputs.

As for the power, you have to estimate your power consumption (not just the shift registers, but also whatever *they* are sourcing current into) and find a 5 V power supply big enough to power your whole circuit.

# Answer
> 0 votes
Here is a whole different approach.

Look at how they built the motion-controlled coffee table:

http://www.evilmadscientist.com/?s=LED+coffee+table

It has hundreds and hundreds of connections, so they subdivided the board so they could have distributed Arduinos.

So it is possible to control that many pins, and it may be best to use multiple Arduinos.

---
Tags: pins, shift-register
---


# Question
Title: Are there any advantages to Wifi shields as opposed to a Yun?
I have an Arduino Uno and I have a remote sensing project for which I need Wifi connectivity. After doing research, I've found that I have 2 options:

1. Buy a WiFi shield for my existing Uno
2. Buy an Arduino Yun with built-in WiFi

Looking at costs, I found that a WiFi shield costs more than double what it costs to buy a Yun, so it would seem to me that the best option is the Yun as I'd save some cash and get a more capable board. However, I can't help but think I'm missing something.

What are the advantages of an Uno plus Wifi shield as opposed to a Yun?

# Answer
> 4 votes
There's a number of things to consider that could sway your choice one way or another:

# Power consumption

The Uno is a small low-power chip to which you add WiFi. The Yun is an Arduino Leonardo with a WiFi router (like you have on your desk) strapped to the back of it. The Yun will therefore consume considerably more power than the Uno.

# Boot time

The Uno takes about 1 second to boot up - faster (instant) if you remove the bootloader and program it direct with a programmer. The Yun takes minutes to boot.

# Stability

The Uno is a solid state single item. The Yun has an entire operating system with filesystems and things. It's far more likely that the Yun will corrupt itself through power loss than an Uno will get struck by a stray neutrino.

# Cost

Yes, the Yun is cheaper. But is cheap always good?

# Remote-ability

The Yun can be completely reprogrammed remotely. A new sketch can be uploaded to the Leonardo portion of it without you even having to be in the same country. The same can't be said for the Uno.

# Power

The Linux portion of the Yun is considerably more powerful than any normal Arduino.

# Answer
> 1 votes
First of all yun is not the same as uno + wifi shield. yun is more like a linux pcc with wifi and a lenoardo.
If you are asking for your options there are more options. For what you want I would go for a ESP8266. Again there are 2 options here:

* uno + ESP8266 (as a wifi shield)
* ESP8266 (as a dev board)

I think it is pretty obvious that the ESP8266 (as a dev board) is the most cost effective.
You can program the ESP8266 just like a uno in the arduino IDE.
So I would advice to take that board.

# Answer
> 0 votes
There aren't just two options.

There are also Dragino and Iduino Yun shields, which are (usually) slightly cheaper than an Arduino Yun. These can be plugged into Leonardo/Uno base boards.

Whereas an Uno or Leonardo requires about 6-7v from the power supply, a Yun shield requires 9-12v (due to the Atheros chip drawing a bit extra).

There is also the Tian, which is the Yun's successor (but at higher cost).

If you're willing to look further afield than Arduino only, you might want to consider a BeagleBone Black (which works out slightly cheaper in terms of cost/feature).

---
Tags: arduino-uno, shields, wifi, arduino-yun
---


title: P I D AND GY80 10 DOF

text:
# Question
Title: P I D AND GY80 10 DOF
I am running the program for GY80 10 DOF , and runs fine . Date is printed on the serial monitor How ever I have failed to use this program for my WalkerBot (walker bot is a Robotic suit that I want to build for 4 years old my grand son He can not walk due to C P ) Unless the PID is not introduced in the program it will not be good for Balancing of the walker Both the program is as under , and my further questions are in comments I need help Please I tried to use the Code Control to insert the codes But it did not work , I may be excused for that Please

the codes

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

     GY80 sensor = GY80(); //create GY80 instance

  void setup()
  {
    // initialize serial communication at 115200 bits per second:
    Serial.begin(115200);
    sensor.begin();       //initialize sensors
  }

     // How to envelop this program with PID
     // where the gyro output is supposed to maintain the vertical position of the //bot , and the accelerometer will be doing countermeasure of tilts
// unless they both are on a feedback with PID this bot will not balance
//as the servomotors if do not respond in runtime the bot will fall
void loop()
{
    GY80_scaled val = sensor.read_scaled();       //get values from all sensors
    // print out values

    Serial.print("Mag:");                         //magnetometer values
    Serial.print(val.m_x,2);
    Serial.print(',');
    Serial.print(val.m_y,2);
// tried to get some output from here for using in PID but failed
if(val.m_y,2 >2 ||val.m_y,2<0){Serial.print("Output has been managed");}
but there was no output
    Serial.print(',');
    Serial.print(val.m_z,2);
    Serial.print(' ');
    Serial.print("Acc:");                         //accelerometer values
    Serial.print(val.a_x,3);
    Serial.print(',');
    Serial.print(val.a_y,3);
    Serial.print(',');
    Serial.print(val.a_z,3);
    Serial.print(' ');
    Serial.print("Gyro:");                        //gyroscope values
    Serial.print(val.g_x,1);
    Serial.print(',');
    Serial.print(val.g_y,1);
    Serial.print(',');
    Serial.print(val.g_z,1);
    Serial.print(' ');
    Serial.print("P:");                           //pressure values
    Serial.print(val.p,5);
    Serial.print(' ');
    Serial.print("T:");                           //temperature values
    Serial.println(val.t,1);

    delay(250);        // delay in between reads for stability
}

```

# Answer
I am sorry, but I may not have understood your post, but I think the problem is your code doesn't work and you don't know why. I think the problem is with this line:

```
if(val.m_y,2 >2 ||val.m_y,2<0){

```

It is because it is not valid code, I suspect its a cut and paste error and should be

```
if(val.m_y > 2.0 || val.m_y < 0.0){

```

the `,2` you use in the print statements specifies the number of digits to print after the decimal point (I think).
> 1 votes

---
Tags: robotics, pid
---


# Question
Title: How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?
I have been trying to generate a PWM wave of 38 Khz (13 microsec= ON period , 13 microsec= OFF period). Currently I am using Timer 0 to generate the PWM wave , however i am confused as to how to prescale the 16Mhz input clock frequency so that i can get 38 Khz from it .

The code is as follows -

```
#include<avr/io.h>
#include<util/delay.h>

uint8_t  dutycycle;
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        DDRG |= (1<<PG5);

        // Clear o/p on Match and Fast PWM Mode
        TCCR0A |=(1<<COM0A1) | (1<<WGM01) | (1<<WGM00) | (1<<COM0B1);// COM0A1/0b1 are the ouput ports , and WGM01 and WGM02 are used for fast PWM mode
        TCCR0B |=(1<<WGM02) | (1<<CS01);//WGM02 is used to set the fast pwm mode with max value stored in OCRA. CS01 is used to prescale the clock frequency to 16Mhz % 8 .
        OCR0A = 52;

}
void dutycycleA(uint8_t dutycycle)
{
    OCR0B = (dutycycle * 52)/100 ;
}
int main()
{
        pwm_init();

        while(1)
        {
            dutycycle=50;
            dutycycleA(dutycycle);
            _delay_ms(1000);
        }
}

```

So , the code is supposed to keep checking the value of OCR0B with the timer value and if it is less than that , then the output is logic HIGH , and if it is same as the timer value , then it'll be logic LOW . the duty cycle is given as 50 so that a pulse waveform of 50% duty cycle is reached .

However I am unable to obtain 38Khz output .

Please help me figure out where I have gone wrong and also suggest corrections to my approach , if wrong .

Thank you .

PS - I am using Eclipse Neon platform.

# Answer
> 1 votes
~~It appears that you didn't set any Clock Select bits. Per datasheet,~~

~~clkT0 can be generated from an external or internal clock source, selected by the Clock Select bits (CS02:0). When no clock source is selected (CS02:0 = 0) the timer is stopped.
~~

~~That could account for getting no output at all, if that's what's happening.~~  \[I had overlooked `(1<<CS01)` in your TCCR0B setup.\]

You have the COM0A1 and COM0B1 bits set, and you apparently assume COM0A0 and COM0B0 are clear. (Note that in the code below, I say `TCCR1A = ...` and `TCCR1B = ...` instead of using `|=`, because `|=` is not reasonable to use for initial setup). In the #7 fast PWM mode that you selected via WGM bits, this would lead to OC0A and OC0B clearing on their respective Compare Matches and setting at BOTTOM, which looks more or less ok for the OC0B pin, if you have OCR0B set to about half of OCR0A. If the OC0A pin clears, however, it probably gets set again a cycle later, if I understand correctly. (However, I'd want to actually test the code, with oscilloscope connected, to say for sure.)

Note that the OCR0A count of 52 and prescaler of 8 will set up a counting frequency of 1600000/(52+1)/8 Hz, ie about 37735.85 Hz, while a count of 51 would give 38461.54 Hz. If accuracy matters, you can use simpler and more accurate code like the following. It uses a prescale of 1 and count of 209, to generate a toggle frequency of 1600000/(219+1) Hz, ie about 76190.48 Hz, and a square wave frequency of about 38095.24 Hz. Note, this code is written for timer 1; it should be straightforward to adapt to timer 0, because 209 is less than 255, the upper limit of TCNT0.

```
// Generate a constant frequency on PB1, using Fast PWM - jw May 2017
enum { OC1Apin = 9 };    // Arduino digital pin #9 = OC1A = PB1

void setup() {  // Set up timer 1
  noInterrupts();               // Turn off interrupts during setting
  TIMSK1 = 0;                   // Turn off timer 1 interrupts
  // Set timer 1 to Fast Pwm mode with OC1A (dig pin 9) toggling
  TCNT1 = 0;                    // Zero the counter
  TCCR1A = 1<<WGM11 | 1<<WGM10  // for Fast Pwm with TOP from OCR1A
    | 1<<COM1A0;                // To toggle OC1A PB1 D9 on Compare Match
  TCCR1B = 1<<WGM13 | 1<<WGM12// for Fast Pwm with TOP from OCR1A
    | 1;                      // Start timer 1 with prescale 1
  // Set OCR1A *after* setting up TCCR1A & TCCR1B
  OCR1A = 209;                // Gen. about 38095.24 Hz
  pinMode(OC1Apin, OUTPUT);
  interrupts();
}
void loop() {}

```

---

*Edit 1:* Here are some of the differences between this code and that shown in the question, aside from using timer 1 instead of 0:

• Initialization of TCCRxA and TCCRxB registers here is done using *Register = expression* forms, rather than *Register |= expression* forms. Just OR-ing your bits in may be a problem if some other CS bits are set. For example, in the Arduino environment, initialization for `millis()` will set a prescale factor of 64, by setting both of the CS00 and CS01 bits, so that when you say `TCCR0B |=(1<<WGM02) | (1<<CS01);` you end up with both of the CS00 and CS01 bits still set, and a prescale of 64 instead of 8.

`TCCR1B = ... | 1; // Start timer 1 with prescale 1` sets the CS00 bit and leaves the CS01 and CS02 bits clear, selecting prescale 1, while `TCCR0B |= ... | (1<<CS01);` selects a prescale factor greater than 1.

• The code shown here generates a square wave because it toggles a pin at a constant rate. The code in the question sets OCR0B to 26, which will give 27 clock-cycles to half of each output cycle, and 26 clock-cycles to the other half.

• The code shown here generates a frequency of about 38095 Hz, which is about 0.25% high, vs a frequency 0.7% low for the code in the question.

---

*Edit 2:* One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle if appropriate). It can decrement a counter, and shut off an output pin when the counter gets to zero. Or could set the output pin low and the CS bits to 0 to stop the counter. For example, if timer 1 is in use:

```
volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

```

To output a specified number of cycles *n*, set the mode of `TogPin` to `OUTPUT` and set `TogCounter` to *2·n*. Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.

To generate a sequence like *m1* cycles on, *n1* off, *m2* cycles on, *n2* off, etc, you could set up an array containing *m1*, *n1*, *m2*, *n2*, etc; then each time `TogCounter` runs down, toggle `TogPin` from INPUT to OUTPUT or vice versa, and load the next array entry into `TogCounter`.

# Answer
> 0 votes
A few ways to get there. 38khz has a period of 421 ticks on a 16mhz Mcu. So

Approach 1. Use the pwm module to Generate it.

Approach 2. Use the timer overflow interrupt to generate it. Simply flip the output pin in the isr.

Approach 3. Use the compare interrupt to generate it. In the isr increment the compare match register by 120 and then flip the output pin.

All of them are fully supported by your chip. The first approach once set consumes no CPU processing power.

edit: this link, https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/, will hopefully provide some inspiration to you. It is for a different application but the gist of the problem is the same.

here is the output, adopting it to generate a 38Khz (37,679Hz to be exact) pulse train on a user specified pin using timer2 compare ch b interrupt.

i think you will benefit a lot in getting the code going on your own but if you really struggle, I can provide you the code as well. but you get a lot more if you try to get it going on your own.

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


title: Dynamically switching pin out

text:
# Question
Title: Dynamically switching pin out
I have a connector with 10 pins, and a bus which uses 2 of the 10 pins.

What I need to do is, in software, attach my arduino to 2 of the 10 pins. I cannot wire it directly as the 2 pins required may be in a different position in different environments.

What are my options?

**EDIT:** Just some background. I have to connect to an OBD II port of a vehicle and cannot to the CAN bus. On some vehicles is may not be on the standard pins in the OBD connector, so I would like to be able to programatically switch the pins being used, in software.

# Answer
> 1 votes
Probably you need two SP10T switches, where you can programmatically decide which of the SPI pins will be sent to which of the 10 outputs which are connected to the 10 pin bus.

---
Tags: wires, software
---


title: LED sequence control by button

text:
# Question
Title: LED sequence control by button
I want to make sequential LED by using arduino that controlled by button. If I press + button, LED will increase from L1 to (L1 and L2 is HIGH), then I press button again, L1, L2, and L3 will be HIGH. If I press again, all the LED (L1, L2, L3, L4) will be high. Same case if I press “ – “ button, LED will be lower from the previous state. Which mean that if L1, L2, and L3 is HIGH. There will be L1 and L2 only HIGH if I press ‘ – ‘ button. I dont how to do it. This is code for increase but I dont know how to make it reverse flow.

```
const int buttonPin = 2; // the pin number of the pushbutton input pin
int ledPins[] = {3, 4, 5,};
 // variables will change:
 int buttonState = 0; // variable for reading the pushbutton status
 int buttonPressCount = 0;
 int numberOfLED = 3;
 void setup() {
  // initialize the LED pin as an output:
  for (int i = 0; i < numberOfLED; i++) {
   pinMode(ledPins[i], OUTPUT);
  }
  pinMode(buttonPin, INPUT);
 }
 void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
   for (int i = 0; i < numberOfLED; i++) {
    if (buttonPressCount % numberOfLED == i) {
     // turn LED on:
     digitalWrite(ledPins[i], HIGH);
    } else {
     // turn LED off:
     digitalWrite(ledPins[i], LOW);
    }
   }
   buttonPressCount++;
   delay(400);
  }
 }

```

# Answer
> 1 votes
My original answer was probably over-kill....Just keep track of how many leds are lit:

```
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
byte num_leds_lit = 0

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        digitalWrite(ledPins[i], i < num_leds_lit ? HIGH : LOW);
    }
}

```

Then, on button press, increase the count:

```
if (num_leds_lit < num_leds) {
    num_leds_lit += 1;
    set_leds();
}

```

Then to turn the leds off with the other button press:

```
if (num_leds_lit > 0) {
    num_leds_lit -= 1;
    set_leds();
}

```

------------------------- Original answer

There are a few ways to do it. One way would be to use a bitmask. I would write a function to turn the leds on/off

```
// Each bit represents the state of one LED (0 == off, 1 == on)
byte led_bits = 0;
int ledPins[] = {3, 4, 5,};
const int num_leds = sizeof(ledPins) / sizeof(ledPins[0]);  // 3 in this example
// Need a mask to make sure we don't set too many bits
const byte led_mask = 0xFF >> 8 - num_leds;   // 00000111B in this case

void set_leds() {
    for (int i = 0; i < num_leds; i++) {
        // Turn on/off based on state of bit
        digitalWrite(ledPins[i], (1 << i) & led_bits ? HIGH : LOW);
    }
}

```

Then, on button press, set the mask:

```
led_bits << = 1;          // Shift left (001 -> 010)
led_bits |= 1;            // Set lsb    (010 -> 011)
led_bits &= led_mask;     // Ensure max bits: (1111 -> 0111)
set_leds();

```

Then to turn the leds off with the other button press:

```
led_bits >>= 1;          // Shift right (011 -> 001)
set_leds();

```

---
Tags: led
---


title: How to manage dependencies?

text:
# Question
Title: How to manage dependencies?
I want to include a dependency like Logging. On its page it says:

* Download zip file
* Put the Logging folder in "libraries\\".

I don't want to believe (with a Maven mindset) that this is the way we manage dependencies in Arduino projects. That means, everybody who checks out my package would have to repeat those steps locally (or do you include "libraries\\" in the version control) What's the best practice for dependency management?

# Answer
Arduino is meant to be easy way for non-technical people and so it hides as much as it can from plain view to be simple.

For simple project it works at the cost of overhead of copying libraries here and there and using Arduino's "IDE". Calling programs "sketches" and manipulate it to hide, that it is in C++. And so on and so on.

If you want to make more complicated projects, version control, good environment and such, you need to leave "simply Arduino way" and start using more powerful and complicated tools.

I personally use https://github.com/sudar/Arduino-Makefile https://github.com/ladislas/Bare-Arduino-Project and have it in GIT repositories.

This way I can share libraries between projects in group, also links to libraries outside the tree works, as well as gits submodules, both allowing you to have updated libraries from 3rd party aviable to all projects, also those old ones.

I still use a lot of Arduino (like setup/loop, digitalRead and such), but also I use "normal" g++ constructs on the way. Later I will diverge even more to plain C/g++/.. code probably, using some RTOS or so, but now my needs are not so far yet. (google "arduino rtos" I am currently reading https://github.com/greiman/NilRTOS-Arduino )

Arduino is not meant to be "best practice" anyway. It is meant to be "fast and easy way to do something, when you know nothing". And it works, as anybody and his dog can start with Arduino and if interested, he can go more far on his own, or he can stick with easy and have fun anyway.
> 8 votes

# Answer
If you want the project to be self contained you can put the library dependencies in the sketch folder. So the folder structure of the Foo sketch with the Logging library dependency would look something like this:

```
Foo
|_Foo.ino
|_src
  |_Logging
    |_Logging.h
    |_Logging.cpp

```

And in Foo.ino you will include the library like this:

```
#include "src/Logging/Logging.h"

```

Unfortunately some libraries use the incorrect include syntax which still works when the library is installed in one of the libraries folders but not when located in the sketch folder. The Logging library does use the correct include syntax but sometimes to put libraries in the sketch folder you will need to fix this. For example, let's say you have a library named Bar and in Bar.cpp you see this:

```
#include <Bar.h>

```

That won't work because if installed in the sketch folder Bar.h will not be located in one of the standard include paths so you need to edit Bar.cpp and change the include syntax to:

```
#include "Bar.h"

```

Which will cause the local folder to be searched for the included file.

The downside to this system is that you may end up with multiple copies of a library so it's more work to update or modify each copy. Of course that can also be a benefit because each project can have its own known-working version of the library that will not be affected by any updates you may make to the same library used in other projects.

I generally just add instructions for how to install library dependencies in the usual manner to the documentation for a project. That should be within the capabilities of the average Arduino user. If a specific version of a library is necessary then you document that. However, there are cases where I have wanted to hand over a self-contained project to someone who is not familiar with the use of the Arduino IDE and that is when I have used the system described above for all necessary 3rd party libraries.
> 1 votes

---
Tags: library
---


# Question
Title: How do I erase internal EEPROM on a Arduino Pro Mini
I'm working on Arduino pro mini. and I store some data in internal EEPROM.

So, I want to erase certain data from 0x00 to 0x28 address in EEPROM.

```
void loop()
{
 ...
 ...
 if(erase_eeprom_flag==1)
 {
   addr_uu=0;
          erase_eeprom_flag=0;
          for(kk=0;kk<28;kk++)
          {
              EEPROM.update(addr_uu,0);

              addr_uu=addr_uu+1;

          }
          Serial.println("OK");
          Serial.println(addr_uu,DEC);
          addr_uu=0;
      }
  }

```

But I got a data like(28 times '0' and other data 'xxx') "0000000000000000000000000000xxxxxxxxxxxx".

ex : 20170519 ---\> expected data: 00000519 (inappropriate data: 000020170519)

So, here actually push "0" / add at begin operation happen but I want to remove data from those address.

Please tell which Arduino function help me for solving my issue.

# Answer
> 4 votes
You are clearing 28 decimal bytes, but your address range is 28 hex bytes, or 40 bytes of data. Hence, the last 12 characters are untouched.

---
Tags: arduino-pro-mini, eeprom
---


# Question
Title: I need to restart Arduino IDE after each compilations
I'm using the Arduino Due and testing an I2C Scanner, the I2C Scanner works correctly but each time I want to upload a newer version of the code I get this error message :

```
No device found on COM11
Send auto-baud
Set binary mode

```

What I need to do in this case is : remove USB, restart the Arduino IDE, reconnect USB, then it works again, one time...

It seems related to this problem : Serial port on mac only works after restarting arduino IDE

I'm not sure but What's maybe also symptomatic is I need to systematically push the restart Button of my board in order to receive something in the Serial Monitor, could it be related ?

Here is the I2C Scanner code I'm using :

```
// --------------------------------------
// i2c_scanner
//
// Version 1
//    This program (or code that looks like it)
//    can be found in many places.
//    For example on the Arduino.cc forum.
//    The original author is not know.
// Version 2, Juni 2012, Using Arduino 1.0.1
//     Adapted to be as simple as possible by Arduino.cc user Krodal
// Version 3, Feb 26  2013
//    V3 by louarnold
// Version 4, March 3, 2013, Using Arduino 1.0.3
//    by Arduino.cc user Krodal.
//    Changes by louarnold removed.
//    Scanning addresses changed from 0...127 to 1...119,
//    according to the i2c scanner by Nick Gammon
//    http://www.gammon.com.au/forum/?id=10896
// Version 5, March 28, 2013
//    As version 4, but address scans now to 127.
//    A sensor seems to use address 120.
// Version 6, November 27, 2015.
//    Added waiting for the Leonardo serial communication.
//
//
// This sketch tests the standard 7-bit addresses
// Devices with higher bit address might not be seen properly.
//

#include <Wire.h>

void setup()
{
  Wire.begin();

  Serial.begin(9600);
  while (!Serial);             // Leonardo: wait for serial monitor
  Serial.println("\nI2C Scanner");
}

void loop()
{
  byte error, address;
  int nDevices;

  Serial.println("Scanning...");

  nDevices = 0;
  for(address = 1; address < 127; address++ )
  {
    // The i2c_scanner uses the return value of
    // the Write.endTransmisstion to see if
    // a device did acknowledge to the address.
    Wire.beginTransmission(address);
    error = Wire.endTransmission();

    if (error == 0)
    {
      Serial.print("I2C device found at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.print(address,HEX);
      Serial.println("  !");

      nDevices++;
    }
    else if (error==4)
    {
      Serial.print("Unknown error at address 0x");
      if (address<16)
        Serial.print("0");
      Serial.println(address,HEX);
    }
  }
  if (nDevices == 0)
    Serial.println("No I2C devices found\n");
  else
    Serial.println("done\n");

  delay(1000);           // wait 5 seconds for next scan
}

```

# Answer
I finally solved the problem, but it's really specific and I don't know if should be on Stack Exchange. Maybe it could give some clues if someone has a similar problem one day...

I was using pin 20 and 21 on my Arduino Due which are supposed to have built-in pull-up resistor. That's what I've read everywhere and it has been said again recently in the answer of an another question I've asked : How to chooce SDA/SCL pair on Arduino Due ?.

**Solution** : Since I'm using SDA1 / SCL1 with Wire1 everything works like a charm. The value I get from the device are correct, no need anymore to restart the board and I can recompile again and again without any problems.

**Edit** : In fact, it work significantly better but I still had to use pullup resistors with these inputs. The goal was to use the MPU 9250 and it seems more stable now.
> 1 votes

---
Tags: serial, i2c, uploading, compile
---


# Question
Title: How do i generate exact number of PWM pulses in arduino?
So my code here generates a PWM wave of 38Khz on Port B pin 7 of arduino Mega 2560 . For that I have used a prescaler of 8 and then set the ICR1 register value to 51 . I have also set the WGM10 ,WGM11, WGM12 and WGM13 bits to 1 , to enable fast PWM mode with Top reference value as ICR1 contents . Similarly , COM1A1 is set , to enable clear output on compare equal else high . CS11 is set to high to enable the prescaler 8 .

My code is as follows -

```
#include<avr/io.h>
#include <avr/iomxx0_1.h>
#include<util/delay.h>
void pwm_init()
{
        // Configure PB.7 as output pin
        DDRB |= (1<<PB7);
        TCCR1A =  (1<<WGM11) | (1<<WGM10) | (1<<COM1A1);
        TCCR1B =(1<<WGM12) | (1<<WGM13) | (1<<CS11);
        ICR1 = 51;
}

void pwm_generate()
{
    OCR1A = (50 * 52)/100 ;
}
int main()
{
pwm_init();
pwm_generate();
}

```

What I require from the program is that , it should stop producing pwm pulses once a sufficient number of pulses are transmitted . For example - The program should output 7 pwm pulses of 38Khz and then it should give logic 0 as output for specified time period . And then after that specified period , it should produce 38 Khz pwm wave again of say, 5 pulses and then again logic 0 for certain duration . And so on ... How do i achieve this ?

PS- This program is actually being written to simulate a pwm wave required by the IR transmitters in TV remote . The PWM pulses represent the ON period and the Logic 0 conditions would represent the gap in between two successive train of PWM pulses.

Picture of waveform for reference -

# Answer
> 2 votes
One way to get a fixed number of pulses is to set up an interrupt handler that is invoked once per toggle (or, once per cycle, whichever is appropriate). It can decrement a counter, and shut off an output pin when the counter gets to zero. Or could set the output pin low and the CS bits to 0 to stop the counter. For example, if timer 1 is in use:

```
volatile byte TogCounter;
...
// In setup():
TIMSK1 = 1<<TOIE1;  // Enable timer 1 overflow interrupt at TOP
...
// Define a timer 1 ISR
ISR(TIMER1_OVF_vect) {      // ISR for timer 1 overflows
  if (TogCounter) {         // Don't decrease if not counting
    --TogCounter;
    if (!TogCounter) {
      pinMode (TogPin, INPUT); // Disable output when count runs out
      // If desired, set a volatile wavetrain-is-done flag here
    }
  }
}

```

To output a specified number of cycles *n*, set the mode of `TogPin` to `OUTPUT` and set `TogCounter` to *2·n* (or to *n* if counting cycles instead of toggles). Note, waveforms will be of more-consistent length if you also clear the counter register just before starting any pulse train.

To generate a sequence like *m1* cycles on, *n1* off, *m2* cycles on, *n2* off, etc, you could set up an array containing *m1*, *n1*, *m2*, *n2*, etc; then each time `TogCounter` runs down, toggle `TogPin` from INPUT to OUTPUT or vice versa, and load the next array entry into `TogCounter`.

# Answer
> 0 votes
simple:

1) generate a pulse train of 38Khz -\> many ways to do that;

2) put a resistor on the pulse train -\> something like 1K will do it;

3) on the other end of the resistor, put a GPIO pin on it; configure it as input, but write a '0' to it;

4) route the clock input of a timer to that GPIO pin; set it to trigger an isr on a given number of pulses -\> many ways to do that;

5) in the isr set up in 4), turn the gpio pin in 3) to output to disable the pulse train; input to enable the pulse train.

6) done.

---
Tags: arduino-mega, pwm, ir, frequency
---


# Question
Title: Arduino Mega Shield Library for Eagle CAD
I'm a noob to PCB designing and electronic stuff. I want to design a pcb shield which is compatible with an Arduino mega 2560. I'm using Eagle CAD. I checked the sparkfun library but I couldn't find a way to design Mega Shield. Can anybody give me a library or any alternative way to do this?

# Answer
> 1 votes
Since you're new user, perhaps it's easier to take an existing project and modify it for your need. For Eagle, examples can be found on Github.

However, due to recent developments in the PCB EDA world I would suggest you take a look at Circuit Maker. It's more fit for sharing an collaborating designs and libraries. You can easily fork an existing board and use their community parts repository.

---
Tags: arduino-mega, shields
---


# Question
Title: Issues while making ESP8266 as web server
I have programmed `ESP8266` with below program. I used USB to TTL convert to program `ESP8266`. This is how I wired my circuit:

USB TTL---------------- ESP8266 ESP-01

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

TX---------------------------RX

RX---------------------------TX

3.3V-----------------------VCC & CH\_PD

GND------------GPIO0

```
#include <ESP8266WiFi.h>

const char* ssid = "shiv";//type your ssid
const char* password = "manmohan@12345";//type your password

WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  // Match the request

  int value = LOW;
  if (request.indexOf("/LED=ON") != -1) {
    value = HIGH;
  }
  if (request.indexOf("/LED=OFF") != -1){
    value = LOW;
  }

  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("<html>");

  client.print("Led pin is now: ");

  if(value == HIGH) {
    client.print("On");
  } else {
    client.print("Off");
  }
  client.println("<br><br>");
  client.println("Click <a href=\"/LED=ON\">here</a> turn the LED on pin 2 ON<br>");
  client.println("Click <a href=\"/LED=OFF\">here</a> turn the LED on pin 2 OFF<br>");
  client.println("</html>");

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

```

It was successful, here are the logs:

```
Archiving built core (caching) in: C:\Users\williams~1\AppData\Local\Temp\arduino_cache_375631\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____feb0d75f3cf4e05271af4f91549cd009.a
Sketch uses 230073 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 32376 bytes (39%) of dynamic memory, leaving 49544 bytes for local variables. Maximum is 81920 bytes.
Uploading 234224 bytes from C:\Users\williams~1\AppData\Local\Temp\arduino_build_189179/sketch_may14d.ino.bin to flash at 0x00000000
................................................................................ [ 34% ]
................................................................................ [ 69% ]
.....................................................................            [ 100% ]

```

Once this was completed, I opened serial monitor and it was empty there, baud rate was 115200. It is weird, Isn't ?

I followed this tutorial https://create.arduino.cc/projecthub/ROBINTHOMAS/esp8266-esp-01-webserver-7248ca and on serial monitor it should be like below snapshot. What wrong I am doing ? Can anyone help me.

# Answer
Tying GPIO0 to ground puts the ESP into programming mode, allowing you to flash it. To actually run the code, pull it high - that is, disconnect it from ground and connect a resistor (about 10k) between GPIO0 and +3.3v.

Do the same with RST.
> 1 votes

# Answer
Thanks @Mark Smith. I used UART to flash new firmware to `ESP8266`. I connected Arduino and ESP8266 in this way to test `ESP8266` new firmware:

Arduino ---------------- ESP8266 ESP-01

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

TX---------------------------TX

RX---------------------------RX

3.3V-----------------------VCC & CH\_PD

Then I opened Serial Monitor on 115200 baud rate and it started to work as expected. Cheers!
> 1 votes

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


# Question
Title: Ethercard. Copying ip address into hisip
I've tried getting help from arduino.cc forum but they arent helping at all (more like being cryptic) i'm kinda a newb at this. And i'm seriously not getting help from there. 2 messages in 8 days from one person and they arent helping.

i have a project that does following

-connects to network -Gets ip address -finds UDP broadcaster -Connections to a web server's hard coded ip address and grabs data -displays it on a screen.

that works fine. but i been trying to get the UDP broadcaster's ip address into the http part of the code so it connects to the broadcaster without having to hard code the IP Address.

here is my code. i want to have the ip address thats is grabed by the udpSerialPrint stament and have it put into the ether.hisip and use it in the ether.browseUrl(PSTR("/arduino"), "", website, my\_callback);

Hope you can help. Thank you.

```
#include "Arduino.h"
#include <Wire.h>
#include <EtherCard.h>
#include "NexText.h"
#include "NexPage.h"
#include <IPAddress.h>

// Present a "Will be back soon web page", as stand-in webserver.
// 2011-01-30 <jc@wippler.nl> http://opensource.org/licenses/mit-license.php

#define STATIC 0  // set to 1 to disable DHCP (adjust myip/gwip values below)

// ethernet mac address - must be unique on your network
static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[700];
static uint32_t timer;

const int buzzer = 9; //buzzer to arduino pin 9

String ipaddy;
String CurrentTime;
String MainBroadcastIP;
String MainBroadcastIP2;
String Solarwatts;
String BatteryA;
String BatterySOC;
String Housewatts;
String Systemname;
String Updatetime;
String BatteryV;

NexText txtstartup = NexText(0,1,"txtstartup");
NexText txtsystemname = NexText(0,2,"txtsystem");
NexText txtsolarw = NexText(0,3,"txtsolar");
NexText txtbatterya = NexText(0,4,"txtbatterya");
NexText txthousew = NexText(0,5,"txthousew");
NexText txtbatterySOC = NexText(0,6,"txtbatterySOC");
NexText txtupdatetime = NexText(0,7,"txtupdate");
NexPage PageMain1 = NexPage(0,8,"Main1");

const char website[] PROGMEM = "192.168.15.3";

NexTouch *nexListenList[] =
{
    &txtstartup,
    &PageMain1,
    &txtsystemname,
    &txtsolarw,
    &txtbatterya,
    &txthousew,
    &txtbatterySOC,
    &txtupdatetime,
    &PageMain1,
    NULL
};

void setup(){
  dbSerial.begin(9600);
  nexInit();

  Serial.println("\n[AC-DC Power Monitor]");
  pinMode(buzzer, OUTPUT);
  txtstartup.setText("Welcome! System is Starting");
  delay(2000);
  txtstartup.setText("Attempting to Obtain an \r IP Address");
  delay(2000);

  Serial.println("Initialising the Ethernet controller");
  //Mega is ether.begin(sizeof Ethernet::buffer, mymac, 53)
  //Duo is ether.begin(sizeof Ethernet::buffer, mymac, 10)
    if (ether.begin(sizeof Ethernet::buffer, mymac, 53) == 0) {
        Serial.println("Ethernet controller NOT initialised");
        txtstartup.setText("Network Card not detected!");
        while (true);
    }

    Serial.println("Attempting to get an IP address using DHCP");
    if (ether.dhcpSetup()) {
        ether.udpServerListenOnPort(&udpSerialPrint, 8888);
        ether.printIp("Got an IP address using DHCP: ", ether.myip);
        char a1[10],a2[10],a3[10],a4[10];
        sprintf(a1,"%d",ether.myip[0]);
        sprintf(a2,"%d",ether.myip[1]);
        sprintf(a3,"%d",ether.myip[2]);
        sprintf(a4,"%d",ether.myip[3]);
        ipaddy = String(a1) + "." + a2 + "." + a3 + "." + a4;
        String msgtext = "Got IP: " + ipaddy;
        txtstartup.setText(msgtext.c_str());
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(250);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        delay(250);        // ...for 1 sec
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(250);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...

    } else {
        tone(buzzer, 400); // Send 0.4KHz sound signal...
        delay(500);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        delay(500);        // ...for 1 sec
        tone(buzzer, 400); // Send 0.4KHz sound signal...
        delay(500);        // ...for 1 sec
        noTone(buzzer);     // Stop sound.
        exit(0);
    }

    #if 1
      // use DNS to resolve the website's IP address
      if (!ether.dnsLookup(website))
        Serial.println("DNS failed");
    #elif 2
      // if website is a string containing an IP address instead of a domain name,
      // then use it directly. Note: the string can not be in PROGMEM.
      char websiteIP[] = "192.168.1.1";
      ether.parseIp(ether.hisip, websiteIP);
    #else
      // or provide a numeric IP address instead of a string
      byte hisip[] = { 192,168,1,1 };
      ether.copyIp(ether.hisip, hisip);
    #endif

    delay(2000);
    PageMain1.show();
    ether.printIp("SRV: ", ether.hisip);
}

void loop(){
        ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 1000;
    Serial.println();
    Serial.print("<<< REQ ");
    ether.hisport = 8181;
    ether.browseUrl(PSTR("/arduino"), "", website, my_callback);
  }

}

void checkserver()
{
    delay(1000);
    Serial.println();

}

void udpSerialPrint(word port, byte ip[4], const char *data, word len) {
IPAddress src(ip[0], ip[1], ip[2], ip[3]);
        char a1[10],a2[10],a3[10],a4[10];
        sprintf(a1,"%d",src[0]);
        sprintf(a2,"%d",src[1]);
        sprintf(a3,"%d",src[2]);
        sprintf(a4,"%d",src[3]);

        MainBroadcastIP = String(a1) + "." + a2 + "." + a3 + "." + a4;
      return;
}

String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;

    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

char* string2char(String command){
    if(command.length()!=0){
        char *p = const_cast<char*>(command.c_str());
        return p;
    }
}

static void my_callback (byte status, word off, word len) {
  Serial.println(">>>");
  Ethernet::buffer[off+300] = 0;
  String web = (const char*) Ethernet::buffer + off;
  Serial.println((const char*) Ethernet::buffer + off);
  int weblengh = web.length();
  String web2 = web.substring(131,weblengh);
  Serial.println("System Name: " + getValue(web2, ',', 0));
  Systemname = getValue(web2, ',', 0);
  Serial.println("Solar Watts: " + getValue(web2, ',', 1) + "W");
  Solarwatts = getValue(web2, ',', 1) + "W";
  Serial.println("House Watts: " + getValue(web2, ',', 2) + "W");
  Housewatts = getValue(web2, ',', 2) + "W";
  Serial.println("Battery SOC: " + getValue(web2, ',', 3) + "%");
  BatterySOC = getValue(web2, ',', 3) + "%";
  Serial.println("Battery Volts: " + getValue(web2, ',', 4) + "V");
  BatteryV = getValue(web2, ',', 4) + "V";
  Serial.println("Battery Amps: " + getValue(web2, ',', 5) + "A");
  BatteryA = getValue(web2, ',', 5) + "A";
  Serial.println("Battery Amps: " + getValue(web2, ',', 6));
  Serial.println("Battery Amps: " + getValue(web2, ',', 7));
  Serial.println("Time: " + getValue(web2, ',', 8));
  Updatetime = getValue(web2, ',', 8);

  txtsystemname.setText(Systemname.c_str());
  txtsolarw.setText(Solarwatts.c_str());
  txthousew.setText(Housewatts.c_str());
  txtbatterySOC.setText(BatterySOC.c_str());
  txtbatterya.setText(BatteryA.c_str());
  txtupdatetime.setText(Updatetime.c_str());

}

```

# Answer
> 0 votes
Well, `ether` is global, so you can access it from your `udpSerialPrint` function. That function gets passed the IP address in the `ip[4]` array, so you can just use `ether.copyIp(ether.hisip, ip);` to set it.

I would also set a flag to say "I have got the IP address" and only attempt to do anything with the website when you know the IP address has been given to you.

---
Tags: arduino-mega, ethernet
---


title: SoftwareSerial too slow for MIDI?

text:
# Question
Title: SoftwareSerial too slow for MIDI?
I tried to use the SoftwareSerial library for MIDI (by 47 effects), but it seems I get regularly corrupted/unexpected messages.

The circuit I'm using works perfectly when I connect it with the HardwareSerial solution (so the problem must lay in software).

What I see is:

* When I press notes and release notes, LED 13 goes on and off correctly.
* When I use Serial.print for debugging I get correct messages. However, in the example below I removed the print statements to have a minimal example).
* When I use SoftwareSerial, LED 13 goes on and off for every note correctly. However, when I send many messages (for example by aftertouch/pitch bend which send a lot of messages in a short time), I noticed Note On/Off commands with 'random' values are sent.

Some sources say SoftwareSerial should work for MIDI, however, so far it is far from perfect. Do I make some mistake?

(btw, the baudrate of MIDI is 31.250 bps, when I use pitchband several hundreds of bytes per second are sent, so far within the MIDI spec).

The sketch I use is:

```
#include <MIDI.h>  // Add Midi Library
#include <SoftwareSerial.h>

SoftwareSerial swSerial(2, 11); // RX, TX

MIDI_CREATE_INSTANCE(SoftwareSerial, swSerial, midiSw1);

#define LED 13    // Arduino Board LED is on Pin 13

void setup()
{
  pinMode (LED, OUTPUT); // Set Arduino board pin 13 to output

  midiSw1.begin(MIDI_CHANNEL_OMNI);
  midiSw1.setHandleNoteOn(MyHandleNoteOn);
  midiSw1.setHandleNoteOff(MyHandleNoteOff);
}

void loop()
{
  midiSw1.read();
}

void MyHandleNoteOn(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, HIGH); //Turn LED on
}

void MyHandleNoteOff(byte channel, byte pitch, byte velocity)
{
  digitalWrite(LED, LOW); //Turn LED off
}

```

# Answer
> 2 votes
The problem with SoftwareSerial is that while it is receiving a packet the Arduino is unable to do anything else - that includes reading bytes from the RX buffer, so it will easily overflow if you send things too rapidly. With HardwareSerial you are able to read from the buffer while it's receiving data, so overflowing is less of a problem.

As soon as the START bit of a packet is received it enters an ISR and reads each of the remaining 9 bits of data (including the stop bit) in a tight loop. That ISR doesn't exit until the whole packet has been received and stored in the RX buffer. If another byte is sent straight away there is little time between the ISR finishing and it being triggered again. The rest of the code, including the MIDI parsing routines which read data from the RX buffer, are then starved of CPU cycles and can't run properly. Send too many bytes together and the limited RX buffer (64 bytes) fills up and overflows, and you lose data.

Another issue with SoftwareSerial is that it has to capture the START bit at the moment it arrives. Any delay in capturing that edge will result in a drift in the bit sampling timing. If there is anything else that is using interrupts at the same time (such as the `millis()` timer) will delay the triggering of the PCINT interrupt used for the START bit detection. Even the SoftwareSerial interrupt itself has a certain amount of time after it has finished receiving the packet where it stores it in the RX buffer and returns from the interrupt routine. If the next packet arrives *before* the ISR is ready to service it there will be a delay - and any delay is bad.

Personally I am of the opinion that SoftwareSerial should never be used for anything, ever. If you need more serial ports then you either need a more powerful chip or you need more than one chip and get them communicating together through another higher speed hardware channel (SPI or I2C, for instance).

SoftwareSerial is only suitable for sending short bursts of data (since it blocks completely while sending) or receiving very short messages sent infrequently.

---
Tags: arduino-uno, softwareserial, midi
---


# Question
Title: Does an Arduino get worn out by too much command execution?
Excuse me if it is a silly question, but I couldn't find an answer.

I've been wondering for a while whether an Arduino (or generally any other micro-controller) gets happy if the code is light and it does not have to execute too much operations. Does a code that has too many ifs, too many loops and all sort of complicated calculations wear out an Arduino sooner than a code that just blinks an LED?

# Answer
No, the code doesn't "wear out" the MCU. In general no matter what you are doing roughly the same level of activity is being performed. Even `delay()` does lots of work while it's "idling".

There are commands to make the CPU do less - place it in an IDLE or SLEEP mode - but these are used to save power rather than to reduce "wear" on the MCU.

Of course there are specific things that do have a limited lifetime and you can only use them a limited amount of times - things like writing to EEPROM and writing to the Flash memory - so you don't want to be doing those all the time. Other than that, no, no matter what you are doing it doesn't wear the MCU out.
> 20 votes

# Answer
It's not. Well, it might slowly wear out if you run it like 20 years....(like most other physical products)? At least it does not rely on code complexity but how many writing operation done in the same memory section. Moreover, when it wear out it will just get bricked and it won't become a simpler code like blinking the LED.

An Arduino (Uno) has three memory parts. SRAM, FLASH, and EEPROM. SRAM is more like a logical transistor gate. It won't wear out by storing variables. FLASH and EEPROM consist of floating gates. They slowly wear out when you write new data. From the datasheet of Ateml microcontroller, it states:

> The Flash memory has an endurance of at least 10,000 write/erase cycles. (From Chapter 8.2)
>
> The EEPROM has an endurance of at least 100,000 write/erase cycles. (From Chapter 8.4)

However, FLASH memory is a space for code execution. Writing operation is not be done while Arduino is running. You only write FLASH memory when you upload a new code. So it will wear out when you upload code at least 10,000 times.

If you really want you can make a special code to self-reprogram FLASH memory usually for the purpose of keeping variable data when Arduino is turned off. When you write this kind of program it will wear out slowly because FLASH memory doesn't have much writing endurance. That's why you will be suggested to use EEPROM which has much more life expectancy, if you want to keep data even when Arduino is turned off.

To sum up, it will wear out by re-writing FLASH or EEPROM memory, not by code execution.
> 6 votes

# Answer
For a hobbyist:

About the only life limiting software related issue might be writing to the FLASH memory as fast as you can from inside a program. But few programs make use of variables that need to survive events like changing batteries.

About the only life limiting hardware related issue is over loading the outputs with low resistance loads (incandescent light bulbs), inductive loads (like directly driving mechanical relays) to name just two. But the question is only about software.
> 6 votes

# Answer
> ... (or generally any other micro-controller) ...

The other answers are great, but there is one small exception.

Ferroelectric RAM (FRAM) is a form of memory that combines the non-volatility of flash and EEPROM, the writability of SRAM, and the density of DRAM.

*However*, read operations on FRAM are destructive to the data stored in the FRAM, and write operations are destructive to the FRAM construction itself (and since the data is destroyed by reading it, it must be written back each time). If your code is located in FRAM then running it will wear down the MCU in time. But given that FRAM has a write endurance in the millions of billions it is unlikely that the MCU will become inoperable due to FRAM in the lifetime of the device.

Examples of MCUs that use FRAM include TI's MSP430FRxx line.
> 5 votes

# Answer
Probably not ... The Atmel chip might get warmer over time (even a delay does not prevent this), however if it has a possibility to release its heat I don't see a problem. But mostly only overclocking can cause really serious problems, or using the Arduino in a fully closed box or in a hot environment.

In comparison: many computers are running for years without switching off, the Atmel (chip) is in that sense no difference, as long as generated heat can be relieved.

You can read more about a heat sensor in Atmels here: Internal Temperature Sensor
> 3 votes

---
Tags: arduino-uno, hardware, code-optimization
---


# Question
Title: Difference between Ultrasonic sensor and Distance Sensor?
What is the difference between an Ultrasonic Sensor and a Distance Sensor?

# Answer
An ultrasonic sensor can usually develop and receive high frequency sound waves. They can be used to measure distance by measuring the time of flight of the sound wave.

```
distance(meters)  = [speed_of_sound(meters/second)][1] x time_of_flight(seconds)
distance(meters) = 343(meters/second) x time_of_flight(seconds)

```

For example, say the time of flight was 0.01 seconds.

```
distance(meters) = 343(meters/second) x 0.01(seconds)
distance = 3.43 meters

```

This is just one way distance can be measured by a processor. Other ways use different types of radiation such as electromagnetic radio and light radiation. Some of these use time of flight. Others use more exotic phase techniques. These types of detectors can be very accurate over long distances. But are usually very costly. They are commonly used for automated car driving.

A completely different approach uses triangulation or parallax of a light beam and a focused linear array light sensor.

These types of detectors normally operate over short distances and are cheap to make. They are commonly used in places like copier machine to detect objects and paper. Or in automated vacuums cleaners to detect floor edges such as stair drop offs.
> 3 votes

# Answer
A proximity sensor is a sensor able to detect the presence of nearby objects without any physical contact, see article proximity sensor.

In that article a lot of types are mentioned and ultrasonic sensors are one of them, so an ultrasonic is one of the types of distance sensors.

Types (copied from the above article):

* Capacitive
* Capacitive displacement sensor
* Doppler effect (sensor based on effect)
* Eddy-current
* Inductive
* Magnetic, including magnetic proximity fuse
* Optical
    + Photocell (reflective)
    + Laser rangefinder
    + Passive (such as charge-coupled devices)
    + Passive thermal infrared
* Radar
* Reflection of ionising radiation
* Sonar (typically active or passive)
* Ultrasonic sensor (sonar which runs in air)
* Fiber optics sensor
* Hall effect sensor
> 2 votes

---
Tags: arduino-uno, sensors, arduino-ide
---


# Question
Title: Setting Time to UTC with Data Logger Shield (with RTC DS1387)
I own an Adafruit Data Logger Shield https://www.adafruit.com/product/1141

I followed this tutorial https://learn.adafruit.com/adafruit-data-logger-shield/using-the-real-time-clock

This part of code

```
if (! rtc.initialized()) {
  Serial.println("RTC is NOT running!");
  // following line sets the RTC to the date & time this sketch was compiled
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

```

adjust RTC to computer date/time... but it's using computer local date/time.

I'd prefer to use UTC date/time but I haven't find a convenient way to do this (except modifying computer date/time which is not very convenient as I want to always be able to reprogram Arduino without hassle of changing local time each time).

# Answer
> 1 votes
There are several approaches you could use.

*Edit 1:* On your development system, you could write a shell script or a batch file to write a file, say `myUTCtime.h`, containing a source-code line like `char *MyUTCtime = "23:59:01";` and somewhere in your sketch say `#include "myUTCtime.h"`. Eg, to create the file in Linux: `echo "char *MyUTCtime = \"$(date -u '+%H:%M:%S')\";" > myUTCtime.h` which on my system produced file myUTCtime.h containing `char *MyUTCtime = "08:20:36";`

• You could define a different time constant, for example by adding `-DMyUTCtime="23:59:01"` into the gcc or g++ command line. (Substitute an appropriate time.) On Linux, this might look like `-DMyUTCtime=$(date -u '+%H:%M:%S')`. In your code you would write `#MyUTCtime` in place of `__TIME__`. *Edit 1:* Note, this is difficult to automate when using the Arduino IDE. It is somewhat easier if using an Arduino Makefile. For example, on Linux one might say `MyUTCtime=$(date -u '+%H:%M:%S') make` (which defines `MyUTCtime` with the current UTC time, and passes the `MyUTCtime` into `make`) and within the makefile, say (eg)

```
ifdef MyUTCtime
  CPPFLAGS += -DMyUTCtime=${MyUTCtime}
endif

```

• You could write your sketch to accept a time-setting command via serial input. To set the time, you would send the time-setting command and the current time in UTC, via serial monitor.

• As Mikael Patel mentioned, you could modify the `__TIME__` string to represent UTC before using it to set the RTC. Here is an example of how to add or subtract an appropriate offset to `__TIME__` to adjust it to UTC. For example, if your offset is an hour ahead of UTC, you would change

```
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

```

to

```
char *compileTime = __TIME__;
compileTime[1] += 1;
if (compileTime[1] > '9')   // Check for carry
   ++compileTime[0];        // Add the carry
rtc.adjust(DateTime(F(__DATE__), compileTime));

```

This code has at least two problems:
• If the compile occurs between 23:00:00 and midnight, the resulting hour will show as 24 instead of as 00 on the next day. One could of course adjust the day of the date, and if that overflows, adjust the month, and if that overflows, adjust the year; or, more simply, one could produce an error in the compile.
• While a 1-hour offset may be appropriate during DST, a 2-hour offset may be appropriate most of the year. One could of course check the date and use a date-appropriate offset of 1 or 2.

---
Tags: time, rtc, datalogging
---


title: Arduino stopped working

text:
# Question
Title: Arduino stopped working
my arduino uno stopped working. It shuts off itself every time i plug it in. This golden thing is ovetheating.

Do i have to replace it or buy a new uno or what.

# Answer
As Gerben has said, that "golden thing" is a resettable fuse (AKA polyfuse).

It's there to protect the USB port of your computer against excess current draw from a faulty board (which seems to be happening, by the way).

If nothing else is connected to the Arduino and the polyfuse keeps tripping, then the fault root cause is probably a short-circuit in the board. From here there are 2 possible scenarios:

1. Least likely: an external agent (metallic flakes, dirt, or something like that) might be causing the short-circuit. Inspect the board, clean it and electrically isolate it when plugging it again (avoid the solder joints getting in contact with a conductive surface, use a case or a mat).
2. More likely: a component has failed in short-circuit mode and is causing the excess current draw that trips the polyfuse. In that case you could try to debug the board (with at least a multimeter, and maybe other instruments) to locate the faulty component and replace it. That's not an easy task unless you precisely know what to do and where to look in the board. You might be better off buying a new board.

If you want to give the repair route a try, check this question. The schematic may be of some help to you. You might want to verify the integrity of the decoupling capacitor in first place.
> 2 votes

---
Tags: arduino-uno
---