How do I see the command line equivalent of clicking Verify?

In the Arduino IDE switch on File>Preferences>Upload erbose and Compile Verbose

When you build you will see all the compiler commands

The verify is often a -v param in the command

You will find the esp8266 platform.txt in a location such as c:\users\[name]\appdata\local\arduino15\packages\esp8266...

The platform.txt contains all the compiler switches, the boards.txt in the same location can also contain board specific switches.

You can not specify different switches for different files in a compilation but you could compile your code into an archive then force it into the build process. Not sure if that is practical or not.


It looks like those properties are only expanded in:

recipe.cpp.o.pattern
recipe.S.o.pattern
recipe.c.o.pattern
recipe.preproc.includes
recipe.preproc.macros

They are not expanded in any of the hook recipes.

This actually makes sense for {source_file} with the current build system because the hooks are not run before and after the compilation of each file but rather before and after the entire sketch compilation, so even if that property was expanded it could only give you an arbitrary filename, perhaps the first file to be compiled in the prebuild hook and the last in the postbuild hook, but that leaves all the other filenames inaccessible so it really wouldn't do much good. See related issue report.

If you're actually trying to use {source_file} to get the preprocessed sketch file, that's accessible from any recipe as {build.path}/sketch/{build.project_name}.cpp.

As for {includes}, it seems like an unnecessary restriction for that property to only expand in specific recipes. If you can present a good case for this behavior being changed, it might be worth opening a feature request to see what the Arduino developers will think.


Communicate from Arudino to computer over 3.5mm port

I didn't read the all page, but it seems it can be achieved, see David Awehr's blog (this one is conected to a android phone instead to a PC tho) and this Hackaday page where they seems to it, but the PC's audio input normally use 44,1kHz or 96kHz, so if you wanna go for the higher Serial speed (let's say just 115200bauds) you should think about it this.


Sending a value from one arduino to another

You could have the LCD Arduino be an I2C master and all the weighing Arduinos be slaves. There's an example of master/slave communication and wiring here: https://www.arduino.cc/en/Tutorial/MasterReader.

I2C supports up to 128 devices and the wiring is very simple.


How can I replace pulseIn with interrupts?

You do not want the reading of the incoming pulse to block your
program execution. This is the very key requirement: you want a
non-blocking pulse reading. You can write a non-blocking replacement
for pulseIn(), but you will have to use it differently. You cannot
expect a non-blocking pulseIn() to return the pulse length whenever
you call it: instead, it would return that value only when you call it
right after the pulse falling edge. On all other circumstances it will
return a dummy value meaning “the pulse is not finished yet, thus I
cannot give you its length right now, please call me later”.

Below is an example of a function implementing this approach. You have
to call it on every loop iteration: the more often you call it, the
better resolution you will have. This function uses 0 as the dummy value
meaning “no answer available right now”:

/*
 * Non-blocking pulseIn(): returns the pulse length in microseconds
 * when the falling edge is detected. Otherwise returns 0.
 */
unsigned long read_pulse(int pin)
{
    static unsigned long rising_time;  // time of the rising edge
    static int last_state;             // previous pin state
    int state = digitalRead(pin);      // current pin state
    unsigned long pulse_length = 0;    // default return value

    // On rising edge: record current time.
    if (last_state == LOW && state == HIGH) {
        rising_time = micros();
    }

    // On falling edge: report pulse length.
    if (last_state == HIGH && state == LOW) {
        unsigned long falling_time = micros();
        pulse_length = falling_time - rising_time;
    }

    last_state = state;
    return pulse_length;
}

A better approach, but harder to implement for a novice, is to use
interrupts. Chris gave you a pointer to Nick Gammon’s tutorial on
interrupts. This is definitely a good reading. But you will also have to
dig into the data sheet of the ATmega328P microcontroller.
It's a little bit daunting, but a must read if you go into low-level
programming. If you follow this path, I suggest you look at the “input
capture” capability of Timer 1 (chapter 20, section 20.9). This is a
feature of the timer that can have it automatically save a timestamp
whenever some external pin changes state. You then use the input capture
interrupt to alert the program when an edge has been detected, and your
interrupt service routine can read the automatically saved timestamp.
Using this approach, you can have extremely accurate pulse length
measurements, independent on how fast your program goes through its
loop().


Your question is incredibly broad. However:

1. Could I complete this project using Uno and Mega?

Yes, almost certainly

2. Is there a method for compiling data and storing/sending using Arduino?

What? Yes, you can store data onto an SD card using a simple level-shifting piece of hardware like this:

3. What are the capabilities of Arduino?

This isn't a reasonable question (it's too broad). I suggest Googling for things people have done. For myself, I made a humidity and temperature sensor using the same processor as in a Uno. It also runs from batteries.

  ... a very time tight project ...

Time is going to be your enemy here. Learning how to drive a touchscreen, save files to an SD card, interpret RS232 data from your sensor, and make it all work reliably is not the sort of thing you will do in 3 days.

Even if you dumped all your hardware on my desk (and I know how to program Arduinos) I would estimate two or three weeks to calmly get each part going individually and then interface them all together.

  Would you suggest using breakout boards over shields?

Shields are well and good if they do what you want them to do. A breakout board will have more flexibility.

  because of pin availability would you suggest trying to use the Mega rather than Uno?

Depends how many pins you need. If you use SPI or I2C you can (probably) drive your display with only a handful of pins.

The Uno will probably have enough, and it has the flexibility that you can easily replace the processor chip if you damage it. You can't do that to the Mega. Plus, more code is written for the Uno so you are more likely to find libraries that work "out of the box" for a Uno.

I wouldn't be getting the "more powerful" device unless you have identified a specific reason to have it. For example, some of the faster and more powerful Arduinos (and other boards) with ARM processors may well do more under certain circumstances, but be somewhat harder to use.


The issue is probably that you need a driver for the onboard CH340G USB-to-serial bridge.

The Baite Electronics Arduino clones are generally of good quality and work well.
There are some differences between them and Arduino-brand Arduinos. Two notable ones are a different voltage regulator and (probably the issue here) a different USB-to-serial bridge IC.  The Arduino brand products use an FTDI IC and Baite uses, in this case, the CH340 USB bridge IC.

The product is described on this webpage and you will see that they say

  UNO MEGA328P CH340G for Arduino Compatible

The CH340G relates to the USB interface IC.
Until about a year ago the USB driver in windows worked with most common USB ICs as well as with FTDI ICs.  However, FTDI changed their system so that the Windows driver will now only work with FTDI brand ICs. So it is now necessary to load a driver into the PC (whether Windows, Linux or other O/S) to suit the CH340.

If you email them Baite will provide a link to the CH340 driver, but they do not usually provide it on their website (reason unknown to me.)

Or, you can obtain a driver from numerous websites.
A web search on eg:  driver ch340 baite arduino
turns up many pages.   How good or how safe any of these is is TBD.

This page claims to provide a Windows 7 CH340G driver and install instructions

This YouTube video describes how to install a driver and provides a link to this page which lists a number of drivers.

This page discusses the issue


Arduino scrolling text program freeze after some time

You malloc but don't free. Of course it's going to leak. Also sizeof(text) doesn't work like that. Instead you can do strlen to get the number of characters in a null-terminated char array.

You can do this without the longText buffer by doing partial copies into screen.

const char space[16] = "                ";
char screen[16];

for (int i = 0; i < sizeof(text) + 17; ++i)
{
    lcd.setCursor(0, line);
    strncpy(screen, space, i); // copy i spaces
    strncpy(screen+i, text, min(17-i, strlen(text))); // copy the rest of the string up to the end whichever is shorter.
    screen[17] = '\0'; // force null termination
    lcd.print(screen);
    delay(350);
}


What is corrrect the way to find roll, pitch, yaw?

For a stationary accelerometer sensing the acceleration of gravity, I see "dead zones" when the Pitch, Yaw or Roll axes are parallel or close to parallel to the gravity vector.

Likely this is why accelerometers are used in conjunction with gyroscopes.

Refer to this NXP (aka Motorola, Freescale & Qualcomm) document for an in depth discussion regarding the necessary math.  Note the section regarding "Regions of Instability".

Also, refer to this class and this class from rutgers.edu which work students through a project using an Arduino and an accelerometer in the 1st class then adds a gyroscope in the 2nd class to improve the response.

(Added Later)

The rutgers.edu links don't appear to work anymore and this link has been suggested as an alternative.


What's wrong with my keypad and time program?

Your function timedate() is called every time through loop() and it has a total of 6000ms of delay. During a delay, NOTHING can happen, not even checking for a keypress.

So, you would have to hold the desired key down until the key = keypad.getKey() statement is executed, which is a minimum of every 6 seconds.

Use of delay() for an interactive program in which user input can happen any time is not desired. Instead, there is a popular example Arduino sketch called "BlinkWithoutDelay" which us used as an explanation of how to avoid using delay() by letting your loop() function run at very high speed and only taking the desired action if the desired time has elapsed since some initiating action.

The more generic concept is called a "State Machine" and there are numerous websites that attempt to teach it, such as this one.

Be prepared to make significant changes to the structure of your program, however, as moving from delay() usage to state machine usage means a re-thinking of your loop() function -- you have to consider it running tens of thousands of times per second, and most of those times it doesn't do anything but check if something needs to be done -- most often the answer is "no, nothing needs to be done this time."


What are some fun things you can do using the ICSP header?

You can use every single last byte of flash on the device.
Since you're performing low-level programming of the device you get the entire chip to play on, without having to worry about bootloaders and such.

You can debug (breakpoint, single-step, watch, disassemble, etc.) the code on the chip using software on your computer.
Admittedly the devices you'd need in order to do so are more expensive than a simple ISP programmer and it only works with specific pieces of software, but it can be done.


Limiting motors to a specific position using while and if loops

You can use millis() feature

unsigned long starttime;

void loop(){

  int EMGv = analogRead(EMG);
  starttime=millis();
  while(EMGv >= 900){
    if (millis()-starttime < 1000) //limit on 1000ms
    {
    move(0, 255, 1); //motor 1, full speed, left
    move(1, 255, 1); //motor 2, full speed, left
    move(2, 255, 1); //motor 3, full speed, left
    move(3, 255, 1); //motor 4, full speed, left
    move(4, 255, 1); //motor 5, full speed, left
    } else {/*turn off motor here*/}
  }


atmega328: external crystal oscillator and uart

There are some specific crystal oscillator frequencies named 'UART friendly'. Using these frequencies would lower % error in UART communications. Please refer to the table in the datasheet, in chapter named "BAUD rate settings" (datasheet of ATMega328: '24.11. Examples of Baud Rate Setting'). There are tables to show error percentage. What to look at is "Error" column. fosc is selected oscillator/crystal frequency. For succesful UART communication you aim for less than 3.5% Error.
 Your crystal speed should depend on your desired communication speed, for example for me the preferred ones are 11059200Hz or 1843200Hz.

or below:

With raising frequency you may expect power consumption and the chip's temperature rise, anyway I wouldn't worry too much about life shortening. More important here would be power consumption rise.
 Do you want the chip(device) to be battery powered? To save on energy you can also consider lower frequencies like 1.8432MHz or 3.6864MHz.


I have built a battery level indicator and have tested with a 12V battery Would it harm my arduino board if I connect a 48V battery?

You have a voltage divider there, which would give (if the pre-set pot was set to the maximum):

Vout = (Vin * R2) / (R1 + R2)
Vout = (12 * 10000) / (100000 + 10000)
Vout = 1.09

Thus a 12V battery would present 1.09V at the analog input.

This same wiring would seem to be in range for a 48V battery:

Vout = (48 * 10000) / (100000 + 10000)
Vout = 4.36

Since the analog input can handle up to 5V, then that should be OK. However I would test the voltage divider output first with a multimeter to make sure it doesn't exceed 5V - before connecting it to the Arduino.

You would probably need to change the code to test for different ranges of input voltages, other than what is used for the 12V battery.


sending 16 bit command via SPI to a NCV7719 (half bridge)

SPI writes in 8-bit bytes. So the writes need to look like this:

  SPI.transfer(0b00000100);  // first byte
  SPI.transfer(0b00000000);  // second byte

Possibly in the other order depending on which byte the device expects first.


You have to keep track of time once a button is pressed (LOW). So buttonLowTime is initialized every time you press the button. In the if logic, you first check if the buttonstate is LOW and if the said time has been passed.
But you also mentioned you want to play the audio once. So you need to keep track if you already played the audio. So, a flag, timeoutAudioPlayed has been created to keep track of that. So, now, the 3rd audio will only play if:

The button is pressed
and is pressed for more than said time (BUTTON_LOW_TIME_MAX)
and if the audio hasn't been played.

void fire()
{
  static int buttonLowTime = 0; <-------------------
  static bool timeoutAudioPlayed = true; <---------

  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState)
  {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay)
  {
    if (reading != buttonState)
    {
      buttonState = reading;

      if (buttonState == HIGH)
      {
        mp3_play (1); //power down sound
      }

      if (buttonState == LOW)
      {
        mp3_play (2);  // fire sound
        buttonLowTime = millis(); <-----------
        timeoutAudioPlayed = false; <---------
      }
    }
  }

  // The logic for timeout audio <------------
  if((buttonState == LOW) && (millis() - buttonLowTime) > BUTTON_LOW_TIME_MAX && timeoutAudioPlayed == false)
  {
    mp3_play (3);
    timeoutAudioPlayed = true;
  }

  lastButtonState = reading;
}


Clear existing array when getting new serial command

To clear an array you would do:

for( int i = 0; i < sizeof(data);  ++i )
   data[i] = (char)0;

or

memset(data, 0, sizeof(data));

, which does the same thing using a library function.

However, because strings of characters (not referring to 'String' objects here) are terminated by a zero byte, only the first byte needs to be zeroed:

data[0] = (char)0;

will do it.


The issue lies with Wemos Module where it only outputs 3.3V which insufficient to 5V Relay so this can be solved by implementing 2N2222 Transistor as per schematic below.


How to encode resistance change (reed) for Arduino?

A reed switch is just a button. Treat it as such. Either connect it between a digital input and ground, with a pull-up resistor (internal one would do) or between a digital input and +5V and use a pull-down resistor.


A question about resistance measurement with arduino

If you know Ohm's Law (which you should) and you realise that the ADC measures voltage, you should be able to work it out from there. But I will go into minute detail for you to ensure you understand.

Ohm's Law defines the relationship between Voltage (V), Current (I) and Resistance (R).

R = V/I

To find one unknown value (in your case R) you need to know the other two values.  That is, the current flowing through the resistor, and the voltage dropped across the resistor.

We have no way of directly measuring current, but we can measure voltage using the ADC. So if we can somehow measure a voltage and use that to calculate the current then we have two of the three values and we can calculate the third. However, calculating the current requires that we know the resistance - and that is what we are wanting to find out.

So we need to then provide a known resistance that we can measure the voltage across, and thus find the current flowing through it. First a couple of reminders of basics:

Current flows the same through all resistances connected in series
The sum of all voltages dropped across resistors in series equals the total voltage across all the resistors.

So if we put two resistors in series and apply an fixed voltage across it (5V in our case) a single current will flow through them both. With that two voltages will be dropped across the resistors - and those two voltages will add up to 5V.

If we have one known resistor and one unknown resistor and we know the voltage dropped across both resistors then we can calculate the current that is flowing through the known resistor. And that current is the same current that is flowing through the unknown resistor. And since we know the voltage drop across that resistor we can then calculate its resistance using that voltage and the current we have just calculated.

Here's the circuit I just described:

Vin us 5V. Let's have R1 as, say, 10KΩ (a common enough value). R2 we don't know.

Using the ADC of the Arduino we measure a value of 681. First we convert that into a voltage:

Vout = 681 / 1024.0 * 5.0
     = 3.325V

So we know that R2 has 3.325V dropped across it, and since all the voltages must add up to 5V we know that R1 has (5 - 3.325) 1.675V dropped across it.

So the current (I=V/R) through R1 must be (1.675 / 10,000) 167.5µA (0.0001675A).

Now we can calculate the resistance of R2 since R=V/I and V is 3.325 and I is 0.0001675, so R must be 19850Ω - or pretty much 20KΩ.

That's the long-hand version from a current-based perspective. However there is a short-cut.

Since the output voltage is a simple ratio of the input voltage defined by the ratio between the resistors we can use that to create a much simpler formula.

From the example above the output voltage is two thirds the input voltage - and R2 is two thirds the total resistance (R1+R2). The two match perfectly.  So we can use a simple ratio calculation to give us the resistor.

For instance, the ratio formula:

Vout = R2 / (R1 + R2) * Vin

(that's R2 as a proportion of the total resistance multiplied by the input voltage)

When rearranged to get R2 gives us:

R2 = R1 * (1 / ((Vin / Vout) - 1))

So taking the voltage we measured above (3.325) and the known resistor (10,000Ω) and the input voltage (5V) and substituting those values into the formula, we get:

R2 = 10,000 * (1 / ((5 / 3.325) - 1))
   = 10,000 * (1 / (1.504) - 1)
   = 10,000 * (1 / 0.504)
   = 10,000 * 1.984
   = 19840

Or pretty much 20KΩ. (Note: the discrepancy in the results is purely due to rounding errors. Use higher precision values and you get better results).

You have to have a rough idea of the kind of order of magnitude of resistor you are trying to find, though, in order to select an R1 of a comparable value so that the voltage Vout is large enough to measure accurately.

Also you need to be aware that the input to the ADC has quite a (relatively) low impedance (can be very crudely thought of as a resistor between the input and ground) which is measured in the low mega-ohm range. This can have an impact on the values you read with the ADC if your resistors are too high, since this impedance will be in parallel to the resistor R2, so you'd actually be measuring the resistance of both R2 and the ADC's input in parallel. To measure very high resistances you should first buffer the ADC through a voltage follower with a very high (tens or hundreds of tera-ohms) impedance input.


Should I try to make my sketches as small as possible, even when I have enough room?

You second code may be smaller in size but due to the function call overhead the max execution speed is reduced.
Does this matter in your case? No, because you have huge delays anyway, but if the code was an actual series of repeated calculations that should be executed as fast as possible then it would make a difference.

As a general rule, smaller code is not necessarily faster too.

For code optimization (either size or speed) you can refer to this application note from Atmel AVR4027: Tips and Tricks to Optimize Your C Code for 8-bit AVR Microcontrollers

I could repeat everything it says here but I don't think there is a point, you can read the original article directly.

Regarding the compiler optimization level. Arduino IDE uses the avr-gcc compiler with a setting for Os optimization.
The avr-gcc available optimization levels are (source1 source2)

O0 or no -O option
At this optimization level GCC does not perform any optimization and compiles the source code in the most straightforward way possible. Each command in the source code is converted directly to the corresponding instructions in the executable file, without rearrangement. This is the best option to use when debugging a program and is the default if no optimization level option is specified.
O1 or -O
This level turns on the most common forms of optimization that do not require any speed-space tradeoffs. With this option the resulting executables should be smaller and faster than with -O0. The more expensive optimizations, such as instruction scheduling, are not used at this level. Compiling with the option -O1 can often take less time than compiling with -O0, due to the reduced amounts of data that need to be processed after simple optimizations.
O2
This option turns on further optimizations, in addition to those used by -O1. These additional optimizations include instruction scheduling. Only optimizations that do not require any speed-space tradeoffs are used, so the executable should not increase in size. The compiler will take longer to compile programs and require more memory than with -O1. This option is generally the best choice for deployment of a program, because it provides maximum optimization without increasing the executable size. It is the default optimization level for releases of GNU packages.
O3
This option turns on more expensive optimizations, such as function inlining, in addition to all the optimizations of the lower levels -O2 and -O1. The -O3 optimization level may increase the speed of the resulting executable, but can also increase its size. Under some circumstances where these optimizations are not favorable, this option might actually make a program slower.
Os
This option selects optimizations which reduce the size of an executable. The aim of this option is to produce the smallest possible executable, for systems constrained by memory or disk space. In some cases a smaller executable will also run faster, due to better cache usage.


Flash a hex file to an MCU/Arduino over the air?

Basically, this is much more involved than it might appear on the surface. If you haven't already, I would make sure that I was comfortable with finding things in the datasheet (and it's a really good datasheet, at that). If you're still up for it, read on.

Bootloader

The way a bootloader works on the ATmega328 is that the memory on the chip is self-modifying. This means you can have a piece of code on the chip that modifies memory on the rest of the chip. A bootloader is one such piece of code that runs when the chip first starts up, and checks to see if there's code to be loaded. If there is, it writes that code to the rest of the memory, and then executes it. See section 12.2 of the datasheet.

The way you would program an actual bootloader is described in detail in section 30 "BTLDR - Boot Loader support". I haven't programmed a bootloader before, so you're on your own here, but there are plenty of resources to guide you. In fact, the datasheet has example code in there for it.

(Note that you must program your chip normally at least once, to put the bootloader on it.)

One thing to note is that bootloaders should be small. You don't want bootloaders to take up a lot of your memory, since they only run once on boot and are really just a convenience feature. There are competitions for writing the smallest/most efficient bootloader, and you'll almost certainly want to write your bootloader in assembly. Notice that the only example code given in the datasheet is in assembly. Which brings me to my next point:

Bluetooth

Bluetooth is very annoying to program for. You have to set up different profiles, or do GATT stuff if your module is actually BLE/"Smart" instead of classic bluetooth, etc. However, I'm assuming from your post that you just have one of those serial modules you can find on eBay for dirt cheap. Before I go on, I want to make this very clear: It is non-trivial to set up. It will take up lots of precious code space on your microcontroller that you would want to use on your actual program. Remember how bootloaders are written in assembly? Writing a bluetooth interface in assembly will probably take a while.

As for how your bluetooth module works; it is basically a serial port, but over-the-air. This means the bluetooth interface that you write would need to bit-bang everything if you don't use the built-in USART (say you need those pins for your actual program), and if you do use the built-in USART, setting that up will take even more time. (For a guide on how to setup the USART, see section 24 of the aforementioned datasheet. See? It's really handy.)

Once you actually have bluetooth working, you can do whatever you want. Since you write the bootloader, you can read data from your bluetooth serial link however you fancy. As long as you know what you're sending, all you have to do is read it back accordingly.

Bonus: Flashing

You are correct that a .hex file is just a huge text file that you send to the chip. However, the way the ATmega is actually programmed is not simply using the serial port; instead, it's a slightly extended SPI protocol. (If you don't know what SPI is, you really shouldn't be doing this. If you're curious, Sparkfun has a nice tutorial on SPI.) This is called ICSP, or "in-circuit serial programming". The way to do this for AVRs is explained in an application note.

Of course, you cannot replicate this with just a bluetooth module. Instead, you would need a co-processor to program your chip for you, and read the data to-be-programmed from your bluetooth module.

TL;DR: This is probably not worth it. If you're planning on doing this, it will take significant resources, and you might even need a better chip to get anything done. You almost certainly should just buy an ESP8266 / ESP32 instead.


SKETCH quits working after unplugging from computer

I have ran into this problem personally. I believe that you are drawing too much power from your computer's USB port. A USB port can give 500 mA output max provides 5 Volts x 0.5 Amo = 2.5 Watts. With real world efficency losses (nominally 80~90% efficent), you can provide a Higher Voltage with Less Current, or a Lower Voltage with More Current, but you can't create powerout of nowhere.

See this post on a similar issue:
http://forum.arduino.cc/index.php?topic=289005.0

I hope this helps.


ESP8266: Interfacing MAX485 TTL-to-RS485 on serial port

You can't redefine pins on the ESP8266. You can, though, use SoftwareSerial to emulate a serial port. There's plenty of examples.
Also you need to use the MAX3485 on 3.3V devices. The MAX485 is for 5V devices.


DFRobot GPS init error [Arduino Uno, SIM808]

We had the same error in the code. But we managed to solve it! You have to insert the SIM CARD to work. We do not know why, but it works!


It is indeed commented out. SeeedStudio is a great company but their code (including code prettifying) is pretty sloppy, and sometimes a little dumbfounding.


Arduino Micro: 69 is supposed to show up when I press 1 on the keypad, however some weird number (15 in this case) is showing up

According to the documentation, the getKey() function is
non blocking. This means it does not wait for a key to be pressed:
it instead returns immediately whether a key has been pressed or not. If
no key has been pressed (i.e. most of the time), it returns a NUL
character, which has the numeric value zero and evaluates to false in
a boolean context. Hence the idiom:
char key = keypad.getKey();
if (key) {  // if a key has actually been pressed
    // handle it
}

The CountDownSequence() function fails to account for this:
void CountDownSequence() {
  char key = keypad.getKey();  // no check for NUL

  if (key == '0') {
    timeV = timeV + 0;  // this has no effect at all
  }

  if (key == '1') {
    timeV = 69;  // this is what you would expect to be executed
  }

  countDownDetect = false;  // these two lines tell the rest of the
  countDownOutput = true;   // program that we are done.
}

Since key will almost certainly be '\0', the program will move to
the next step without ever initializing timeV.
As a side note, I recommend you try to rewrite your program as a finite
state machine. A single state variable would make it less
confusing and easier to understand than the current collections of
booleans.

Edit: Expanding on the idea of the finite state machine. I tried an
implementation of your concept based on it.
For handling a menu system, where the user can navigate through several
on-screen “pages”, the most obvious first approach is to have one state
per page displayed. For this program, these states could be:

MENU, which offers the choice to move to either of the following two
pages
SET_COUNT allows the user to set the countdown duration
TWR allows him to compute the thrust/weight ratio
COUNT_DOWN actually runs the countdown timer

In the following, I added an extra transitional state called START
that comes right before MENU. This is not required, and its only
purpose is to avoid code repetition by having a single transition
(START → MENU) responsible for actually drawing the menu.
When implementing a finite state machine, my first recommendation would
be to start by drawing a state diagram like this:

In this diagram, each transition is labeled with the event that triggers
it. The events are key presses, save for “finished” which means that the
countdown is done. The state diagram can become significantly more
complex than this as you add new functionality. It is, however, a very
good way of designing your system from the point of view of user
interaction.
Once you are happy with the state diagram, the coding is just a matter
of translating it to a switch/case construct, with one case per
state. Here is my take at it:
/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 0.70
   An Open-Source Project by John Seong
*/

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

const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

Keypad keypad=Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

// Show a two-line message on the LCD.
void lcdShow(const char *line0, const char *line1) {
  lcd.clear();
  lcd.print(line0);
  lcd.setCursor(0, 1);
  lcd.print(line1);
}

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcdShow("Jeb's Launch", "Control System");
  delay(3000);
  lcdShow("Alpha Build 0.70", " STUDIO HORIZON");
  delay(3000);
  lcdShow("Welcome, Kerman", "Press any key...");
  while (!keypad.getKey()) ;  // wait for key press
}

void loop() {
  static enum {START, MENU, SET_COUNT, COUNT_DOWN, TWR} state = START;
  static uint32_t last_second;  // millis() value on last full second
  static int count;             // countdown value

  char key = keypad.getKey();

  switch (state) {
    case START:  // transitional state
      lcdShow("1. Countdown", "2. TWR");
      state = MENU;
      /* fallthrough */
    case MENU:
      if (key == '1') {  // Countdown
        lcdShow("Enter time", "seconds: ");
        count = 0;
        state = SET_COUNT;
      } else if (key == '2') {  // TWR
        lcdShow("Thrust:", "# to continue...");
        state = TWR;
      }
      break;
    case SET_COUNT:
      if (key >= '0' && key <= '9' && count <= 99) {
        lcd.print(key);
        count = 10 * count + (key - '0');
      } else if (key == '#') {
        lcdShow("Take off in", "     seconds");
        // Force a refresh on entering COUNT_DOWN:
        last_second = millis() - 1000;
        count++;
        state = COUNT_DOWN;
      } else if (key == '*') {
        state = START;
      }
      break;
    case COUNT_DOWN:
      if (millis() - last_second >= 1000) {
        last_second += 1000;
        count--;
        if (count == 0) {
          Serial.println("Take off!");
        } else if (count < 0) {
          state = START;
          break;
        }
        lcd.setCursor(1, 1);
        lcd.print(count<10 ? "  " : count<100 ? " " : "");  // pad
        lcd.print(count);
      } else if (key == '*') {
        state = START;
      }
      break;
    case TWR:
      if (key == '*' || key == '#') {
        state = START;
      }
      break;
  }
}

Note the comment “fallthrough” between START and MENU. This
indicates that the lack of break at this place is intended: the
processing of the MENU case will follow right after the processing of
the START case, in the same loop iteration. The purpose of the fall
through is to not loose the current key press, if any. If this is not
important, you could put a regular break here and defer the handling
of MENU to the next loop iteration.
Note also that the key presses are checked with tests of the form
if (key == SOME_VALUE), which means there is no need for an extra
if (key) to test whether there was an actual key press.


Initializing pointer to vector of objects inside another object

This is wrong:

Device device;

void setup()
{
   device = Device();
}

I don't know what your intentions are, but the first line instantiates device. You don't need to do anything in setup here. It sort-of looks like you are trying to call the constructor but that is called when the class instance is created (in the first line).

Preset* Presets[];

What's this? A pointer to an array of zero length?

    *Presets = (Preset*)malloc(sizeof(Preset) * NumPresets);

Now you are allocating memory for a pointer to the array to be big enough to hold the contents of the array.

for (int p = 0; p < NumPresets; p++)
{
    Presets[p] = new Preset("test", NumPixels, NumPatterns);
}

Now you are allocating memory for the contents of the array again.

There is too much dereferencing going on here. Please post a Minimal, Complete, and Verifiable example. For example, make the classes in question do not much. Then make code we can actually work on.

  I realize the first call is to the default constructor, but in the setup i do the real construction ...

Well, you can't call the constructor twice. What is commonly done is to do nothing (or almost nothing) in the constructor, and then make a begin function which you call in setup. This function can then do whatever is required at the proper time.


How to choose between Lithium-ion vs NiMH batteries to power Arduino on the go.

Look at Battery University for many good ideas.

Both NimH and LiIon are viable for your application.

LiIon are easier to manage well if managed well.
ie do it right and they are easy to manage, but cut corners and they are easier to destroy.

NimH can be abused more with a slow degradation in capacity - although complete destruction is possible.

As a LiIOn cell has a ~= 3.0V to 4.2V range you'd probably probably need a step up inverter with 1 cell, or a buck regulator with 2 cells, which is 'annoying'. If you are prepared to use the cell over say a 3.4V to 4.2V range with an LDO regulator for a 3.3V system then you lose a significant amount of available capacity but increase battery cycle life substantially.

Nimh give 1.0 - 1.2 V/cell so eg

6 cells give 6 - 7.2V for a 5V system,
5 cells give say 5.25V - 7V if run down to 1.05V for a 5V system with a suitable LDO regulator, and
4 cells give 4 - 4.8V for a 3V3 system.

NimH are easier overall to build half well and get half good results.

LiIon are slightly harder to get going with in most cases, work very well if treated well, and are VERY unforgiving of bad treatment past a certain point.


The analog pins function as digital pins number 14 - 19, with 14 being A0 and 19 being A5. I had hooked it up backwards.

This time we're gonna get funky
Everybody check your pins
Check check check check your pins
Check check check check your pins


Reading values from TTP229 capacitive touch sensor on arduino

mpr121 gives raw values
it has 12 electrodes/capacitance sensing inputs

https://www.sparkfun.com/datasheets/Components/MPR121.pdf
https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/DataStream


Transfer serial data to struct variable in Arduino

You read the serial port one char at time, and assign it to test1.pt[i], where i is an index varying from 0 to 15.

And test1 cannot be const, because you are going to modify it with the serial data.

Here is a test code showing how to do it.

struct testing_var
{
    const char *name;
    byte key[32];
    byte pt[16];
};

//  test1 cannot be 'const'
static testing_var test1 = {
    .name        = "Speck-128-ECB",
    .key         = {0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00},
    .pt   = {0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20},
};

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

void loop() {
  Serial.println("Enter 16 chars:");
  //  Read 16 chars from Serial
  for (int i=0; i < 16;) {
    if (Serial.available()) {
      test1.pt[i++] = Serial.read();
    }
  }
  // Do something with the data, like print it.
  for (int i = 0; i < 16; i++) {
    Serial.print(char((test1.pt[i])));
  }
  Serial.println();
}


Why do I have to open Serial Monitor to display what is in loop function?

Hard to tell from your fritzing which actual ESP8266 pin you are using, but you require a pull up resistor on the data line of the DHT22.

My guess is that you are using one of the serial UART pins for the data connection, and opening the serial monitor activates the output of the onboard UART chip which then acts as your missing pullup resistor.


Issues programming Arduino Uno with Sparkfun's MAX3232 breakout board

Switching the power off to the MAX3232 appears to be okay.
There are no components connected to the Rx and Tx lines on the breakout board to complicate it.

Unfortunately the break out does not give access to pin 1, EN which is "Enable Control", or pin 18 SHDN "Shutdown Control". AFAICT they could have been used to turn off the receiver and transmitters of the MAX3232. That would have been ideal. Maybe contact Sparkfun and suggest the improvement to put them on pads for folks to use, and offer to beta test it :-)

The datasheet for the MAX3232 says that it is able to withstand a continuous short on the Tx line, so it sounds pretty tolerant to minor abuse. Also, the diagrams dont show any pull-ups on the MOS/TTL Tx line. So I would expect it t be okay if you shut the power off, but continued to wiggle the Tx Rx pins.

An alternative would be to disconnect the Tx pin from the Arduino, so that the MAX3232 wouldn't interfere with the host PC's USB comms. It sounds like the thing on the RS232 connection will ignore data it receive while the Arduino is being programmed. If that is not true, then it would need to be disconnected too.

At the moment, switching off power looks like a reasonable approach.
Disconnecting Tx and Rx also looks reasonable, and slightly better than powering the MAX3232 off.

Do you know how you want to do that?

NB: The MAX232 datasheet shows that part should not be driven by a high when the chip is unpowered. However the MAX3232 datasheet does not carry that warning. My preference would be to use the MAX3232 signals 'EN' and 'SHDN'. However those are not available on the breakout. I'd recommend having the part powered, and disconnecting Tx and Rx from the Arduino.


Arduino Nano -- cannot download, no /dev/tty*** device

This is probably a duplicate question and duplicate answer, but ...

Flip the board over, look at the bottom. If it says "FTDI" then this answer doesn't apply. But many cheap clones have moved to the CH340G chip for USB serial communication, it's a tenth of the cost with a tenth of the (unused) features.

You can find CH340/341 drivers from the manufacturer at WCH.CN or linked at the bottom of this post.

Or, skip the USB altogether and search for "ISP" on Tindie and grab a USBASP or TinyISP programmer.


What is the fastest and easiest way to transmit arduino's sensor data to a PC wirelessly

The fastest way would be to use a laser link!! Yeah lasers. You could go with wifi or some other custom wireless but lasers will guarantee the highest energy density and therefor best bandwidth.  This guy claims near 10 MB/s with his setup:

http://www.instructables.com/id/Laser-Transceiver/


Extract binary numbers from infrared sensor that uses I2C bus

There are likley two problems:

An invalid device address is used. The device address is 0x10 and the Arduino Wire library expects it that way (and not in the shifted version with read/write bit).
Your code uses two separate transactions, however the datasheet specifies a single transaction with a repeated START condition for separating the write and read part.

So an improved version looks like so:

#define DEVICE_ADDRESS 0x10

void loop() {
    Wire.beginTransmission(DEVICE_ADDRESS);
    Wire.write(0x80);  // readout command
    Wire.endTransmission(false); // stop sending without ending transaction (repeated START)
    Wire.requestFrom(DEVICE_ADDRESS, 6); // request 6 bytes
    uint8_t data[6];
    for (int i = 0; i < 6; i++) {
        data[i] = Wire.read();
    }
}


What is the potentiometer doing here? Why is it necessary?

It's there to control the "offset voltage" of the LCD, which is what controls the contrast of the display.

My lcd screen doesn't show anything. Does anyone knows why??

Maybe you wired it wrong. Maybe you didn't put the potentiometer in the circuit because you didn't understand what it is for. Maybe you just need to adjust the contrast by turning said potentiometer. It's hard for us to tell. By showing us what you intended to build and then telling us that what you actually built doesn't work, there is nothing we can tell you. There must be some difference between what you intended to build and what you did build, but we can't see what you built, so we can't have any clue.


Have heard of similar problems with Mac. Not a Mac user myself. Sometimes the Arduino can somehow trigger a current fault in the USB of Mac's and will need to be shut down and rebooted for it to work again.

Try rebooting your Mac.

If you have a cheap chinese Arduino you might need other drivers for it. Check what chip you have closest to the usb connector.


ESP8266 stops working when I use 2x static const char(PROGMEM)

See Guide to PROGMEM on ESP8266 and Arduino IDE.

Since you put your char array into PROGMEM, special functions must be used to load it from flash into RAM; so to load it into a String object, the FlashHelper class must be used. You can simply use the macro FPSTR(progmem_ptr).

#include <Arduino.h>

void setup() {
    Serial.begin(115200);
    Serial.println("\nStart firmware");

    static const char HTML1[] PROGMEM = R"=====(
    <!DOCTYPE HTML><html><head>
    <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
    )=====";

    static const char HTML2[] PROGMEM = R"=====(
    <button type='button' onclick='sendData(2)'>Test2</button>
    )=====";

    String html_return = HTML1;
    html_return += "<button type='button' onclick='sendData(1)'>Test</button>";
    Serial.println("Before Second Const Char");
    //html_return += HTML2; //crashes
    html_return += FPSTR(HTML2); //works
    Serial.println("Result");
    Serial.println(html_return);
}

void loop() {

}

Outputs

Start firmware
Before Second Const Char
Result

        <!DOCTYPE HTML><html><head>
        <meta charset='utf-8' name='viewport' content='width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0'>
        <button type='button' onclick='sendData(1)'>Test</button>
        <button type='button' onclick='sendData(2)'>Test2</button>


How to use multiple SPI slaves in MKR1000 if it doesn't have Slave Select (SS/CS) pin?

The Arduino doesn't care what pin you use for SS since you just use digitalWrite() on it anyway. You use any pin you like for one slave, so you can use any other pin you like for another slave.

The ATMega-based boards need pin 10 to be set as an output for SPI to function, but you don't then have to use that for the actual slave select. The only time it becomes a real slave-select pin is when using the Arduino itself as a slave.


No.  Your link is to an analog NTSC camera.   Digitally handling data from this would require a high speed analog to digital converter and some fairly sophisticated cleanup logic.

It is simply not compatible to use this with a small embedded system.

If you really want a camera for a resource constrained embedded system, seek a still camera with a serial or SPI output.

Most video tasks will however be better done on more capable embedded systems falling outside the realm of Arduino-style approaches, and therefore soundly off-topic here.


Unable to connect and configure ESP8266 wifi module with Ardunio Mega

Your ESP8266 module is most likely fried now, if your wiring diagram is any indication of your actual hardware setup.

The ESP operates at 3.3V, which means that every pin on it can receive no more than 3.3V as input. And it looks like you've directly connected the ESP's TX pin with the Arduino, without using a level shifter. The Arduino GPIO pins work on 5V logic levels.

Test this module out with a level shifter (resistor divider network, 3.3V zener, level shifter IC; pick your poison). If the ESP still doesn't respond, swap it out with a new one and repeat.


Is it okay to short IN and GND pins of relay module with controller ground?

It is not okay. The base-emitter of an NPN transistor acts as a diode. That means pin D1 is shorted to GND via a "diode". You need a resistor to the base of the transistor.

The relay module has already a transistor to drive the relay and also a flyback diode. The control signal that is needed depends on the relay module. The explanation "5VDC to 12VDC (some boards may work with 3.3)" on the page of the relay does not sound reliable.
The relay module on that page is not the module that you have. You have a different module that is activated with a low signal.
Nevertheless, I think that a transistor can be used when the IN and GND of the relay module are connected to the collector of the transistor.

Could you please not try to make the schematic as small as possible. A schematic should explain how everything is connected.

Could try to connect the collector only the IN pin? As in the schematic below.

In your circuit diagram, the mains "neutral" is connected to an earth ground symbol. I hope you are not going to connect a mains wire to ground.

When the IN and GND are connected, then the resistor to the transistor needs to be lower. The ESP8266 can output 12 mA. Let's use 10 mA for safety: (3.3V - 0.5V)/10mA = 280 Ω. I suggest using a resistor of 330 Ω or more.


There is a fundamental difference between a simple function and a function that is a member of a class.  You can't use a function pointer to point to a member function of a class: simply because that member function also includes information about the class instance that it belongs to.
The proper C++ way to handle it is to use std::function, but the Arduino AVR compiler lacks the full STL (Standard Template Library), so that can't be used on normal Arduinos. Other cores do have it, so you may well be able to use it on the ESP8266.
If you want to make your code portable between systems that may not have the full STL then there's other tricks you have to do:

Use a wrapper function (which as you have found works), or
Make a polymorphic class and store a pointer to the instance cast to the parent class - the parent class defines the functions that are allowed to be called from the pointer.


Humidity values returned by DHT22 sensors failing after some time

This is how it looks when they fail.

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

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

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

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

Link:

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


Where is the documentation for the Emoro GLAM pro module?

What you are searching can be found via googling, if you know, what to google for. I write a formal answer to this, because there is neither a link on the product page of the manufacturer, nor is it very easy to find for a beginner.

Have you seen this repository emoro-2560-library on github? It seems to incorporate libraries for nearly ever function of the Emoro, including the bluetooth functionality of the GLAM board. You can find examples in the GLAM examples folder.

How did I found it? I googled for "emoro github". A better search phrase would be "emoro 2560 github" (Since Emoro 2560 is somewhat the extended name of the robot). I used the term "github", since most libraries for Arduinos and their derivates/variants are hosted on github. If you are search for a library, you can first search for them on github. Most times you will find something. Often these libraries also serve as a kind of documentation (as real and good documentation can be rare to find).

Now somewhat unneeded, but from the library code and the pictures on the product page of the GLAM module, I think, that a serial bluetooth module with AT firmware like HC-05 is used. If you ever want to look past the bluetooth library for the robot, you would need to go that way. (How a Hc-05 is controlled can also be googled)


How to connect LED lights for 3D Printed Robot

The key point for WS2812B LEDs is, that they can be daisy chained. This means, that everyone of them has one data input and 1 data output. If you connect the data output of one LED to the data input of the other, you created a short strip with 2 LEDs. Doing this multiple times creates a bigger LED strip. It's not relevant, if the LEDs are arranged into a physical strip, or arranged into complex forms. The LEDs are addressed by their position in the strip. The microcontroller sends a data stream to the first LED. It will read the first 3 bytes (1 byte per color) and forward the rest of the stream to it's data output, so to the next LED.

So you can wire all the LEDs on your robot in a way, that you basically only have 1 LED strip. In this case you only need 1 pin on your Arduino (plus Vcc and ground of course).

Or, if it's to cumbersome to wire all LEDs together, you can make multiple strips, divided by zones on your robot (like 1 strip for the face, 1 strip for the chest, ...). Every strip will need it's own pin on the Arduino.

Which way you go is your decision and also depends on how many pins you have free.

  My question is, is it possible to connect all the LEDs i plan to use on one microcontroller (ie: Ardruino Uno or Nano)

Yes, one microcontroller is plenty enough for this. As I wrote, for 1 strip you only need 1 data pin.

  Most of the examples I can see on youtube are projects using LED strips. Are they diffrences in the way they are connected?

This depends on what strips they have. If they use WS2812B strips, it is all the same. As said, the physical arrangement of the LEDs doesn't matter. But there are also other types of strips, for example the not-individually-addressable-single-color types, or the not-individually-addressable-RGB types (which often have one PWM line per color).

  Another problem is coding for the ardruino..i'm totally clueless.

Have a look at the Adafruit Neopixel library or the FastLED library (both on github). They are libraries, that will hide most of the complexity from you and will make it easy to control the LEDs. They both have examples, that you can use to get started. Adafruit also has good tutorials for this. You can google them.

  For the power source, I was thinking about using a small powerbank or 2x 18650 batteries as the power source.

I don't know, how much current these batteries can give you. I will leave that to you for your research. But be sure, that you can always provide the needed current. One WS2812B LED can draw up to 60mA (20mA per color), if you set them to full brightness white. So 40 WS2812B LEDs, can draw up to 2.4A. I guess, that your robot also has motors, which can also draw a big amount of current. So keep the total current draw in mind and don't ever try to draw this current through the Arduino (since this might fry the voltage regulator).


Arduino - Getting error - 'TCCR2' was not declared in this scope

Looks like this code is pretty old. It's assuming that any Arduino that isn't using an ATmega168 is using an ATmega8. In reality, the ATmega8 hasn't been used on any Arduino boards in the last ten years or so -- it's pretty much obsolete.

The easiest fix will be to remove the non-'168 branch (between #else and #endif), and make the '168 branch default (remove the #if line). This will probably still fail on ATmega32U4 boards, but at least it'll now work on ATmega328 hardware.


while (digitalRead(bt_Select)==HIGH||digitalRead(bt_Reject)==HIGH){}
should be
while (digitalRead(bt_Select)==HIGH&&digitalRead(bt_Reject)==HIGH){}
The first loop would break only if you press both buttons at once. I believe you are trying to break if either button is pressed.


why am I losing data over serial communication between arduino and pc

Are you hand-typing the commands? It is pretty difficult to do that consistently. I ask because your code collects data from the serial buffer until the buffer is empty - i.e. when you pause even slightly in your typing - and tries to act on whatever it has collected so far. That may be (probably will be!) an incomplete command. Even if your terminal uses line-by-line entry, there is still the risk that your code could notice an empty buffer between characters within a line.

Try collecting characters until it sees a newline, instead. That is probably what you intended, and it will be immune to your typing speed. You'll still need to test for .available, but that should only allow the code to collect more characters. Keep collecting until it sees a newline.

What (I think) is happening now is called a race-condition. That means that the program's behavior is dependent on which of two (or more) events happens first, and the order of their occurrence is indeterminate. Race conditions are especially hard to find when the order of two events is almost always the one you expected. Notice the "gotcha" word in that sentence? :)


It's not related to the delayMicro, but to the max speed of the Serial/UART driver, which is not documented, but according to some people it can reach 500 kbps.

However, 10 bytes, each 500 us (2000 Hz) means 10 * 11 (including some stop/start bit) * 2000 = 220.000 bits, so you have some headroom left. Maybe there is also some timing overhead.

Anyway, probably the only way to go is using an interrupt, and expect the Uno is not able to do anything else.

A better option might be to send less or send smarter (i.e. not 10 bytes, but maybe some compressed/binary form if not already thought about).


Xbee shield to shield connection sends but not receives correctly

The xbee pins can only read up about 1.2V which it will show 256 bit. You should check how much the photoresistor is giving out because it might gives something that is more than the xbee pin can handle.


Arduino with ATmega32U4 low power but keep Serial1 working

For Power Down/Standby Mode you would have to use an Interrupt Pin to reactive the MCU. If you do not mind possible loss of the first character you could connect an Interrupt Pin to Serial1 RX and wake up on the first start bit.

The startup delay (i.e. time until UART is up and working) may impact the first character received. You could always start off by sending a number of null character as a "wake up call"; classical break sequence.

Cheers!

Ref. ATmega16/32U4, Chap. 7. Power Management and Sleep Modes.


Communication over I2C protocol with more than one A/D device

Yes, you need different devices for different addresses. Up to 8 addresses are possible:

  The first part
  of the control byte consists of a 4-bit device code, which
  is set to 1001 for the MCP3021. The device code is fol-
  lowed by three address bits: A2, A1 and A0. The default
  address bits are 101 (contact the Microchip factory for
  additional address bit options).The address bits allow
  up to eight MCP3021 devices on the same bus and are
  used to determine which device is accessed

The number after the A in the part number indicates the address:

Off the shelf you get address 5. If you want other addresses you have to order them specially from Microchip.

The device sacrifices flexibility in favour of size. If you want multiple devices on the same bus and not have to order different parts specially then you generally end up with a bigger chip with more pins to allow you to manually configure the sub-address.


Passing a time_t array as a function parameter

When you pass an array to a function it "collapses" the array into just a pointer. All the receiving function knows is the type of the contents of the array (time_t) and where it starts in memory - it knows nothing about the size of the array.
The sizeof() call just gives you the size of that pointer, not the size of the memory it points to.
sizeof() is not actually a function, it's a compile-time construct. It can't know anything about runtime values, only what is there at compile time.
Instead you must pass the length of the array with the array as a separate parameter, which can only be calculated in the same scope as where the array is defined, and then only by using the original name of the array.  It is typical to create a macro to do this for you at the time you make the array:
time_t conLog[logSize];
#define CONLOG_SIZE (sizeof(conLog) / sizeof(conLog[0]))

Then pass that to your function:
initLog(conLog, CONLOG_SIZE);

Alternatively, since you already have the size in a constant in this case, you could just use that:
initLog(conLog, logSize);


How to get a character from a serial Parsed http response?

You can send json format instead of pipes enclosed and parse the value. Else use regex expression to match ||0|| or ||1|| .


Serial.println(static_cast<char>(RSV_Resp_test[1]));

works.  I still don't understand why the reinterpret_cast errors out.


Can anyone help be get readings off of my potentiometer with a push of a button?

I had a very similar issue an it is that you aren't setting up your button as an INPUT_PULLUP. When you press the button, you are sending 5V or ground through it depending on your circuit. But then it won't reset on release. That is why either you can put a physical resistor as the schematic shows here:

or you can simply change the button initialization to INPUT_PULLUP.


Using an IR sensor from another manufacturer

Yes, you will need to connect the sensor ADC line to an ADC input on the Arduino and calculate the range from the analogread result.  You should be able to use one of the Sharp sensor libraries, although you may need to apply a correction factor to the distance results.


Where does arduino IDE store the latest board selection?

It is stored in preferences.txt in your Arduino data folder.

You can find more about that file, including where to find it, here.

Some of the keys you may be interested in are:

board=uno
serial.port=COM3
serial.debug_rate=115200

However maybe for your workflow the Arduino IDE isn't the best tool for the job.  You may consider arduino-builder, which is the back-end that the Arduino IDE uses to do the actual compiling, or maybe another IDE entirely, such as PlatformIO or UECIDE.


A divider is used to (as the name suggests) reduce a higher voltage to a lower voltage.  Using a divider on a small voltage will only make it smaller and harder to measure.

To get the most out of your measuring you need to have the reference voltage as close to the highest voltage you want to measure as possible.  The highest voltage that can be applied is not dependent on the reference voltage, but the supply voltage, and as 1.2V is way less than 5V (or 3.3V on a 3.3V board) you have no worries there.

So you need to change the reference voltage - the voltage that the ADC uses as its upper measurement voltage.  That's simple enough, since many of the Arduino boards include an internal 1.1V analog reference voltage generator that you can switch to (see: analogReference())

So when you have switched to the 1.1V analog reference the ADC is capable of measuring 0-1.1V in 1024 steps.  That's 1.1/1023=0.00107V per bit of precision.

The formula is:

V = ADC / 1023 * Vref

So a reading of 1 would give you 0.00107V - a reading of 2 would be 0.00215V, etc.  That's plenty of resolution to meet your 2 decimal places requirement.

One thing to note though is that the internal 1.1V reference isn't that stable or accurate (or not even there on some chips).  If you need better stability and accuracy then it could pay to use an external voltage reference chip.  These are like a linear voltage regulator but are far more accurate and stable (and can't provide lots of current).  Pick one that is greater than your upper measurement voltage but as close to it as you can get (so just above 0.8V) and feed the output into the external ARef pin and switch the analog reference to the EXTERNAL mode.

You could use a voltage divider on the external ARef pin to provide a low reference voltage, but the stability and accuracy will be no better (and probably worse) than the internal 1.1V voltage reference, so there really is no point.


In my case when I try to connect to my router, I get the following output:
AT+CWJAP="myssid","mypassword"
WIFI CONNECTED
+CWJAP:1

FAIL
WIFI DISCONNECT

The reason is that the ESP8266 I have is setup with DHCP disabled by default. To enable it you can try the following:
AT+CWDHCP=1,1

If that works, you will get this message:
OK
WIFI GOT IP


Would a non-blocking timer solution work?

Yes.  Your "timer" doesn't have to be anything more than a start time from millis() and a flag.  Then your loop just compares the start time to the current millis() value, and if it's more than the interval you wanted, do the "thing".  In code:

uint32_t startTime;
bool waiting = false;
const uint32_t PUMP_DURATION = 30000UL;

void setup()
{
  // start the "timer"
  startTime = millis();
  waiting = true;
}

void loop()
{
  if (waiting && (millis() - startTime >= PUMP_DURATION)) {
    waiting = false;
    // do something now!
    foo();
  }

The flag keeps it from checking when the pump isn't running.

If you have multiple timed things, just make another set of variables (i.e., startTime2 and waiting2).  Give 'em better names, eh?

There are also Arduino libraries that encapsulate this common design pattern.  TimeMark is one.

Here's some sample code on the Arduino forum.


The Bootlader
If you want to burn the bootloader to the standalone AVR that you will be using, you can do so using a programmer like the USBasp. Or, you can simply use the Arduino  itself to do this.

Open the ArduinoISP sketch from File > Examples.
Upload it.
Push reset on the Arduino.

Wire it up
Next, wire up the AVR on a breadboard as shown here: Arduino ISP

If you are using a variant/derivative, use a crystal that matches the crystal on your board. You might have not_in_sync() trouble if you don't.
Add a 10uF capacitor between RESET and GROUND on the Arduino, if you are using Uno, or something similar.

Burning the Bootloader
Then select Arduino as ISP as the programmer.

Goto Tools > Programmer.
Select Arduino as ISP.

Now click on Tools > Burn Bootloader.
Verifying it all works
Once that is done, open the Blink LED example and try uploading it to the AVR. You have to use the Upload using Programmer option from File > Upload using Programmer. You can verify if it is successful, by connecting an LED to pin 19 of the AVR, and checking if it blinks.
Notes:

Remember that the pins on an AVR don't map to the corresponding pins on the Arduino, even if they are both the same chips. Search for "AVR to Arduino pin mapping" for your chip on Google. Here's the ATMega8 to Arduino pin mapping.

Don't forget to connect the ground lines of the AVR and the Arduino.

This worked for me using an ATMega8A-PU. It should work with the 8L too.

Post here if you have any problems. Glad to help :)


Possible to drive Waveshare E-ink without driver hat?

No, you need the hat, or something equivalent. Turn it over. You see all those components? They exist to generate the right voltages for the ePaper display. Without those it won't work.
Sure, you can recreate it from the schematic, but why bother when you have it already?


I agree with Majenko's proposal for a proto shield, or if you need a "flat" design beside the Mega get yourself a striped (one /two sided and in different sizes) vero board (its like a breadboard to solder)

You could even use Fritzing to design the most efficient layout for this option in regards to space/material saving or minimum solder points


The ATmega1284P provides 128kB of flash, 16kB of SRAM, 4kB of EEPROM, and 2 USARTs in a 40/44/49-pin package. Mighty 1284P provides Arduino support for the '1284P.

There aren't too many actual boards that feature it, but it can be used very easily on a breadboard or custom PCB with a programmer.


How to declare a global variable in the .h file?

.h file is included by the compilation preprocessor as text into the .c or .cpp file. It is included as if you would replace the #include preprocessor instruction with the content of the .h file. (The Arduino .ino file is converted to cpp file before preprocessing.)

After the inclusion the cpp file is compiled to 'object' (.o file). If the cpp file contains a variable definition the variable is defined in this object file. If your .h file contained a variable definition, the it is also in this object file.

If two cpp files included the .h file with the definition of the variable, then the variable will be in two object files and the linker will exit with an error, because of two variables with the same name.
If only one cpp/ino files includes the variable definition, then it is OK. It is not a good practice, but sometimes a necessary compromise. (example of it)

To have one global variable made accessible by a .h file, the variable should be only declared in the .h file and be defined in one cpp file. Usually it is a pair of .h and .cpp file with same name.

An example of global variable is Serial. It is a global object of type HardwareSerial declared in HardwareSerial.h as

extern HardwareSerial Serial;

and defined in HardwareSerial0.cpp as

HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);

Do you see the difference? The declaration has the keyword extern and the definition has in this case parameters for the constructor of the object. The declaration with extern keyword makes object Serial visible in all cpp files which include HardwareSerial.h (or an include file which includes HardwareSerial.h like Arduino.h included by ino to cpp conversion).


You first need to make a communication between both Arduinos and then you can control RGB led from any Arduino.

For the connection between both the Arduinos, you can make a serial port interface for doing this, you just need softwareserial.h library. Then you just need to connect the RGB LED to one Arduino. Then when you send a command from another Arduino to that one, the Arduino (Connected to RGB LED) can operate the LED according to the command.


The VCC lines aren't directly connected - you just have a shared data line with some voltage on it, which is always lower than VCC because of the resistor. Each device "talks" to the I2C bus by briefly connecting those lines to GND, which is common between both devices. Current is limited by the pull-up resistor, so it never gets too high. This makes it safe to directly link devices running at slightly different voltages.


You need:

SD card + reader
GPS module
Air sensor
WIFI ESP 8266 should be ok
Arduino Uno or Mega, depending on if everything fits and calculations to be performed

Start with finding each component, read examples how to use them, than combine them.

Looks like a big project to start with if you are new to Arduino.


Extremely unstable analogRead() on Arduino Nano when powered from an external source

You can use a branded 5 V charger made for cars. You can directly connect this to 5 V pin of the Arduino.
By doing this:

you are protecting the Arduino from the noise as well as high voltage spikes coming from the car 12 V supply
protecting yourself and others coming in contact with the Arduino or the sensors connected to the Arduino.

You can also

consider filtering the analog data read
protection circuits such as surge protection diodes or a 5.7 V Zener across 5 V and Ground of Arduino


Using SoftwareSerial for the serial monitor

Short answer: no.

Pins 0 and 1 an an Uno are directly wired to the PC communication chip. You could make a board that was wired differently and connected SoftwareSerial to the PC, but you would have to switch it back to pins 0 and 1 when uploading to the arduino somehow.

On an arduino leonardo "Serial" for communicating with PC over USB is different from "Serial1", which is connected to pins 0 and 1 on the board. You can use both simultaneously, so if you really need to use hardware serial and PC comms at the same time, I recommend you buy a leonardo.


It seems that the 2 rows and columns have not been connected correctly.

In the diagram or with the example program you can find out to which pins these
should be connected and check if the wiring is ok (and the wires itself).

You can also switch two wires around to see if it makes a difference.

Note that some Chinese LED matrices might use different pins (and do not have a data sheet).


How to connect Big Dome Button with arduino

As others have said, the 12V powers the switch's internal LED.

EDIT:
Switches don't need power. If you skip all power to the switch it will still work but it won't light up.
End of edit:

If you want the switch to light up, connect the V in to 12V, or if you connect it to 5V, it will be dim, but -probably- still light. (You are certain to have a 5V pin on your Arduino board. Using that means you don't need a separate 5V supply.)
Now connect one lead of the switch to a digital input, and the other lead to ground.
Then set your switch pin to INPUT_PULLUP mode. Now your switch will read HIGH until it's pressed, then it will read LOW.
create a variable at the top of your code called buttonState:
byte buttonState = HIGH;

Also define an unsigned long variable nextReadMillis:
unsigned long nextReadMillis = 0;

and a pressCount variable:
unsigned int pressCount = 0;

And define a debounceTime:
#define debounceTime 50

In your loop, do something like this:
void loop() {
    //Get the new millis(value)
    unsigned long newMillis = millis();

    //only look at the new button value if enough time has elapsed.
    if (newMillis >= nextReadMillis) {
       byte newButtonState = digitalRead(buttonPin);

       //Only do something if the button state has changed
       if (buttonState != newButtonState) {
          buttonState = newButtonState;
          nextReadMillis = newMillis + debounceTime;
          //If the button is now in the pressed (LOW) state, increment the count
          if (buttonState == LOW) {
              pressCount++;
          }
       }
    }
}

That's pseudo-code. It likely has syntax errors. It's not meant to be copy/pasted. Use it as a guide for your project.
The code using millis() is a version of "software debouncing." Electrical switches tend to "jitter" or "bounce" between their on and off states very rapidly when they are first pressed/released. By only checking for state changes after a brief delay, you ignore the jitter in the readings.
Note that if you want your LED to only light when the button is pressed, you could control it with another digital pin. You'd assign a different pin to controlling the LED output, set that pin to OUTPUT mode, and switch the pin based on button state inside the body of the if (buttonState != newButtonState) if statement.
If your LED draws ≤20mA at 5V, you could connect it directly to your output pin. If it draws more than that, you will need a transistor to drive it so you don't draw too much current from your output pin and burn it out. Wiring a transistor driver is beyond the scope of this post however.


Arduino RBBB - Device not accepting address

I fixed it. Here is how I did it.

First, I tried connecting just the BUB II to via the USB. Same error, thus I ruled out the Arduino RBBB as the source. I then decided that perhaps it was the voltage jumpers (black things on the pins sticking out in the first picture). After removing them, it works under dmesg, yielding the below.

[  214.044563] ftdi_sio 3-1:1.0: FTDI USB Serial Device converter detected
[  214.044687] usb 3-1: Detected FT232RL
[  214.044696] usb 3-1: Number of endpoints 2
[  214.044704] usb 3-1: Endpoint 1 MaxPacketSize 64
[  214.044712] usb 3-1: Endpoint 2 MaxPacketSize 64
[  214.044718] usb 3-1: Setting MaxPacketSize 64
[  214.045209] usb 3-1: FTDI USB Serial Device converter now attached to ttyUSB0

Thus I wanted to put them back on so I wouldn't lose them. I proceeded to try various combinations till it worked. Ultimately, I ended with 5V for VOUT and VL for LGLV. If that is a bad idea, someone please comment, but it works.

May this help someone else.


Arduino and WS2812 RGB LED Strip "freezing"

Try changing rgbIndex++; to rgbIndex=(rgbIndex+1)%numRGBleds;. I thing the problem is the int rgbIndex rollover, which occurs after about 9 hours.

Also try changing delay(1000) to delay(1). That way the problem might pop up a lot faster.


HID multiCLASS RFID reader all Mifare to Wiegand 32bit

For this specific reader, communication is only one way, from the reader to the Arduino via Weigand protocol.  Because of this, changes to the configuration for these readers is handled by proprietary RFID cards obtained from HID Global. The reader reads the card, and changes its configuration accordingly.  I was able to reach out to HID Global technical support and they are sending me a card that will change the configuration to output 56bit CSN/CSR/UID for mifare cards (which will cover the 7byte UID of mifare ultra).

Thanks for the comments that helped me work this through.


Today I measured again without the development board. Just the CPU, same setup otherwise (original code, using the FTDI cable as power source) and I got a reading of about 6-8µA. I guess that answers it! Thanks everyone for your help!


Floating pins: digitalRead returns always high or always low

Floating means it would generate any value. This could be a result of innumerable factors and it is HIGH in this case! you cannot expect anything other than a HIGH or LOW.

Think of it this way-
It's fluctuating in a range of about 900-1000 but the range is still very close to 1023 hence it results in a HIGH.

Some other time it may be near the lower values then it would show LOW.


Issues while making ESP8266 as web server

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

Do the same with RST.


ESP32 saving data to SD card in .csv doesnt format correctly

In Arduino SD library FILE_WRITE constant instructs the function to open the file for append, but in the esp32 SD library it opens the file for rewrite. Use FILE_APPEND to open the file for append.

File file = SD.open(path, FILE_APPEND);


Help managing the fallout from timer0 mode and prescaler change on ATMega2560 without modifying wiring.c

The millis() roll over

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

The overflow in delayMicroseconds()

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

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

48188 × 4 − 5 = 61675 (modulo 216)

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

The cycles burned by the Timer 0 ISR

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

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

Use another timer for millis()

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

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

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

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

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

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

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

    // Disable Timer 0 interrupts.
    TIMSK0 = 0;

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

    pinMode(LED_BUILTIN, OUTPUT);
}

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

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

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


Arduino Uno R3, WS2812B, 1 strip of 60 leds, segmented in to 4

The used library doesn't give you the direct possibility to automate the segment changes. So you need to write that code yourself.
Currently you are setting up all segment in setup() and starting them together via start(). Instead you should add the corresponding segment only, when it should be on, and removing all segments, that should not run. In the following I don't remove and add a segment, but I'm replacing the previous segment (described below)
I propose a code like the following, to light up each element after the other for a specific time each (not tested):
#include <WS2812FX.h>

#define LED_COUNT 60

#define LED_PIN 13

#define SEGMENT_INTERVAL    3000
unsigned long segment_timestamp;
uint8_t current_segment = 0;
#define SEGMENT_N   4

WS2812FX ws2812fx = WS2812FX(LED_COUNT, LED_PIN, NEO_GRB + NEO_KHZ800);

void setup() {
    ws2812fx.init();
    ws2812fx.setBrightness(85);
    ws2812fx.start();
}

void loop() {
    if(millis()-segment_timestamp > SEGMENT_INTERVAL){
        segment_timestamp += SEGMENT_INTERVAL;
        switch(current_segment){
            case 0:
                ws2812fx.setSegment(0,  0, 14, FX_MODE_COMET, BLUE,  3000, false);
                break;
            case 1:
                ws2812fx.setSegment(0, 15, 29, FX_MODE_SCAN, RED, 3000, true);
                break;
            case 2:
                ws2812fx.setSegment(0, 30, 44, FX_MODE_SCAN, BLUE,  3000, false);
                break;
            case 3:
                ws2812fx.setSegment(0, 45, 60, FX_MODE_SCAN, RED, 3000, true);
                break;
        }
        current_segment = (current_segment + 1) % SEGMENT_N;
    }
    ws2812fx.service();
}

What happens here? First we use the millis() function in the pattern of the BlinkWithoutDelay example to time the change of segments to every 3s (3000ms) without blocking the execution of the other code (here the service routine of the LED animation). I will not go into detail here, since this principle is described at numerous places through the web and this site. Just search for something like "Arduino millis" or "Arduino Blink without delay". Now is only important, that the code inside the if statement will be executed every 3s (can be changed with SEGMENT_INTERVAL).
In the if statement we use a switch statement to set the corresponding segment, that should be activated at that time. Here we always set the segment 0, since only one segment is active at any time. Instead of removing the previous segment and adding the new one, we just change the previous segment to the data of the new segment.
With the line
current_segment = (current_segment + 1) % SEGMENT_N;

we increment to the next segment, while wrapping around from segment 3 to segment 1 via the modulo operator %. This is needed to loop through the segments.
The call to ws2812fx.service() is still needed, since it handles the actual animation of the current segment.

Note, that the above code can still be improved. You could save all the segment data in an array of structs and replace the switch statement with one line, using the current_segment'th element of the array. I will leave that improvement to you.


Not sure where you got the library from, but if it's from this github repo, you're using it wrong.

The function prototype for modbus_configure is:

void modbus_configure(long baud, byte _slaveID, byte _TxEnablePin, unsigned int _holdingRegsSize, unsigned char _lowLatency);

The example file shows how to use it correctly

modbus_configure(115200, 1, 2, TOTAL_REGS_SIZE);


How to read main code inside main code in Arduino?

Interesting. If you want hex you have to tell it to print in hex. If I change your display line to:

Serial.println(displayInt, HEX);

Then I get:

940C
3594
35
C00
940C

Compare this to what the decompiled file looks like:

   0:   0c 94 35 00     jmp 0x6a    ; 0x6a <__ctors_end>
   4:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>
   8:   0c 94 5d 00     jmp 0xba    ; 0xba <__bad_interrupt>

If you take the endianness into account (you are reading words, not bytes) then it is the same.

If you change it to read bytes it looks better:

void setup() {
  Serial.begin(115200);
  while (!Serial);  // wait for serial port to connect. Needed for native USB

  for(int k = 0; k < 12; k++) {
    byte c = pgm_read_byte(k);
    char buf [3];
    sprintf (buf, "%02X", c);
    Serial.println(buf);
  }
}

void loop() {
}

I increased the baud rate to 115200. I'm always puzzled when people use 9600 baud. Do you hanker for the olden days, when 9600 baud modems were the fastest you could get?

That gives this result:

0C
94
35
00
0C
94
5D
00
0C
94
5D
00

As you can see, it is exactly correct.


Arduino Serial.println() keeps transmitting data even when conditions are imposed

If you had put a Serial.print inside loop you would have seen the problem. Debugging displays are very helpful. Like this:

void loop()
{
  i++;
  Serial.println (i);   // <---- debugging
  if(i<2)
  {
    Serial.print('#');
    Serial.print('1');
    delay(10);
  }
}

Since you are adding 1 to i each time around the loop, how long do you think it will go before i overflows? It will go up and up, get to 32767 and then become -32768, and then count back to 0. During that time it will be less than 2, and it will do the printing of "#1".


Can i create a function inside of void setup()?

No. You do not create functions within functions.

You can create a function, and then call it both from setup() and loop() if you so wish.


connection between Arduino Uno with nRF24L01 and notebook with wireless card

Absolutely no. Can you connect your bluetooth headset to the wireless router? No because even if they share the same band they "speak" different protocols. So why could you do that with the nRF24L01?

If you want to communicate with your PC you have three options:

Choose nRF24L01. In this case, since the PC does not have that device, you will need to make an adapter (the easiest one could be an USB adapter). You can connect a microcontroller to a USB to serial converter and to the nRF24L01 and use it as a bridge.
Choose Wifi. Then you'll need a new transceiver for the arduino UNO you are using (maybe the ESP8266, which is around 2$) but can be a bit more complicated for just sharing data (I never used it, though, so I can be wrong).
Choose bluetooth. Usually this is my preferred way to communicate with a board. Cheap (the HC-06 module is about 2-3 $) and easy to use (the interface is a plain serial).

Good luck ;)


Yes, I agree with @Paulo Soares to use 2 Arduinos.

It makes little sense to make the 2nd wireless jump between the 2 Arduinos using a complex packet protocol such as TCP/IP.  This project uses 2 Xbee radios.  I suspect it is also possible to accomplish this using COTS model airplane radio.  This may be talked about here but it is not clear if the hardware talks to existing R/C hardware or to proprietary hardware.


MCP A(0, 9);
 MCP B(1, 8);
 MCP C(2, 7);
 MCP D(3, 6);
 MCP E(4, 5);
 MCP F(5, 3);

CS on pin 10 is often used for Ethernet
CS on pin 4 is often used for SD


I only had experience with the MQ2 sensor (more info here), so I'm going to use it as an example. If you have different sensors double check their datasheets.

Now, the main current consumption for these comes from the heater. Can you turn the heater off to save some power? Apparently not, since they say that

  Please note that the best preheat time for the sensor is above 24
  hours.

So, for the moment, let's consider all five sensors turned on at the same time.

The heater specs say that its resistance is around 33 ohm +/- 5% in the worst case this means 31.35 ohms. At 5V, this means 160mA for each sensor. Five of them are 800mA, and then let's add something like 50mA for the rest of the circuit (just a random number, and highly depends on the rest of the circuit).

Now, how is the UNO powered? If it is powered from the USB, the maximum current you can draw is 500mA (so 850mA is not allowed). So.. No powering from USB. If, on the other hand, the board is powered by the barrel jack, the onboard regulator can dissipate roughly 1-1.5W (taken from this thread). The power dissipation comes from the input voltage. With a 9V input, about 3V (slightly more) will need to be handled by the regulator. At 850mA, this means 2.5W (Not ok). In both cases you will need an external 5V power supply. With a 7V input (the very minimum you can apply) you will have to dissipate roughly 1.2V, at 850mA this means 1.02W. Please beware that this means something like 80-90°C of temperature increase in that area, so the part will become very hot. And moreover its lifespan will be reduced. So use this path only if really necessary.

If you reduce the performances and start powering just one sensor at a time (this means longer time before having it fully operational, and adding some transistor to switch them on and off) this data can change. I mean, if put a transistor to stop powering it, and then turn on one sensor at a time, you will be able to reduce the maximum current consumption to 210mA.

This means that you will be able to get power from the USB port; moreover you will be able to use the external power connector for voltages up to 10.5V (0.8V on the diode, so 4.7V on the regulator - around 1W). This comes at a price, of course: the heater will work for 1/5 of the time, so it will be harder to reach the temperature required for the measurement


Here is a 1/2 software 1/2 hardware solution:

You actually have 6 pwm pins (from the silk screen notation in your picture).  So you can control 2 RGB LEDs independently.  If you added 4 more transistors that are used to gate the common 5v going to each of the 4 RGB LEDs you could control them in pairs.  That is, you could turn on 2 independently controlled RGB LEDs and let the 6 PWM outputs control the brightness and color of each of the 2 for, say, 100ms.  Then you could turn those off and turn on the other 2 independently controlled RGB LEDs for 100ms.  During the switch, you would change the PWMs for the 2nd set of RGB LEDs.  The draw back to this approach?  You may start noticing the LEDs flickering.  You may have to adjust the rate which you switch between the two pairs of LEDs.  And, of course, it may not work as you expect it to.

Totally different approach:

You can use programmable RGB LEDs:

And use this Arduino software library. These types of RGB LEDs have the PWM build in.  The Arduino sends out serial data to the first LED which strips off its RGB data.  Then sends the data to the next RGB LED which does the same.  So you can control many RGB LEDs using a single pin on your Arduino.


ATtiny44 millis() not working with 16 MHz external clock

Let me guess: "much more time" is about, ohhh, 16 times?

When millis() was written, it had to assume what the input clock was. There is no way to detect the speed of the input clock: to do so would require another clock! So the writers of the function defined a starting constant, set it to 1000000, and required anyone that changed the clock would have to change that constant.

Find the constant, and set it to 16000000. Voilà!

Here's an article on the source code of the function:

https://ucexperiment.wordpress.com/2012/03/16/examination-of-the-arduino-millis-function/


Here's an example of how to do it:
jump_table.ino
int func1(int arg)  { return arg + 1; }
int func2(int arg)  { return arg + 2; }
int func3(int arg)  { return arg + 3; }
int func4(int arg)  { return arg + 4; }
int func5(int arg)  { return arg + 5; }
int func6(int arg)  { return arg + 6; }
int func7(int arg)  { return arg + 7; }
int func8(int arg)  { return arg + 8; }
int func9(int arg)  { return arg + 9; }
int func10(int arg) { return arg + 10; }

int (*jump_table[10])(int) = { func1, func2, func3, func4, func5,
                               func6, func7, func8, func9, func10 };

void setup() {
}

void loop() {
  int index = 2;
  int argument = 42;
  int result = (*jump_table[index])(argument);
  // result is 45
}

All functions stored in the array must have the same signature.  This simply means that they must return the same type (e.g. int) and have the same arguments (a single int in the example above).

You can do the same with static class methods (but not instance methods).  For example you could use MyClass::myStaticMethod in the array above but not MyClass::myInstanceMethod nor instance.myInstanceMethod:
class MyClass {
public:
  static int myStaticMethod(int foo)   { return foo + 17; }
  int        myInstanceMethod(int bar) { return bar + 17; }
}

MyClass instance;

There's a similar question over on stackoverflow.


It isn't enough to power the module with 3.3V. You also have to level-shift the Arduino's 5V TX signal to 3.3V that is acceptable by the GPS module's RX pin, using a 1:2 voltage divider.

You should also know that the Arduino's 3.3 V pin can't source more than 50 mA; your module's current draw may sometimes exceed this limit (max is 67 mA). Instead, connect the Arduino's 5 V pin (which can source up to 500 mA) to the VCC of the GPS module through an LM1117T 3.3 V regulator:

The input goes the Arduino 5V pin and the output goes to the NEO-6M VCC. Connect all GNDs together.

Then run a basic sketch like this:

#include "SoftwareSerial.h"

SoftwareSerial gps(4,3);

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

void loop(){
  while (gps.available())
    Serial.write(gps.read());
}

This will basically make the Arduino grab any NMEA data sent by the NEO-6M and forward it to your PC's serial monitor. If you receive legible data, it means you've established comms with the module. You can then upload your original sketch.


What you want is an array of function pointers.

void anim1() {
    // blah blah
}

void anim2() {
    // blah blah
}
// ... etc ...

typedef void (*animptr)();

animptr anims[10] = {
    anim1,
    anim2,
    anim3,
    // ... etc ...
    anim10
};

Then you can use:

anims[animNumber]();


Changing ESP-12E NodeMCU to ESP-01S - how to trigger sketch?

Use io 0 as the esp-01S pin wired to Micro, but change the logic for pull-up, because esp-01S has a pull-up resistor on io 0 of the esp8266. Use LOW to trigger the action and HIGH as normal state.

On Arduino Micro side set the output pin HIGH before you set it as OUTPUT. This will avoid the LOW state. While the Micro pin is in INPUT state after power-up, the pull-up resistor on esp-01S will pull io 0 HIGH.