message:
Sketch upload freezes during write

I'm trying to upload a huge sketch to my **Uno R2**. It's compiling just fine but it fails to upload at 94% of writing to flash...

The program is so large because of a big array of data in a separate .h file:

    #include <avr/pgmspace.h>
    const unsigned char PROGMEM data[] = {
      0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7f, 0x80, 0x7f, 0x80, 0x7f, 0x80, (etc...)

A test sketch with just 12 bytes of data uploads fine, so the problem is either with the size or some weird bug triggered by some of the data.

Unless i'm missing something, this should technically work.

Command:

        /home/hatagashira/.arduino-1.6.5/hardware/tools/avr/bin/avrdude -C/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/build8921209068074674980.tmp/program.cpp.hex:i

Output:

    avrdude: Version 6.0.1, compiled on Apr 14 2015 at 19:04:16
             Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
             Copyright (c) 2007-2009 Joerg Wunsch

             System wide configuration file is "/home/hatagashira/.arduino-1.6.5/hardware/tools/avr/etc/avrdude.conf"
             User configuration file is "/home/hatagashira/.avrduderc"
             User configuration file does not exist or is not a regular file, skipping

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

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

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

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: safemode: lfuse reads as 0
    avrdude: safemode: hfuse reads as 0
    avrdude: safemode: efuse reads as 0
    avrdude: reading input file "/tmp/build8921209068074674980.tmp/program.cpp.hex"
    avrdude: writing flash (30110 bytes):

    Writing | ###############################################    | 94% 5.10savrdude: stk500_recv(): programmer is not responding

body: My two arduino nanos did flash and run the program correctly. I suspect a problem with the uno's serial communication but unwilling to troubleshoot further (i only have one uno). I decided to switch to the nano for further prototyping.


sender: user

message:
Using 2 RGB lights over Bluetooth with a DigiSpark

I'm not that experienced with electronics but I am learning. And I've set a challenge for myself. I have a Digispark USB Development board (and many more but I want to use this one!), I have a Bluetooth module and I have two RGB LEDs which I want to control over the Bluetooth connection. Each LED has to be controlled separately and I want to be able to set each color separately and be able to mix about 256x256x256 colors. Which means, PWM connections. The Bluetooth connection would listen to instructions, receiving four bytes containing RGB values and a value between 0 and three to pick which light needs to be set. (0=None, 1=left, 2=right, 3=both)
Also important is that it needs to be small. It will end up in a container of of roughly 3x3x10 CM in size. (Slightly bigger than 1x1x3 inch.)

The challenge is that Digispark only has 6 pins available so that's not enough to handle this all. I could use three pins and use a 74HC165N Shift Register but that would just turn each color on or off, thus limiting me to 8 colors. That's not good enough! Besides, I also need to connect the four pins of the Bluetooth module.

So my question is simple: What would I need more to build this project? To send the proper six analog signals while having enough pins to handle the Bluetooth datastream?

sender: assistant

body:
> Which means, analog connections.

Nope. It means PWM.

How would you control the brightness of a single LED?

By generating a PWM signal with:

 -  sufficiently high frequency to not be able to notice the flickering;

 -  duty cycle proportional to the brightness you want/need, where 100% is full brightness, and 0% is OFF

You only have to do that for each colour of the RGB LED you want to drive.
Ideally you would use a HW block capable of generating the PWM signal, but it can be also bit-banged, should you run out of PWM blocks.

Just keep in mind that different colours have different currents (for the same level of brightness), so you have to pay attention at calculating the correct value of the resistor applied to each colour.

If you prefer to ensure that each channel is driven by a HW PWM generator, you can also use an external driver. Ex: [I2C 6-channels PWM generator][1].

  [1]: http://www.intersil.com/en/products/audiovideo/display-ics/led-backlight-drivers/ISL97671A.html


message:
How do I know which is ground and power in Piezo?

I have a piezoelectric sensor. Both pins are the same length. I have one like this: [Piezo picture][1]. On the Piezo it's written *muRata* and *01P*. How do I know which do I send to the digital pins and which to the ground? I have an Arduino Uno.

  [1]: https://cdn.solarbotics.com/products/photos/93c51bd69dcc15a0f60bb6bb4c96d4df/lrg/17855-dscn3894.JPG

body: On the one I have, the shorter pin is ground. I discovered that empirically - a scientific word for "I tried it the wrong way round the first time but the magic smoke stayed inside." Afterwards I inspected it more carefully, I found a '+' embossed in the top surface nearer one side. :-o


body:
If you're using just one or sound quality doesn't matter: it doesn't matter.

Otherwise you need to figure it out with a scope like [this][1]:

- Connect both poles of the connector of the PZT to an oscilloscope (time base approx. 50ms/div, y-axis 200mV/div).
- Slightly tap the head of the PZT with your finger. As a result you should get a voltage pulse on the oscilloscope.
- Positive Amplitude  -> + pole of the piezo is connected to the inner conductor of the oscilloscope BNC connector.
- Negative Amplitude -> + pole of the piezo is connected to the outer conductor of the oscilloscope BNC connector.

  [1]: http://service.toptica.com/index.php?pg=kb.page&id=7


message:
Open the Uart0 Serial Port on Intel Edison

I'll preface this buy saying I am very new to working with Arduino boards or hardware in general.
I am attempting to follow a tutorial on instructables

http://www.instructables.com/id/PCBot/step4/Printer-test/

I have my board and printer wired up properly and I have git cloned the python thermal printer. My issue begins at this paragraph:

> Open the UART0 serial port
by default the GPIO's of the edison are disables.

>You can enable them by programming the edison via the Arduino IDE or by using the MRAA library available for several programming languages.

>To open enable the UART0 port, TX RX on the edison breakout board, open a Python shell in the thermal and write:

>import mraa

>x=mraa.Uart(0)

I opened a python shell and entered the `import mraa` lines and tried to run the `printertest.py`

I receive an error that says no module named serial. I am not sure where the issue is. I thought the Edison already had python serial installed. I did try to install it with `opkg install python-serial` but it didn't work. If my issue is with enabling the Uart0 port I am not sure how to go about doing it. I have the Arduino IDE installed but I have no idea how to go about enabling it via the Arduino IDE. The instructions are a bit vague in that paragraph.

*Update I have successfully installed pip and got pyserial installed. Now when I try to run the printertest.py I get an error `OSError: [Errno 2] No such file or directory: '/dev/ttyAMA0'` which I think is potentially caused by me not succesfully opening Uart0 port but I am not sure how to. I tried adding the import in a shell as well as adding it directly to the code via nano

body: I have solved the issues and successfully connected this printer with the Compute Module. I solved the issue by changing the target of `/dev/ttyAMA0` to `/dev/ttyMFD1` as shown by http://iotdk.intel.com/docs/master/mraa/edison.html . This was the final step after I had installed pyserial.


message:
esp8266 garbage out only when using SoftwareSerial

I'm trying to operate the esp8266. When I connect RX+TX pins to pins 1+2 on the Arduino, everything works fine. but when I'm trying to use software serial all hell breaks loose and the recieved data is garbadeged (It seems like everything is ok but I can't read the output data...
more interesting, the output is not consistent!

example:

    #include <SoftwareSerial.h>
    SoftwareSerial esp8266(11, 10); // RX, TX
    void setup() {
        // put your setup code here, to run once:
        esp8266.begin(19200);
        Serial.begin(115200 );
    }

    void loop() {
        esp8266.write("AT\r\n");
        String buffer;
        Serial.print("SENDING AT...");
        for(uint64_t time = millis();(time+1000) > millis();)
           for(;esp8266.available();buffer+=(char)esp8266.read());
        buffer.replace("\r\n"," ");
        Serial.println("RESPONSE:" + buffer);
    }
And the output:
[![enter image description here][1]][1]

I've tried changing the SerialMonitor baud rate, the input pins, but results are all the same.

I've recently changed the MCU(uno) to a different and even a different esp module from a different supplier,
I am still getting the same results! I can't be the first one to encounter such phenomena...

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

body:
Try dropping the SoftwareSerial connection speed to 19200. Ie, esp8266.begin(19200). 115200 it is the absolute max the SoftwareSerial can theoretically handle.
Also if you are not using all the change interrupt pins on your MCU (Uno/Nano?) then use any 2 pins from 10, 11, 12 or 13 rather than 3, 2 // RX, TX.
Not sure about sendCommand function. If you just want to test the connection then it should be as simple as:

    SoftwareSerial esp8266(10, 11); // RX, TX

    void setup() {
        esp8266.begin(19200);
        Serial.begin(115200 );

        char buffer[50];
        esp8266.write("AT\r\n");
        esp8266.readBytes(buffer, sizeof(buffer));
        Serial.println(buffer);

    ...
    }

Obviously once you need to open web pages and recieve responses then you will need a libary to handle IDP+ data. With a bit of coercion I got Adafruit_ESP8266.h working with SoftwareSerial.


body:
A quick thing to try out.

Try changing `Serial.begin(115200);` to `Serial.begin(9600);` and leave  `esp8266.begin(115200);`.

I'm also completely new to Arduino, but I remember seeing the junk values when the serial monitor baud rate is set to a different value than the Arduino's Baud rate.

I was using Arduino Uno and if I set the baud rate to a value other 9600 in the serial window, I was seeing junk values in println function calls.

i.e Set `Serial.Begin(9600);` and the Serial Montior baud rate also `9600`.


body: From my experience, if you want to have a consistent data transfer over the softserial, you must disable (in Arduino) the global interrupts for the time of transmission. To disable global interrupts use cli() command, to enable it again use sei() command.


message:
Problem with connecting ESP8266 to arduino

I have:

 - Arduino Uno
 - [ESP8266][1]

Problem:
I see SoftAP and can connect to it. But I can't send AT-commands to ESP8266 from Arduino.
I use Arduino app v.1.6.5 for send command to ESP8266 via Arduino. But I don't get answer. And ESP8266 doesn't blinking.

I use this scheme:

[![Scheme for connecting Arduino and ESP8266][2]][2]

Please, help me. I'm trying to fix this is very time consuming.

  [1]: http://www.amazon.com/gp/product/B00PI6TO8U
  [2]: https://i.stack.imgur.com/Co7kW.png

body:
I had the same problem. I solved it doing the following:

Connect Arduino TX to a voltage divider (to get 3,3V) and then to TX on ESP8266
Connect Arduino RX to RX on ESP8266

It should work!.

Please read the information on this link
http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf


body:
I had the same problem. I used `SoftwareSerial` library, so you should set baud rate as 115200 for communication with esp8266. It might look like this:

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(2,3);

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

It helped in my case.


body:
You must need to add another power supply, which will give to the wifi module not just the correct voltage (3v) but the mA that it need.  / other thing you may need to do is connect the ground of Arduino to Ground of the power supply. For me works good.

the connections would be like this

 1. esp TX     > arduino dpin 10
 2. esp RX     > arduino dpin 11
 3. esp CH     > to VCC 3V
 4. esp RST    > to pushbutton connected to gnd
 5. esp GpIO 0 > none
 6. esp GpIO 2 > none
 7. esp VCC > power supply 3v
 8. esp GND > power supply gnd


message:
Extracting high and low bytes from long

I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.

    #define highWord(w) ((w) >> 16)
    #define lowWord(w) ((w) & 0xffff)

The first line i clearly understood like this, please make corrections if i am wrong.

    32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100

by right shifting last 16 bits we will arrive at

    32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010

I am not able to interpret the second line.

    #define lowWord(w) ((w) & 0xffff)

I would be very grateful if some body explain how the above line of code works?
Thanks.

body:
The second line masks off the top two bytes using a bitwise AND.

When you use a bitwise AND it follows the normal rules for any boolean truth table.  1 & 1 = 1, 1 & 0 = 0...  Since the value is being ANDed, effectively, against 0x0000FFFF, the top two bytes will be cleared to zero while the bottom two bytes are preserved.  In this way you can extract the lower two bytes out of the four byte long.


body:
An alternative way of seeing the two operations is through the operators "integer division" and "reminder of the integer division".

In a more generic fashion:

`#include <limits.h>`

`#define highBits(value, number_of_high_bits) \
 (value / (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))`

`#define lowBits(value, number_of_high_bits) \
 (value % (1 << (sizeof(value) * CHAR_BIT - number_of_high_bits)))`

This will work regardless the number of bits used for `value` and with an arbitrary number of `high_bits` to either keep or shave.


message:
Capacitive sensor MPR121 on Arduino Uno—how many will work?

I need to attach several capacitive sensors MPR121 with each of them using all of its 12 electrodes to an Arduino Uno.

Could you please tell me, how many will work with the voltage and current Arduino Uno supplies?

body:
The answer is 4 regardless of the current consumption.

You can have 4 MPR121 devices on an I2C bus (by connecting the ADDR pin to the right place to select 1 of 4 addresses), and the Uno has one I2C bus - so that means 4 devices.

You *could* use software I2C to add more devices on other pins, but that's slow and clunky.

But that aside, if you used something to increase the number of I2C buses available, according to the datasheet the peak current consumption is 1mA during sampling, and assuming 300mA maximum for the Arduino's 3.3V regulator, that would mean a maximum of 300 MPR121 connected to the Arduino.  Note that, if you could actually *get* to the Arduino amongst that tangle of wires, you'd find it getting rather hot...


message:
433Mhz transmitter interference when using long cable, only on Arduino Due

When the 433 transmitter is wired close to the Arduino Due (within 12" away), it works as expected. But when I put it on the end of a 15' cable, it has the following 2 symptoms:

-All the other nearby 433Mhz transmitters and receivers stop working. (I've never seen this happen from any other cause).

-My Extech 480836 EMF meter shows a big jump in electromagnetic radiation along the entire length of the 15' cable (it jumps from *0.1 uW/m2* to *3 mW/m2* a few inches away). The reading only goes down to normal if I unplug the transmitter's data wire from the Arduino.

The transmitter in question is still able to send signals correctly when wired with a 15' cable to the Due (properly activating remote switches), even though it disables every other 433 transmitter in the area.

I've tested this with 2 different kinds of 433 transmitters, getting the same result. Both of the transmitters work fine whenever wired closely to the Arduino Due, and both work as expected when connected to an Arduino Uno. The problems still occur even if I'm not sending any wireless transmissions from the code. Disconnecting the transmitter's data wire from the Arduino Due causes the problem to stop immediately.

I'm using the [RCSwitch library][1]. The simple code below works fine on an Arduino Uno, whether the transmitter is wired far or close to the Uno. The same code works fine with the Due when the transmitter is close to the Due. But when the transmitter is wired 15' away from the Due, then the problems occur. On the Due I've tested using 5v and 3v for powering the transmitter. Changing the voltages doesn't seem to affect the problem.

    #include <RCSwitch.h>
    RCSwitch mySwitch = RCSwitch();

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

      // Transmitter is connected to Arduino Pin #8
      mySwitch.enableTransmit(8);
    }

    void loop() {}

Why am I having this strange behavior? Do you have any suggestions on how to fix it?
  [1]: https://github.com/sui77/rc-switch

body:
I think I found the problem. It seems that there's an anomaly with the Due where when a pinmode is set as OUTPUT, it sets the pin as HIGH by default, whereas with the other Arduinos it's set as LOW. This forum page is discussing the problem: http://forum.arduino.cc/index.php?topic=154869.0

Likewise this page suggests the problem is a bug with the wiring_digital.c file: http://forum.arduino.cc/index.php?topic=185230.0

In RCSwitch.cpp, this is the enableTransmit code:

    void RCSwitch::enableTransmit(int nTransmitterPin) {
      this->nTransmitterPin = nTransmitterPin;
      pinMode(this->nTransmitterPin, OUTPUT);
    }

It seems the code sets the pin as OUTPUT, which would cause an anomaly on the Due alone.

I solved the problem by calling the enableTransmit function just before sending a signal, and then calling disableTransmit() immediately afterwards. Can anyone think of a cleaner/better solution?

Out of curiosity, can anyone suggest what a standard transmitter might be sending when the data line is constantly held at HIGH?


message:
How to read the serial data from a ATMEGA8 on a PC using Arduino?

I want to check if a device is working or not. It is a custom made PCB with a Atmega8. It was given to me along with the AVR code. How do I read the data that it sends on my laptop using a arduino, preferably a Arduino Uno?

I tried connecting the output UART pin to the Rx of the arduino, and then provided the common ground. Then I opened serial monitor on my laptop but I a m not getting anything. Is it because the PCB is damaged or am I doing it wrong?

I have the AVR code which was burned on the IC, so I can provide you with more information if you need.

body:
You can download this example code to your Arduino UNO...

https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

Make sure the baud rate on the line `mySerial.begin(4800)` to match the baud rate your device is sending.

Then run "Serial Terminal" from the Arduino IDE and connect the output of your device to pin 10 on the Arduino.

If the baud rate is correct, you should see the Serial output from your device in the serial terminal window.

## Why you might not want to direct connect

Here is the schematic of the serial port section of the Arduino UNO...

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

The TX pin on the header is connected directly connected to the TXD/PD1 pin on the ATMEGA chip as highlighted in red. This pin will be actively driven if any of the following happen...

1. There is a sketch running on the Arduino than enables the serial port (i.e. includes `Serial.begin()`).
2. There is a sketch running on the Arduino that enables pin 1 as output (i.e. includes `pinMode(1,OUTPUT);`).
3. The Arduino reboots and runs the bootloader, which always briefly enables the serial port on startup.

There are some devices that can be permanently damaged by having their serial output tied to an actively driven signal, especially a +5 volt one like we have here. The BBB is one of them (I know from experience!).

One response suggested downloading the `BlinkMe` sketch into the Arduino, presumably to make sure there is not another sketch running that could enable the serial port. This is the right idea, but you have to keep in mind that the UNO will [reboot anytime the RTS line is toggled][2]. Here is a not-so-far-fetched scenario...

1. You load `BlinkMe` into the UNO.
2. You connect the device to the TX pin on the UNO.
3. You launch `Tools-Serial Monitor` from the Arduino IDE to see the serial data.
4. The Serial Monitor window opens and toggles the RTS line (does this every time you launch it).
5. The UNO reboots.
6. The bootloader runs and enables the serial port on the ATMEGA.
7. The connected device is cooked.

Also keep in mind that even if the attached device can tolerate being connected to an actively driven signal, once you connect another signal to the Arduino TX pin then you loose the ability to communicate with the Arduino.

Loading the `Softserial` sketch takes the same number of steps as loading the `BlinkMe` sketch, reduces the chance of of damaging the connected device, and also allows you to keep access to the Arduino while you are doing all this.

  [1]: https://i.stack.imgur.com/qRkWM.png
  [2]: https://arduino.stackexchange.com/questions/439/why-does-starting-the-serial-monitor-restart-the-sketch


body: If you connect the TX pin on your device to the 'TX' pin on the Arduino, then load a sketch such as 'blink' that won't initialize the Arduino's own UART, you can use the Arduino's onboard USB-UART adapter to talk to your device.


message:
pushing accelerometer data in packets from an arduino due to the pc and unto processing

I'm quite a newbie to this and I've been struggling for sometime now with my school project, trying to find a way to send accelerometer data from my MMA7361 in data packets, I understand that I have to send the data in packets, but I'm having problems going about it. One of the requirements of the project is that I have to send the data in array-packets of all the individual axes (e.g. a buffer array to hold the x-axis value, another for the y-axis value and also for the z-axis value). I have read quite a lot of documentation on the internet about this  but putting it together is a challenge. Below is the infamous MMA7361 code sketch, do please help out if you can thankyou.

        #include <AcceleroMMA7361.h>

        AcceleroMMA7361 accelero;
        int x;
        int y;
        int z;

        void setup(){
            Serial.begin(9600);
            accelero.begin(13, 12, 11, 10, A0, A1, A2);
            accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
            accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
            accelero.calibrate();
        }

        void loop(){
            x = accelero.getXRaw();
            y = accelero.getYRaw();
            z = accelero.getZRaw();
            Serial.print("\nx: ");
            Serial.print(x);
            Serial.print("\ty: ");
            Serial.print(y);
            Serial.print("\tz: ");
            Serial.print(z);
            delay(500);                                     //(make it readable)
        }

body:
It's pretty simple to store the x, y and z co-ordinates in three separate arrays. Instead of storing them in single `int` variables you can just store them in `int` arrays. You can make three arrays that are of size 1000 a store the raw values there. In order to iterate through the arrays within `loop()` you can set up `i` at global scope and include an if statement that will know when the arrays are filled, for example `if (i == 1000)` and within this if statement you can set up a `for` loop that will iterate through the arrays and print their values and after reset `i` to `0` and then reset the buffer arrays i.e. fill them with zeroes. This last step is not needed since they will be overwritten anyway but it is good to have so you don't accidentally use old values.

Also the `for` loop that will print the values will take 8 minutes with that `delay(500);` You can make this delay smaller or print the value before each `if` statement as the data comes in.

    #include <AcceleroMMA7361.h>

    AcceleroMMA7361 accelero;
    int xAxisBuffer [1000] = {0};
    int yAxisBuffer [1000] = {0};
    int zAxisBuffer [1000] = {0};

    int i = 0;

    void setup(){
        Serial.begin(9600);
        accelero.begin(13, 12, 11, 10, A0, A1, A2);
        accelero.setARefVoltage(3.3);     //sets the AREF voltage   to 3.3V
        accelero.setSensitivity(LOW);           //sets the sensitivity to +/-6G
        accelero.calibrate();
    }

    void loop(){
        // This stores the x, y and z values in their
        // respective arrays
        xAxisBuffer[i] = accelero.getXRaw();
        yAxisBuffer[i] = accelero.getYRaw();
        zAxisBuffer[i] = accelero.getZRaw();
        ++i; // moves to the next position

        if (i == 1000){ // the arrays are full
            // prints the (x, y, z) values
            // because the delay is .5 seconds it will
            // take about 8 minutes to print all 1000
            for (int j = 0; j < 1000; j++){
                Serial.print("\nx: ");
                Serial.print(xAxisBuffer[j]);
                Serial.print("\ty: ");
                Serial.print(yAxisBuffer[j]);
                Serial.print("\tz: ");
                Serial.print(zAxisBuffer[j]);
                delay(500); //(make it readable)
            }
            // restart at beginning of the arrays
            i = 0;
            // reset the arrays
            memset(xAxisBuffer,0,sizeof(xAxisBuffer));
            memset(yAxisBuffer,0,sizeof(yAxisBuffer));
            memset(zAxisBuffer,0,sizeof(zAxisBuffer));
        }
    }


message:
Debouncing a limit switch in Arduino ISR with delays

I have a limit switch attached to an arduino Mega 2650 for motion control. The limit switch's two Normally Open contacts are connected to an Arduino Pin and ground, such that when the Limit Switch is engaged, the Arduino Pin gets short circuited to ground.

As expected, I have bouncing issues with this setup. I confirmed it using counters in my ISRs. Finally, I wrote the following code that seems to reliably identify whether my limit switch is engaged or disengaged at any given point in time.

 const int lsOuterLeftIn = 18; // lsOuterLeftIn is my Limit Switch
 const int LED = 9;
 volatile bool lsEngaged = false; // flag for limit switch engaged
 void setup() {
  pinMode(lsOuterLeftIn, INPUT_PULLUP);
  pinMode(LED, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR1, FALLING);
  attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR2, RISING);
 }
 void  loop() {
  if (lsEngaged) digitalWrite(LED, HIGH);
  else digitalWrite(LED, LOW);
 }
 void ISR1(){
  delay(100);
  lsEngaged = (digitalRead(lsOuterLeftIn));
 }
 void ISR2(){
  delay(100);
  lsEngaged = (digitalRead(lsOuterLeftIn));
 }

But, here is my problem. I came upon this [Arduino documentation page][1], and it says

    "Since delay() requires interrupts to work, it will not work if called inside an ISR. "

But, I do make use of `delay()` inside ISRs and it seems to work, what is going on? Do I have a situation where things are working at the moment, but could break easily because the `delay()` function could malfunction on me as the documentation says?

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt

body:
What you can do (and is anyway far better than waiting in interrupt context), is to have a volatile variable, which you set in the interrupt (say to 1) and in the main loop you check it: once it is set, you execute the delay and then read the value.

Alternatively, if you can change the sensor, just trade the mechanical switch for an optical end run sensor. If your moving object has steady movement, you will not get any bounces from the optical coupler. Then you can just poll it.


message:
Requesting references for learning about the upload process

I would like to know of references that discuss the process of uploading code onto an Arduino board. I have read this [reference](https://www.arduino.cc/en/Hacking/BuildProcess) on hacking the Arduino and an outline of the build process. I also found this [segment](https://www.arduino.cc/en/Hacking/LibraryTutorial) on creating Arduino libraries informative.

Overall I am interested in tracing through an upload process to learn more detail about how the programming works. I would like to understand which C-libraries are used. I would like to understand how the code is uploaded onto the Arduino. One example that I would like to see is an direct upload of C or C++ code without using the IDE gui. I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++). I would ideally like to read about something like this which makes use of the Arduino libraries.

Looking forward to hearing back responses, and being a part of this community. Any references and comments appreciated.

----------

**Edit #1** (request for more information from the accepted answer):

*How does the main sketch trace through the C/C++ code?*

For example, in the make file shown in the accepted answer:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o

*Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?*

I would think so, being that it is compiled every time we change the main sketch.

*Lastly, how is the outputted .hex file uploaded to the board?*

----------

**Edit #2** Trouble compiling with make method

I am having issues with the manual compiling process, I am using *Arduino 1.6.5 r5*. It seems that *malloc.c* and *realloc.c* are not in the same place as they were in IDE 1.0.6.. Here is the makefile.

    #
    # Simple Arduino Makefile
    #
    # Author: Nick Gammon
    # Date: 18th March 2015
    #
    # Edited by: Kyle Lawlor
    # Date: 30th October 2015

    $H# where you installed the Arduino app
    ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

    # various programs
    CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
    CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
    AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
    OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

    # create a file called Blink.cpp in same base dir
    MAIN_SKETCH = Blink.cpp

    # compile flags for g++ and gcc

    # may need to change these
    F_CPU = 16000000
    MCU = atmega328p

    # compile flags
    GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
    CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
    CC_FLAGS  = $(GENERAL_FLAGS)

    # location of include files
    INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

    # library sources
    LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

    build:

     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
     rm core.a
    # $(AR) rcs core.a malloc.c.o
    # $(AR) rcs core.a realloc.c.o
     $(AR) rcs core.a WInterrupts.c.o
     $(AR) rcs core.a wiring.c.o
     $(AR) rcs core.a wiring_analog.c.o
     $(AR) rcs core.a wiring_digital.c.o
     $(AR) rcs core.a wiring_pulse.c.o
     $(AR) rcs core.a wiring_shift.c.o
     $(AR) rcs core.a CDC.cpp.o
     $(AR) rcs core.a HardwareSerial.cpp.o
     $(AR) rcs core.a HID.cpp.o
     $(AR) rcs core.a IPAddress.cpp.o
     $(AR) rcs core.a main.cpp.o
     $(AR) rcs core.a new.cpp.o
     $(AR) rcs core.a Print.cpp.o
     $(AR) rcs core.a Stream.cpp.o
     $(AR) rcs core.a Tone.cpp.o
     $(AR) rcs core.a USBCore.cpp.o
     $(AR) rcs core.a WMath.cpp.o
     $(AR) rcs core.a WString.cpp.o
     $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
     $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
     $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

The build fails unless the lines involving those two functions are commented out. I searched in the directories but had no luck in finding the libraries, so I decided to move forward in testing things out.

Here is the file I am using as *Blink.cpp*.

    #include <Arduino.h>

    void setup(){
        pinMode(13, OUTPUT);
    }

    void loop(){
        digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
        delay(1000);              // wait for a second
        digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
        delay(1000);              // wait for a second
    }

Again, the *build does compile* ignoring *malloc* and *realloc*. I am unsure of whether these are critical libraries as I am not very familiar with C/C++. While the libraries do compile, *there is an error* derived from the `delay()` function in *Blink.cpp*.

Here is that:

    "/home/wiz/programs/arduino-1.6.5-r5/hardware/tools/avr/bin/avr-gcc" -Os -Wl,--gc-sections -mmcu=atmega328p -o Blink.cpp.elf Blink.cpp.o core.a -lm
    core.a(wiring.c.o): In function `delay':
    /home/wiz/programs/arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/wiring.c:113: undefined reference to `yield'
    collect2: error: ld returned 1 exit status
    make: *** [build] Error 1

I am unsure at this point whether or not this error is related to the fact that *malloc* and *realloc* have not been compiled. I have traced back into the *wiring.c* file to find out where `yield()` was. That file starts with an `#include "wiring_private.h"` and here is the delay function and yield:

    void delay(unsigned long ms)
    {
            uint16_t start = (uint16_t)micros();

            while (ms > 0) {
                    yield();
                    if (((uint16_t)micros() - start) >= 1000) {
                            ms--;
                            start += 1000;
                    }
            }
    }

Here are the include statements from the *wiring_private.h* header.

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <stdio.h>
    #include <stdarg.h>

    #include "Arduino.h"

Perhaps on of these contain the `yield()` function, which is not being seen correctly?

Does anyone have any advice for what I am doing wrong regarding building manually with 1.6.5? Any comments or further comments will be appreciated.

-------

**Edit #3** Identified where `yield()` function is located.

*Project directory:*

    .
    ├── abi.cpp
    ├── Arduino.h
    ├── binary.h
    ├── Blink.cpp
    ├── Blink.cpp.d
    ├── Blink.cpp.o
    ├── CDC.cpp
    ├── CDC.cpp.d
    ├── CDC.cpp.o
    ├── Client.h
    ├── core.a
    ├── HardwareSerial0.cpp
    ├── HardwareSerial1.cpp
    ├── HardwareSerial2.cpp
    ├── HardwareSerial3.cpp
    ├── HardwareSerial.cpp
    ├── HardwareSerial.cpp.d
    ├── HardwareSerial.cpp.o
    ├── HardwareSerial.h
    ├── HardwareSerial_private.h
    ├── HID.cpp
    ├── HID.cpp.d
    ├── HID.cpp.o
    ├── hooks.c
    ├── IPAddress.cpp
    ├── IPAddress.cpp.d
    ├── IPAddress.cpp.o
    ├── IPAddress.h
    ├── main.cpp
    ├── main.cpp.d
    ├── main.cpp.o
    ├── new.cpp
    ├── new.cpp.d
    ├── new.cpp.o
    ├── new.h
    ├── Printable.h
    ├── Print.cpp
    ├── Print.cpp.d
    ├── Print.cpp.o
    ├── Print.h
    ├── run.mk
    ├── run.mk~
    ├── Server.h
    ├── Stream.cpp
    ├── Stream.cpp.d
    ├── Stream.cpp.o
    ├── Stream.h
    ├── Tone.cpp
    ├── Tone.cpp.d
    ├── Tone.cpp.o
    ├── Udp.h
    ├── USBAPI.h
    ├── USBCore.cpp
    ├── USBCore.cpp.d
    ├── USBCore.cpp.o
    ├── USBCore.h
    ├── USBDesc.h
    ├── WCharacter.h
    ├── WInterrupts.c
    ├── WInterrupts.c.d
    ├── WInterrupts.c.o
    ├── wiring_analog.c
    ├── wiring_analog.c.d
    ├── wiring_analog.c.o
    ├── wiring.c
    ├── wiring.c.d
    ├── wiring.c.o
    ├── wiring_digital.c
    ├── wiring_digital.c.d
    ├── wiring_digital.c.o
    ├── wiring_private.h
    ├── wiring_pulse.c
    ├── wiring_pulse.c.d
    ├── wiring_pulse.c.o
    ├── wiring_pulse.S
    ├── wiring_shift.c
    ├── wiring_shift.c.d
    ├── wiring_shift.c.o
    ├── WMath.cpp
    ├── WMath.cpp.d
    ├── WMath.cpp.o
    ├── WString.cpp
    ├── WString.cpp.d
    ├── WString.cpp.o
    └── WString.h

`yield()` is located in *hooks.c*. I do not understand why the function is not available to *wiring.c*.

------

**Edit #4** Compilation working

Structure of *arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino*:

    .
    ├── abi.cpp
    ├── Arduino.h
    ├── binary.h
    ├── CDC.cpp
    ├── Client.h
    ├── HardwareSerial0.cpp
    ├── HardwareSerial1.cpp
    ├── HardwareSerial2.cpp
    ├── HardwareSerial3.cpp
    ├── HardwareSerial.cpp
    ├── HardwareSerial.h
    ├── HardwareSerial_private.h
    ├── HID.cpp
    ├── hooks.c
    ├── IPAddress.cpp
    ├── IPAddress.h
    ├── main.cpp
    ├── new.cpp
    ├── new.h
    ├── Printable.h
    ├── Print.cpp
    ├── Print.h
    ├── Server.h
    ├── Stream.cpp
    ├── Stream.h
    ├── Tone.cpp
    ├── Udp.h
    ├── USBAPI.h
    ├── USBCore.cpp
    ├── USBCore.h
    ├── USBDesc.h
    ├── WCharacter.h
    ├── WInterrupts.c
    ├── wiring_analog.c
    ├── wiring.c
    ├── wiring_digital.c
    ├── wiring_private.h
    ├── wiring_pulse.c
    ├── wiring_pulse.S
    ├── wiring_shift.c
    ├── WMath.cpp
    ├── WString.cpp
    └── WString.h

The reason the `yield()` function was not recognized was because I was not compiling with *1.6.5* correctly. Below is an updated *makefile* that compiles the *Blink.cpp* seemingly correct. I have yet to verify the sketch works on upload to the Arduino (via `avrdude`). The mistake was that I did not compile `abi.cpp`, `HardwareSerialx.cpp`(0-3), and `hooks.c`. `hooks.c` is where the `yield()` is located.

Updated *makefile*:

    #
    # Simple Arduino Makefile
    #
    # Author: Nick Gammon
    # Date: 18th March 2015
    #
    # Edited by: Kyle Lawlor
    # Date: 30th October 2015

    $H# where you installed the Arduino app
    ARDUINO_DIR = /home/wiz/programs/arduino-1.6.5-r5/

    # various programs
    CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
    CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
    AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
    OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

    # create a file called Blink.cpp in same base dir
    MAIN_SKETCH = Blink.cpp

    # compile flags for g++ and gcc

    # may need to change these
    F_CPU = 16000000
    MCU = atmega328p

    # compile flags
    GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
    CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
    CC_FLAGS  = $(GENERAL_FLAGS)

    # location of include files
    INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/avr/variants/standard"

    # library sources
    LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/avr/cores/arduino/"

    build:

     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    # $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)hooks.c -o hooks.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
     $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)abi.cpp -o abi.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial0.cpp -o HardwareSerial0.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial1.cpp -o HardwareSerial1.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial2.cpp -o HardwareSerial2.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial3.cpp -o HardwareSerial3.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
     $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
     rm core.a
    # $(AR) rcs core.a malloc.c.o
    # $(AR) rcs core.a realloc.c.o
     $(AR) rcs core.a hooks.c.o
     $(AR) rcs core.a WInterrupts.c.o
     $(AR) rcs core.a wiring.c.o
     $(AR) rcs core.a wiring_analog.c.o
     $(AR) rcs core.a wiring_digital.c.o
     $(AR) rcs core.a wiring_pulse.c.o
     $(AR) rcs core.a wiring_shift.c.o
     $(AR) rcs core.a abi.cpp.o
     $(AR) rcs core.a CDC.cpp.o
     $(AR) rcs core.a HardwareSerial.cpp.o
     $(AR) rcs core.a HardwareSerial0.cpp.o
     $(AR) rcs core.a HardwareSerial1.cpp.o
     $(AR) rcs core.a HardwareSerial2.cpp.o
     $(AR) rcs core.a HardwareSerial3.cpp.o
     $(AR) rcs core.a HID.cpp.o
     $(AR) rcs core.a IPAddress.cpp.o
     $(AR) rcs core.a main.cpp.o
     $(AR) rcs core.a new.cpp.o
     $(AR) rcs core.a Print.cpp.o
     $(AR) rcs core.a Stream.cpp.o
     $(AR) rcs core.a Tone.cpp.o
     $(AR) rcs core.a USBCore.cpp.o
     $(AR) rcs core.a WMath.cpp.o
     $(AR) rcs core.a WString.cpp.o
     $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
     $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
     $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

Are *malloc.c* and *realloc.c* being used anymore? I searched across *1.6.5* for a directory similar to *avr-libc*, I couldn't find anything. I'm guessing they are no longer in use.

--------

**Edit #5** Upload via *avrdude*

Basically this command worked for my board (Arduino Uno SMD):

    avrdude -v -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:/path/to/Blink.cpp.hex:i

This is all to say that the latter makefile in this post correctly builds the *.hex* file. Which can then successfully be uploaded onto the board. (Using Arduino 1.6.5).

body:
> I am interested in tracing through an upload process to learn more detail ...

I covered the uploading process in some detail here: <https://arduino.stackexchange.com/questions/15936/what-happens-when-code-is-uploaded-using-the-bootloader>

---

>  I would like to understand which C-libraries are used

See my post about [How the IDE organizes things](https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them)

---
> One example that I would like to see is an direct upload of C or C++ code without using the IDE gui.

I wrote a simple Makefile on the [Arduino Forum](http://forum.arduino.cc/index.php?topic=308853.msg2145054#msg2145054):

    #
    # Simple Arduino Makefile
    #
    # Author: Nick Gammon
    # Date: 18th March 2015

    # where you installed the Arduino app
    ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

    # various programs
    CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
    CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
    AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
    OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

    MAIN_SKETCH = Blink.cpp

    # compile flags for g++ and gcc

    # may need to change these
    F_CPU = 16000000
    MCU = atmega328p

    # compile flags
    GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
    CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
    CC_FLAGS  = $(GENERAL_FLAGS)

    # location of include files
    INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

    # library sources
    LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

    build:

        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
        rm core.a
        $(AR) rcs core.a malloc.c.o
        $(AR) rcs core.a realloc.c.o
        $(AR) rcs core.a WInterrupts.c.o
        $(AR) rcs core.a wiring.c.o
        $(AR) rcs core.a wiring_analog.c.o
        $(AR) rcs core.a wiring_digital.c.o
        $(AR) rcs core.a wiring_pulse.c.o
        $(AR) rcs core.a wiring_shift.c.o
        $(AR) rcs core.a CDC.cpp.o
        $(AR) rcs core.a HardwareSerial.cpp.o
        $(AR) rcs core.a HID.cpp.o
        $(AR) rcs core.a IPAddress.cpp.o
        $(AR) rcs core.a main.cpp.o
        $(AR) rcs core.a new.cpp.o
        $(AR) rcs core.a Print.cpp.o
        $(AR) rcs core.a Stream.cpp.o
        $(AR) rcs core.a Tone.cpp.o
        $(AR) rcs core.a USBCore.cpp.o
        $(AR) rcs core.a WMath.cpp.o
        $(AR) rcs core.a WString.cpp.o
        $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
        $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
        $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

There are quite a few more complex ones around.

---

> I want to see kind of the "bare-minimum" necessary for programming the Arduino (in C/C++).

Here:

    int main ()
     {
     }

---

> Does part of the main sketch transfer through in the compilation of malloc.c and realloc.c (as well as the c/c++ files)?
>
> I would think so, being that it is compiled every time we change the main sketch.

I'm not sure I understand the part about "transfer through" but basically functions which are needed in the main sketch are linked into the combined file by the linker.

Effectively these are the main parts:

    # Compile main sketch
        $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o

    # Compile libraries
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
        $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    ...

    # Remove temporary "combined libraries" file
        rm core.a

    # Add compiled libraries into combined file "core.a"
        $(AR) rcs core.a malloc.c.o
        $(AR) rcs core.a realloc.c.o
    ...

    # Link main sketch to combined libraries (linker will discard things not needed)
        $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm

    # Make an .eep (EEPROM) file
        $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep

    # Make the main .hex file
        $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

---

> Lastly, how is the outputted .hex file uploaded to the board?

There are various ways of achieving this. The IDE calls the program `avrdude` which is designed to upload a .hex file to a processor. You can also just copy the .hex file to an SD card and upload it using a board programmer.

---

> Are malloc.c and realloc.c being used anymore?

They **are** being used, the trick is to find them.

I can't see them being directly linked in a 1.6.5 compiler output, so I am assuming (I can't prove it right now) that they are linked in by default from libc.a (the default C library). Being a default library it is not mentioned on the linker line.

In my (Linux) installation I found that library here:

    ~/Development/arduino-1.6.5-r5/hardware/tools/avr/avr/lib/libc.a

If you do a `nm` on it you find this (amongst other things):

    malloc.o:
    00000002 C __brkval
             U __do_clear_bss
             U __do_copy_data
    00000002 C __flp
    00000146 T free
             U __heap_end
             U __heap_start
    00000000 T malloc
    00000000 D __malloc_heap_end
    00000002 D __malloc_heap_start
    00000004 D __malloc_margin
    0000003e a __SP_H__
    0000003d a __SP_L__
    0000003f a __SREG__
    00000000 a __tmp_reg__
    00000001 a __zero_reg__

From `man nm`:

      "D"
      "d" The symbol is in the initialized data section.
     ...
      "T"
      "t" The symbol is in the text (code) section.

---

See <http://www.linuxtopia.org/online_books/an_introduction_to_gcc/gccintro_17.html> :

> The C standard library itself is stored in '/usr/lib/libc.a' and contains functions specified in the ANSI/ISO C standard, such as 'printf'---this library is linked by default for every C program.

---

I am guessing here that `malloc` and `free` moved into the standard (default) library since version 1.0.6 (or they wanted to override it with a bugfix) and it is now being found, by default, in the standard C library as described above.

You should be able to find more about AVR libc at its page: <http://www.nongnu.org/avr-libc/>


message:
Math with analog input values coming out wrong

Im getting stuck in a while loop because Im having trouble running a calculation on some sensor values. When I read my four sensors values and compare the ratio of the first two to the second two, I keep getting 0.00, no matter what the values are. Here's my code:

    while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
        if (backleft + backright > frontleft + frontright) {
          myStepper2.step(10);
        }
        if (backleft + backright < frontleft + frontright) {
          myStepper2.step(-10);
        }
        int backleft = analogRead(A0);
        int backright = analogRead(A1);
        int frontleft = analogRead(A2);
        int frontright = analogRead(A3);

        Serial.print("Backleft Reading: ");
        Serial.println(backleft);
        Serial.print("\n");
        Serial.print("BackRight Reading: ");
        Serial.println(backright);
        Serial.print("\n");
        Serial.print("Frontleft Reading: ");
        Serial.println(frontleft);
        Serial.print("\n");
        Serial.print("Frontright Reading: ");
        Serial.println(frontright);
        Serial.print("\n");
        float ratio = (frontleft + frontright) / (backleft + backright);
        float math = (5 + 6) / (4 + 5);
        Serial.print("Math: ");
        Serial.println(math);
        Serial.print("Ratio: ");
        Serial.println(ratio);
        Serial.print("\n");
        delay(500);

      }

Im getting values for my sensors (backleft, backright, frontleft, frontright), but 'ratio' always comes out 0.00. Because of that, Im getting trapped in the loop I believe. What's going on here?

Also, just to check, I added 'math' float as that quick calculation, but I'm getting a value of 1.00 in Serial Monitor. Why? It should be 1.222.

body:
Read this: [Integer arithmetic and overflow](http://www.gammon.com.au/forum/?id=12146).

    float math = (5 + 6) / (4 + 5);
    Serial.print("Math: ");
    Serial.println(math);

The compiler is treating your expression (the RH side of the "=" sign) as **integers**. Thus it is working out:

    11 / 9 = 1

Then you assign that `1` to a float. Too late to make it a float! It is already truncated.

Try:

    float math = float (5 + 6) / float (4 + 5);
    Serial.print("Math: ");
    Serial.println(math, 4);  // 4 decimal places

You get:

    Math: 1.2222

---

This also looks wrong:

    while ( ( (frontleft + frontright) / (backleft + backright) <= 0.8 ) || ( (frontleft + frontright) / (backleft + backright) > 1.2) ) {
        if (backleft + backright > frontleft + frontright) {
          myStepper2.step(10);
        }
        if (backleft + backright < frontleft + frontright) {
          myStepper2.step(-10);
        }
        int backleft = analogRead(A0);
        int backright = analogRead(A1);
        int frontleft = analogRead(A2);
        int frontright = analogRead(A3);

How many `backleft` variables do you have? The one in the `while` instruction will **not** be the one you are doing the analogRead on. It doesn't "forward read" variables. I bet you have a different `frontleft` / `backleft` etc. set of variables declared earlier. These will **not** be updated inside the loop.

(To make them get updated drop the word `int` from inside the loop).


message:
atmega328 raspberry pi 2 communication

I have an atmega328p (running on it's internal 8mhz clock) receiving data over rf. I need the data received to be communicated to the raspberry pi 2 using its gpio pins, I cannot use USB. I don't have the budget for a gertduino. Is there any way to do this directly? I only need to be able to receive serial output on the pi, no uploading sketches.

body: Both the Arduino and the Raspberry PI have interfaces like SPI, I2C and UART. These interfaces will make it easy for you to communicate between the two. I suggest you search for UART unless you need a very high data throughput, then you need to go for SPI. But unless you want to send over a thousand messages per second UART will work just fine.


message:
Dimming 6W (24V DC 0.25A) LEDs using Arduino

I want to dim 24 LEDs which are powered by a transformer outputting 24V 6W at 0.25A

I am worried about temperatures, especially considering the circuit has to stay on for several hours keeping the LEDs off.

Would a TIP122 transistor be ok?

Any tips for keeping the transistor off until the dimming process starts?

body: I would suggest using the [CAT4101](http://www.onsemi.com/pub_link/Collateral/CAT4101-D.PDF) constant current sink PWM LED driver.  It can handle up to 1A at up to 25V and deals with the constant current regulation for you - just provide at least the 24V you need and enough current capacity and connect the correctly calculated current setting resistor and the CAT4101 will do the rest for you.  You can then control it through the PWM input pin direct from the Arduino.


message:
How to access parse cloud functions using arduino?

I have created rest service using .js file on Parse.com.
I want to access cloud function from arduino.

i tried this

client.get(https://myAppID:javascript-key=myJavaScriptKey@api.parse.com/1/functions/hello");

i am getting error "Method not allowed".

Solution :
Somehow i got the answer which is as follows.I hope it will help others.

     ParseCloudFunction cloudFunction;
     cloudFunction.setFunctionName(function_name);  //string ("hello")
     cloudFunction.add("light_sensor", light); //pass parameter to cloud

     ParseResponse response = cloudFunction.send();
     Serial.println(response.getJSONBody());

body:
I read api of Parse and there i got the class to call cloud function from
Arduino.I hope it will help others.

     ParseCloudFunction cloudFunction;
     cloudFunction.setFunctionName(fnname); //String ("hello")
     cloudFunction.add("light_sensor", 139); //parameter

     ParseResponse response = cloudFunction.send();
     Serial.println(response.getJSONBody());


message:
Arduino Uno + Adafruit Ultimate GPS Shield Serial issue

I've had an Arduino Uno for a couple of months-making basic sketches-and recently purchased an Adafruit ultimate GPS shield and attached with soldered headers. This shield has 2 options for reading data, direct and soft serial.

I can sit near a window in my house and receive data using the direct method. This is just due to uploading a blank sketch and reading the serial window. Next, I tried to use one of the examples included in the Adafruit_GPS library and the serial window shows a bunch of nonsense updating.

Has anyone else seen this problem? I'm wondering if its the digital pins on the Arduino that I may have damaged since the example code has a simple phrase to display at the start, and I don't even get this.

Code eg: Serial.println("Get version!").

Just to verify, both boards have power and the direct method was giving me good GPS readings, the serial method gave me junk (not even a simple printed phrase to start), and I verified the Soft Serial switch was flipped and the baud rates matched in code and serial window.

I've attached pictures of the direct method results from that in the serial window, and then the junk results using an unaltered sample serial code. Any help with this would be appreciated.

[![Direct Method Results][2]][2][![Direct Method Example Results][3]][3]

  [1]: https://i.stack.imgur.com/xRK5z.jpg
  [2]: https://i.stack.imgur.com/vbf7N.jpg
  [3]: https://i.stack.imgur.com/jDQpn.jpg

body:
It looks like you are using the wrong baud rate somewhere.

You mentioned that you had checked your baud rates but check again because the second terminal window looked as if the baud rate was wrong.

In your terminal window. Go to bottom right hand corner where it says 9600 and change it to match the serial speed set in your arduino code.

Or it could be that you are receiving too much data as per the bottom of this article:  https://learn.adafruit.com/adafruit-ultimate-gps-logger-shield/soft-serial-connect


body:
Definitely a baud rate problem. The GPS is sending at 9600.

When you use a sketch to receive the data, the SoftwareSerial .begin should be set to 9600. The Serial.begin should be set to a rate higher than 9600, so that the Arduino cannot fall behind in relaying the data to the PC.

If this does not solve you problem, please post your sketch and a wiring diagram so we can analyze it further.


message:
Are DAC pins useful for anything besides working with audio?

Whenever I run into information about DAC, it seems to be related to audio processing. Are there any other use cases where DAC might be useful, or have any advantages over regular ADC PWM output on an Arduino?

body:
DACs have many uses outside the realm of audio.

Basically a DAC is used any time you want to generate a specific voltage for whatever you need it for - that could be to generate a waveform for audio, or it could be for any other situation, such as:

* Setting an offset point for an op-amp
* Creating a comparison voltage for comparing another signal to
* Controlling the bias voltage of a transistor
* Generating a specific reference voltage for an external (or even the internal) ADC

The list goes on.  There are many places you would want to use a DAC.  And why a DAC above PWM? Well basically it boils down to:

* Precision - the DAC can generate a more precise voltage than a filtered PWM signal
* Noise - the DAC generates a much smoother voltage with better response than filtered PWM which either has switching noise and fast response or less switching noise and delays in voltage level changes.


body:
They are incredibly useful.  They are essentially how you deal with the analog world.

For example, I'm using two of them in a project here that uses a frequency generator and a couple of op-amps to create a VSWR bridge, allowing me to figure out the resonant frequencies of an antenna...  The parts with the arduino cost less than $20... Buying something that does the same thing is about $300!

So, yes, they are very useful. :)


message:
How to put arduino in sleep mode?

I need to put arduino in sleep mode. I did not find the library avr/sleep.h . From where to download it.

body:
`avr/sleep.h` is part of the compiler. You don't need to download it.

There are other libraries that act as a wrapper to it to make life easier:

* https://github.com/lowpowerlab/lowpower
* https://github.com/rocketscream/Low-Power


message:
Cast from long to int

How does arduino uno cast from **long** to **int**?

Does it truncate the bits? (Does it just delete the 16 most left bits?)

body:
Yes, it just blindly chops off the upper 16 bits.  That means that the sign can change between the two.

For instance, 123456789 gets truncated to -13035 and -123456789 truncates to 13035.

To see that in more detail, look at the binary.  123456789 in binary is:

    0000 0111 0101 1011 1100 1101 0001 0101

Truncate that at 16 bits and you get:

    1100 1101 0001 0101

And of course the high (sign) bit is set, so the value is negative.


message:
Arduino port recognition

New Arduino Uno, Arduino 1.6.3, MBP running 10.10.5.

The Arduino IDE is running, I connect to the laptop via usb. The green LED is on the amber light is on but it's not blinking.

I attempted to upload the blink file from File>Example>Basic>Blink. It compiles without issue but won't upload. I get the can't open device "/dev/cu.usbmodem1421" : No such file or directory...

I have attempted using the reset button, changing ports, cycling the IDE and the computer. The killer is that I've had an Arduino on this laptop before.

Any suggests for getting the Arduino linked and operational.

body:
I think you may not install arduino hardware and ftd drivers,
Follow the steps given here and then check,

1. Download the latest version of Arduino software and install it.

2. Open windows device manager - You can open windows device manager by right   clicking on 'My Computer' and choosing Properties. In the new Window, Click on    Device Manager

3. Now Scroll Down the List of Devices in the Device Manager till you come to a Device or expand Ports (COMM).

4. Now you should see Arduino hardware with warning icon or without.

5. Now do right click on arduino hardware name. Now, Windows will provide you two options, Choose the one that says “Locate and install drivers manually from a specific Location.”

6. By browsing locate arduino installed folder, then update.

If you previously done these procedure or now, then open arduino software

1. Go to tools and choose board as what you have like (arduino uno, mega, due etc....)

2. then in tools menu you should choose serial port (example comm 10, comm 21, comm 8 etc...) in which the arduino board connected, some time the board name displays with serial port otherwise you can observe from device manager ports list.

3. now upload blink example and check.


body:
Sorry to dredge up an old thread (well, really only replying to one that got robo-dredged :), but maybe this will help someone someday.

A /dev/cu.<something> is a unix port designation. "cu." meant a port used for modems, back in the mists of time but probably isn't relevant today. But what we do learn from it is that the OP is probably using a Mac, and for sure, not Windows.

"/dev/cu.usbmodem1421" is a typical device name for an Arduino as seen by a Mac on a particular one of its USB ports - the numeric part varies according to which Mac USB port the Arduino is connected to each time.

Arduinos & FTDI devices do not need additional drivers on Mac OS (that may not be true for other, non-FTDI USB-to-serial devices).

In this case, the OS already reports seeing (what looks like) an Arduino. The suggestion already put forward, checking the board-type and port selections in the IDE's 'Tools' menu, is the place to start.


message:
Humidity values returned by DHT22 sensors failing after some time

I've built a weather station using Arduino that measures temperature/humidity and pressure using an Adafruit 8266 HUZZAH. Temperature and Humidity are measured using a DHT22 sensor a ordered from AdaFruit. The project was completed about 4 months ago and for the first three months has returned what appears to be good data. Eventually, the humidity values started returning garbage, values around 1%.

I replaced the DHT22 sensor with another, this time from a random eBay seller. This also worked fine for about a week (humidity values appear to look good in the 20-60% range).

Then all of a sudden, they dropped to 1% again.

If I run the DHTtester program (instead of my program) against the sensor and my Uno development board, the result is also 1% humidity for this sensor.

     DHTxx test!
     Humidity: 1.00 % Temperature: 19.20 *C 66.56 *F Heat index: 17.96 *C 64.33 *F
     Humidity: 1.00 % Temperature: 19.20 *C 66.56 *F Heat index: 17.96 *C 64.33 *F

So at this point, I know the problem is not with my program (happens with both my program and the DHTtest program), not with my Arduino (happens with both the 8266 in "the field" and my Uno on my couch). So something must be happening to the sensors in the field, where they work for a week to a few months, and then fail?

Any ideas?

I'm beginning to think some bug/critter is eating or doing something to the sensor (maybe they are attracted to it because it's warmer), but anyway is there a good way to shield if this is the case without affecting the values? Any other way to see what is going on?

     // Example testing sketch for various DHT humidity/temperature sensors
     // Written by ladyada, public domain

     #include "DHT.h"
     #define DHTPIN 2     // what pin we're connected to

     // Uncomment whatever type you're using!
     //#define DHTTYPE DHT11   // DHT 11
     #define DHTTYPE DHT22   // DHT 22  (AM2302)
     //#define DHTTYPE DHT21   // DHT 21 (AM2301)

     // Connect pin 1 (on the left) of the sensor to +5V
     // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
     // to 3.3V instead of 5V!
     // Connect pin 2 of the sensor to whatever your DHTPIN is
     // Connect pin 4 (on the right) of the sensor to GROUND
     // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

     // Initialize DHT sensor.
     DHT dht(DHTPIN, DHTTYPE);

     void setup() {
       Serial.begin(9600);
       Serial.println("DHTxx test!");
       dht.begin();
     }

     void loop() {
         // Wait a few seconds between measurements.
         delay(2000);
         // Reading temperature or humidity takes about 250 milliseconds!
         // Sensor readings may also be up to 2 seconds 'old'
         float h = dht.readHumidity();
         // Read temperature as Celsius (the default)
         float t = dht.readTemperature();
         // Read temperature as Fahrenheit (isFahrenheit = true)
         float f = dht.readTemperature(true);

         // Check if any reads failed and exit early (to try again).
         if (isnan(h) || isnan(t) || isnan(f)) {
             Serial.println("Failed to read from DHT sensor!");
             return;
         }

         // Compute heat index in Fahrenheit (the default)
         float hif = dht.computeHeatIndex(f, h);
         // Compute heat index in Celsius (isFahreheit = false)
         float hic = dht.computeHeatIndex(t, h, false);

         Serial.print("Humidity: ");
         Serial.print(h);
         Serial.print(" %\t");
         Serial.print("Temperature: ");
         Serial.print(t);
         Serial.print(" *C ");
         Serial.print(f);
         Serial.print(" *F\t");
         Serial.print("Heat index: ");
         Serial.print(hic);
         Serial.print(" *C ");
         Serial.print(hif);
         Serial.println(" *F");
    }

body:
Can't really help as I have the same problem ! , DHT22 on an ESP8266 has failed twice , while a DHT11 on a similar system has worked faultlessly for months (Thingspeak 27272) , DHT11 is inside the house while the DHT22 is below the house in the carport, Only thing I have come up with is that the DHT22 MAY be failing due to exhaust/hydrocarbon fumes from the car startups

Art


body:
This is how it looks when they fail.

The DHTxx are very low cost sensors, optimised for cheap volume production.

We don't know under what condition you actually use your sensors. Also, there's the phenomenon of knock-offs and low-grade selling.

In his comprehensive test, Robert J. Smith found a failure rate of 33% and concludes a mean life expectancy of one to two years.

A slightly more expensive alternative is the SHT series of temperature and humidity sensors. My personal experience is that they tend to tolerate some abuse (i.e. complete submersion in water) and don't age as quickly.

Link:

 - failure analysis: http://www.kandrsmith.org/RJS/Misc/Hygrometers/dht22_first_failure.html
 - general writeup: http://www.kandrsmith.org/RJS/Misc/Hygrometers/calib_dht22_dht11_sht71.html#conclusions


body: I have had the exact same experience using a DHT11 with Huzzah. I found that the problem tends to happen after high humidity conditions (>85% relative), my solution was to place silicone caulk and heatshrink tubing around the connections to prevent dew buildup. That solved my problem with my third replacement. It has been two months now with no issues.


message:
Accuracy of liquid level measurement using sonar sensor

Is it a good way to measure liquid level in a water tank using a general purpose sonar sensor? How can echoes from the tank walls affect measurement accuracy?

I have a cylinder shaped **horizontal** 700L water tank, used for emergency water supply. I need to measure the water level with approx. 5% accuracy and display it in my kitchen.

[![sonar sensor][1]][1]

**UPDATE! Today I found this helpful page: [Home Heating Hacking Part 1 or How to Measure an Oil Tank][2].
I had no time to realize my idea, but it's exactly what I wanted to do. So take a look.**

  [1]: https://i.stack.imgur.com/0XD5H.jpg
  [2]: http://alaskanshade.blogspot.ch/2013/12/home-heating-hacking-part-1-or-how-to.html

body:
I've implemented this on my 2 x 23,000 litre water tanks using 2x hc-sr04 sensors mounted on the tank lids and a nano in the pump house. Yes water is a good hard reflective surface to bounce the ultrasonic sound waves off. My tanks have an overflow outlet but not sure how well the eletronic will last? However they are cheap to replace. It is only early days but the overall the results are looking good.
Couple of points:

 1.polling occurs hourly.

 2.I only power the ultrasonic sensor just before taking a reading.

3.Has a sound detection sensor to alert on water pump overrun, ie a leak.

good luck


message:
Can BUS Shield on Arduino Leonardo - Can't init CAN

I'm hoping to get some help with this as I am unable to get the CAN to Initialize.

I have the sparkfun Can-Bus shield: https://www.sparkfun.com/products/13262

and an Arduino Leonardo board.

I'm using the following code to try to connect my 2008 Audi S6 to the Arduino board:

    #include <Canbus.h>
    #include <defaults.h>
    #include <global.h>
    #include <mcp2515.h>
    #include <mcp2515_defs.h>
    #include <Canbus.h>
    char UserInput;
    int data;
    char buffer[456];  //Data will be temporarily stored to this buffer before being written to the file

    //********************************Setup Loop*********************************//

    void setup(){
    Serial.begin(9600);
    while(!Serial);
    Serial.println("CAN-Bus Demo");

    if(Canbus.init(CANSPEED_500))  /* Initialise MCP2515 CAN controller at the  specified speed */
      {
    Serial.println("CAN Init ok");
      } else
      {
        Serial.println("Can't init CAN");
      }

      delay(1000);

    Serial.println("Please choose a menu option.");
    Serial.println("1.Speed");
    Serial.println("2.RPM");
    Serial.println("3.Throttle");
    Serial.println("4.Coolant Temperature");
    Serial.println("5.O2 Voltage");
    Serial.println("6.MAF Sensor");

    }

    //********************************Main Loop*********************************//

    void loop(){

    while(Serial.available()){
       UserInput = Serial.read();

    if (UserInput=='1'){
     data=Canbus.ecu_req(VEHICLE_SPEED, buffer);
     Serial.print("Vehicle Speed: ");
     Serial.print(data);
     Serial.println(" km/hr ");
     delay(1000);
    }
    else if (UserInput=='2'){
     data= Canbus.ecu_req(ENGINE_RPM, buffer);
     Serial.print("Engine RPM: ");
     Serial.print(data);
     Serial.println(" rpm ");
     delay(1000);

    }
    else if (UserInput=='3'){
     data= Canbus.ecu_req(THROTTLE, buffer);
     Serial.print("Throttle: ");
      Serial.print(data);
     Serial.println(" %% ");
     delay(1000);

    }
    else if (UserInput=='4'){
     data =Canbus.ecu_req(ENGINE_COOLANT_TEMP, buffer);
     Serial.print("Engine Coolant Temp: ");
     Serial.print(data);
     Serial.println(" degC");
     delay(1000);

    }
    else if (UserInput=='5'){
     data=Canbus.ecu_req(O2_VOLTAGE, buffer);
     Serial.print("O2 Voltage: ");
     Serial.print(data);
     Serial.println(" V");
     delay(1000);

    }
    else if (UserInput=='6'){
     data=Canbus.ecu_req(MAF_SENSOR, buffer);
     Serial.print("MAF Sensor: ");
     Serial.print(data);
     Serial.println(" g/s");
     delay(1000);

    }
    else
    {
      Serial.println(UserInput);
      Serial.println("Not a valid input.");
      Serial.println("Please enter a valid option.");
    }

    }
    }

Overall, I just can't get the CAN to initialize. I've looked online and just can't seem to find a solid solution. I've tried other libraries as well to no avail.

Please assist!

body:
Had this problem myself. Found this fixed it

Change the following line...

    _delay_us(10);

To...

    _delay_us(50);

In the `MCP2515.c` file in the library


body:
Increasing that delay in the MCP2515.c file also fixed this issue for me.
I am running the sparkfun Can-Bus shield on an Arduino pro-mini, and here is my serial monitor output before the change, and after:

12:56:38.580 -> CAN Read - Testing receival of CAN Bus message
12:56:39.556 -> Can't init CAN
13:01:40.992 -> CAN Read - Testing receival of CAN Bus message
13:01:42.016 -> CAN Init ok


message:
How to switch program in arduino using android app?

I have 2 programs made for my arduino.The first one is for solving a maze automatically and the second one is for controlling the robot with a android app.I wanted to control the robot with the app I made as soon as it has finished solving the maze.
                   Is it possible to upload both the program in the arduino and run it one at a time?If so can you tell me how?

body:
Once I made a sketch to run multiple programs. I wrote a `setup` and `loop` function for every different "program", (e.g. `setup_p1`, `setup_p2`, ... `loop_p1`, ...) and then wrote a simple `main` sketch to handle them all.

In my application I choose the program at startup with a 3-dipswitch, but you can easily switch this to allow "on the fly" switching.

I choose to use a callback because it's faster than just checking the mode every time, at least in my case

    // callback for loop function
    typedef void (*loopfunction)();
    loopfunction currentloop;

    void setup()
    {
      // Set dip-switch pins as input
      pinMode(MODE_PIN2,INPUT_PULLUP);
      pinMode(MODE_PIN1,INPUT_PULLUP);
      pinMode(MODE_PIN0,INPUT_PULLUP);

      // Concatenate the dip-switch values
      byte mode = 7 - ((digitalRead(MODE_PIN2) << 2) | (digitalRead(MODE_PIN1) << 1) | digitalRead(MODE_PIN0));

      // choose the correct mode
      switch(mode)
      {
        case 0: // Shutdown - do nothing
                break;
        case 1: // Program 1
                setup_p1();
                currentloop = loop_p1;
                break;
        case 2: // Program 2
                setup_p2();
                currentloop = loop_p2;
                break;
        ...
      }

      // Not a valid program: halt
      if (!currentloop)
      {
        while(1);
      }
    }

    void loop()
    {
      // Execute the current loop
      currentloop();
    }


message:
Can anyone explain how this code can be converted to work on a Arduino Uno

I was hoping someone could help, im totally new to this. I wish to use this code for a Raspberry Pi on an Arduino Uno with the Adafruit SD data logging shield. It is for recording reed switch closures on a tipping bucket rain gauge. The interrupt and bounce time are to allow program interrupts and false tip suppression. I am looking to tie it in with the RTC and SD storage options on the Arduino. Any help appreciated.

    #!/usr/bin/python3
    import RPi.GPIO as GPIO
    import time

    # this many mm per bucket tip
    CALIBRATION = 0.200
    # which GPIO pin the gauge is connected to
    PIN = 17
    # file to log rainfall data in
    LOGFILE = "log.csv"

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    # variable to keep track of how much rain
    rain = 0

    # the call back function for each bucket tip
    def cb(channel):
     global rain
     rain = rain + CALIBRATION

    # register the call back for pin interrupts
    GPIO.add_event_detect(PIN, GPIO.FALLING, callback=cb, bouncetime=300)

    # open the log file
    file = open(LOGFILE, "a")

    # display and log results
    while True:
     line = "%i, %f" % (time.time(), rain)
     print(line)
     file.write(line + "\n")
     file.flush()
     rain = 0
     time.sleep(5)

    # close the log file and exit nicely
    file.close()
    GPIO.cleanup()

body:
This should help get you started but don't expect it to actually work as it is. Note that i did not test this at all, it's for example purposes.  if there is a specific programming problem it should be addressed separately instead of handing out working code.

    const int CALIBRATION = 0.200;   //Calibration Constant
    int pin = 2;                     //Pin it's on, this is int0 for uno.
    volatile int rain = 0;           //Used in interrupt routine

    void setup() {
        Serial.begin(9600);
        pinMode(pin, INPUT);
        attachInterrupt(digitalPinToInterrupt(pin), cn, FALLING);
    }

    void loop() {

         /* Output OR LOG DATA HERE
            Also You need a Time Library and RTC (Real Time CLock) the above
            code is for a raspberry pi that has all that. */

    }

    void cb() {
        rain = rain + CALIBRATION;
    }


message:
Arduino keypad matrix example? ( teensyduino )

I'm a beginner using Arduino with a Teensy 3.2 board and programming it as a usb keyboard. I have two 4 button membrane switches. Their button contacts are on pins 1-8, and the 9th pin holds a soldered together wire of both membrane switches' "ground" line or whatever it's true name is; the line that completes the circuit.

Basically when you press the buttons they are supposed to simply type "a, b, c..." respectively. I've been told I need to use a matrix for this.

I'm looking for an example of how to code a keyboard matrix that effectively supports a one row/9 column line (or vice versa?) I've been unable to find that solution online.

All I have so far is this code which, when the button on the second pin is pressed, sends tons of "AAAAAAAAAAAAAAAA" keystrokes.

    void setup() {
      // make pin 2 an input and turn on the
      // pullup resistor so it goes high unless
      // connected to ground:
      pinMode(2, INPUT_PULLUP);
      Keyboard.begin();
    }

    void loop() {
      //if the button is pressed
      if(digitalRead(2)==LOW){
        //Send an ASCII 'A',
        Keyboard.write(65);
      }
    }

Would anyone be able to help?

body:
By your description, you don't have a matrix.  You have them wired as just 8 straight switches.

A matrix would be if you had the 4 switch pins of one keypad wired to the same switch pins of the other keypad, and the two common connections from the keypads wired to two separate IO pins.

At the moment your code is responding whenever a button is in the low state. Instead it needs to respond only when the button *transitions* from the high state to the low state.  To do that you need to know what state all the buttons were in the previous pass through loop to compare them to what they are in this pass through loop - and if any have changed then they have either been pressed or released.

You should also implement debouncing to that you don't get false presses.

If you don't want to learn how to do all that yourself I have a handy library that will do it all for you:

* https://github.com/MajenkoLibraries/DebouncedInput

If you want to convert your setup to an actual matrix to save on IO pins you want to read the Arduino Keypad tutorial:

* http://playground.arduino.cc/Main/KeypadTutorial


message:
Sending data from Arduino to the server where arduino (sketch) acts as a client

I want to make simple client-server program where arduino behave as a client. For example I have a LED connected in arduino board that is controlled by a switch. With the switch I can turn off and on the LED. Now I want to send the status of that LED to another computer wirelessly (let's say within the Local network). That computer will act as a server and update the change as soon as the LED changes its status. I am not expecting any complete code, I just want to know how could it be done in general? May be some links can help me? Because this is my first time working with client-server in arduino sketch, I need some kind of guidelines. Thank you.

body:
A simple HC-05 module will give you a wireless bluetooth connection.  They're fairly simple to setup, and you can write data to them the same as one would the Arduino serial console.  Obviously they can read data too.

    SoftwareSerial bt_serial(2, 3); // RX | TX
    bt_serial.begin(9600);

    [...]

    if (led_state != last_led_state)
    {
        if (led_state == HIGH)
            bt_serial.print("1");
        else
            bt_serial.print("0");
        last_led_state = led_state;
    }

On the "server" side, a simple program reading the mapped bluetooth serial port would do the job.  For example, some python code:

    import serial
    import sys

    serial_port = serial.Serial(port='COM8:', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)

    try:
        serial_port.open()
    except:
        print("Failed to open port")
        sys.exit(2)

    while (True):
        try:
            led_state = serial_port.read()
            if (led_state != 0):
                print("LED is on")
            else:
                print("LED is off")
        except:
            pass

    serial_port.close()   # yes, it never gets here


body:
Even though I like Kingsley's answer I thought I'd add to this using Wi-Fi becuase you had mentioned LAN.

These two links should be enough to help you:
[WifiChatServer][1]
and [C# Telnet Library][2]

Those links can sort of be dissected to fit your needs, but if you need some actual code just tell me.

Now I am aware that **the Arduino is acting as a server and the computer acts as a client**, but I believe this setup is better because it's easier to manipulate connecting to servers on the computer rather than on the arduino side.

  [1]: https://www.arduino.cc/en/Tutorial/WiFiChatServer
  [2]: http://www.codeproject.com/Articles/19071/Quick-tool-A-minimalistic-Telnet-library


message:
Is there a way to use functions defined in a library in any class?

I'm trying to design a menu interface on a 1.8'' TFT display module. I've got it working with the Adafruit_ST7735 + Adafruit_GFX libraries. At least when I was just trying out the features... But now I'm trying to organize the code in Classes as this thing will get too complex soon. I have done some Java and C, so I started learning C++. I've been reading and coding nonstop for a week now, but there are some things that I can't wrap my head around that keep me from making any progress for a couple of days already.

So... For example there's a function public void drawRect(); in Adafruit_ST7735 library and I have a function draw() that draws a bunch of related stuff to the display in my own class (Rectangle.cpp). Say I initialize the display in my main program file how can I use that drawRect() function in my Rectangle::draw()?

Also Rectangle will be used for composing other parts of the menu interface and will probably be initialized in a collection or as a member of another class.

I've tried a bunch of different things but I've come to a dead end.

EDIT:

main program:

    #include "_v0_0_0.h"
    #include <Adafruit_GFX.h>    // Core graphics library
    #include <Adafruit_ST7735.h> // Hardware-specific library
    #include <SPI.h>

    #include "Point.h"
    #include "Rectangle.h"
    #include "SomeView.h"

    #define  TFT_CS  4
    #define  TFT_RST 0
    #define  TFT_DC  10

    Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);
    SomeView a_view;

    void setup()
    {
     tft.initR(INITR_BLACKTAB); // initializes the display
    }

    void loop()
    {
     a_view.draw(); //draw something to view (a button, scrollbar, menu item, etc)
     while (true) {}
    }

SomeView.h:

 #include "Rectangle.h"

 class SomeView {
 private:
  Rectangle a_rectangle;
 public:
  SomeView();
  void draw();

  const Rectangle& getRectangle() const {
   return a_rectangle;
  }

  void setRectangle(const Rectangle& rectangle) {
   a_rectangle = rectangle;
  }
 };

SomeView.cpp:

 #include "SomeView.h"

 SomeView::SomeView() :
   a_rectangle(Point::Point(0, 0), Point::Point(0, 0)) {
 }

 void SomeView::draw() {
  a_rectangle.setCorners(Point::Point(0, 0), Point::Point(2, 6));
  a_rectangle.draw();

  a_rectangle.setCorners(Point::Point(20, 66), Point::Point(100, 100));
  a_rectangle.draw();
 }

Rectangle.h:

    #include "Point.h"
 #include <Adafruit_GFX.h>    // Core graphics library
 #include <Adafruit_ST7735.h> // Hardware-specific library
 #include <SPI.h>

 class Rectangle{
 private:
  Point p1;
  Point p2;
 public:
  Rectangle();
  Rectangle(Point& p1, Point& p2);
  void setCorners(const Point& p1, const Point& p2);
  void draw();

  // ... getters and setters for the points
 };

Rectangle.cpp:

    #include "Rectangle.h"

 Rectangle::Rectangle() : p1(), p2()
  {
  }

 Rectangle::Rectangle(Point& p1, Point& p2) : p1(p1), p2(p2)
  {
  }

 void Rectangle::setCorners(const Point& p1, const Point& p2) {
  this->p1 = p1;
  this->p2 = p2;
 }

    // this is where I want to use a function from the adafruit library
 void Rectangle::draw() {
  Adafruit_ST7735::drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);

 }

body:
Yes, there is a way.

However that's not how object oriented programming (OOP) is supposed to be used, at least in theory.

Most likely you won't like my advice, but here it is: take it easy, find a good book or online course and learn to program on a system that is simpler to debug, than a microcontroller.

Your PC, for example.

C is closer to the HW than java. C++ can be seen as both of them, but there is not so much you can do without learning C, properly.
From that perspective, C++ can be seen also as a superset of C, only much more complex.

Have a look at [this explanation][1], for example.
It's quite simple, but exhaustive. Read it carefully and you will find out that pointers are not so difficult to grasp, after all.

If you spend enough time to get the basics right, it will save you lots of frustration (and, yes, time!) later on.

For a more systematic approach, try [this][2].

  [1]: http://karwin.blogspot.fi/2012/11/c-pointers-explained-really.html
  [2]: http://www.cplusplus.com/doc/tutorial/


body:
There are two basic methods to do what you want:

1. Inheritance
2. Pointer passing

Inheritance involves making your new class a *child* class of the Adafruit TFT class.  You new class then gets all the public functions of the Adafruit class - it essentially becomes the Adafruit class *plus* your extra functions overlaid over the top:

    class Rectangle : public Adafruit_ST7735 {
        ...
    };

You have to ensure that you provide a suitable constructor that passes the right parameters to the Adafruit parent class, and then you create a Rectangle class *instead* of the Adafruit class in your sketch.

* Inheritance tutorial: http://www.cplusplus.com/doc/tutorial/inheritance/

That is fine if you just want one class that uses the functions from the Adafruit class.  The second option is to pass a pointer (or reference) to the Adafruit class to your other classes, either when you construct them or at function call time.  For instance, you might have:

    class Rectangle {
        private:
            Adafruit_ST7735 *_tft;

        public:
            Rectangle(Adafruit_ST7735 &tft) : _tft(&tft) {}
    };

Then in your function you can use:

    void Rectangle::draw() {
        _tft->drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), ST7735_GREEN);
    }

You would, of course, construct your class with:

    Adafruit_ST7735 myTFTScreen(blah blah blah);
    Rectangle myRect(myTFTScreen);

Then call `myRect.draw();`.


message:
What is the purpose of the howMany integer in the wire.onReceive() function from the example code?

In the master write/ slave read example for the wire library, there is an integer declared howMany that is never used.

     void setup() {
       Wire.begin(8);                // join i2c bus with address #8
       Wire.onReceive(receiveEvent); // register event
       Serial.begin(9600);           // start serial for output
    }

    void receiveEvent(int howMany) {
      while (1 < Wire.available()) { // loop through all but the last
       char c = Wire.read(); // receive byte as a character
       Serial.print(c);         // print the character
    }
     int x = Wire.read();    // receive byte as an integer
     Serial.println(x);
    }

As the function does not work without it, i would like to know what is its exact purpose.I would imagine that is something regarding the buffer size.

body:
It tells you how many bytes have been received, and consequently how many you can read with `Wire.read()`.

Before you have read anything with `Wire.read()` `Wire.available()` will return the same value.  As you read from the buffer `Wire.available()` will decrease, but `howMany` will stay the same.


body:
The reference page <https://www.arduino.cc/en/Reference/WireOnReceive> states:

> Parameters
>
> handler: the function to be called when the slave receives data; this should take a single int parameter (the number of bytes read from the master) and return nothing, e.g.: `void myHandler(int numBytes)`

I suggest you look at the reference pages for the functions in future before asking what they do.


message:
H-Bridge L298N motor driver

I have 2 motors connected to a dual H-Bridge motor driver and the H-bridge connected to an arduino uno, It was working fine at first but now my motors are spinning very slow and the car bearly moves, I have changed the batteries  but still moves slow and with no power, please help

body:
You can try to bisect the problem.

Remove the Arduino and drive the motors with wires: replace the input for the pwm signal with a +Vcc and you will get the same as if the Arduino was outputting a PWM with 100% duty cycle.

This should allow you to diagnose if there is a problem with the driver/motors.

If that shows no problem and the wheels spin as expected, then you have some issue (either sw or electrical with the Arduino).

But at least you can halve the complexity of the problem.


message:
Relay doing opposite to digital pin

I have a Arduino UNO with a Ethernet shield which hosts a basic HTML page with a button on it which controls a Relay module.

I'm trying to connect to a computer's power button so I can turn it on remotely.

I have found out that the relay basically does the opposite to the digital pin's output

Normally open Relay

HIGH = Open

LOW = Closed

I connected it through a NOT Gate made using a NPN transistor and it works perfectly how I wanted it.

Now to the question... Is there a way to write the code to make the digital pin = HIGH straight away and fast enough to not allow the relay to close the circuit and accidentally turn the computer on/off when the Arduino restarts, so I don't have to use a NOT Gate.

body:
You could use a less invasive way to turn on your computer: [wake on LAN][1]. In this case you only need to generate the magic packet.

It won't work in forcibly turning off the PC, but it's more generic and doesn't require HW hacking.

  [1]: https://en.wikipedia.org/wiki/Wake-on-LAN