message:
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 : https://arduino.stackexchange.com/questions/28238/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
    }

body:
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 : https://arduino.stackexchange.com/questions/38523/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.


sender: user

message:
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.

sender: assistant

body: 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.


message:
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 -[![][1]][1]

  [1]: https://i.stack.imgur.com/hoBgW.png

body:
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.


body:
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`.


message:
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("");

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

      if(value == HIGH) {
        client.print("On");
      } else {
        client.print("Off");
      }
      client.println("

");
      client.println("Click here turn the LED on pin 2 ON
");
      client.println("Click here turn the LED on pin 2 OFF
");
      client.println("");

      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.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/A3AFd.jpg

body:
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.


body:
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!


message:
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?

body:
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.

 - https://github.com/zortness/rocket-mega-shield
 - https://github.com/practicalarduino/ProtoShieldMega

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.


message:
Storing a 2 dimensional Array in PROGMEM

I am running a Mega 2560 processor board.

I have a large "unsigned char" database currently stored in a 2 dimensional array in SRAM.  I have plenty of room in program memory and need to move the database to PROGMEM.  It appears that the rules around how to use PROGMEM have changed and the documentation does not reflect the change. I have found a way to store the array in PROGMEM and can access the data statically (ARRAY[0,1]).  If I try to access the array dynamically, (ARRAY[var1,var2]), I get junk.

Since I have seen some questions what I mean by "static" and "Dynamic" I gladly add the following examples:

    //Array initialization

    const static unsigned char __attribute__ ((progmem)) Image_1d_Array[234]={
      0x00, 0x0e, 0xf8, 0xff, 0xdf, 0x03, 0xc0, 0x1d, 0x60, 0x1f, 0x60, 0x00, 0x03,
       0xdb, 0x01, 0x00, 0x08, 0xe3, 0x07, 0x00, 0x0e, 0x00, 0x1e, 0x30, 0x00, 0x00,
       0x00, 0x0e, 0xf0, 0x07, 0xfc, 0x01, 0xc0, 0x39, 0x00, 0x1f, 0xe0, 0x00, 0x03};

    void setup:
      int i;
      char myChar;

    //  Static read.  This will give me the correct values
      Serial.print("Image= "); Serial.println(Image_1d_Array[0],HEX);
      Serial.print("Image= "); Serial.println(Image_1d_Array[1],HEX);
      Serial.print("Image= "); Serial.println(Image_1d_Array[2],HEX);
      Serial.print("Image= "); Serial.println(Image_1d_Array[3],HEX);
      Serial.println("");

    //  Dynamic read.  This will give me the junk values
      for(i = 0; i <=11; i++){
         Serial.print("AImage= ");
         myChar = pgm_read_byte_near(&Image_1d_Array + i);
         Serial.println(myChar,HEX);
        }

I can't even get a single dimensional array to work dynamically.

Does anybody understand the new rules to access the array?? The following data structures from the Arduino reference manual are no longer supported

<pre>
prog_char - a signed char (1 byte) -127 to 128
prog_uchar - an unsigned char (1 byte) 0 to 255
prog_int16_t - a signed int (2 bytes) -32,767 to 32,768
prog_uint16_t - an unsigned int (2 bytes) 0 to 65,535
prog_int32_t - a signed long (4 bytes) -2,147,483,648 to * 2,147,483,647.
prog_uint32_t - an unsigned long (4 bytes) 0 to 4,294,967,295
</pre>

body:
You wrote:

    myChar = pgm_read_byte_near(&Image_1d_Array + i);

Here `&Image_1d_Array` is the address of the array. Its type is “pointer
to an array of 234 unsigned chars”. When you add `i` to this pointer,
per the rules of pointer arithmetic, you are actually adding to the
address `i` times the size of the array.

What you actually mean by `&Image_1d_Array` is “the address of the first
element of the array”, which can be written `&Image_1d_Array[0]`. Or you
could rely on the usual “decay to pointer” semantics, and simply write
`Image_1d_Array`, as suggested  in Johnny Mopp's comment.

Now you should have noticed that both `Image_1d_Array` and
`&Image_1d_Array` behave as pointers to the same memory address, only
they have different types. See the
[C FAQ](http://c-faq.com/aryptr/aryvsadr.html) and references therein
for more on this distinction.

Note that the usual way of doing what you want is:

    myChar = pgm_read_byte_near(&Image_1d_Array[i]);


message:
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
    }

body:
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.


message:
GPS module not working with sensor

I am connecting my Soil Moisture Temperature Sensor SHT10 with GSM Module SIM900A and GPS GY-GPS6MV2. Individually, all components work properly and give proper values. But when I interface all three components with Arduino, only Temperature sensor seems to work and GPS does not give any values.
Even If I connect only SHT10 and GPS with Arduino Uno (without GSM), only SHT10 gives values but GPS doesn't.

My code is:

    #include <AltSoftSerial.h>
    #include <TinyGPS++.h>
    #include <SHT1x.h>

    AltSoftSerial gpsSerial (11,12);

    TinyGPSPlus gps;

    #define dataPin 6
    #define clockPin 7
    SHT1x sht1x(dataPin, clockPin);
    float TEMP, HUMID;

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

    void loop()
    {
    TEMP = sht1x.readTemperatureC();
    HUMID = sht1x.readHumidity();
    Serial.println(TEMP);
    Serial.println(HUMID);
    gps_value();
    }

    void gps_value()
    {
    while(gpsSerial.available())
    {
    gps.encode(gpsSerial.read());
    }

    if(gps.location.isUpdated())
    {
    Serial.println("Latitude: ");
    Serial.println(gps.location.lat());
    Serial.println("Longitude: ");
    Serial.println(gps.location.lng());
    Serial.println("Altitude Feet: ");
    Serial.println(gps.altitude.feet());
    Serial.println("Horizontal Dilution of Precision: ");  //lower the better
    Serial.println(gps.hdop.value());
    Serial.println("");
    }
    }
What is happening here ?

[Datasheet of SHT10 ][1]

[![SHT10][2]][2]

  [1]: https://cdn.sparkfun.com/datasheets/Sensors/Pressure/Sensirion_Humidity_SHT1x_Datasheet_V5.pdf
  [2]: https://i.stack.imgur.com/M06L4.jpg

body:
You could have used SoftwareSerial instead of AltSoftSerial.Since you are using AltSoftSerial please go through its library file to check how you need to deal with it.
For Software Serial you need to use predefined Rx , Tx pins of Arduino rather than defining any other pins of it for Rx,Tx
for connecting those to Rx Tx of tempterature sensor.
For GPS try to define any 2 pins of Arduino as Rx Tx so that you can connect them to Rx Tx of GPS.Hope this helps you.


body: As already mentioned this seems to be a current related problem. You are powering your Arduino over Usb. The sensors themselves do work fine. Yet connecting all of them seems to draw too much current so they won’t work properly. (See [this post](https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins) for more information on current.


message:
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());

    }

body:
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.


message:
Including an arduino library in Eclipse Neon (undefined reference to)

I'm trying for the first time to use Arduino Libraries (Servo.h & Servo.cpp in this case) in Eclipse IDE.

So far I've managed to compile and run Arduino code using [this tutorial][1] (I suppose many of you already know it).

The problem comes when I add the Servo.cpp and Servo.h files and try to run the program:

        13:35:08 **** Incremental Build of configuration Release for project Servo ****
    make all
    arduinoEclipse/subdir.mk:268: warning: overriding commands for target `arduinoEclipse/wiring_pulse.o'
    arduinoEclipse/subdir.mk:261: warning: ignoring old commands for target `arduinoEclipse/wiring_pulse.o'
    Building file: ../ServoTest.cpp
    Invoking: AVR C++ Compiler
    avr-g++ -I"C:\arduino\arduinoEclipse" -Wall -Os -fpack-struct -fshort-enums -ffunction-sections -fdata-sections -funsigned-char -funsigned-bitfields -fno-exceptions -mmcu=atmega328p -DF_CPU=1600000UL -MMD -MP -MF"ServoTest.d" -MT"ServoTest.o" -c -o "ServoTest.o" "../ServoTest.cpp"
    Finished building: ../ServoTest.cpp

    Building target: Servo.elf
    Invoking: AVR C++ Linker
    avr-g++ -Wl,-Map,Servo.map,--cref -mrelax -Wl,--gc-sections -mmcu=atmega328p -o "Servo.elf"  ./arduinoEclipse/CDC.o ./arduinoEclipse/HardwareSerial.o ./arduinoEclipse/HardwareSerial0.o ./arduinoEclipse/HardwareSerial1.o ./arduinoEclipse/HardwareSerial2.o ./arduinoEclipse/HardwareSerial3.o ./arduinoEclipse/IPAddress.o ./arduinoEclipse/PluggableUSB.o ./arduinoEclipse/Print.o ./arduinoEclipse/Servo.o ./arduinoEclipse/Stream.o ./arduinoEclipse/Tone.o ./arduinoEclipse/USBCore.o ./arduinoEclipse/WInterrupts.o ./arduinoEclipse/WMath.o ./arduinoEclipse/WString.o ./arduinoEclipse/abi.o ./arduinoEclipse/hooks.o ./arduinoEclipse/main.o ./arduinoEclipse/new.o ./arduinoEclipse/wiring.o ./arduinoEclipse/wiring_analog.o ./arduinoEclipse/wiring_digital.o ./arduinoEclipse/wiring_pulse.o ./arduinoEclipse/wiring_shift.o  ./ServoTest.o
    ./ServoTest.o: In function `setup':
    ServoTest.cpp:(.text.setup+0x8): undefined reference to `Servo::attach(int)'
    ./ServoTest.o: In function `loop':
    ServoTest.cpp:(.text.loop+0x20): undefined reference to `Servo::writeMicroseconds(int)'
    ServoTest.cpp:(.text.loop+0x5a): undefined reference to `Servo::writeMicroseconds(int)'
    ServoTest.cpp:(.text.loop+0xbc): undefined reference to `Servo::write(int)'
    ./ServoTest.o: In function `_GLOBAL__sub_I_myservo':
    ServoTest.cpp:(.text.startup._GLOBAL__sub_I_myservo+0x4): undefined reference to `Servo::Servo()'
    collect2.exe: error: ld returned 1 exit status
    make: *** [Servo.elf] Error 1

As you can see in the console output, it compiles correctly, but when it comes to the linker, it doesn't find the function references from the Servo.cpp.

As I have seen in [this post][2], the problem comes from the fact that I need also to generate an .a (static library) file in order to link both .h and .cpp files. Still, I have no idea how I am supposed to generate this file.

For this project, I have just added in arduinoEclipse folder all the .cpp and .h files from `C:\arduino\hardware\arduino\avr\cores\arduino`, `C:\arduino\hardware\arduino\avr\variants\standard` & `C:\arduino\libraries\Servo`.

Do you see what I could be missing?

Thank you in advance

  [1]: https://www.codeproject.com/Articles/1003347/Creating-Arduino-programs-in-Eclipse?msg=5394929#xx5394929xx
  [2]: https://arduino.stackexchange.com/questions/14266/arduino-in-eclipse-ide-how-to-add-spi-library-core-library-already-added

body:
The arduino build process is described here: https://www.arduino.cc/en/Hacking/BuildProcess
You do not really need to build a archive. You can link all your source files but that will result in a far bigger file to upload to the embedded device.
The normal CDT process to build a archive is by having 2 projects. One for the "archive" one for your sketch and then use project dependencies.
However since Arduino IDE 1.5 this process is hard to maintain because changing settings for your sketch may force you to change your archive compilation settings.
As far as I know; out of the box CDT does not support creating a library and linking it to a "executable" in one project. This is something Sloeber (road 1 in the article) has added.
I know this because I'm authoring Sloeber.


body: I don't have eclipse handy right now, so I may not have the menu options verbatim here, but with eclipse there are more steps to including a library than just writing the line in the code.  Go to the project in the project explorer and right click the project name.  Hit import and select the option for importing Arduino libraries into the sketch.  It should bring up a dialog with a list of all the libraries you have installed and you can choose from there.  Then there will be a folder in your project called includes IIRC and it will have a link to the library that you imported.  Now when you compile it will find the library.


message:
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?

body:
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][1]

  [1]: http://playground.arduino.cc/Main/InternalTemperatureSensor


body:
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.


body:
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](http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf), 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.


body:
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.


body:
> ... (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.


message:
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).

body:
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](https://github.com/sudar/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.


message:
Difference between Ultrasonic sensor and Distance Sensor?

What is the difference between an Ultrasonic Sensor and a Distance Sensor?

body:
A proximity sensor is a sensor able to detect the presence of nearby objects without any physical contact, see article [proximity sensor][1].

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.

  [1]: https://en.wikipedia.org/wiki/Proximity_sensor

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


body:
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][1] 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][2] of a light beam and a focused linear array light sensor.
[![enter image description here][3]][3]

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.

  [1]: https://en.wikipedia.org/wiki/Lidar
  [2]: https://en.wikipedia.org/wiki/Parallax#Distance_measurement
  [3]: https://i.stack.imgur.com/fTp02.jpg


message:
ESP8266 not working. No response

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/GOb3K.jpg

Hello. I have begun working with an ESP8266 and an Arduino Uno. The connection I used is shown below, except I am using an Arduino Uno. The rest of the connection is the same.

The code I'm using is:

    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial(2, 3); // RX | TX

    void setup() {
      Serial.begin(9600);
      ESPserial.begin(9600);
      Serial.println("");
      Serial.println("Remember to to set Both NL & CR in the serial monitor.");
      Serial.println("Ready");
      Serial.println("");
    }

    void loop() {
      if (ESPserial.available()) {
        Serial.write( ESPserial.read() );
      }
      if (Serial.available()) {
        ESPserial.write(Serial.read());
      }
    }

But the serial monitor is only printing:

>Remember to to set Both NL & CR in the serial monitor.
>
>Ready

What to do?

body: You need to pull RST high - that is, connect a 10k between +3.3v and the ESP8266-01's RST pin.


body:
ESP01 has two variants (blue PCB and black PCB), the old is configured to use 9600 baud (blue PCB) and the newer one uses 115200 baud (black PCB) as default.

There is also a difference in memory, 512kByte (4Mbit) or 1MB (8Mb) between the old and new version.

So try to change

    ESPserial.begin(9600);

to

    ESPserial.begin(115200);

And preferably both 9600 to 115200.


body:
ESP8266 WiFi modules typically have a baud-rate of 115200. This not only won't work with a 9600 baud host but SoftwareSerial can't go that fast. Or, more precisely, it can generally push out characters at that speed but it can't keep up with incoming ones. [See this answer][1] for how to change the speed of your module to 9600 baud.

Short answer: You have to reconfigure your ESP module to 9600 baud to use it with SoftwareSerial. You can do it blind (transmit a baud-change command to it at 115200 baud, even though you won't be able to read the reply). Once done, it will remain at 9600 baud and successfully communicate in both directions.

  [1]: https://arduino.stackexchange.com/questions/38289/at-command-is-not-responding-on-serial-monitor/38323#38323


message:
Arduino stopped working

my arduino uno stopped working. It shuts off itself every time i plug it in. This golden thing is ovetheating.[![][1]][1]

  [1]: https://i.stack.imgur.com/EyNXN.jpg
Do i have to replace it or buy a new uno or what.

body:
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][1]. The schematic may be of some help to you. You might want to verify the integrity of the decoupling capacitor in first place.

  [1]: https://arduino.stackexchange.com/questions/36463/differences-between-a-real-and-clone-arduino-uno


message:
8Ω speaker, what resistor values to use?

I want to connect 2 speakers of 8 ohm to 2 (different) pins of the Arduino.
However, for this example one speaker is enough.

I came across a lot of circuits without or with a single resistor which on other foras was not adviced, where one pin directly controls the speaker. This way (assuming 0,02A is the max recommended output for a pin), the resulting power is like 0.02A * 5V = 0.1W.

My speaker is 0.5W (8 ohm) and I want to hear how hard that is :-)

But it seems I have to use something with a transistor to isolate the path.
I came across this circuit:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/vxynt.png

However, when I would calculate the values or R1 and R2 myself I would get:

1. R2: Afaik, the recommended output for a pin is 0.02 A. This means:
V = I * R <=> 5 = 0.02 * R <=> R = 5 / 0.02 = 250Ω -> 270Ω (nearest higher value)

2. R1: my speaker is 0.5W, 8Ω.
P = V * I <=> 0.5 = 5 * I <=> I = 0.1A
V = I * R <=> 5 = 0.1 * R => R = 50Ω, which is Rtotal below:
Rtotal = Rspeaker + R1 <=> R1 = Rtotal - Rspeaker = 50 - 8 = 42Ω => 47Ω (nearest higher value)

This result in
V = I * R <=> 5 = I * (R1 + Rspeaker) <=> I = 5 / (47 + 8) = 5 / 55 = 0.0909 A
P = V * I = 5 * 0.0909 = 0.4545 W (so I lose 'just' 10%)

Are my calculations correct, and I assume the +5V pin of the Arduino will not have trouble giving 90.9 mA ?

Update:

I have some more questions regarding the accepted answer:

1. Would it mean if I use 7 transistors, all my voltages will be used for transistors and nothing is left (7 times 0.7 V which is approx. 5 V?)
 **** Answer = No, a transistor will add Voltage so 7*0.7= 4.9Volt added ***
2. I assume I can better use as less as possible to 'switch' a transistor? *** Answer = No, 0.7-Volt required, 5V is fine depending on the rating of the transducer ***  (but enough to be able to switch it) ? You say R2 can be smaller, but I can better make it higher not to waist voltage? *** Answer = Changing the resistor will change the volume, look at the wattage rating for the speaker ***
3. I already built the circuit below (but with a BC547 transistor) ... using a 0,25W R1 resistor. I guess I was lucky (?) *** Answer = No, luck has no part, that transistor would work fine within the parameters used, look at the datasheet ***
4. Regarding the base pin of the transistor ... by making the resistor higher (see item 2 above) ... that would help also not to burn the transistor pin? *** Answer = No... please view the datasheet and ratings for the hw ***
5. Again about the transistor, so I should make the resistor R2 in such a way that the gain times the mA is driving the speaker? (need to calculate this again) *** Answer No, and I think you are thinking of "Gain" the wrong way, "Gain" is a "DB" measure and is for how well AC is transferred between antenna. ***
6. You say to remove R1 completely ... but than I expect V = I * R <=> 5 = I * 8 => I = 0.625A ... P = V * I = 5 * 0,625 = 3.1W which blows the speaker? *** Answer = Wrong way of looking at the 8-Ohm Impedance rating, Impedance is AC ***

body:
Basically you are right and it should work.

But if you want to go to details, it would be better look on AVR328 documentation, as nothing is as easy as it looks in Arduino tutorials.

- maximum (really maximum) current on pin is 40mA for one DC pin and 200mA for all pins together (otherwise destruction of the processor is possible - never ever try to reach it), also  datasheet states:

> Although each I/O port can source more than the test conditions (20mA
> at V CC = 5V, 10mA at V CC = 3V) under steady state conditions
> (non-transient), the following must be observed:
> ATmega48A/PA/88A/PA/168A/PA/328/P: 1] The sum of all I OH , for ports
> C0 - C5, D0- D4, ADC7, RESET should not exceed 150mA. 2] The sum of
> all I OH , for ports B0 - B5, D5 - D7, ADC6, XTAL1, XTAL2 should not
> exceed 150mA. If II OH exceeds the test condition, V OH may exceed the
> related specification. Pins are not guaranteed to source current
> greater than the listed test condition.

so 20mA is not `recomended` but is `maximum guaranteed to be provided under some more conditions met` - if you can, you should use less (also even if it works for one module on one pin, it may fail mysteriously for mor modules on more pins).

- Even if 20mA is guaranteed for one pin, the voltage on it would drop more then 0.5V if you drain so much
- you cannot draw as much on too many pins together
- also the maximum you can draw is less if you want higher frequency (I think the sound is not usually in category, where it matter too much)

In your equation 1 you used 5V/20mA, you should use 4.4V/20mA also keep in mind, that there is usually like 0.7V on base of open transistor (depends of type) - so the R2 can be even smaller, if you use only few pins.

About R1 - if you open the transistor, there can be like 0.2V on the collector, so the current is like 4.8V/6.8Ohm = 0.7A - on UNO board v3.0 is used NCP1117 as stabiliser, which can support even 1A (if powered not from USB, but 7V and higher source (if such source can give as much) so it could work too, but beware as it is about 4.8V*0.7A=3.4W so R1 should be able to stand at least as much if the pin is HIGH for any longer time. If the pin is oscilating, the SPKR adds it current to that, so the value can be even higher (I would not use anything under 5W for R1).

On the other hand - Q1 2N3904 can support Ic max 200mA, so you could burn it by setting the pin for HIGH (or for PWM with more like 20% HIGH or more - switching makes even more heat) so you should use othe transistor here.

And this Q1 have current gain over 30 even for such currents as 100mA, so you need just 1/30 of Ic go thru the base from pin (so you need supply only 3.3mA to have 100mA thru Q1, 6.6mA is able to force 200mA and burn the transistor, if not properly cooled. 20mA is clearly much more than needed anyway.)

I would suggest some darlington transistor here or something like that, if you want manipulate such currents.

If your speaker is 0.5W only, you will burn more power on the R1 than on the speaker - not good result. It would be better just manipulate the speaker directly (put it instead of R1 and leave the R1 and C1 out).

(but on usual Arduino setup the power source and all is usually so underrated, that there is a good chance, that it would not be able to supply enough power to burn your equipement out, just it would drop the voltage and maybe fail randomly. Who knows. Also breadboards and long thin wires with bad connection adds a lot of resistance and voltage drops and manufacturers publish as `maximal rating` what the product should survive, which is usually a lot les, than is needed to sure destroy it, so many `experiments` can survive even if they should burn on simple paper calculations - which is part of why Arduino is so popular - is cheap and usually does not burn even if managed out of specs.)


body:
The speaker rating of 8 Ω is AC resistance, speaker impedance. Impedance (AC-Resistance) changes based on the frequency of the signal fed into it.

If you are worried about hurting the speaker and need to calculate power driving that particular "load", look at the speaker Wattage rating.
Say it is 1 W for example, and you are providing 5 V d.c., the amperage required will be: 0.2 A.

    V * A = W
    0.2 * 5 = 1

So the DC resistance is actually:

    V = I * R (0.2 / 5 = 0.04 Ω).

Give it a higher amplitude... say 5.7 V to account for a transistor no resistor, and you get about 0.175 A. and a change in DC resistance again to 0.0301 Ω.

If the power supply is AC, the impedance needs to be matched to the speaker impedance to get best energy efficiency, otherwise the amplifier can be damaged.

For that circuit I suggest you place a variable resistor where the resistor is in your circuit to allow for a volume change. Also a flyback diode maybe a good idea, that will protect the speaker but take down voltage 0.7 V d.c. keep in mind you have that transistor there adding 0.7 V d.c.! so it evens things out too using that diode.

That diode placed on the high (+) side of the circuit, before the speaker and after the variable resistor.


message:
How do I use ultrasound to track a moving object?

I'm trying to create a small scale, dumb-downed version of the pitch tracking systems used to detect the speed and direction of baseballs.

 I'm currently working with an HC-SRO4 sensor and an Arduino, but I'm unsure how to expand because a single sensor can't track an object that's not moving linearly (ie rising or falling as it moves). My team's idea was to make a grid of multiple HC-SRO4's connected to one Arduino, but we're worried that the delay will be too large if we try to turn them on sequentially to avoid interference.

How can we use ultrasound to track a moving ball?

body:
Yes you can use ultrasound to track a moving target, but I really doubt it could be done with an Arduino.

You need to be able to ping the object at least 3 times in the time it takes to move your beam width.  3 times because if you know where it is with the centred ping you need to calculate the direction of travel by pinging either side of the centre to see if it is there.

You then need to track it in three dimensions.  To do this you will need multiple sensors ideally at least 3 for 2D and 3 for 3D, so at least 6.  3 sensors in a plane will give you a reasonable degree of accuracy, but you beam width is key to this, the narrower the better.

Now you have to triangulate the position of the object, well actually work out the area of probability (for both planes) you never 'know' where it is really.

Oh and all 6 sensors need to have different frequencies to prevent interference, you then need to add in reflection processing to reduce false signals.

Its just much easier to buy a Pixy camera and download the software that they have for visually tracking your balls.


message:
Something's wrong with my code for a 4 digit 7 segment clock display

I'm trying to do a clock using 4x7 segment displays but once I run the code **the Display doesn't turn on**

here's my Code that I'm like 90% sure that there's nothing wrong with it

    bool A = 2;
    bool B = 3;
    bool C = 4;
    bool D = 5;
    bool E = 6;
    bool F = 7;
    bool G = 8;
    int PWR1 = 10;
    int PWR2 = 11;
    int PWR3 = 12;
    int PWR4 = 13;
    int TimeSec = 0;
    int TimeMin1 = 0;
    int TimeMin2 = 0;
    int TimeHour1 = 8;
    int TimeHour2 = 0;
    int Display = 0;
    int Loop = 0;
    int Digit = 0;
    int Memory1 = 0;
    int Memory2 = 0;
    int Memory3 = 0;
    int Memory4 = 0;
    int Rewrite1 = 0;
    int Rewrite2 = 0;
    int Rewrite3 = 0;
    int Rewrite4 = 0;

    void setup() {
      pinMode(A, OUTPUT);
      pinMode(B, OUTPUT);
      pinMode(C, OUTPUT);
      pinMode(D, OUTPUT);
      pinMode(E, OUTPUT);
      pinMode(F, OUTPUT);
      pinMode(G, OUTPUT);
      pinMode(PWR1, OUTPUT);
      pinMode(PWR2, OUTPUT);
      pinMode(PWR3, OUTPUT);
      pinMode(PWR4, OUTPUT);
    }
    void loop() {
      loop:
      delay(250);
      Digit = Digit + 1;
      if (Digit > 4) { Digit = 1; }
      if (Digit == 1) { goto digit1; }
      if (Digit == 2) { goto digit2; }
      if (Digit == 3) { goto digit3; }
      if (Digit == 4) { goto digit4; }

      // Supposedly turns on the 7-segment display that is next in line to have its digit edited but doesn't work?
      digit1:
      digitalWrite(PWR1, HIGH);
      digitalWrite(PWR2, LOW);
      digitalWrite(PWR3, LOW);
      digitalWrite(PWR4, LOW);
      Display = Memory1;
      goto skip;
      digit2:
      digitalWrite(PWR2, HIGH);
      digitalWrite(PWR1, LOW);
      digitalWrite(PWR3, LOW);
      digitalWrite(PWR4, LOW);
      Display = Memory2;
      goto skip;
      digit3:
      digitalWrite(PWR3, HIGH);
      digitalWrite(PWR1, LOW);
      digitalWrite(PWR2, LOW);
      digitalWrite(PWR4, LOW);
      Display = Memory3;
      goto skip;
      digit4:
      digitalWrite(PWR4, HIGH);
      digitalWrite(PWR1, LOW);
      digitalWrite(PWR2, LOW);
      digitalWrite(PWR3, LOW);
      Display = Memory4;
      skip:

       // Manual Turning on of LEDs is overcomplicated and can be made much shorter yes I know :(
       if (Display == 1) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(B, LOW);
        digitalWrite(C, LOW);
      }
      if (Display == 2) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(G, LOW);
        digitalWrite(E, LOW);
        digitalWrite(D, LOW);
      }
      if (Display == 3) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(C, LOW);
        digitalWrite(G, LOW);
        digitalWrite(D, LOW);
      }
      if (Display == 4) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(B, LOW);
        digitalWrite(G, LOW);
        digitalWrite(F, LOW);
        digitalWrite(C, LOW);
      }
      if (Display == 5) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(F, LOW);
        digitalWrite(G, LOW);
        digitalWrite(C, LOW);
        digitalWrite(D, LOW);
      }
      if (Display == 6) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(F, LOW);
        digitalWrite(G, LOW);
        digitalWrite(C, LOW);
        digitalWrite(D, LOW);
        digitalWrite(E, LOW);
      }
      if (Display == 7) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(C, LOW);
      }
      if (Display == 8) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(C, LOW);
        digitalWrite(D, LOW);
        digitalWrite(F, LOW);
        digitalWrite(G, LOW);
        digitalWrite(E, LOW);
      }
      if (Display == 9) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(C, LOW);
        digitalWrite(D, LOW);
        digitalWrite(F, LOW);
        digitalWrite(G, LOW);
      }
      if (Display == 0) {
        digitalWrite(A, HIGH);
        digitalWrite(B, HIGH);
        digitalWrite(C, HIGH);
        digitalWrite(D, HIGH);
        digitalWrite(E, HIGH);
        digitalWrite(F, HIGH);
        digitalWrite(G, HIGH);
        digitalWrite(A, LOW);
        digitalWrite(B, LOW);
        digitalWrite(C, LOW);
        digitalWrite(D, LOW);
        digitalWrite(E, LOW);
        digitalWrite(F, LOW);
      }

      // Checks how many times it has looped over
      Loop = Loop + 1;
      if (Loop < 4) {goto loop;}
      else
      {
        // Resets Loop count and counts 1 second (normally it has a delay(1000) but the delay(250) on the loop to account for LED's turning on is counting for me )
        Loop = 0;
        TimeSec = (TimeSec + 1);
        if (TimeSec == 60) {
          TimeMin1 = (TimeMin1 + 1);
          Memory1 = TimeMin1;
          TimeSec = 0;
          if (TimeMin1 == 10) {
            TimeMin2 = (TimeMin2 + 1);
            Memory2 = TimeMin2;
            TimeMin1 = 0;
            Memory1 = TimeMin1;
            if (TimeMin2 == 7) {
              TimeHour1 = (TimeHour1 + 1);
              Memory3 = TimeHour1;
              TimeMin2 = 0;
              Memory2 = TimeMin2;
              if (TimeHour1 == 10) {
                TimeHour2 = 1;
                Memory4 = TimeHour2;
                TimeHour1 = 0;
                Memory3 = TimeHour1;
                if (TimeHour1 == 3 && TimeHour2 == 1) {
                  TimeHour2 = 0;
                  Memory4 = TimeHour2;
                  TimeHour1 = 1;
                  Memory3 = TimeHour1;
                }
              }
            }
          }
        }
      }
    }

And here's how it's Wired up[![][1]][1]

  [1]: https://i.stack.imgur.com/iR0eS.png

Also I think that I have to make a clock of my own for the Timer or else it will become a problem later on but I don't know how to make 2 loops so if someone can tell me how to do it (preferably in a way that I can understand xD) I'd be very grateful

**Notes:**

- The Displays are Common Anode so to turn on a LED I used `digitalWrite(ledpin, LOW)` for a negative output
- I'm not using a 4 digit 7-segment display -- I'm using 4 individual 7-segment displays
- Resistors are 220 Ohm
- The Picture was made using https://circuits.io
- I'm still new at this so my code may have some newb mistakes or just stuff that was made overcomplicatedly simple if you know what I mean :P

UPDATE 1:

I fixed it now the problem was I was setting the variables to bool instead of integer but I still can't figure out how to do a self-sufficient clock because the current code now runs but doesn't turn on as fast as I need to

body:
There are several bugs that I spot right off the bat.  First off, you should never need goto in C++.  You should be able to use if, for, and while to completely eliminate those. goto makes code hard to follow and read, so it makes it nearly impossible for someone else to try to debug.  Be nice to yourself and forget that goto ever existed.  I would suggest hitting a C++ tutorial and learning about functions, because most of the places you've used goto, what you really needed was a function call.

Second is this:

    bool A = 2;
    bool B = 3;
    bool C = 4;
    bool D = 5;
    bool E = 6;
    bool F = 7;
    bool G = 8;

A bool is meant to hold a true or false value, not a pin number.  You should use int here, or better yet save a few bytes and use byte.  But not bool.  The second issue here are the single capital letter variable names.  Those are always a bad idea.  Many of them (B and F for sure) are already defined as macros in the core.  They're not available for you to use.  Single letter variable names are bad form, but single capital letters are right out.

Third is the way you have the digits connected.  There should be a resistor for each segment, or you will have brightness differences depending on how many segments are in use at any one time.  But that can wait until you get the code worked out.

Finally, here is some code for working with 7-segment displays.  It's a lot easier to work with than the whole thing you've got written out.  See if you can follow it and ask questions if you don't understand.  This code would count 0 to 9 over and over on a single 7 segment display.

    byte digits[] = {0b1111110 , 0b0110000, 0b1101101, 0b1111001,
    0b0110011, 0b1011011, 0b1011111, 0b1110000, 0b1111111, 0b1111011};

    // pins to segments g,f,e,d,c,b,a
    byte pins[] = {3,4,5,6,7,8,9};

    void displayNumber(int aNumber) {
      for (int i = 0; i < 7; i++) {
        digitalWrite(pins[i], digits[aNumber] & (1 << i));
      }
    }

    void setup(){
      for (int i = 0; i < 7; i++){
        pinMode(pins[i], OUTPUT);
      }
    }

    void loop(){
      for (int i = 0; i < 10; i++) {
        displayNumber(i);
        delay(1000);
      }
    }


message:
Problem with 2 decimal places/2 significant figures

Lora/GPS Shield + Arduino Uno + PLX-DAQ (latest custom version)

I have a problem on how to generate more than 1/2 decimal output.
Currently, I'm trying to generate GPS Lat and Long(code from TinyGPS++) on PLX-DAQ

[![enter image description here][1]][1]

Just like in the image. Latitude generated in 1/2 decimal places.
I'm trying to get more than 2 decimal places.

For example : from 3.2 to 3.123953

Coding link:
https://www.dropbox.com/s/rqjpnsc9pg33f9n/Coding.txt?dl=0

Thanks.

  [1]: https://i.stack.imgur.com/rWoEz.jpg

body:
You're talking about the output from this line?

    Serial.println( (String) "DATA,DATE,TIME," +flat+ "");

drop the use of the String class and make that two separate print statements.  Then you can use the second argument to print to define the precision.

    Serial.print("DATA,DATE,TIME,");
    Serial.println(flat, 6);

That gets the same end result output going out the serial line, but lets you specify the precision and avoids the nasty String class.


message:
I am trying to combine an automatic door lock with an RFID MFRC522 with a IR REMOTE program

I am getting this error.

    Arduino: 1.8.2 Hourly Build 2017/02/17 11:33 (Windows 8.1), Board: "Arduino/Genuino Uno"

    Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

    (.text+0x0): multiple definition of `__vector_7'

    libraries\REMOTE\IRremote.cpp.o (symbol from plugin):(.text+0x0): first defined here

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Arduino/Genuino Uno.

    This report would have more information with
    "Show verbose output during compilation"
    option enabled in File -> Preferences.

Here is the entire code:

    #include <RFID.h>
    #include <Wire.h>  // i2C Conection Library
    #include <LiquidCrystal_I2C.h>  //Memanggil i2C LCD Library
    LiquidCrystal_I2C lcd(0x3F, 16, 2);

    #include <SPI.h>
    #include <RFID.h>
    #define SS_PIN 10
    #define RST_PIN 9

    RFID rfid(SS_PIN,RST_PIN);

    const int buzzer = 7;   //Passive buzzer ke Pin D7 dan GND
    const int doorLock = 8; //Driver Selenoid Door Lock/Relay input ke pin D8
    int serNum[5];          //Variable buffer Scan Card

    int cards[][5] = {      //ID Kartu yang diperbolehkan masuk
      {120, 181, 196 ,101, 14}

    };

    bool access = false;

    int alarm = 0;
    uint8_t alarmStat = 0;
    uint8_t maxError = 5;
    void setup(){
        Serial.begin(9600);
        lcd.begin();
        SPI.begin();
        rfid.init();

        pinMode(doorLock, OUTPUT);
        digitalWrite(doorLock, HIGH);

      tone (buzzer,1200);
      lcd.setCursor (0,0);
      lcd.print(F("  RFID System   "));
      lcd.setCursor (0,1);
      lcd.print(F(" Control Access "));
      delay (2000);
      lcd.clear();
      noTone (buzzer);
    }

    void loop(){
      if (alarm >= maxError){
        alarmStat = 1;    }

      if (alarmStat == 0){
      lcd.setCursor (0,0);
      lcd.print(F(" -System Ready- "));
      lcd.setCursor (0,1);
      lcd.print(F(" Scan Your Card "));

        if(rfid.isCard()){

            if(rfid.readCardSerial()){
                Serial.print(rfid.serNum[0]);
                Serial.print(" ");
                Serial.print(rfid.serNum[1]);
                Serial.print(" ");
                Serial.print(rfid.serNum[2]);
                Serial.print(" ");
                Serial.print(rfid.serNum[3]);
                Serial.print(" ");
                Serial.print(rfid.serNum[4]);
                Serial.println("");

                for(int x = 0; x < sizeof(cards); x++){
                  for(int i = 0; i < sizeof(rfid.serNum); i++ ){
                      if(rfid.serNum[i] != cards[x][i]) {
                          access = false;
                          break;
                      } else {
                          access = true;
                      }
                  }
                  if(access) break;
                }
            }

           if(access){
              Serial.println("Welcome!");
              lcd.setCursor (0,0);
              lcd.print(F(" DOOR UNLOCKED!! :)"));
              lcd.setCursor (0,1);
              lcd.print("ID:");
              lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
              lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
              lcd.print(rfid.serNum[4]);
               digitalWrite(doorLock, LOW);
               tone (buzzer,900);
               delay(100);
               tone (buzzer,1200);
               delay(100);
               tone (buzzer,1800);
               delay(200);
               noTone(buzzer);
               delay(600);
               lcd.setCursor (0,0);
               lcd.print(F("WELCOME"));
               lcd.setCursor (0,1);
               lcd.print(F("AutoLock after "));
               for(int i=5; i>0; i--){
                lcd.setCursor (15,1); lcd.print(i);
                delay (1000);
               }
               digitalWrite(doorLock, HIGH);
               lcd.clear();
          } else {
               alarm = alarm+1;
               Serial.println("Not allowed!");
               lcd.setCursor (0,0);
               lcd.print(F(" ACCESS DENIED!!  "));
               lcd.setCursor (0,1);
             lcd.print("ID:");
               lcd.print(rfid.serNum[0]); lcd.print(rfid.serNum[1]);
               lcd.print(rfid.serNum[2]); lcd.print(rfid.serNum[3]);
               lcd.print(rfid.serNum[4]);
               tone (buzzer,900);
               delay(200);
               noTone(buzzer);
               delay(200);
               tone (buzzer,900);
               delay(200);
               noTone (buzzer);
               delay(500);
               lcd.clear();
           }
        }
        rfid.halt();
    }
    else {
      lcd.setCursor (0,0);
      lcd.print(F("-System LOCKED- "));
      lcd.setCursor (0,1);
      lcd.print(F(" Please Wait "));
    for(int i=5; i>0; i--){
    tone (buzzer,4000);

    lcd.setCursor (13,1); lcd.print(i);
    lcd.print(F("  "));delay (1000);}
    noTone (buzzer);
    alarmStat = 0;
    alarm = 0;
      }
    }

    //code  of an IR REMOTE

    #include <IRremote.h>

    int RECV_PIN = 2; // the pin where you connect the output pin of TSOP4838
    int lock =13 ;
    int itsONled[] = {};
    /* the initial state of LEDs is OFF (zero)
    the first zero must remain zero but you can
    change the others to 1's if you want a certain
    led to light when the board is powered */
    #define code1 26775 // code received from button 1

    IRrecv irrecv(RECV_PIN);

    decode_results results;

    void remote()
    {
      Serial.begin(9600);   // you can comment this line
      irrecv.enableIRIn();  // Start the receiver0
      pinMode(lock, OUTPUT);

    }

    void loop_1() {
      if (irrecv.decode(&results)) {
        unsigned int value = results.value;
        switch(value) {
           case code1:
             if(itsONled[1] == 1) {        // if first led is on then
                digitalWrite(lock, LOW);   // turn it off when button is pressed
                itsONled[1] = 0;           // and set its state as off
                Serial.println("ledl OFF");
             } else {                      // else if first led is off
                 digitalWrite(lock, HIGH); // turn it on when the button is pressed
                Serial.println("led 1 ON");
                 itsONled[1] = 1;          // and set its state as on
             }

              break;
        }

        Serial.println(value); // you can comment this line
        irrecv.resume(); // Receive the next value
      }
    }

body:
1.  You can't use tone and IRremote in the same sketch as they are both trying to use the same timer interrupt.

1.  Don't use the hourly build.  It's not tested.  Get the latest stable version if you are working on your final project.  You don't want unknown bugs.  Let the beta testers use the hourly build.  For something like a final project you need things to work, so stick with the stable version, not the bleeding edge of development.


body:
The error message `multiple definition of __vector_7` means that you have more than one interrupt handler defined for the interrupt that has interrupt vector 7.

Although the ATmega328x datasheet in a table called *Interrupt Vectors in ATmega328 and ATmega328P* refers to interrupt vector 7 as the Watchdog Time-out Interrupt, that probably is misleading, because only the following ISRs can be defined in `Tone.cpp`:

    ISR(TIMER0_COMPA_vect)
    ISR(TIMER1_COMPA_vect)
    ISR(TIMER2_COMPA_vect)
    ISR(TIMER3_COMPA_vect)
    ISR(TIMER4_COMPA_vect)
    ISR(TIMER5_COMPA_vect)

(These can be defined, but typically most are not.  All of them are conditional upon which MCU is selected.)

The article [*multiple definition of '__vector_7'*](http://forum.arduino.cc/index.php?topic=133553.0) at arduino.cc attributes the problem to the last of those ISRs, `ISR(TIMER5_COMPA_vect)`.   Anyhow, in short, you might need to check what board or MCU you are compiling for, or may need to find a substitute for one of `Tone` or `IRremote`, the libraries that are both defining the ISR that has a conflict.

*Edit 1:* The article [TimerFreeTone Library v1.5: Play tones without timers and therefore no conflicts](http://forum.arduino.cc/index.php?topic=235774.0) at arduino.cc describes a *TimerFreeTone v1.5* library that generates tones without using timers.  You might be able to use that library in place of the `Tone` library that has a conflict.


message:
How can I get my Attiny85 interupt to trigger

I have an ATTiny85 set up to detect a magnet passing over a hall sensor. Every 2 detection's I want it to light up an LED.

I decided to do the code using the arduino IDE and the code is as follows:

    const int hallPin = 2;     // the number of the hall effect pin
    const int ledPin =  1;      // the number of the LED pin

    // variables will change:
    volatile int hallState = 0;         // variable for storing the hall counter

    void setup() {

      pinMode(ledPin, OUTPUT);
      pinMode(hallPin, INPUT);
      digitalWrite(hallPin, HIGH);

      // Attach an interrupt to the ISR vector
      attachInterrupt(0, pin_ISR, FALLING);
    }

    void loop()
    {
      if(hallState>1)
      {
          digitalWrite(ledPin,HIGH);
          delay(2000);
          digitalWrite(ledPin,LOW);
          delay(2000);
          hallState=0;
      }
    }

    void pin_ISR()
    {
        hallState++;
    }

I've dry run this a bunch of times and cant see anything wrong with it. I use the digitalWrite on the hall pin to enable the internal pullup. But the circuit just doesnt work.

Here is the circuit:

[![Diagram of circuit][1]][1]

I connected a multi meter to the hall effect sensor on its own just to check if it was working. I added an external pull up using a 10k resistor and it worked as expected 5v when no magnet present and almost 0 volts when a magnet is brought in range.

So my guess is my interrupt routine isnt working in my code, what could I be doing wrong? I've read in the documentation that pin 0 is the correct interrupt pin on the attiny85

Edit: Adding Schematic

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/oz2be.png
  [2]: https://i.stack.imgur.com/Xjwpw.png
  [3]: https://i.stack.imgur.com/vMyM6.png

body:
You main problem is that you have wired up your MCU wrong.

Pin 5 (PB0) is *not* the external interrupt pin. Pin 7 (PB2) is the external interrupt 0 (INT0) pin.

As a result your code will not do anything when the hall sensor changes because it is not looking at it.

---

I would suggest not trying to use the `attachInterrupt()` abstraction. Instead I would simply enable the external interrupt directly:

    GIMSK |= _BV(INT0);

And use a proper ISR handler:

    ISR(INT0_vect) {
        //Your ISR code here.
    }


message:
programming arduino in pure c

I'm trying to flash pure c-code to arduino Mega2560 board from linux using avr-gcc & avrdude. Compilation is done , now trying to flash using avr-dude, getting error as "*avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00*"

I used below command to produce hex file

    avr-gcc -mmcu=atmega2560 -DF_CPU=16000000UL led.c -o led.elf
*In file included from led.c:3:0:
/usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed" [-Wcpp]
 # warning "Compiler optimizations disabled; functions from <util/delay.h> won't work as designed"*

And then

    avr-objcopy -j .text -O ihex led.elf led.hex
finally for flashing

    avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex
FYI: port is correct & RX pin is blinking i.e connection is perfect between computer & board

body:
> In file included from led.c:3:0:
> /usr/lib/avr/include/util/delay.h:95:3: warning: #warning "Compiler
> optimizations disabled; functions from won't work as designed"

You should start by fixing this. Simply add `-Os` to the compiler
command line. This means “optimize for size”, and is the standard
optimization option used with Arduinos.

> avr-objcopy -j .text -O ihex led.elf led.hex

If your copy of avrdude was compiled with libelf (like the one supplied
with Ubuntu is), you don't need this: you can hand your elf file
directly to avrdude.

> avrdude -F -V -c arduino -p ATMEGA2560 -P /dev/ttyACM3 -b 115200 -U flash:w:led.hex

`-F` tells avrdude to **not** verify the device signature. `-V` tells it
to **not** verify the upload. I wouldn't use any of these options unless
I had a very good reason to do so. `-c arduino` is wrong: it selects the
upload protocol used by optiboot (used, e.g., in the Uno). The
Mega 2560 uses a different bootloader based on the “wiring”
protocol. I would also add the `-D` option (disable auto erase) because
I saw the Arduino IDE using it, and because without this option I get
the error:

    avrdude: erasing chip
    avrdude: stk500v2_command(): command failed

In the end, the upload command ends up being something like:

    avrdude -p atmega2560 -c wiring -P /dev/ttyACM3 -b 115200 -D -U led.elf


message:
How to make DC motor rotate a specific number of turns?

Can someone please give the code which can be used to rotate the dc motor a specific number of rotations like 2 rotations or 5 rotations. I'm using arduino uno board.

body:
No! That is not how motors work.

If you need precision control you need to use a stepper motor or servo.

You could implement some solution with a geared motor and position sensor, but this really only works (imprecisely) with a slow rotation speed.


body: You can't. You either have to attach a sensor to the motor shaft to measure the numbers of rotations or use a stepper motor.


message:
Correct use of interrupt vs monitoring switch

Background:
I have a uni assignment which requires an autonomous robot to do a number of tasks and then finish in a set spot after being triggered to start by an outside physical interaction. I've set up a light limit switch to detect this interaction.

My approach would normaly be to look for the switch in the loop to go high and then run through my code and put a really long delay at the end.
e.g.

    switchState = digitalRead(switch);
     if (switchState == HIGH){
     //do my routine which is a function defined outside of the loop
    }
Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

body:
No, an interrupt here would be pointless.

You use an interrupt to detect a change on an input whilst you are doing something else. It's a good way of getting instant (or near instant) notification of something happening.

If you're using the input to start something going when there's nothing happening then you gain nothing other than extra complexity by using an interrupt. You're not doing anything else, and you don't need an instant response, so just polling the input is the simplest option.


body:
> Would this be an appropriate use for an interupt instead of the method above. I'm still trying to understand the best practice usage.

it depends critically on your definition of "go high", ie. if you are looking for a transition to high, or if you are looking for the switch to be high. edge triggererd vs. level triggered.

As is, your existing (level-triggered) logic can be easily implemented via an interrupt, as will an edge triggered logic.

interrupt-driven code is generally more efficient for slow / infrequent inputs: it doesn't waste the cpu's processing power. But it does add a level a complexity that can be difficult to handle for beginners.

As for me, I think it is (practically) impossible to code without the use of interrupts.


message:
analogRead over a certain time

I would like to read an analog value using analogRead, save this value and compare it to an analogRead value 5 ms later. How would this code look? Because giving a variable the value of analogRead(A0); would mean it is constantly changing, making it impossible to compare two values.

thanks in advance

body:
The simplest and crudest method:

    int val1 = analogRead(A0);
    delay(5);
    int val2 = analogRead(A0);

    if (val2 > val1) {
        // It went up (for example).
    }


body:
You just need to copy the value into another before you overwrite it with `analogRead(A0)` and then compare those two variables.

<!-- language: c++ -->

    int prev_value = 0;
    int value = 0;
    unsigned long prev_read_time = 0;

    void setup() {
        prev_read_time = millis();
        value = analogRead(A0);
    }

    void loop() {
        if (millis() - prev_read_time > 5) {
            prev_read_time = millis();
            prev_value = value;
            value = analogRead(A0);
            if (prev_value != value) {
                // value changed
            }
        }
    }