Servo motor activation with pressure sensor

You don't tell what pressure sensor are you using, but suppose that a call to readPressure() will give as pressure as an int

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup()
{
    myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
    int pressure = readPressure();

    if(pressure >= 10 && pressure <= 70) {
        //  Pressure is in range. Move the servo.
        for(pos = 0; pos <= 30; pos += 1) { // goes from 0 degrees to 180 degrees
            // in steps of 1 degree
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);                       // waits 15ms for the servo to reach the position
        }

        for(pos = 30; pos>=0; pos-=1) {   // goes from 180 degrees to 0 degrees
            myservo.write(pos);              // tell servo to go to position in variable 'pos'
            delay(5);                       // waits 15ms for the servo to reach the position
        }
    }

    //  Wait for another 1.5 sec before next loop().
    delay(1500);
}

Of course, you have to complete the code with the actual sensor calls.


Are there any commonly available and supported backlit, monochrome graphic LCDs with more than 128x64 pixels?

Here you can find a bunch of displays at new haven display, which are big and OLED and not too expensive:

2.7" 128x64 OLED
3.12" 256x64 OLED

Those OLED Displays have a really excellent viewing angle and can be read from far (given you accept those sizes, which are >2").

Otherwise, the biggest I know about are LCD ones from NHD over there:

320x240 LCD with backlight

What's good with them, it's that they can cope with production in case this is needed, their prices are decent and their product just work(cTMr). You can find the u8g library to run them.


I am building an robotic arm by using flex sensor, servo and 2 xbees

Without knowing more about the actual problem of "doesn't move properly", what I initially see is that you are transmitting values 0-9 by using Serial.println(), which sends the byte data, and also a newline (ASCII value 10), so your RX code is probably getting alternating input of the intended value, and the value 10, which is getting subtracted from 48 (the ASCII value of '0'), mapped and constrained to 0.

Try changing your TX script to call Serial.print() instead. Your receiver doesn't care about each value showing up on a new line -- it doesn't know about lines.


How to make MEMS IR Thermal Sensor - D6T-44-L06 work with Arduino?

Yes should be really easy to implement, as it work like almost all i2c sensor; this manual as also some code example, the chip address, and finally the registry address; that is all you need.
http://www.mouser.com/pdfdocs/D6T01_ThermalIRSensorWhitepaper.pdf


There are currently no expansion boards (shields) for the Arduino platform that are designed to do what you're asking of it. At most you'll find shields that can support up to 2 maybe 3 motors. My recommendation for a beginner would be to experiment with a breakout board like this one: https://www.sparkfun.com/products/9457 It's compact and can easily control 2 of the motors you need, three together and you could control up to 6.


Have I bricked my Arduino Uno? Problems with uploading to board

It probably isn't bricked

I've got quite a few Arduinos, and over the last few years have only ever "bricked" one, and I think that was by zapping it with static electricity. Unfortunately that particular one had a SMD (surface mounted) processor chip, so it isn't easy to try swapping it with another chip.

Stay calm, and try the following steps ...

Example board

An "Arduino Uno" is not just one thing that might fail. It has multiple major components, and possibly only one has failed (if any). See this reference photograph:

Major components are:

Atmega16U2 processor - this handles the interface to the USB connection
Atmega328P processor - this is the "main" processor which has your sketch on it
Voltage regulator - this converts incoming power from the power jack to 5 V
Power LED (green) - marked "On"
Indicator LED (yellow) marked "L" - connected via an op-amp to digital pin 13
Rx and Tx LEDs (yellow) - these indicate if the USB chip (Atmega16U2) is receiving or transmitting

Note that the Rx and Tx LEDs are not connected directly to digital pins 0 and 1 on the board (marked Rx and Tx). They only illuminate if you are doing serial communications via USB, not if you have something (like a GPS) plugged directly into digital pins 0 and 1.

Also note that since the "L" LED is connected via an op-amp, it may illuminate if pin 13 is set to an input in your sketch. This is normal. It doesn't mean that something is erroneously sending data.

Check the power

USB power

Plug the board into your computer with the USB cable and check that the green "On" LED lights up.
Use a multimeter and a couple of jumper leads to test between the 5V pin and the GND pin (arrowed at the bottom). You should get a reading of around 5.0 V (I got 5.04 V on mine).

(You can buy a cheap multimeter for around $10 if you don't have one, but you are better off getting a better one for around $50 - check all the electronics web sites and stores.)

Also test between the 3.3 V pin and the GND pin - you should get 3.3 V.

If you do not get 5 V with the USB cable plugged in make sure the other end is connected to your computer. Also try a different cable.

Power jack

If you are using, or planning to use, the power jack (marked "power in" on the photo) disconnect the USB, and plug in a power supply - which should be 7 to 12 V DC with positive on the center pin.
Measure the 5 V and 3.3 V pins as above. You should still see the same voltages on them.

If you get 5 V with the USB connected, but not with the power supply then the voltage regulator (marked on the photo) is probably damaged. Or, possibly the power supply has failed. Try a different power supply to confirm which it is.

Check the power-on LED flash

If you have the Optiboot bootloader (the Uno normally ships with that) then if you press and release the Reset button, or unplug and plug the USB or power cable back in, the "L" LED should flash quickly 3 times. The "on" and "off" times are 50 ms each, the three flashes should be over within about 1/3 of a second.

If it doesn't, you may have a problem with the bootloader, or the main processor chip (Atmega328P).

Try uploading a sketch

Important: If you are having trouble uploading sketches remove any connected devices (like shields). Also remove jumper wires plugged into the board sockets. In particular, there should be nothing plugged into digital pins 0 and 1 (Rx and Tx) because that will interfere with communicating with the uploading computer.

Choose one of the simple example sketches (eg. Blink) and try to upload it. This is what you should see:

The "L" LED should flash 3 times. This is because the main chip is being reset by a command from the uploading process.
The "Rx" LED should flash quickly. This is the instructions from the uploading process trying to activate the bootloader.
The "Tx" LED should flash quickly. This is the processor acknowledging the uploaded data.

You may see the above, even if the uploading process fails. This could be because the wrong board type is selected.

If only the "Rx" LED flashes, it could be because of a problem with the bootloader, or the main processor chip (Atmega328P). Someone is knocking, but no-one is at home!

Check the board type

If the LEDs flash, but you get a message like this:

avrdude: stk500_recv(): programmer is not responding

Check the board type:

If you have the wrong board type selected it will probably send the wrong uploading instructions, and time-out or otherwise fail. If you are like me and have different boards lying around it is easy to forget that the last upload you did was for a different board type.

Check the comm port

If the LEDs don't flash at all, you may have the wrong comm port selected.

Check the comm port:

Try a different PC / Mac if possible

Try your Arduino on a different PC/Mac if you have one to hand. This can narrow down whether or not you have an issue with the particular computer you have plugged it into, or computers in general.

Do a loopback test

Disconnect all shields and other wires
Remove the board from the power
Connect a jumper wire from RESET to GND (orange wire in photo)
Connect a jumper wire from Rx to Tx (white wire in photo)

Wiring:

Plug in the USB cable, and start up a terminal program - such as the Terminal Monitor in the Arduino IDE. Type something and send it (eg. hit Enter in the Terminal Monitor).
Everything you type should be echoed back.

If everything is echoed back: That confirms you have the right comm port, the USB cable is OK and the USB interface chip (Atmega16U2) is probably OK.

If nothing is echoed back, check:

You have the correct comm port.
Try a different cable. Some cheap USB cables only have power wires and not data wires.
Check the device driver for the Arduino is installed. You probably don't need to do this if that board worked previously on this computer, but it can be worth doing if this is the first time you plugged this board into this computer.

Test the Atmega16U2 chip

If your board fails the loop-back test, and you are certain the USB cable is OK, then you can test the Atmega16U2 chip itself. There is an ICSP (In Circuit Serial Programming) header on the board, adjacent to the Atmega16U2 chip, and near the USB socket.

Disconnect the power first (unplug the USB cable and any power cable).

Then you can connect the ICSP header via 6 jumper wires to a known good Uno, as shown in the photo:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the Atmega16U2 chip is marked with a small white dot, near the "F" in "AREF". Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".

Connect up:

Good board         Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Double-check your wiring.

Then on the "known good" board install the "Atmega_Board_Detector" sketch as described on the Atmega bootloader programmer page. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Detector".

Once installed, open the serial monitor, set it to 115200 baud, and you should see something like this:

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x94 0x89
Processor = ATmega16U2
Flash memory size = 16384 bytes.
LFuse = 0xEF
HFuse = 0xD9
EFuse = 0xF4
Lock byte = 0xCF
Clock calibration = 0x51
Bootloader in use: No
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 4096 bytes starting at 3000

Bootloader:

3000: 0x4B 0xC0 0x00 0x00 0x64 0xC0 0x00 0x00 0x62 0xC0 0x00 0x00 0x60 0xC0 0x00 0x00
3010: 0x5E 0xC0 0x00 0x00 0x5C 0xC0 0x00 0x00 0x5A 0xC0 0x00 0x00 0x58 0xC0 0x00 0x00
3020: 0x56 0xC0 0x00 0x00 0x54 0xC0 0x00 0x00 0x52 0xC0 0x00 0x00 0xEE 0xC4 0x00 0x00
...
3FE0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
3FF0: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF

MD5 sum of bootloader = 0xD8 0x8C 0x70 0x6D 0xFE 0x1F 0xDC 0x38 0x82 0x1E 0xCE 0xAE 0x23 0xB2 0xE6 0xE7
Bootloader name: Arduino-dfu-usbserial-atmega16u2-Uno-Rev3

First 256 bytes of program memory:

0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00
10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00
20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00
30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00
...

However if you get a message like this:

"Failed to enter programming mode. Double-check wiring!"

That would appear to indicate that your ATmega16U2 is not working.

Test the ATmega328P chip

Disconnect the power from the "known good" Arduino Uno and rewire the ICSP jumpers as per this photo, to connect them to the "main" processor on your Uno:

The pin-outs for the ICSP header are (from the top):

Pin 1 on the ICSP header near the ATmega328P chip is marked with a small white dot, below the "N" in "ON".

The wiring is the same as before, except you are connecting to the other ICSP header - the one at the end of the board, furthest from the USB socket.

Good board       Target Uno

  MISO                MISO    (pin with dot - pin 1)
  VCC                 VCC
  SCK                 SCK
  MOSI                MOSI
  D10                 /RESET
  GND                 GND

Once connected, open the serial monitor, set it to 115200 baud, and you should see something like this:

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul  9 2015 at 08:36:24 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Bootloader in use: Yes
EEPROM preserved through erase: No
Watchdog timer always on: No
Bootloader is 512 bytes starting at 7E00

Bootloader:

7E00: 0x11 0x24 0x84 0xB7 0x14 0xBE 0x81 0xFF 0xF0 0xD0 0x85 0xE0 0x80 0x93 0x81 0x00
7E10: 0x82 0xE0 0x80 0x93 0xC0 0x00 0x88 0xE1 0x80 0x93 0xC1 0x00 0x86 0xE0 0x80 0x93
...

MD5 sum of bootloader = 0xFB 0xF4 0x9B 0x7B 0x59 0x73 0x7F 0x65 0xE8 0xD0 0xF8 0xA5 0x08 0x12 0xE7 0x9F
Bootloader name: optiboot_atmega328

First 256 bytes of program memory:

0: 0x0C 0x94 0x35 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
10: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
20: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
30: 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00 0x0C 0x94 0x5D 0x00
...

In this case it confirms that the main processor is working, and has the Optiboot bootloader on it.

Things you can fix

Failed voltage regulator

This isn't easy to replace, but it is only needed if you use the power jack. If you run from USB then it is not required. Alternatively you could arrange for a 4 to 5 V supply (eg. 3 x AA batteries) and connect them to the 5 V socket on the board directly.

Failed ATmega16U2 chip

This is only required for uploading sketches via the USB port, and serial debugging. It isn't particularly easy to replace because it is a SMD (surface mounted device). However you can manage without it.

You can upload sketches via the ICSP header, if you purchase a ICSP programming device.

Examples of such devices plugged into the ICSP socket:

(Those photos were taken of a Ruggeduino, but the concept is the same).

You can also get an FTDI cable, like this:

Connect it to your board's serial ports like this:

FTDI    Arduino Uno

GND       GND  (black wire on FTDI cable, blue jumper wire)
CTS       not connected
VCC       5V
TxD       D0 (RX)
RxD       D1 (TX)
RTS       To RESET with a 0.1 µF capacitor in series with it (green wire)

Now you can upload sketches directly to the main processor, bypassing the USB chip.

You can also use my Atmega chip stand-alone programmer to upload .hex files - this lets you copy the .hex file for a sketch onto an SD card, and then program the board via the ICSP header.

Failed ATmega328P chip

The main processor can be replaced fairly easily if it is mounted in a socket. Get a replacement chip from somewhere like Adafruit for around $US 6. Alternatively, try eBay. Try to get a chip which has the Optiboot bootloader already on it, to save hassle.

Carefully prise the existing chip out of the socket, and install the new one, taking note of the location of pin 1. Pin 1 has a notch on the chip, and its correct orientation is noted on the first photo in this post with a yellow dot (closest to the edge of the board). You will probably need to straighten the legs slightly. Hold the chip by the ends and gently push down onto a flat surface, like a desk, until the are pushed inwards a bit. Try to not touch the metal pins, you may zap them with static electricity.

ATmega328P responds but has no bootloader

I have a sketch at Atmega bootloader programmer which will replace the Optiboot bootloader. The wiring is the same as for the chip detector sketch. The code is at GitHub - nickgammon/arduino_sketches. If you click the Download button on that page you will get a number of useful sketches. The one you want is called "Atmega_Board_Programmer".

Install the sketch on your "known good" Uno, and connect it to the target board with the wiring shown earlier.

Open the Serial Monitor on your "good" Uno and you should see this:

Atmega chip programmer.
Written by Nick Gammon.
Version 1.35
Compiled on Jul  9 2015 at 15:06:58 with Arduino IDE 10604.
Attempting to enter ICSP programming mode ...
Entered programming mode OK.
Signature = 0x1E 0x95 0x0F
Processor = ATmega328P
Flash memory size = 32768 bytes.
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ...

Type "U" for the Uno (Optiboot) loader.

Using Uno Optiboot 16 MHz loader.
Bootloader address = 0x7E00
Bootloader length = 512 bytes.
Type 'Q' to quit, 'V' to verify, or 'G' to program the chip with the bootloader ...

Type "G" to program the chip.

You should see:

Erasing chip ...
Writing bootloader ...
Committing page starting at 0x7E00
Committing page starting at 0x7E80
Committing page starting at 0x7F00
Committing page starting at 0x7F80
Written.
Verifying ...
No errors found.
Writing fuses ...
LFuse = 0xFF
HFuse = 0xDE
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x83
Done.
Programming mode off.
Type 'C' when ready to continue with another chip ...

This takes about one second. Now the bootloader is installed.

Watchdog timer problems

The watchdog timer (off by default) can be configured to reset the processor after a certain time. The intention is to recover from a "hang" for a processor deployed in the field. However if the timer is set for a short period (like 16 ms) then the processor can reset again before the bootloader has a chance to do anything.

The symptoms are that you cannot upload any new sketches. Some modern bootloaders (like Optiboot) take steps to stop this problem as one of the first things they do. However others do not.

This can be difficult to recover from, because once the sketch runs, you have the problem of it resetting, and if you have the problem you can't replace the sketch. People often report that they have to burn a new bootloader to recover. However that is only because, as a side-effect, burning a bootloader erases the current sketch.

There is a way of recovering. Take these steps:

Power off the board completely (remove the USB cable).
Hold down the Reset button, and keep it held down (or, run a jumper wire from the RESET pin to the GND pin). This stops the problem sketch from starting, and thus activating the watchdog timer
Still holding down Reset, reconnect the USB cable.
Start uploading a sketch that does not have this problem (eg. Blink)
Once the IDE reports "Uploading" release the Reset button (or remove the jumper wire).
It should now upload OK - as the sketch which activated the watchdog timer never started.

Problems with the Mega2560 upload

I mention this here, even though this post is really targetting the Uno board, because it is quite common.

Some versions of the Mega2560 bootloader look for "!!!" in the incoming upload from the PC, and if they see that, drop into debugging mode. This causes the upload to fail.

Example code:

Serial.println ("Furnace overheating!!!");

Solutions:

Install a more recent bootloader. My "bootloader uploader" sketch mentioned earlier in this reply should install a bootloader that does not have that issue.

Or (more simply):

Do not use "!!!" in your sketch.

Problems uploading to the Leonardo / Micro / Esplora etc.

Boards with the ATmega32u4 as their main (and only) processor can be trickier to upload to. This is because the same chip has to handle uploads and also run your code.

There is a small window of opportunity, after the board is reset, when it looks for a new sketch to be uploaded. The technique for uploading to these boards is:

Compile your sketch without errors.
Start the upload
As soon as the IDE reports "Uploading" press and release the Reset button.

You only have a second or so to do this, before the old sketch starts running. Don't be discouraged if you have to repeat this process a couple of times. That is normal.

References

Solving problems with uploading programs to your Arduino
Sketch to detect Atmega chip types
GitHub site with chip detector / bootloader programmer
Atmega bootloader programmer
Atmega chip stand-alone programmer to upload .hex files
Engbedded Atmel AVR® Fuse Calculator
Arduino Uno Rev3 pinouts photo


You can connect a single output to as many input loads as you like, provided the current is sufficient to hold the output voltage within the input thresholds. See the datasheet for the H bridge to find out what the input load and thresholds are, and compare them with the output from the Arduino.


Just wanted to update and let anyone who had a similar issue learn how I solved the problem.
My baud rate was set to 1152000 rather than 115200. Setting it to 115200 solved my problem.


This is a classic example where you want to create a class.  A class will contain all the control logic for dealing with one pin - all the functions, all the variables, etc.

Then you just create as many instances of the class as you need for your different pins. Each one is completely separate from the other, and each one can be controlled at will.

For instance, you might make something like this (untested):

class FaderPin {

    private:
        uint32_t timestamp;
        int motor_pin;
        int fadeInterval;
        int minPWM;
        int maxPWM;
        int fadeDirection;
        int fadeValue;

    public:
        FaderPin(int pin, int minp, int maxp, int interval) {
            motor_pin = pin;
            minPWM = minp;
            maxPWM = maxp;
            fadeInterval = interval;
            fadeDirection = 1;
            fadeValue = minp;
            timestamp = millis();
        }

        void fade() {
            uint32_t thisMillis = millis();
            if (thisMillis - timestamp >= fadeInterval) {
                // yup, it's time!
                if (fadeDirection == 1) {
                    fadeValue = fadeValue + fadeIncrement;
                    if (fadeValue >= maxPWM) {
                        // At max, limit and change direction
                        fadeValue = maxPWM;
                        fadeDirection = 0;
                    }
                } else {
                    //if we aren't going up, we're going down
                    fadeValue = fadeValue - fadeIncrement;
                    if (fadeValue <= minPWM) {
                        // At min, limit and change direction
                        fadeValue = minPWM;
                        fadeDirection = 1;
                    }
               }
               // Only need to update when it changes
               analogWrite(motor_pin, fadeValue);
               // reset millis for the next iteration (fade timer only)
               timestamp = thisMillis;
           }
       }

};

Then you can:

FadePin motorOne(5, 0, 255, 10);
FadePin motorTwo(6, 0, 255, 10);

And regularly call:

motorOne.fade();
motorTwo.fade();


Releasing gas from a bottle via Arduino - opening a valve?

If you can tolerate a decreasing flow as the pressure in the bottle drops, a simple restrictor (fluidic equivalent of a resistor) will limit the flow but of course, I = E/R; the flow will be proportional to the bottle pressure. If that is acceptable, it is probably the cheapest, simplest, and most reliable way.


Accessing Values From Array Within a Library

This code (from the example) is what prints a single index - index Idx:

Serial.print(F("Ch"));Serial.print(Idx);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(Idx));Serial.println(F(" us")); }

To print, say, index 3 you'd use

Serial.print(F("Ch"));Serial.print(3);Serial.print(F("="));Serial.print(TinyPpmReader.width_us(3));Serial.println(F(" us")); }

To simply get the value from index 3, without printing it:

int a = TinyPpmReader.width_us(3);

(assuming it's an int)


Using malloc() and free() for a stack/linkedlist

On my answer to the question you are referencing, I state that “If
you use the heap like a stack (last in is first out), then it will
behave like a stack and not fragment.” This seems to be exactly your
usage pattern, thus you should not fear fragmentation. Of course, the
caveat written in Michel Keijzers’ answer applies: you should make sure
that no other part of your code, including libraries, is using
malloc() and free().

Just to give some evidence, the avr-lic documentation provides some
implementation details about malloc:

  When allocating memory [...] If nothing could be found on the
  freelist, heap extension is attempted. [...] When deallocating the
  topmost chunk of memory, the size of the heap is reduced.

All this can be seen in action in the source code of malloc() and
free(), which is abundantly commented and quite readable.

Edit 1: From the same section of the avr-libc documentation, we learn
about how realloc() grows a memory chunk:

  If [...] the old chunk is at the top of heap, and the above freelist
  walk did not reveal a large enough chunk on the freelist to satisfy
  the new request, an attempt is made to quickly extend this topmost
  chunk (and thus the heap), so no need arises to copy over the existing
  data.

Based on this, I would suggest you use an array, rather than a linked
list, and use realloc() to adjust the size of the array. A linked list
of n objects of size m has a memory cost n × (m+4):
each objects has an overhead of 2 bytes for the linking pointer, plus 2
bytes for malloc()'s internal bookkeeping. The cost of an array would
be only (n × m)+2.

In this case, however, it is essential that no other part of your code
uses malloc(), otherwise realloc() could end up allocating a whole
new array, which would be very costly.

Edit 2: I wrote a small test program that randomly grows and shrinks
a memory buffer. Running the test on an Uno shows that the allocated
memory chunk never changes address even though its size varies wildly.

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

void loop()
{
    static void *p;
    static size_t sz;
    sz = random(max(sz, 22) - 20, min(sz + 20, 1536) + 1);
    p = realloc(p, sz);
    Serial.print((uintptr_t) p);
    Serial.print("  ");
    Serial.println(sz);
}


You have discovered delay() does not guarantee the period of your code.  This is because the period of your code is the delay() plus the time for your code to execute.

What you need is a hardware clock to give your code an indication that a fixed period has expired.  This is one of several Arduino timer libraries. The timer library web page describes your problem in more detail with example code using delays and using the timer library features.


How to connect multiple NodeMCUs and 1 PC over wifi and have PC control NodeMCUs?

I would not consider it easier to connect a NodeMCU to the PC just to act as a Wifi interface. Most computers already have means of connecting to a network. Wether it is via Wifi or LAN is not important. Every PC has a LAN port on it's mainboard. You could connect it directly to your Wifi router.

Using a NodeMCU as you proposed would mean, that you have to program for 2 platforms: The main logic on the PC and the Wifi communication on the NodeMCU. That does not really make it easier.

The communication depends on your wanted topology. I would build the PC as Server and the NodeMCUs as clients. You can easily create a webserver programmatically with python, for example with Flask, as I have done it once. Though there even might be better webserver modules for python. It is really not that difficult and you already need to write a program for the game logic on the PC,so why not using python. Though of course you could choose any language, that you like. Python is just an easy choice, that I already did.


There's multiple things you can do.  Here's some examples.

1: Move code out of loop() and intosetup():

const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds
}

void loop() {
}

2: Stop loop() from looping:

const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {

    digitalWrite(forwards, LOW);
    digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
    delay(20000); // wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
    delay(20000);// wait 2 seconds

    digitalWrite(forwards, HIGH);
    digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
    delay(2000);// wait 2 seconds

    while (1); // Stop here and do nothing forever
}

3: Set a "I have done it" flag:

const int forwards = 7;
const int backwards = 6;//assign relay INx pin to arduino pin
bool complete = false;

void setup() {
    pinMode(forwards, OUTPUT);//set relay as an output
    pinMode(backwards, OUTPUT);//set relay as an output
}

void loop() {
    if (!complete) {
        digitalWrite(forwards, LOW);
        digitalWrite(backwards, HIGH);//Activate the relay one direction, they must be different to move the motor
        delay(20000); // wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, LOW);//Activate the relay the other direction, they must be different to move the motor
        delay(20000);// wait 2 seconds

        digitalWrite(forwards, HIGH);
        digitalWrite(backwards, HIGH);//Deactivate both relays to brake the motor
        delay(2000);// wait 2 seconds

        complete = true;
    }
}

Each has benefits and drawbacks. Which is right for you depends on what you are actually trying to achieve.


first of all, you need to understand how these sensors work.

the sensor itself is just a resistor (like a normal resistor, with 2 legs) which is constructed from materials that are affected in presence of a specific gas. the gas changes its resistance. but as it's obvious, these type of materials are not calibrated.
in order to make that resistor sensitive enough, we have to warm it. so the manufacturer puts a simple coil element near the resistor in the capsule and you connect it to 5v. it warms up (it draws a lot of current) and thus, the effect of gas on the resistor becomes greater and we can measure it easily. when they say connect and let it be for 24 hours they mean warming up the resistor. I think it's a little high. I used them after a few minutes of warming up but it depends on situation and desired precision.
the resistor and element, have separate pins and are completely independent. you have to connect the coil to 5v (because manufacturer made it like that) and use the resistor anyway you like. even with a ohmmeter.
as we have to use Arduino, so we have to measure a resistor with the ADC of Arduino. the procedure is straightforward. you put a normal resistor in series with the sensor resistor and make a voltage divider (search that if you don't know about it. it's a fundamental thing to know in electronics).I think there should be a schematic in datasheet for it. and you measure the voltage with ADC.

and some notes :

you have to use A0 pin of the module if you want reading the value like the procedure above. this pin is the output of voltage divider(the sensor + blue pot on the board) and should be connected to ADC.
the D0 is just the output of another circuit present on board for another purpose. it's a comparator output. it's used for situations where you only need to do something (like turning emergency lights on and off) when the gas goes up from a level. you don't read anything with ADC. you just turn the pot to set a threshold (that's empirical) and digital pin get high and low according to that.
the voltage divider's GND and VCC are connected to GND and VCC of heating element accordingly. so you have just one pair of GND/VCC


According to anything I could find, the Echo output is normally low and then goes high for a duration equal to the range. Your initial while condition is inverted, and you need to check for both edges.

unsigned long up, down;

// trigger pulse
while (!(PINB & _BV(PB5)))
  ; // wait for leading edge
up = millis();
while (PINB & _BV(PB5))
  ; // wait for trailing edge
down = millis();
Serial.println(down - up);


unsigned long triggerMillis = 0;

  if (digitalRead(CONTROLLINO_A8) == HIGH && !skeleLatch)
  {
    skeleLatch = 1;
    wTrig.trackPlayPoly(2);
    triggerMillis = millis();
  }

  if (millis() - triggerMillis >=14000 && skeleLatch)
  {
    digitalWrite(CONTROLLINO_R1, LOW);
    skeleLatch = 0;
  }

This should work, depending on how long your CONTROLLINO_A8 is staying high you might want to invest some more time to set up an interrupt on that pin, to make sure you don't miss a trigger.


1st LED turn ON when 1st button is pressed and other LEDs remaining OFF

First of all you have not implemented a stay on time of 5seconds delay(5000); but only 50ms delay(50);.

Second, you are not really switching of your LED's if no further button is pressed.

Change your loop() to the following, I guess this will help you to start your next steps into getting familiar with your code:

    void loop() {
      int stateButton_1 = digitalRead(pinButton_1); //read the state of the Button_1
      if(stateButton_1 == 1) {      //if Button_1 is pressed
         digitalWrite(LED_1, HIGH); //LED_1 on
         digitalWrite(LED_2, LOW);  //LED_2 off
         delay(5000);
      }
      digitalWrite(LED_1, LOW); //Switch off LED_1

      int stateButton_2 = digitalRead(pinButton_2); //read the state of the button 2
      if (stateButton_2 == 1) {
         digitalWrite(LED_1, LOW);
         digitalWrite(LED_2, HIGH);
         delay(5000);
      }
      digitalWrite(LED_2, LOW); //Switch off LED_2
    }

Hint: Using delay() is often not a good construct, better to do it with millis(), but this means some more changes. For the start in your case delay() will do, but check out what here in different Questions/answers is already written about delay() vs. millis()


Arduino Micro interference between analog inputs

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

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


ESP8266 (ESP-01) Not booting with load on IO pin 2

Simply invert the logic - so that LOW turns the SSR on and HIGH turns it off.

Try something like this:

simulate this circuit – Schematic created using CircuitLab

The P-channel FET will invert the logic. Pull GPIO2 LOW and it will turn on the FET which will enable the SSR. The 10KΩ resistor keeps the GPIO pin (and the gate of the FET) HIGH at other times.

If the GPIO pin can sink enough current to directly drive the SSR you can leave out the FET:

simulate this circuit

Again the logic is inverted. Pull GPIO2 LOW to sink current through the SSR to turn it on. The resistor keeps the GPIO pin held HIGH when booting.


Where to connect an external power source for an Arduino motor driver shield to?

There are two things you need to do:

Prevent the motor drawing its power from the micro-controller board.
Make sure that all the grounds are connected but avoiding motor current return through the micro-controller board.

simulate this circuit – Schematic created using CircuitLab

Figure 1. A good wiring configuration. The heavy wires carry the motor current.

Note that there is one ground connection between the micro-controller and the motor system. The return current for the 12 V supply does not pass through the micro-controller board.


Interesting issue with my wifi Car project

the nodemcu's 9v battery gets hot in a minute and stops working. What am i doing wrong?

You're using a 9V battery.

Those batteries are useless. They have very little capacity, and can provide very little current. The NodeMCU needs a lot of current.

Choose a better battery. Maybe a Li-Poly battery would be good (mobile phone batteries are good for this).


Don't use the voltage divider and never set the Uno pin HIGH.

Pull io 0 of esp8266 LOW with pinMode of the Uno pin.

pinMode(TO_ESP_IO0, OUTPUT); // sets the pin LOW

pinMode(TO_ESP_IO0, INPUT); // let it to the io0 pull-up resistor


char ha;
void setup() {
  pinMode(3, OUTPUT); //pump
  Serial.begin(9600);
}

void loop()
{

  //.:.bluetooth control block
  if (Serial.available()) //check serial data availability
  {
    ha = Serial.read();
    if(ha == '9') //received data is char '9'
    {
      digitalWrite(3, HIGH); //turn on
      delay(2000);
      digitalWrite(3, LOW); //turn off
    }
  }
  else
  {
    //.:.manual control block
    if(digitalRead(2)){
      digitalWrite(3,HIGH);
      Serial.println("Plant is Being Watered as the soil is dry");
      delay(5000);
      digitalWrite(3,LOW);
    }
  }
}


Simple compiler design help: Variable length arrays?

In C++ there is a std library container called vector you can use to create variable length arrays. You can use it like this:

#include <vector>
// ...
std::vector<int> commands;
// ...
// parse string and generate commands, add your commands with push_back
commands.push_back(new_command);
// and you can access elements in the array like normal
commands[0];
// and also see how many elements are in the array
commands.size();

I also want to mention the std stack, which I think would be a helpful class for managing the states of your nested loops. Each time your interpreter enters a new loop for example, push to the top of the stack how many times to run, and each iteration count down till 0 and pop (just as an example).

Edit:
Because you can't use vectors C++ also supplies the new and delete keywords to dynamically allocate and delete memory. However as arduino has really low memory I don't recommend trying to implement an expansible array on this.
This post here mentions that program memory and global memory is shared on 2K: new operator on arduino

You may just want to go with a reasonably sized static array on arduino considering the memory limitations. I would suggest using a pool or the new + delete stuff but any implementation you add to deal with memory management will take away space you need for your interpreter and its instructions.

Also I don't know what data type you've chosen to represent your instructions but char is probably best  on the embedded implementation if your instruction set is small as it only occupies one byte each.


Can a MEMS accelerometer sensor be used as a shock sensor?

Sure you can. A "shock" is merely a large amount of acceleration over a short period of time.

You would probably want to set the MPU6050 to its least sensitive setting (±16g), and you might even be able to make use of the "tap" function whereby the MPU6050 itself looks for a sudden short sharp shock to trigger an interrupt (though that may be a little too sensitive for your needs, I don't know).


Arduino-based mains frequency monitor follow-up

You should remove the capacitor. It won't remove any DC offset because there can be no DC offset. From where would the DC offset be relative? There is only two points in the circuit, and both of them are direct from the transformer and is an AC waveform. There is no concept of a DC offset in such a circuit.  All the capacitor will do is impose a phase change between the current and voltage of the AC waveform limiting the current during the conducting period of the diodes. You have a resistor for that function.

You make some incorrect assumptions about how to read the data. You talk about outputting a signal and somehow finding out if the transistor is on or not by if that signal is being output. That's completely backwards. Instead you should treat the transistor like a simple pushbutton and provide it with a pullup (or pulldown if you prefer) resistor, like this:

simulate this circuit – Schematic created using CircuitLab

You should feed the signal into an interrupt-enabled pin (such as D2 on the Uno as shown) so that an interrupt can be used for capturing the incoming edge time. Better would be to use the Input Capture peripheral, but that is harder to program for as there is no (AFAIK) library for it.

Yes, it would be possible to use the internal pullup resistor of the input pin instead of an external one, however using an external one allows you to fine tune the resistance which, coupled with the gate capacitance of the input pin, forms a low-pass filter limiting the frequency range you can monitor. At 50Hz it shouldn't be a problem though, so the choice is yours. Personally I use an external one.


I guess it's something with the circuit ... can you add it to your question.

Also, make sure buttonPin has the values 13 and 12 in the first and second index.

Btw, The following code is functionally identical:

void loop()
{
    if (digitalRead(buttonPin[0]) == HIGH)
    {
       lcd.print("  Screen A ");
    }
    if (digitalRead(buttonPin[1]) == HIGH)
    {
       lcd.print("  Screen B ");
    }
}

If you want to have the loop and a flexible amount, use something like:

#define NR_OF_PINS 2

int buttonPins[NR_OF_PINS] = { 8, 9 };
String screens[NR_OF_PINS] = { "Screen A", "Screen B" };

void loop()
{
    for (int pin = 0; pin < NR_OF_PINS; pin++)
    {
        if (digitalRead(buttonPins[pin]) == HIGH)
        {
            lcd.print(screens[pin]);
        }
    }
}

Update

My answer is related to the code before you edited.

Remarks:

After your edited code, you forgot to declare buttonPin:

int buttonPin[] = { buttonPin1, buttonPin2 };
You do not use long randNumber
Instead of a global variable int buttonState  you can create it locally in the loop function (although you do not need it according to my code above).

buttonState = digitalRead(buttonPin[x]);
Also, what you high likely want to add is button debouncing (check the arduino example about this), unless you add a delay after showing a screen of a considerable amount (like 100 ms or more).


What is the most accurate sensor for detecting ping pong ball?

I've had some good luck with using the Pixy camera system.

http://www.cmucam.org/projects/cmucam5/wiki

You get a maximum of 50 FPS and can detect and locate different objects based on hue. The library function getBlocks() returns the X and Y center location of each of the objects the camera detects. You teach the camera what hues to recognize as blocks, and adjust the detection thresholds. I use mine in monochrome infrared light by adding a visible filter and lens kit from http://irlock.com/


Power supply change change gps readings?

The Pi can only supply ~50mA from 3.3V. This is unlikely to be enough to run GPS.

In addition USB can only supply 500mA. This is marginal at best, and below the recommended minimum for Pi.


The ESP-01 ... and all ESP8622 ... have two modes for operation.

Flash mode / Boot load mode - on bootup (at the time an electrical current is first applied, or after the reset pin is grounded), if the GPIO0 (GPIO Zero) pin {On the ESP-01 this is the 7th pin} is connected to ground, the chip goes into non-run, receive program mode.  This is where you load the compiled program.

Normal - on bootup (as above), but GPIO0 is NOT ground, then the ESP-01 goes into run mode.


Timer function without the use of a library

Your code is not bad in terms of efficiency. You have, however,
duplicated code, which is bad in terms of program size, but also makes
the program harder to read and to maintain. A good rule for programmers
is “do not repeat yourself”. Then, when you find yourself writing almost
identical functions, you should try to find a way to merge them into a
single function.

Here it is easy: the only difference between your timer functions is
that they use a different previousMillis variable. Also, the name of
the currentMillis variable is different, but it being a local
variable, this difference is irrelevant. Then, to merge them into a
single function, you only have to give to this function a reference to
the relevant PreviousMillis.

bool timer(unsigned long &last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - last_time >= period) {
    last_time = now;
    return true;
  }
  return false;
}

And you use it like this:

void loop() {
  static unsigned long previousMillis1;
  static unsigned long previousMillis2;
  static unsigned long previousMillis3;

  if (timer(previousMillis1, 1000)) Serial.println(1);
  if (timer(previousMillis2, 2000)) Serial.println(2);
  if (timer(previousMillis3, 3000)) Serial.println(3);
}

I took the liberty of making all the previousMillis local to loop(),
since they are only used there. Making them static means their values
are remembered between call to loop(), much like global variables.

In plain C you would use pointers instead of references. It is basically
the same, except that with pointers you are explicitly manipulating
addresses, while this is implicit with references:

bool timer(unsigned long *last_time, unsigned long period)
{
  unsigned long now = millis();
  if (now - *last_time >= period) {
    *last_time = now;
    return true;
  }
  return false;
}

void loop() {
  /* [...] */
  if (timer(&previousMillis1, 1000)) Serial.println(1);
  /* [...] */
}

The next step in code modularity would be to wrap this timer function,
together with the associated data (last_time and period), inside a
class:

class Timer
{
public:

  Timer(unsigned long _period)
  : period(_period), last_time(millis()) {}

  bool shouldRun() {
    unsigned long now = millis();
    if (now - last_time >= period) {
      last_time = now;
      return true;
    }
    return false;
  }

private:
  unsigned long period;
  unsigned long last_time;
};

Then, you would use it like this:

Timer timer1(1000);    // period = 1000 ms
Timer timer2(2000);    // period = 2000 ms
Timer timer3(3000);    // period = 3000 ms

void loop() {
  if (timer1.shouldRun()) Serial.println(1);
  if (timer2.shouldRun()) Serial.println(2);
  if (timer3.shouldRun()) Serial.println(3);
}


How to enable maximum Dead Code Removal?

Enable your IDE's verbose of the compile via the preferences. From there you can see exactly what and how it is being compiled.

In short the IDE (and toolchain) will compile everything and anything it can find into an object. Where only the used code is compiled in the linking phase, as garbage collection is enabled with the "--gc-sections" command.

Note that the optimization level is "-Os" or "Optimize for size". In IDE 1.0.+ this appears to be hardcoded. Where as in IDE 1.5.+ the compiler options are configurable, in "\arduino-1.5.6-r2\hardware\arduino\avr\platform.txt" can be customized to meet your needs.

Where you can use the avr-objdump command as described in https://stackoverflow.com/questions/15291750/does-importing-libraries-load-everything-in-arduino/15296808#15296808.

I would recommend 1.5.6r2 and not 1.5.7 as the gcc commands won't run individually without some path manipulation.


I cannot compile the Arduino sketch when I remove the void loop function?

You can't, and shouldn't, remove the loop function. Arduino sketches must have a setup function and a loop function. The setup function is called once and the loop function is called repeatedly.

Just make your loop function look like this:

void loop() {
    movefor ();
    moveback ();
}

Your motor will move forward, then move backwards, forever.

Note that you should read up on how to avoid using the delay function. You really need to use millis() to do your timing rather than delays. Do an internet search on "Arduino blink no delay." That's basic Arduino programming.


It's coming from the program itself:

int direction = 1;

That means "Create a signed integer called 'direction' and assign it the value 1.


Arduino Nano, ICSP header and 595 Shift register

It is extremely confusing to have a variable val and then use _val in your function but then:

  shiftOut(dataPin,clockPin,LSBFIRST,val);

As James pointed out, you are not sending the value passed to the function, to the shift register.

Also this is just going to give you a boolean:

 updateRegister(!i);

Why take "not i" there?

I suggest you use SPI and not muck around with shiftOut. I have a page about the 595 chip including example code. eg.

#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop


At a guess I would say your main problem is you are defining your TMRpcm objects within the setup and loop functions, which means that as soon as that function exits the TMRpcm objects will be disposed of. I.e., it won't work. It may start playing a sound in setup(), but it will stop (and maybe even crash completely) before you even have a chance to hear it.

Your TMRpcm object must be declared globally for you to have any hope of making it work.

TMRpcm tmrpcm;

void setup() {
    // ....
    tmrpcm.speakerPin=9;
    tmrpcm.setVolume(6);
    tmrpcm.play("1.wav");
}

etc.

Another thing to note is that TMRpcm plays the sounds asynchronously. That is, it doesn't wait while it plays the sound, so if you play one sound and then another sound the second sound will start before the first one has even begun playing, so you'll never hear the first one.  Instead, if you want to play sounds sequentially, you should for the first sample to finish using something like:

while (tmrpcm.isPlaying()) {
    delay(1);
}

which will stop your sketch running until the last sound has finished.  Including the delay(1) is a good idea since it allows yield() to execute allowing anything that needs it to run (not really a problem on an Uno, but on things like an ESP8266 it's absolutely critical or you get a watchdog timeout).


How to Serial read two consecutive chars sent by computer to Arduino?

Presuming that code is the interior of loop(), your Arduino will spin until a character arrives, that is, until Serial.available()>0 becomes true.

It then reads the character with Serial.read() and if it's an 'a' immediately does another Serial.read().  In general, some delay occurs between characters arriving via a serial interface.  Whenever the serial buffer is empty, an immediate Serial.read() will return -1 instead of an ASCII character.

To fix this problem, test for availability of a character before doing the second read.  For example, you could add

while (!Serial.available()){}

before the read, to delay until a character is available.


The ENA/ENB (enable A/B) pins have to be at HIGH level (either hardwired or set by an mcu). There exist lots of different driver boards (mostly based on the same ICs) which sometimes don't provide this enable pin, but they are "enabled" by default. You didn't tell us which board you use, but you'll know.


Adafruit RGB LCD w/ Shield kit connection to arduino uno?

The idea of shields is that they (in theory) can be stackable.
(In practice they are usually not)
This means that technically you can do this:

That's why by design every shield connects to every Arduino pin but uses only some of them. That way shield is mechanically well attached to the Arduino, and can pass "unused" pins to the shield above it.

Your shield is designed to be always "on top" so I think it only connects to some pins just for mechanical support. Technically the LDC screen needs only 6 pins and 1 pin per button.

EDIT:
I read now that the shield you got uses only 2 pins and communicates using I2C bus (which is perfect) so I'm 100% sure that it's designed to be on top of the stack and work together with other shields and uses extra pins for mechanical support.


How do you make an Arduino count down timer?

For (int i = 0; i < 12; I++) {
      Int pixelNum1 = 1;
      strip.setPixelColor( pixelNum1, 244, 0, 0);
      strip.show();
      delay (27);
      pixelNum1 ++;
    }

Assuming you fix the upper-case lower-case issues here first, you've still got a scope issue.  Since pixelNum1 is defined inside the for loop, it will go out of scope at the end of the for loop.  So it will be 1 on every iteration and it won't increment like you seem to think it will.

Why don't you just get rid of it altogether and use i+1 instead?


The easiest way is not to create a new (dynamic) array every time you need one, but create one array (like you probably have). However, an array always has a fixed length, which is defined during declaration. An easy way to denote that e.g. only the first 10 items are filled, is to create an integer variable, that has value 10, which means that from the array (e.g. int myArray[20] only the first 10 values are saved. Whenever you add a new value in the array, use

myArray[filledSize++] = newValue;

This will add the new value at array element [filledSize] and increase the filledSize. You can add protection that filledSize should never be more than the size of the array.

To clear an array you simply use

filledSize = 0;

And whenever you iterate through the array you use

for (int elem = 0; elem < filledSize; elem++)
   {
       myArray[elem] ...

However, in many cases you want a ring buffer, I will not elaborate on it, but maybe you can check into this, to see if this is more appropriate in your case.


Different ways (and the fastest) to compute sines (and cosines) in Arduino

The two basic methods are mathematical calculation (with polynomials) and lookup tables.

The Arduino's math library (libm, part of avr-libc) uses the former. It is optimised for the AVR in that it is written with 100% assembly language, and as such is almost impossible to follow what it's doing (there's zero comments as well). Rest assured though it will be the most optimised pure-float implementation brains far superior to ours could come up with.

However the key there is float. Anything on the Arduino involving floating point is going to be heavyweight by comparison to pure integer, and since you are only requesting integers between 0 and 90 degrees a simple lookup table is by far the simplest and most efficient method.

A table of 91 values will give you everything from 0 to 90 inclusive. However if you make that a table of floating point values between 0.0 and 1.0 you still then have the inefficiency of working with floats (granted not as inefficient as calculating sin with floats), so storing a fixed point value instead would be far more efficient.

That may be as simple as storing the value multiplied by 1000, so you have between 0 and 1000 instead of between 0.0 and 1.0 (for instance sin(30) would be stored as 500 instead of 0.5). More efficient would be to store the values as, for instance, a Q16 value where each value (bit) represents 1/65536th of 1.0. These Q16 values (and the related Q15, Q1.15, etc) are more efficient to work with since you have powers-of-two which computers love to work with instead of powers-of-ten which they hate working with.

Don't forget as well that the sin() function expects radians, so you first have to convert your integer degrees into a floating point radians value, making the use of sin() even more inefficient compared to a lookup table that can work directly with the integer degrees value.

A combination of the two scenarios, though, is possible. Linear interpolation will allow you to get an approximation of a floating point angle between two integers. It's as simple as working out how far between two points in the lookup table you are and creating a weighted average based on that distance of the two values. For instance if you are at 23.6 degrees you take (sintable[23] * (1-0.6)) + (sintable[24] * 0.6). Basically your sine wave becomes a series of discrete points joined together by straight lines.  You trade accuracy for speed.


How to upload one program into several Arduinos at once?

Are you programming them for the first time or doing a update?

If is the first programming, I cant see another way.

Otherwise, If is a update and your Arduino have a Wifi module you could try something like an update on the air, where you put your new firmware in a server for example and all devices updates yourself automatically or by a command.

Google for Arduino OTA (on the air) you will get a lot of source code and examples of doing that.


You should avoid pulseIn for a quadcopter, the main reason being that pulseIn takes too long to execute.

pulseIn waits for a pulse to start, then waits until that pulse finishes, and then returns how long it took to finish. Standard RC signals pulse at 50-60Hz, with the "high" part of the signals being between 1 and 2 milliseconds. 60Hz is one pulse per 16 milliseconds or so.

What that amounts to is pulseIn taking at most 18 milliseconds, but never less that 1 millisecond to execute per channel. lets say you want to measure 4 channels (throttle, pitch, yaw, roll); the average time would be around 40 milliseconds.

In general 40 milliseconds isn't so long, but your quad will need to read the accelerometer and gyroscope and stabilize itself more often then that in the air. A loop that takes 40 ms is running at 25Hz, but the stabilize loop in all the quadcopter implementations I'm familiar with is run at 100Hz or higher (thats areoquad, multiWii, and ardupilot).

You should use interrupts to read the values, because interrupts are non blocking, and give higher quality readings. Some specialized quadcopter boards have other processors read the actual RC signals and send the result back to the main processor to cut down on the number of interrupts they have to use.

FYI, The standard servo output library sends new signals at 50Hz. Those open source quadcopters use their own implementations that run at higher output frequencies, since brushless ESCs support that. There is a pull request with code to add support for different refresh intervals to the arduino servo library here that I have tested; You could try appling it as a patch to your installation if the output rate gives you trouble down the road.


The problem here is you set pull-up on D0. So even if button is not pressed it will be at high state because of pull-up. You would need pull-down for this to work (Arduino does not have it).

The pullups are useful if you want to connect pin to GND when button is pressed. When button is not pressed it will have defined state (HIGH because of pull-up) and when pressed it will be pulled LOW by button. You can imagine pull-up as a resistor to Vcc.

So for this to work I would put the other end of button to GND and it will work (One end to D0, second on GND). Condition in code should be altered (a == 0) but otherwise all can be the same.

Other option is to connect external resistor in range 1K-100K Ohm between pin D7 and GND and turn off pull-up in code. That resistor would serve as pull down.

Just one more note. If you are not using other pins it is the best to leave them as inputs. Setting an "unused" pin as output and setting it to HIGH can damage the pin if you accidentally connected it to GND (because in previous sketch you experimented something).


Arduino nano to esp8266 level shifting needed?

The arduino nano v3's logic is 5v, and the ESP8266's logic is 3.3V, so you need to do level shifting between both.
Using a voltage divider drains more current (guess not an issue in this case) and it's ok only when going from 5V to 3.3V (when the signal must be shifted from 3.3V to 5V in the links you provide, it looks like it's based on that 3.3V is still considered "HIGH" on a TTL signal).

I personally prefer using a level shifter, it just complicates a bit the Bill Of Materials, but you won't have to debug the level shifting part.

And better than that, using an arduino mini pro @3.3v working directly at 3.3V gets rid of this hassle.


Joy-IT RS232 Shield and RS232 voltage levels

Yes, that shield will handle the level shifting for you. If you look closely at the images of the shield, you see the MAX232 chip, which is a commonly used chip for getting UART (which is the Serial interface of the Arduino) to speak over RS232.
And yes, RS232 uses different voltage levels. The UART on a microcontroller usually uses the voltages 0V and 5V (or 3.3V depending on  it's supply voltage), which is also called TTL levels (Transistor-Transistor Logic), while RS232 mostly works with +-10V (though different voltages are also inside the standard). You see, that this is a symmetrical voltage around ground (0V).


Get accelerometer values from BNO055 using adafruit's Unified Sensor Library

Findings

If I use the same sensors_event_t in the code and use event.acceleration and event.orientation within the loop() and they provide me exactly the same values. I in fact get the same values for heading, pitch, roll and acceleration in x, y, z direction.

sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.heading);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.pitch);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.roll);
  Serial.println(F(""));
 Serial.print((float)event.acceleration.x); // same as roll
 Serial.println(F(""));
 Serial.print((float)event.acceleration.y); // same as pitch
 Serial.println(F(""));
 Serial.print((float)event.acceleration.z); // same as heading
 Serial.println(F(""));

Sensor

I have a Blue Dot BNO055 sensor and it has marking on it for X, Y, Z directions as follows:

I crossed checked with the logic of Euler Angles from Wikipedia

If i rotate along the x Axis, I do in fact get roll (0 to 360) and so on.

Inference

The Adafruit_Sensor library provides only orientation values when used with BNO055 and Linear acceleration values need to be called separately using the Adafruit_BNO055.

code for Linear Acceleration and orientation

  sensors_event_t event;
  bno.getEvent(&event);

  Serial.print(F("Orientation: "));
  Serial.print((float)event.orientation.heading);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.pitch);
  Serial.print(F(" "));
  Serial.print((float)event.orientation.roll);
  Serial.println(F(""));
//  Serial.print((float)event.acceleration.x); // same as roll
//  Serial.println(F(""));
//  Serial.print((float)event.acceleration.y); // same as pitch
//  Serial.println(F(""));
//  Serial.print((float)event.acceleration.z); // same as heading
//  Serial.println(F(""));

  imu::Vector<3> li_ac = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);
  Serial.print(F("Li. Acc.: "));
  Serial.print((float)li_ac.x());
  Serial.print(F(" "));

  Serial.print((float)li_ac.y());
  Serial.print(F(" "));

  Serial.print((float)li_ac.z());
  Serial.print(F(" "));
  Serial.println();

  delay(BNO055_SAMPLERATE_DELAY_MS);


Why is my Serial port not printing the right output?

In the first example you are adding an integer to the address of a string literal and then converting it to a String.

In the second example you are converting a string literal to a String and then appending an integer.

The key point here is string literal. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a String you end up with garbage.


What is the difference between python and arduino programming?

Arduino uses a language that is derived from Processing, which looks like C++.

Python is a different language, although both have similarities (both Object Oriented for example).

What is 'complex' depends on what your background is. C++ is in general more complex than Arduino, but most people using Arduino program in C++, so most examples can be found in C++, which makes support from other users easier.

If you are new to programming, I suggest using the 'standard' Arduino IDE.

To be complete, Arduino is not a programming language, it is a platform. In general, every language can be used to write Arduino code, but only a few have compilers for creating Arduino (machine) code.


1) Just break out the headers on the GPS module to make for connections to the UNO.

2) Add a SD expansion slot on top of the GPS Module and break out the pins for those as the required pins for those as well.

3) I am not sure what you are asking exactly, but it seems to me that you want to analyze the data real-time.  Get a network shield and make sure you can SSH into it through another computer.

Note: When I say "break out the pins", I am simply saying either solder on some extra headers, or wires.


It looks like you want to create a struct and initialize it. Like this:

struct EncryptText
{
    const char *name;
    byte key[32];
    byte plaintext[16];
    byte ciphertext[16];
};

EncryptText test = {
    "Speck-128-ECB",
    {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                     0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                     0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
    {0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                     0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18}
};

Then it appears you want to use that object. Note that to access each member of the struct you have to use dot notation (ex: test.key):

void testCipher(BlockCipher *cipher, size_t keySize, bool decryption = true)
{
    Serial.print(" Encryption ... ");
    cipher->setKey(test.key, keySize);
    cipher->encryptBlock(buffer, test.plaintext);

    for(byte b=0; b<16; b++)
    {
        Serial.print(buffer[b], HEX);
    }

    if (memcmp(buffer, test.ciphertext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");

    if (!decryption)
        return;

    Serial.print(" Decryption ... ");
    cipher->decryptBlock(buffer, test.ciphertext);

    for(byte b=0; b<16; b++)
    {
        Serial.print(buffer[b], HEX);
    }
    if (memcmp(buffer, test.plaintext, 16) == 0)
        Serial.println("Passed");
    else
        Serial.println("Failed");
}


Can it time between blips, store the time between blips, subtract one time from the other and divide one time by another and display it?

What you are looking for is the millis() function.
It returns the time that passed in milliseconds since the board power up.
With this function you can find the time delta, and achieve all the described calculations.
For more information


Converting 8 bit binary to a hexadecimal pair as unsigned char

As StarCat suggested, I can just send decimal values using the same function SendData I was provided with. Because the e-ink board can only communicate in 8-bit commands I still had to split my decimal value before sending it.
This is the function I used to send decimal data in 8-bit pairs:
void Epd::SendDecAsData(int dec) {
  if (dec == 0) {
    SendData(0);
    SendData(0);
  } else {
    SendData((dec-1) / 256);
    SendData((dec-1) % 256);
  }
}


Why do MEGA2560 digital pins go high on serial disconnect?

When you connect and disconnect from the Arduino, the usb host chip resets the entire device. If you do not want this you can cut the RESET trace on the board.

some boards have a jumper here instead that can be removed.

more info here

https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


The Arduino is tougher than it looks. ;-) Or maybe you were just lucky.

The exact point of failure of an IC is hard to predict, because of part
to part variations, and because it can depend on many uncontrolled
factors (duration of fault, temperature, voltages and currents on other
pins, part history...). Then, the absolute maximum ratings are not the
predicted point of failure. They are rather a lower bound:

The part should not fail if you do not exceed the ratings
it may fail anywhere beyond those limits.

Time is, however, also a factor. The manufacturer says that operating
the part close to the limits for an extended period may shorten its
lifespan.


I think the problem is being caused by the size of your ISR's.
When using ISR's, it's important to make the code as short as possible and you should certainly avoid using any functions!
I would change each of your ISRs to:
ISR(TIMER3_COMPA_vect) {
    m1_steps_done++;
}
ISR(TIMER4_COMPA_vect) {
    m2_steps_done++;
}
ISR(TIMER5_COMPA_vect) {
    m3_steps_done++;
}

then, in the main loop of your code, you can change it so that if m1_steps_done, or m2_steps_done or m3_steps_done has increased, execute the step and configure functions


You can use Eclipse, along with AVR-GCC and AVRDude and an AVR plug-in for Eclipse. Debugging may be a little painful since you don't have all the tools that Atmel Studio gives you. I'd question your employer if you aren't allowed to use the best (free) tools even if they do run on Windows.

Really all you need is the avr-gcc and avrdude to write software for it, you can use any text editor (although it isn't really convienent).  Seems like they are pigeon-holing you into a difficult job. Good luck.


So what you're asking is:

If distance is greater than 10:

Turn on

If distance is less than 5:

Turn off

That's not hard to code, since you already have an "if" there that compares the distance.
 if(distance>5){
   digitalWrite(motor,HIGH);
   delay(30000);
   digitalWrite(motor,LOW);
 } else {
   digitalWrite(motor,LOW);
 }

becomes:
if (distance > 10) {
    digitalWrite(motor, HIGH);
}

if (distance < 5) {
    digitalWrite(motor, LOW);
}

See how there's a direct 1:1 correlation between the English I wrote at the top and the code below it? That's often a good way to understand code: write it out in plain English step by step what you want and what decisions you need to make - then there's usually a simple conversion from English to code.
The hardest part of learning to program is understanding the logic. Do that in English first and the writing of the code itself becomes so much easier.


CH340 Nano avrdude: stk500_getsync() not in sync resp=0xa4

Arduino has recently changed to using a different bootloader on their official Nano boards that communicates at 115200 baud rather than the previous 57600 baud. Support for these new boards was added in Arduino AVR Boards 1.6.21. The new Nano board definition is not compatible with old Nanos and likely most 3rd party Nanos so backwards compatibility is provided via the Tools > Processor > ATmega328P (Old Bootloader) menu selection.


If you can upload sketches, I don't think it is that big of a deal but if you can't, check the TX and RX pin tracks since if those tracks are shorted, they can keep the indicator lights on for ever due to the Serial code on the Arduino. To get further help, please tell me what happens if you try uploading code.


undefined reference to `PPMintIn::PPMintIn(int)'

As both Majenko and I tried to explain in Pass a member function pointer to a method of a foreign class (EDB Lib) you can't pass a class member function where a static function is expected.

Your error is on:

PCintPort::attachInterrupt(latest_interrupted_pin, &rising, RISING);

Error:

/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp: In member function ‘void PPMintIn::rising()’:
/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp:22: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function.  Say ‘&PPMintIn::rising’

PCintPort::attachInterrupt expects a PCIntvoidFuncPtr variable:

int8_t PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode)

That is:

typedef void (*PCIntvoidFuncPtr)(void);

That is a static function (not a class function).

However you have it as a class function:

class PPMintIn{
public:
    PPMintIn(int pin);
    void begin();
    void getSignal();
    int _pin;
    volatile int pwm_value;
    volatile int prev_time;
    uint8_t latest_interrupted_pin;
private:
    void rising();
    void falling();
};

Now you can make rising and falling static but now they can't access any of the class variables (eg. pwm_value, prev_time, latest_interrupted_pin).

The whole thing needs a redesign. You could try making PPMintIn a namespace rather than a class.

Regarding one of the comments:

Unless your class implements operator() this line doesn't make sense:

chan1(15);

Please copy and paste error messages into the post, don't make people go to Imgur to find a screenshot of some text.


Question on how "f" value is calculated in converting Morse Code to laser audio from this tutorial

This is not a good tutorial. The receiver works by assuming 14 dotLen time periods for each character. There is a loop that runs 14 times, with a 200ms delay between each iteration. If the laser is detected, then a is incremented, otherwise f is incremented. This means that the sum of a and f is always 14, and the case where a==0 means nothing was transmitted. The incomplete receiver code shows only 10 options for received characters and leaves out a==5 (which would be R or U), but does define 1 through 10 otherwise.

The receiver code does not differentiate between dots and dashes, it only counts the number of dotLen transitions where light is detected. This is not Morse Code.

The receiver code cannot distinguish between S (dot-dot-dot) and T (dash) because they both have 3 dotLen value. Same for A (dot-dash) vs. N (dash-dot).

If you want to understand decoding morse code, this is not a good tutorial to follow. It does not decode morse code, and I cannot see how it would work even with it's companion transmitter program.


You need to reinstall the AI Thinker AT firmware.

Here's how you do it: How to flash ESP8266 firmware update ESP-01 AI thinker

Last time I did it I used the esptool.py program, and used the ai-thinker-0.9.5.2.bin firmware (there's two versions on there, the default 115200 baud, and a 9600 baud variant).

On Linux I then used the command:

foo@bar:~$ ./esptool.py --port /dev/ttyUSB0 --baud 57600 write_flash 0 ai-thinker-0.9.5.2.bin
Connecting....
Detecting chip type... ESP8266
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 512KB
Flash params set to 0x0000
Compressed 520192 bytes to 165297...
Wrote 520192 bytes (165297 compressed) at 0x00000000 in 29.0 seconds (effective 143.3 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting...

This was, of course, with GPIO0 held LOW for programming mode (I actually use an adaptor with a programming switch that controls GPIO0), and for other operating systems you will need to change the port name to suit (COM3:, /dev/cu.usbmodem4873, etc).


What I think is happening here is that the HWBE fuse is set (hardware boot enable).

From the datasheet:

  The Hardware Boot Enable Fuse (HWBE) can be programmed so that upon
  special hardware conditions under reset, the bootloader execution is forced after reset.

What this means is that under normal booting (power-on reset) the bootloader is not entered, and the device immediately identifies as a TTY device (ttyACM0) as you saw:

[ 6329.384088] cdc_acm 1-1.3:1.0: ttyACM0: USB ACM device

However if you manually reset it, it enters DFU mode with its bootloader, so you can reprogram the main code. Thus it identifies differently:

[ 6278.684841] usb 1-1.3: Product: ATmega16U2 DFU

Thus, a forced reset via the Reset pin acts differently to a power-on rest. By design.

If you search for uno enter dfu mode you will get quite a few hits. People use that technique to reprogram their ATmega16U2 (eg. to act as a MIDI interface).


Your schematic does not show a connection from the ground line of the 12V battery to the GND connection on the Arduino.  This is required.


What is the difference between declaring a variable outside of loop and declaring static inside loop?

The most basic difference is of scope.

In the first case, you are declaring a global variable. It is a variable that is accessible in every scope after its definition.

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

void inc();
int count = 0;

void loop()
{
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

void inc() //Can edit the value of count
{
  count=count+1;
};

In the second case, you are declaring a static variable with local scope. The variable will persist for the entire program run similar to global variables, but will be accessible only in the code block it is declared in. This is the same example, with only one change. count is now declared as a static variable inside loop.

void inc();

void loop()
{
    static int count = 0;
    Serial.println(count);
    count++;

    inc();

    delay(500);
}

This will not compile as the function inc() does not have access to count.

Global variables, however seemingly useful, come with some pitfalls. These can even cause damage when it comes to writing programs that can interact with the physical surroundings. This a very basic example of something that is quite likely to happen, as soon as programs start getting larger. A function may inadvertently change the state of a global variable.

void setup()
{
    Serial.begin(9600);
}
void another_function();
int state=0;

void loop()
{
    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Inadvertently changes state
  state=1;

}

Such cases are very hard to debug. This type of problem however, can easily be detected, by simply using a static variable.

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

void loop()
{
    static int state=0;

    //Keep toggling the state
    Serial.println(state);
    delay(250);
    state=state?0:1;

    //Some unrelated function call
    another_function();
}

void another_function()
{
  //Results in a compile time error. Saves time.
  state=1;

}


You can use the toneAC library, which allows even better handling of piezo speakers then the standard "tone"-functions.

  Features: Nearly twice the volume (because it uses two out of phase pins in push/pull fashion)
      Higher quality (less clicking)
      Capability of producing higher frequencies (even if running at a lower clock speed)
      Nearly 1.5k smaller compiled code
      Bug fixes (standard tone library can generate some odd and unpredictable results)
      Can set not only the frequency but also the sound volume
      Less stress on the speaker so it will last longer and sound better

With the library you can do something like:

int freq = 1000
int vol = 10
int length = 0
boolean background = true

toneAC(freq, vol, length, background);

The tone now will play forever in the background, until you stop it with:

toneAC(0);


How to flash an ATmega directly without a dedicated flashing device?

Your initial assumption "An ATmega microcontroller can be flashed by a C compiler and a USB dedicated device (ISP)." is wrong.

The C compiler converts the source code into assembly language. It is then passed to an assembler which converts it to object code. The linker then creates an ELF file from it all. That is then converted into a HEX file using objdump.

That HEX file is then loaded by another program, avrdude, which knows how to control the USB-connected programming device. That device then issues special instructions to the chip through the ISP port to copy the data loaded from the HEX file into the memory of the chip in the right way.

It's quite a complex procedure and you require some active component in the mix to do the job. Just connecting an SD card and hoping it will work is, I am sorry to say, a laughable concept. You require something that a) understands how to read data from an SD card and can interpret it, and b) knows how to program an ATMega through ISP.

It is possible to create something that does that, using another chip, such as another ATMega, and writing the software to do it. If you feel adventurous, of course. You would basically have created a stand-alone programmer, which has advantages when you want to do field upgrades, but is pointless when you are sat at your desk developing software.


Using special Arduino "boolean" Data Type instead of standard "bool" data type

While the other answers give generally useful information, the authors seem to have not read the question very carefully because they are talking about the bool type rather than the boolean type. In the Arduino API, boolean is a type alias for bool, as defined in Arduino.h:

https://github.com/arduino/Arduino/blob/1.8.3/hardware/arduino/avr/cores/arduino/Arduino.h#L125

typedef bool boolean;

So you can use the boolean type just as you would bool and any standard C++ programming reference will instruct you in the use of bool. For this reason the other answers which mistakenly refer to bool are still somewhat useful.

Apparently at some point in the past the Arduino folks decided the name boolean would be more beginner friendly than bool, perhaps to be consistent with the Processing language. However, as discussed here:

https://github.com/arduino/Arduino/issues/4673

the unnecessary use of a non-standard type is now considered by some to be a poor decision as its use makes code less portable and really doesn't provide any clear advantage over bool. A proposal is in the works to remove the use of boolean from all official Arduino code and document bool in the Arduino reference and some even wish to formally deprecate boolean. Therefore my advice is to use bool instead of boolean in your code.


Powering an Arduino directly from a motor driver (DRV8825) or external power source?

why exactly is there only one power supply being shown here, is it because the Arduino can get its power from the driver?

No. It is assumed that you will provide the power to the Arduino yourself - either through the USB connection to the computer, or through the barrel jack.

  The thing I want to know, is whether this circuit would function without an external power supply for the Arduino or not?

No. The Arduino requires power to be provided.

  And if not, would connecting the Arduino to the power supply via the VIN pin work?

Yes, but it's not ideal.  At 12V the power wasted by the on-board linear voltage regulator will be proportionally high.  As long as all that is being powered is the Arduino itself that shouldn't be too bad, but if you try to draw any significant current either out of the 5V pin or through multiple IO pins (for example to drive lots of LEDs) then it will overheat and potentially shut down.

A more ideal arrangement would be to connect a 5V switching regulator to the 12V battery and use that to power the Arduino either through the 5V pin or the USB connector. Personally, I use cheap UBEC modules from RC model suppliers. They are small, low-cost, and very easy to wire up.


How to read high voltage (40-65v) from a Solar Battery bank

You need a voltage divider with resistors that have large values.

  ...but with all values I have tried one resistor almost melts as soon as you connect to battery.

This suggests that you have been using values that are too low.

So lets go through the calculations to select good resistor values.

1/4 Watt resistors are common and easily available so I will base my calculations on that. These calculations will also be suitable for 1/2 Watt and 1 Watt resistors.

I am also going to add some margin above the 65V max that the solar panel can output (plus it makes the math easier)

Max Voltage = 100V

The voltage Divider:

Let's simplify. Almost all of the current will be going from your source, through the resistors (R1 & R2) to ground. Let's simplify by initially calculating the resistance required if R1 & R2 were combined into a single resistor:

From V = I x R
And P= V x I

Minimum resistor = V^2 / P

R = 75^2 / 0.25

R = 22500 Ω minimum

I would go further and say double that because I never like operating a resistor right on its maximum power rating. ie  the minimum that R1 + R2 should equal is 50kΩ.

Lets play it safe and say that R1 + R2 is 100kΩ. The ESP8266 ADC pin input voltage range is 0 to 1V. Input is 0-100 V (which covers the required 40-65V range). Now all we have to do is calculate for R1.

Note: Most ESP8266 development boards come with an internal voltage divider. For these boards the input range is 0 to 3.3V.

Edit: The OP tells me that they get a max analog reading at 3.0V not 3.3V. Adjust the below calculations for an input voltage of 3.0V not 1V.

The formula to calculate the output voltage is:

Vout / Vin = R2 / (R1 + R2)

1 / 100 = R2 / 100kΩ

0.01 = R2 / 100k

Therefore R2 = 1k Ω

R1 = 100k - R2 = 99kΩ

I would up R1 to 100kOmega; as it will only result in a 1% error.

So R1 = 100kΩ and R2 = 1kΩ

Values of R1 = 49.5kΩ and R2 = 500Ω would also work.

In this case R1 could be made up of 2-3 resistors in series:
47KΩ
2.2KΩ
300Ω or 330Ω (optional)

The raw ADC input on the ESP8266 chip is 0-1V with a high input impedance (~20M). This means an op-amp buffer is not needed.

However, if you are interested, a op-amp circuit can be built from a 741 IC (among others) and is configured like this:


How to make 4 digits 7 segments common cathode thermometer

First thing to check is that you have the IC and the 7-segment display module connected the correct way around. As a reference, the green wire is attached to Pin 14 of the 74HC595 IC, so pin 1 would be the top right pin. The 7-segment display should have the the dot points towards the bottom.

Check that you have a common cathode display. You can do this by applying a voltage, through a 220 ohm resistor, verifying that it lights up when positive is on pins A-G and Gnd connected to the common cathode pin.

Check the code by removing the temperature section of the code and just writing '0's to all 4 digits. In fact it would be worth testing the digits one by one. The below code should do just that (unverified):

const int clockPin = 7;    //74HC595 Pin 11
const int latchPin = 8;    //74HC595 Pin 12
const int dataPin = 12;    //74HC595 Pin 14
const int digitPins[4] = {5,4,3,2};

void setup(){
  for(int i=0;i<4;i++)
  {
    pinMode(digitPins[i],OUTPUT);
    digitalWrite(digitPins[i], HIGH);
  }
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
}

void loop() {
  for(int i=0;i<4;i++)
  {
    //select the digit by enabling the common cathode (sink)
    digitalWrite(digitPins[i], LOW);

    // write '0'
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, 63);
    digitalWrite(latchPin, HIGH);
    delay(1000);
  }
}

This code will display a '0' one digit at a time, each for 1 second.  If this code works then I suspect the problem lies in the updateDisp() function.

NB: In your code, tempPin is setup twice as an input.


It may be possible to modify that program in order to get such a large
frequency range:

change the local oscillator frequency to 3.5 kHz
drastically shorten the filter's time constant in order to get a
wider passband

However, the homodyne detection scheme is best suited for building very
narrow band filters. In your case, the upper limit you want is quite
close to the Nyquist frequency (4,808 Hz), so I suggest you use a
high-pass, rather than a band-pass filter. The simplest high-pass you
can get is a numerical derivative:

y[n] = x[n] − x[n−1]

The gain of this filter is 2×sin(π×f/fsamp), so you get the
−3 dB cutoff at fsamp/4 ≈ 2,404 Hz. If you need
something better, you may want to try a higher order filter. But then
you get deep into the territory of digital filter design, which can be
tricky, especially if you have no experience with the z-transform or you
want to implement the filter in fixed point.

Edit: If you really want a bandpass, the simplest I can think of is
this two-pole filter:

y[n] = 0.360 x[n] − 0.885 y[n−1] − 0.552 y[n−2]

It will give you a maximum gain of roughly 1 at about
3.43 kHz, and −3 dB cutoffs at 3 and 4 kHz. A
straightforward floating point implementation would be:

float filter(float x)
{
    static float y1, y2;
    float y = 0.360 * x - 0.885 * y1 - 0.552 * y2;
    y2 = y1;
    y1 = y;
    return y;
}

You should convert this to fixed point if you want to use it, otherwise
I doubt your Arduino will have the processing power to run every sample
through it. Below is a plot of this filter's gain, compared with the
simple derivative, which I divided by 2 in order to normalize its
gain:

Note that the gain gets flat as you approach the Nyquist frequency, and
stays relatively high (above −5.4 dB).


Wemos: relay shield doesn't work on top of the stack

Yes, there is a pin conflict.  The relay uses D1, however D1 is (as you can see from looking at the schematics) part of the I2C connection for the SHT30.

You will have to find some way of modifying the relay shield to use a pin that's not part of I2C.


need help regarding modification of arduino code

This looks like the TM1637 DISPLAY:
TM1637Display display(CLK, DIO);

And this is the 16×2 LCD:
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

All interactions with this LCD are handled by this lcd object. If you
want to get rid of it, just remove every single statement that
references this “lcd” object.


You need to reset IRQCount back to 0 before attaching the interrupt again. Otherwise it will just continue counting from where it stopped last time.

I would actually keep the interrupt attached and just reset the variable just before the delay. That way the overhead of attach/detachinterrupt doesn't get added to the 25ms delay.

volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
}

void IRQcounter() {
  IRQcount++;
}

void loop() {
  // put your main code here, to run repeatedly:
  IRQcount = 0;
  delay(25);
  int result = IRQcount;
  Serial.print(F("Counted = "));
  Serial.println(result);
}

Since an int is 2 bytes an interrupt might occur in the middle of setting/reading those two bytes. This might result in an occasional wrong value. To prevent that you should disable interrupt while setting/reading the value

volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
}

void IRQcounter() {
  IRQcount++;
}

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

  cli();//disable interrupts
  IRQcount = 0;
  sei();//enable interrupts

  delay(25);

  cli();//disable interrupts
  int result = IRQcount;
  sei();//enable interrupts

  Serial.print(F("Counted = "));
  Serial.println(result);
}


i am not able to figure out the problem due to which i can't upload my sketch to nano

Another idea - try using Windows Filemanager to navigate down through the folder path shown in the error message and see if the avrdude.conf file exists in the specified place. this probably will not solve your problem but it might help to understand what is happening. Good luck - Bob


Serial device file no longer shows up in /dev/ after working fine for months

The fact that dmesg gives you nothing at all is the most telling fact.  The there was a communication problem, or the firmware had messed up on the USB interface chip, then you'd expect something to show up - even if it was something along the lines of "device not accepting address 8: -71"

We can ignore the main ATMega2560 chip since that has no bearing on the USB interface.  Instead we're interested in the ATMega16U2 (or whatever is on your board version).

So some things you need to confirm by probing around on the board with a multimeter, or better still, an oscilloscope:

Check that there is power to the board through the USB.
Check that there is power both sides of the green (or brown-ish if you have a clone) poly-fuse near the USB socket
If you have an oscilloscope, switch the probe to 10x and look for oscillations on the crystal's pins.
Grab the datasheet for your ATMegaxxU2 chip and get the pinout.  Check that there is power on the pins there should be power on.
Check that the RESET pin of the ATMegaxxU2 chip is HIGH.

If you have a hardware programmer, or another Arduino you can use as a hardware programmer, connect it to the 2x3 header (you may need to populate it first) and try get it to identify the chip ID.  Try to re-flash the USB interface firmware.

Another thing to check is the USB socket itself.  Those big chunky USB sockets look strong, but they're actually quite flimsy inside.  The metal leaves that the plug presses against can bend with time and not make a good contact.  Using a fine needle try lifting them up slightly so they make better contact with the cable.  I think Arduino are the only people that still use them in an active product these days ;)


Understanding the compilation/linking/upload process (so I don't have to use the IDE)

If you want an exact duplication of what the IDE does but want it driven from the command line, that's what Ino is for. The full Arduino build process involves copying a lot of files from a lot of places, and is generally not trivial to duplicate.

If you're ready to let go of .ino files and the Arduino libraries, you get a much simpler toolset. avr-gcc compiles, avrdude uploads, and you're done. Here's one of my makefiles from a simple project:

CC=avr-gcc
CXX=avr-c++
CXXFLAGS=-Wall -Wextra -mmcu=atmega1284p -Os
CFLAGS=$(CXXFLAGS)
BINARY=ledmatrix
OBJECTS=

all: $(BINARY)
↹@avr-size $<

$(BINARY): $(OBJECTS)

clean:
↹@rm -f $(BINARY) $(BINARY).hex $(OBJECTS)

upload: $(BINARY).hex
↹@avrdude -c usbasp -p m1284p -U flash:w:$<:i

%.hex: %
↹@avr-objcopy -j .text -j .data -O ihex $< $@

.PHONY: all clean upload

If copying-and-pasting, be sure to replace all "↹" with tab characters.

EDIT:

I have created a repository with my buildsystem on Github.


Turning a motor on and a led at the same time for a given time period

If you just want the led on with the motor then put a couple of digitalWrite statements in your motorOnThenOffWithSpeed function to turn the led on and off at the same time you turn the motor on and off.


Let's break it down :)

  Please upgrade the firmware

Visit here to upgrade the firmware of your board. Your original post doesn't show the fw version, but could have outdated library references and has been noted many times that outdated fw will not work.

https://www.arduino.cc/en/Hacking/WiFiShieldFirmwareUpgrading

Also add this to your project to help us determine your firmware:

  Serial.print("Firmware version: ");
  Serial.println(WiFi.firmwareVersion());

My guess is that it is less than 1.1.0. If the Arduino IDE is out of date, and the board is newer,  the NOT EQUAL TO(!=) may suggest that the firmware is newer than the library which could also be an issue.

Just b/c it connects to your router, doesn't mean that it can still communicate correctly.

One last side note, some versions of Arduino IDE have proven to be problematic with uploading a sketch to a wifi shield. A quick search with your Arduino version followed by the Wifi Shield not connecting could point you in the right direction. eg- Arduino x.xx wifi shield not connecting

Hope this helps!


Replicate a Waveform Exactly with An Arduino Uno

If you're looking to speed your code up I would recommend not using digitalWrite or Serial. When using digitalWrite it can take quite a few unneeded clock cycles to turn the pin on or off, as a replacement I would suggest looking into using port manipulation.

Example of turning a pin on or off with a preprocessor macro using port manipulation

#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

Using port manipulation in your code:

#define DIGITAL_WRITE_10_HIGH() PORTB = PORTB | B00000100     // Town ON only pin 10
#define DIGITAL_WRITE_10_LOW() PORTB = PORTB & ~B00000100     // Turn OFF only pin 10

void timing()
{
    //incomingByte = Serial.read(); // If needed uncomment, but it's slow
    //Serial.println(incomingByte); // If needed uncomment, but it's slow

     // Set pinMode in setup()
     DIGITAL_WRITE_10_HIGH();
     delayMicroseconds(16000);
     DIGITAL_WRITE_10_LOW();
     delayMicroseconds(2000);
     DIGITAL_WRITE_10_HIGH();
 }