How do I convert this program to assembly from c++

The obvious solution for converting any program to assembly is... to
compile it! You can disassemble the resulting binary with a command
like:

avr-objdump -S -C the_program.elf > the_program.lss

This will output a listing of the program, with the original source
interspersed with an hex dump of the binary and the corresponding
disassembly.

  The part I am really stuck on is the analogRead() function.

Here it goes:

000003a6 <analogRead>:
 3a6:   8e 30           cpi r24, 0x0E   ; 14
 3a8:   08 f0           brcs    .+2         ; 0x3ac <analogRead+0x6>
 3aa:   8e 50           subi    r24, 0x0E   ; 14
 3ac:   87 70           andi    r24, 0x07   ; 7
 3ae:   20 91 00 01     lds r18, 0x0100 ; 0x800100 <__data_start>
 3b2:   90 e4           ldi r25, 0x40   ; 64
 3b4:   29 9f           mul r18, r25
 3b6:   90 01           movw    r18, r0
 3b8:   11 24           eor r1, r1
 3ba:   82 2b           or  r24, r18
 3bc:   80 93 7c 00     sts 0x007C, r24 ; 0x80007c <__TEXT_REGION_LENGTH__+0x7e007c>
 3c0:   80 91 7a 00     lds r24, 0x007A ; 0x80007a <__TEXT_REGION_LENGTH__+0x7e007a>
 3c4:   80 64           ori r24, 0x40   ; 64
 3c6:   80 93 7a 00     sts 0x007A, r24 ; 0x80007a <__TEXT_REGION_LENGTH__+0x7e007a>
 3ca:   80 91 7a 00     lds r24, 0x007A ; 0x80007a <__TEXT_REGION_LENGTH__+0x7e007a>
 3ce:   86 fd           sbrc    r24, 6
 3d0:   fc cf           rjmp    .-8         ; 0x3ca <analogRead+0x24>
 3d2:   80 91 78 00     lds r24, 0x0078 ; 0x800078 <__TEXT_REGION_LENGTH__+0x7e0078>
 3d6:   20 91 79 00     lds r18, 0x0079 ; 0x800079 <__TEXT_REGION_LENGTH__+0x7e0079>
 3da:   90 e0           ldi r25, 0x00   ; 0
 3dc:   92 2b           or  r25, r18
 3de:   08 95           ret

Now, in order to more easily make sense of it, you need to know what all
those magic numbers mean. The command

avr-nm -nC the_program.elf

will dump the symbols associated with every RAM and flash address. In
order to tell those apart, 0x800000 is added to every RAM address. This
will tell you that, in this specific program, the RAM address 0x0100
is actually the address of the variable analog_reference from the
Arduino core library. Thus, you can replace the line

 3ae:   20 91 00 01     lds r18, 0x0100 ; 0x800100 <__data_start>

by

    lds  r18, analog_reference

Then you can use the datasheet to get the names of the memory-mapped IO
registers, and the names of the bits from those registers. I have done
all this for you, so here is the cleaned-up disassembly of
analogRead():

analogRead:
    cpi  r24, 14
    brcs 1f
    subi r24, 14
1:  andi r24, 0x07
    lds  r18, analog_reference
    ldi  r25, 1<<REFS0
    mul  r18, r25
    movw r18, r0
    clr  r1
    or   r24, r18
    sts  _SFR_MEM_ADDR(ADMUX), r24
    lds  r24, _SFR_MEM_ADDR(ADCSRA)
    ori  r24, 1<<ADSC
    sts  _SFR_MEM_ADDR(ADCSRA), r24
2:  lds  r24, _SFR_MEM_ADDR(ADCSRA)
    sbrc r24, ADSC
    rjmp 2b
    lds  r24, _SFR_MEM_ADDR(ADCL)
    lds  r18, _SFR_MEM_ADDR(ADCH)
    ldi  r25, 0
    or   r25, r18
    ret

If you compare this with the source code of analogRead(), it
should now make perfect sense.

  I am trying to implement a program in assembly

Now, if you want to write the assembly yourself, that's a whole
different story. If you allow yourself the use of the Arduino core, then
you can simply

    ldi r24, 14  ; pin A0 is pin 14
    call analogRead

If you don't want to rely on external libraries, and really write
everything yourself, it's going to be a lot harder. I suggest you do
this as a two-step process:

Step 1: Learn how to program the ATmega328P in plain C, at the
register level, using no library other than the avr-libc. You can start
by reading this short tutorial about direct port access.
But then you should quickly move on to studying the
datasheet and the manual of the avr-libc. Yes,
that's a lot to digest. I hope you didn't expect this to be quick and
easy. But note that, on those documents, you can skip all the chapters
related to functions you are not going to use.

  I am really stuck on is the analogRead() function.

In the specific case of your example program, you don't need a version
of analogRead() that can read any pin with any reference. You can
instead write a simpler version that just reads the currently selected
pin using the currently selected reference:

int simple_analog_read(void)
{
    ADCSRA |= 1<<ADSC;                    // start the converion
    while (ADCSRA & (1<<ADSC)) continue;  // wait till it's done
    return ADC;                           // return the reading
}

Of course, this assumes you have appropriately initialized the ADC.

  int voltage = sensorValue * (5.0 / 1023.0);

You really, really don't want to implement something like this in
assembly. The AVR hardware supports neither floating point nor
divisions. All this is handled by the compiler through supporting
libraries, and they are not simple. What you really want is something
like

int voltage = (sensorValue * 5) >> 10;

which is incidentally more correct, as the scaling factor is 5/1024, not
5/1023 (see the datasheet).

Step 2: Learn assembly, and rewrite your low-level C code in
assembly. If your C code is low-level enough this should not be too
hard. As a learning aid, you can ask the compiler to do it for you and
then try to make sense of what it did. If you just try to compile the
simple_analog_read() function I wrote above you will see the
translation to assembly is almost trivial.


The way to go depends on the time range, that the event will have. The Arduino framework already includes a function for timekeeping: millis(). It returns the number of milliseconds since the startup (much like a clock) and measures the time via the hardware Timer0 and it's interrupts. This function will work good in the 2 digit millisecond range and above. With single digit millisecond or the microsecond domain, you should instead use micros() with works similar, but returns the microseconds since startup. For the low microsecond range and below you would need to work directly with a dedicated hardware timer, configuring it via its hardware registers.
Here I would show the principle of millis()/micros(), since that is most likely what you need. In the following I will only write millis(), but all the calculations can also be done with micros(). The only difference for the calculations is the factor 1000 between milli- and microseconds.
When you look at your watch and want to measure a time difference, you take note of the start time and the end time. Then you calculate the difference to get the event duration. You can do the same with millis():
unsigned long starttime = millis(); // take note of start time
// here the event to measure
unsigned long endtime = millis(); // take note of end time
unsigned long duration = endtime - starttime; // duration of the event in ms

So in your code you need to check for a rising edge of your signal. On every rising edge you calculate the time difference between the last timestamp and the current time. Then you reset the timestamp. Something like this:
int last_input_state = LOW;
unsigned long timestamp;

//setup here

void loop(){
    int current_input_state = digitalRead(2); // get current signal level
    if(current_input_state && !last_input_state){ //check, if signal is now high and was low before
        unsigned long current_time = millis(); // take note of the current time
        unsigned long duration = current_time - timestamp; // calculate the duration and do something with it
        timestamp = current_time; // update the timestamp with the current time
     }
     last_input_state = current_input_state; // update the last input state with the new measured one
}

Note:

This code is non-blocking. It needs to run fast and continuously to work correctly. You cannot do long blocking things in the rest of your code, like using high delay() calls, but you shouldn't do that either way, since that will block anything from going on.
You can go even further to lift the weight from your CPU and use an interrupt to sense the rising edge. You could use attachInterrupt(digitalPinToInterrupt(pin), service_function, RISING); and provide a void service_function(), which does the timestamp measurement and calculation (basically the same code as in the if statement of the code above).


How to burn bootloader into arduino uno without using another arduino

There are 3 main options how to write bootloader or program to AVR over ISP.

dedicated AVR programmer or Arduino ISP programmer
other Arduino with Arduino as ISP sketch or similar
parallel port of a computer


You're not using digitalWrite properly. You should do:

if (digitalRead(domeLightIn) == LOW && brightness != 255){

Just a sidequestion. What is pin7 connected to? If it's a 12v signal, you'd have to convert it down to 5v somehow.

Also, the 12v in the car can be up-to 14v, and can have some huge spikes. Not sure if the sainsmart's regulator can handle those spikes. It might die prematurely. It's also just wasting 60% (generating heat!), turning 12v to 5v. I would suggest adding one of those cheap car-phone-chargers.


Is it possible to extract a hex file via UART from an Arduino?

AVRDUDE which is used by the IDE to send the content of HEX file from your computer, as a feature letting it to get back the data of the flash, in order to compare and see if data are correct.

For a UNO try:

avrdude -patmega328p -carduino -P/dev/cu.usbmodemFD121 -b115200 -U flash:r:"flash.bin":r

I think it would not be very hard to change that for a Mega.

It works fine. I have use that a lot to debut my "Android Updater" which allow the user of my board to update the code themselves.

PS: Just for info, you'll not get back the HEX file as in the flash, you have only some "pieces" of the HEX file.


Normally you don't need to change the fuse settings, this configuration should be fine with the default arduino setting of

lowfuse=0xff

highfuse=0xde

extendedfuse=0x05

Serial should work fine.


Is my ATmega broken, and would replacing it with another break that one, too?

Besides breaking a pin while removing the IC from its socket, or static electricity during manipulation, I don't see what could fry the ATmega.

However, it is possible that the R2 ATmega has a different bootloader and that may be an issue.

If I was you I would just remove the ATmega from the R3 board and test it on a breadboard (don't need a lot of components to do that); at least that could tell you if it is fried or if it is the R3 board that is fried...


FreeRTOS: Object not created properly from within task

'Strange memory errors' you seem to be describing values that have gone out of scope.

This is all based on your code, so I may have misunderstood.

The third parameter is causing a memory leak, unless you happen to be deleting it within MyClass (which is normally, not always, bad practice).

It sounds to me that you are trying to access values that have gone out of scope.

Its also possible that this OS requires you to do something to allow the memory to be shared between the tasks.


Are there any products based on Arduino that are sold by companies?

In theory, an Arduino board could be used in some low-end professional products (i.e. where the performance and memory limitations aren't an issue). The build quality of the official boards is certainly good enough. The only issue they would potentially have is making suitably robust connections -- i.e. anything plugged into a female header would have the potential to get shaken loose.

In practice though, using an Arduino board would only make sense for extremely small-scale projects, where only a few units will be produced, and where there will be a minimum of external circuitry.

A commercial project would normally have a custom circuit board designed. That allows them to economise on space and features, eliminating unnecessary costs. Even if it only saves a small amount per board, it can make a big difference if you're doing mass-production.

With that said, a professional product could certainly use an AVR microcontroller or similar at its heart (much like the Arduino boards). Atmel was producing chips long before Arduino was around, and their products are well known and widely used. The choice really depends on the needs of the individual project.


Serial Monitor stops working when using PinMode

My issue was that pin 7 was connected to the reset pin on the Arduino, meaning every time it was set to output, the Arduino was reset.
You can see this here:
void setup()
{
  Serial.begin(9600);

  Serial.println("a");

  delay(100);

  pinMode(7, OUTPUT);
}

void loop()
{
  Serial.println("test");
}

which outputs a stream of a's separated by 100ms (plus a bit)


Serial communication using Arduino and TeraTerm

... I just hooked up Tx and Rx to the Arduino's Rx0 and Tx0.

But neither device knows what voltage they are. You need to connect ground as well so that they have a common reference.


You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.

The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.


Instance does not name a type, in function void loop (8x8 matrix)

MyBlink:0: error: 'Instance' does not name a type

Once I deleted the line Instance code: on the first line both errors went away.

Cheers


How to make an arduino button to forget his past purpose?

What you likely need is a state machine. The behavior of the actions depends on the state the program is currently in.

In your case, the state machine might look like this:

What does it mean?

black circle: this is where the system powers on
rectangle: a state
arrow: a transition from one state to another
green text: action

For the problematic double click action, you can see:

it changes the state from "set size" to "speed"
in all other cases, it does not change the state (actually it changes the state to the same state)

I always recommend drawing the state machine before implementing it. It makes mistakes much more obvious.

There are several ways to implement it. The easiest one being a switch/case. More advanced implementations may use object orientation. When using switch/case, I prefer to have one method per state, like so:

void loop()
{
    switch(state):
        case setsize:
             setsize();
             break;
        case speed:
             speed();
             break;
        ...
}

If you know about function pointers, it gets even easier:

enum State {
  setsize = 0,
  speed,
  clock,
  temperature
};

State state;

void setup() {
  state = State::setsize;
}

typedef void (* functionPointer) ();
functionPointer process[] = {do_setsize, do_speed, do_clock, do_temperature};
void loop() {
  process[state]();
}

void do_setsize()
{
  state = State::speed;
}
void do_speed()
{
  state = State::clock;
}
void do_temperature()
{
  state = State::speed;
}
void do_clock()
{
  state = State::temperature;
}


Common button on two Arduinos and two computers

The ground of both computers are connected also via their power lines. You get a ground loop that might result in malfunctions and/or defects.

Think about using a galvanically separated connection, for example via an optocouple.


Reading values with HC-05 and sending commands at the same time working inconsistently

Actually got it working myself, but thank you so much for your help @chrisl

Ditched the for loop completely just to try things out and reorganized my code a bit. Surprisingly it started to work well enough.

Basically just moved my measuring stuff outside the while loop*(and now that I think about it, why would it ever be withing the while loop? Literally makes no sense)* and to the end of the whole void loop part, and only polled for state changes within the while loop while the BT connection was active.

Doesn't miss a command as far as I can tell, and the adjustment is within 2 seconds when using my whole code, which is perfect. Also the whole program doesn't just freeze itself while trying to think what happened when the change set was send.

Here's a short version, should somebody bump into this thread in the future.

void loop() {
   while(Serial.available() > 0){
    state = Serial.read();

  if (state == '0') {stuff happens here,
    }
    }  //End of the while loop.

  sensors.requestTemperatures();
  delay(1000);
  Celcius=sensors.getTempCByIndex(0);
}


trying to make wemos d1 code modular causes collect2: error: ld returned 1 exit status exit status 1

You are calling Funcs::Connect::connectWifi() right here:

conn.connectWifi();

since conn is of type Funcs::Connect

But you defined a function Funcs::connectWifi():

namespace Funcs
{

  void connectWifi() {

where I think you meant to have connectWifi be a member of that Connect class.

namespace Funcs
{

  void Connect::connectWifi() {

That's not the only issue with your code, you also create the instance in setup and let it go out of scope after calling just the one function.  But that's a different kind of error.  It's legal code, just probably doesn't do what you want.


Add a second delay after:

digitalWrite(X_STEP_PIN    , LOW);

Also try increasing the delay maybe you are pulsing the step pin too fast.


Read data from arduino once only serial communications (jSSC)

Unless there is a fault in the library you are using there is nothing wrong with the Arduino code, this can be seen from the serial output.

The fault is with the receiving java code, pump test data into that to see what is wrong.


Interfacing Arduino UNO with TFT LCD and WiFi Shield

I agree with Chris on this. The uno is limited where it comes to pins and and ram, you should probably look at a mega, or similar.

As far as running both at once, i don't think it would be possible with the uno, with the ram limitations, as well as pin limitations, you'll be hard pressed to get them going at the same time, within the same sketch.

While technically it is possible to use alternative pins, i doubt there will be enough unused pins to shift an entire shield over to on the Uno

If you're looking for a cheaper rout, you may look at adding a secondary Uno to run the wifi, and send any data you need displayed to the uno running the tft via serial coms.


No, this is not possible.

The camera outputs a JPEG image. To display that on the TFT screen it is necessary to decompress that JPEG image and send the raw 16-bit (RGB565) colour information to the screen.

The Arduino doesn't have enough memory to do the job.

I wrote an absolute minimal JPEG decompressor a while back. It uses the absolute minimum memory possible (it operates on one macroblock at a time), and still requires around 100KB. That's 50x more than the Arduino Uno has.

Also on a 200MHz, 32-bit chip with FPU it takes about a minute to decompress a 320x240 pixel image. I can't even begin to imagine how many days that would take on a little Arduino Uno even if it did have enough memory to do the job...

As has been suggested, you need a more powerful board. And if you're going that route you may as well drop the useless OV7670 and get a Raspberry Pi with a proper Pi Camera module (or at least a USB webcam).


Is there a sensor to measure a distance between 2 point as in range [0-2 meter]?

You can use a lot of different methods with advantages/disadvantages:

Use an IR LED/receiver and calculate the distance of travelling of the lights. Disadvantage: you need a very precise timing mechanism (light is fast), also take latency into account for non-light parts, and hardware needs to be in visible range and pointing to each other with LEDs)
Use an ultrasonic sensor like SR-HC04. Disadvantage: devices must point to each other in a small precise angle.
Using an RF method and sending/receiving e.g. via nRF24L01+ 2.4 GHz trasnceivers, to check the difference in time between sending and receiving when very close or a few meters apart. However, there might be aspects that might distort the result (other receivers/transmitters, what kind of material is in between, nRF antenna placement/direction etc). Using lowest speed (most reliable), highest power.


Try adding a delay into your loop. In your code pin 13 will toggle very rapidly, much too fast to see it. For example:

void loop() {
  digitalWrite(13,HIGH);
  delay (1000);
  digitalWrite(13,LOW);
  delay (1000);
}

It doesn't look wired correctly. For an N-channel MOSFET the Source should go to ground, like this:


where is the digitalPinToInterrupt macro defined

Generally, if you want to find identifiers in your Arduino board support, you can run the ctags program on the libc and Arduino core files.  ctags is used as part of the build process in its effort to generate C++ declarations for you.  So it is generally available to you as an Arduino user.  You should find ctags or ctags.exe in:

/path/to/arduino15/builtin/tools/ctags/version-number/

This can be run against your board support in:

/path/to/arduino15/packages/vendor/hardware/architecture/version-number/

And your standard libraries found under directories in the form of:

/path/to/arduino15/packages/vendor/tools/compiler-tool/version-number/

If you're wondering what /path/to/arduino15/ would be on your system, it's documented here in terms of where the preferences file is stored.  The relevant paths containing and version numbers and architecture names should show in the verify/compile output when verbose mode is turned on in preferences.
Specific example
On my linux system with reasonably current versions of UNO-related things, my command-line would look like:
~/.arduino15/packages/builtin/tools/ctags/5.8-arduino11/ctags \
    -f /tmp/output-file \
    -R \
     ~/.arduino15/packages/arduino/hardware/avr/1.8.3/ \
    ~/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/avr/include/

The resulting tag file can then greped or just opened and the following entries can be found, showing the filenames and line numbers to investigate:
DigitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/circuitplay32u4/pins_arduino.h   138;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/ethernet/pins_arduino.h  79;"    d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/gemma/pins_arduino.h 64;"    d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/leonardo/pins_arduino.h  160;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/mega/pins_arduino.h  110;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_control/pins_arduino.h 120;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_motor/pins_arduino.h   115;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/standard/pins_arduino.h  79;"    d

In the case of an UNO the standard variant is the significant declaration.

There are different implementations of ctags.  The one used by the Arduino support files is Exuberant CTAGS and you may want to read its documentation, to learn how to control the program to display differently to only search for specific identifiers, etc.  It is also typically used with editors that have some special support for the resulting tags file, to jump to definitions, like an IDE would.


You will have to check in the servos datasheet for the maximal current, that it draws (motors draw more current, when inhibited by mechanical force, so be sure to get the maximal current from the datasheet). From the data, that you gave us, I think it will draw rather much current. So you should not power it over the USB port of your PC (which gives 500mA at maximum). Also you should not use the 5V pin of your Arduino, or you may fry components like the diode, that lies in the current path from USB to 5V pin.

For your step down module, you will also have to check, if it can provide the current, that the servo needs, or you may kill it. If you want to use USB, you can use a standard USB charger or powerbank. Often these can provide more than 1A (depending on the actual product). Most USB wallwart chargers have a current specification on them. But (as said earlier) don't provide the power through the Arduino. Provide it directly from the source, so that the possibly high current for the servo does not have to pass trough the Arduino. You can also power the Arduino with the same source in parallel to the servo, so that you don't need two sources or a converter.

For more info, you will have to provide more information about the servo


After a chat with OP, it turned out this was a more complex issue, probably a memory overrun.

This cannot be seen in this small snippet, but the whole program is using memory extensively (global variables and dynamic memory heap allocation).

Heavy use of String variables is a likely explanation for the observed behavior.
Also a lot of string literals are putting more pressure on memory in the OP program.

Here are my suggestions:

Replace all "..." string literals with flash-stored strings with F("..."). That will reduce the initial SRAM size used.
Replace all String variables with pure C-string (char* and char arrays) and use standard C string functions such as strcpy, strcat, strlen, strcmp, strchr... This forces to pre-allocate string to their maximum size, but this can be controlled at compile-time (for string variables defined as global). For this point, I also suggest to read a good tutorial on strings in C language.
Use const whenever possible (instead of variables that waste memory)
Use the smallest type needed for each variable, e.g. avoid int (2 bytes) when you need to store a boolean value, prefer bool type (only one byte) or even use 1 byte to store 8 boolean values and use boolean logic to manipulate each value.


Parsing Integers from Serial data stream

Here is a sketch that uses strtok() and atoi() to parse the data and store the results in an integer array.

char testInput[] = "<1,2,3,4,5,512>\r\n";
uint16_t myArray[6] = {};

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char* pch = strtok(testInput,"<>,\r\n");

  while(pch != NULL){
    myArray[counter] = atoi(pch);
    pch = strtok(NULL, "<>,\r\n");
    counter += 1;
  }

  // Print out the contents of the integer array.
  for(int i = 0; i < counter; i++){
    Serial.println(myArray[i]);
  }

}

void loop(){}

EDIT

Based on your comments, I have another sketch for you to try.

// Sample input: <1,2,3,4,5,512>
char testInput[40];
uint16_t myArray[6] = {};
int counter = 0;

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

void loop(){

  if(Serial.available() > 0){

    Serial.readBytesUntil('\n', testInput, 40);

    char* pch = strtok(testInput,"<>,\r\n");

    while(pch != NULL){
      myArray[counter] = atoi(pch);
      pch = strtok(NULL, "<>,\r\n");
      counter += 1;
    }

    Serial.print (myArray[0]);
    Serial.print (", ");
    Serial.print (myArray[1]);
    Serial.print (", ");
    Serial.print (myArray[2]);
    Serial.print (", ");
    Serial.print (myArray[3]);
    Serial.print (", ");
    Serial.print (myArray[4]);
    Serial.print (", ");
    Serial.println(myArray[5]);

    counter = 0;
  }
}


ESP8266 send TCP HEX packet with 4 chars

After searching and experimenting on this, I believe the short answer to the question is that you need to send the command string like a buffer of characters AND put your Hex Coded command for the LED controller as an escaped string of characters.

Here is my code (it toggles the LED Controller between Green and Blue every 5 seconds, but you can extend this for other commands and colors as described at http://jpelectron.com/sample/Electronics/WiFi%20LED%20control/):

/*
Send Commands to LED Controller via Wifi Network and Wemos D1 Board
*/
#include <ESP8266WiFi.h>

const char* ssid     = "***yourWifiSSID***"; //Change this value for your network
const char* password = "***yourWifiPassword***"; //Change this value for your network
boolean connected = false;
boolean colorToggle = false;

void WiFiEvent(WiFiEvent_t event) {
    //Serial.printf("[WiFi-event] event: %d\n", event);

    switch(event) {
    case 3:
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        connected = true;
        break;
    case 6:
        Serial.println("WiFi lost connection");
        connected = false;
        break;
    }

    // 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
    // 1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
    // 3 : WL_CONNECTED after successful connection is established
    // 4 : WL_CONNECT_FAILED if password is incorrect
    // 6 : WL_DISCONNECTED if module is not configured in station mode

}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    Serial.begin(115200);
    WiFi.disconnect(true);
    delay(1000);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

}

// the loop function runs over and over again forever
void loop() {
    //if we are connected
    if(connected){
      digitalWrite(LED_BUILTIN, LOW); //Turn on LED on the Board
      turnLEDSOn();
    }
    else
    {
      digitalWrite(LED_BUILTIN, HIGH); //Turn off LED on the Board
      setup();
    }
}

void turnLEDSOn() {
    const uint16_t port = 5577;
    const char * host = "192.168.10.2";  //Change to whatever your LED Controller IP is

     WiFiClient client;

     if (client.connect(host, port)) //Try to connect to TCP Server
     {
        Serial.println("Connected to LED Controller... ");
        if (colorToggle)
        { //Green
          char command[] = "\x31\x00\xff\x00\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = false;
          delay(5000);
        }
        else
        { //Blue
          char command[] = "\x31\x00\x00\xff\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = true;
          delay(5000);
        }

        Serial.println("Command sent ... "); // command is the color or animation sent to the LED controller
     }
     else
     {
        Serial.println("connection failed ... ");
     }

      if (client.available())
      {
        //Read from LED Controller
        char c = client.read();
        Serial.print(c);
      }

      if (!client.connected())
      {
        Serial.println();
        Serial.println("disconnecting ... ");
        client.stop();
        for(;;);
      }
}


Send HTTP get request from GSM SIM800c and Arduino

You haven't instructed the module to make a request yet.
With the AT+HTTPPARA command, you are just configuring the request you want to make. In your case, you just specified the URL you want to call.
Next, you have to send
AT+HTTPACTION=1

to make the actual request using the HTTP GET method, and then you can read the HTTP response using
AT+HTTPREAD

Keep in mind that after AT+HTTPACTION you will receive an unsolicited result code in the format
+HTTPACTION: <Method>,<StatusCode>,<DataLen>

this will happen after the module will actually do the request and will have the response.


New Arduino Motor Shield Short Circuiting my board?

Thanks to @jwpat7, I have discovered that the reason it is not working is that the seller has messed up and sent me 3 of the same chip, 74HC595N. After doing some research, I have purchased the LM293D Chips.


The global constructors run right after the initializations performed by
the C runtime startup code, and right before main() gets called.
In a nutshell, the C runtime initialization code:

does some low-level initializations (e.g., setup the memory)
calls the global constructors
calls main(), which in turn

calls init() to do the Arduino-specific initializations
calls setup()
repeatedly calls loop()

The fine details are probably platform-specific. For AVR-based boards,
they are documented in the avr-libc manual.


Linear voltage regulators have an internal parasitic diode that shorts the output to the input. You have burned out this diode which has destroyed the regulator, but it is highly unlikely that any other components have been damaged. You can get away with cutting away the legs of the regulator, but complete removal will be difficult due to the large size of the tab connection and will likely result in damage to the other components.


Check out how the DS3231 Alarm functions work.  They will interrupt even a delay() statement.  At the appointed time the specified function is called.

This same question was answered here:

How to set Alarms on the DS3231 easily?

For another way to see how to set this up, let me refer you to this article:

Build Programmable Time-based Switches Using a Real Time Clock

The code can be downloaded Here


An ATMEGA2560 has no enough computational power to perform on-the-fly decoding, even at resolutions as low as 160x128 pixels and low frame rates.

The best you can hope for is a 20 fps, 16 bpp, 160x128 pixel video, directly streamed from the SD card, uncompressed (800kB/s), if the MCU runs at 16MHz. Even with such low specs, you'll have to use a trick, to implement a direct peripheral to peripheral transfer.

We made a guide here for the Arduino Uno (i.e. ATMEGA328P), but it should work also for ATMEGA2560 with little modifications: https://next-hack.com/index.php/2017/08/14/how-to-play-a-video-on-arduino-uno-46-playing-a-20-fps-animation-from-sd-card/

On the same link you'll find also the youtube links for a video guide.


Yes you could although this means you're measuring in relation to the Arduino's logic voltage, which is slightly below 5v (due to a diode's voltage drop) or the voltage of vref.


Getting a binary string and convert it to decimal

What you want are the bit-shifting operators << and >>, and the OR operator |:

for(int i = 0; i < 4; i++) {
    Serial.println(digitalRead(5 + i));
    Dstate = Dstate | (digitalRead(5 + i) << i);
}

You'll notice I changed the loop so it runs from 0 to 3 instead of 5 to 9 - it makes other parts easier if you start counting from 0.

Then the line:

Dstate = Dstate | (digitalRead(5 + i) << i);

is where all the magic happens.  Let's break it down:

digitalRead(5 + i)

That of course gives you a 0 or 1 for pins 5, 6, 7 and 8 in turn.

<< i

That shifts the value returned by digitalRead() left i bits.  For instance, if digitalRead() returns 1 and i is 0 then 1 is left shifted 0 times so remains as 0b0001.  If i is 1 then it left shifts one bit, so the value becomes 0b0010.  If i is 2 then it shifts two bits, so you get 0b0100.

Finally the result is combined with the current value of Dstate with OR, so the four values basically get laid over the top of each other.

So say you have the four switches in the positions ON-OFF-ON-OFF and Dstate starts off as 0, then the sequence would be:

i = 0, digitalRead = 1, shifted = 0b0001, OR = 0b0001
i = 1, digitalRead = 0, shifted = 0b0000, OR = 0b0001
i = 2, digitalRead = 1, shifted = 0b0100, OR = 0b0101
i = 3, digitalRead = 0, shifted = 0b0000, OR = 0b0101


How to create a serial communication connection between Cubieboard running Android and Arduino

Using the library you linked should be a simple case of downloading the library's jar file from https://github.com/mik3y/usb-serial-for-android/releases and adding it as a reference/library/dependency (I forget what eclipse calls them) in your eclipse project.

Then of course providing you connect with the right baud rates and so on it should work.


Loading a file off an sdcard and displaying it on port 80 isn't hard. Just check out the 'Ethernet' library and the 'SD' library.

I don't want to discourage you too much about the PHP part, but you won't be able to load the official PHP interpreter onto the Arduino. Simply not enough memory available.

However, if you just want to have dynamic website such as display variables or output from sensors, then you could write your own code interpreter for dynamic web pages that would fit in the memory of an Arduino, just think a bit smaller in scope as far as what it can handle. Maybe you'll end up writing a new library for dynamic webpages for Arduino sensor data.

If you really need to run a PHP interpreter then you can try something like a Rapsberry Pi and hook it up to the Arduino for sensor input using the I2C protocol.


return 0 resets the device. Use while(1); instead, to make it wait indefinitely.


Arduino configure script for conditional compilation of libraries

The problem here is that the Arduino IDE is not setup for doing this. Any real IDE has the possibility to set defines.

If you want your library to be used by arduino IDE users you will have to go to dirty routes like the #include and config.h approach already mentioned.
If I'm not mistaken arduino IDE compiles libraries with the full include path so you can have the config.h next to your sketch.ino file.

If the library is not intended for arduino IDE users I would advice using a real IDE like my Arduino Eclipse Plugin.


Implementation help with difference equation

I assume what you want is a digital filter. Each time you collect a
sample x[n], you feed it to the filter, and the filter returns the
corresponding y[n] given by
y[n] = 0.4142 y[n−1] + 0.2929 x[n−1]
In order to compute this result, the filter has to remember the previous
value of its input (x[n−1]) and of its output (y[n−1]). You need two
variables for storing this information, which I would call x1 and
y1. Note that the filter doesn't need to remember anything older than
that, so there is no use in storing more data. No need to create arrays
for storing the whole x and y sequences. Since the values have to be
remembered between calls to the filter, they have to be global
variables. Alternatively, they can be local to the filter provided they
have the static qualifier.
Once you have those two variables, you just have to apply the formula to
compute y[n]:
static float x1, y1;  // x[n-1], y[n-1]
float y = 0.4142 * y1 + 0.2929 * x1;

There is just one more thing to take care of before returning y: the
variables x1 and y1 have to be updated in order to hold the
current values of the filter's input and output. This way, next time
the filter is called, the values will have the previous values, as
expected. The whole filter is then
/*
 * Single pole low-pass filter.
 * transfer function:   H = 0.2929 / (z - 0.4142)
 * recurrence relation: y[n] = 0.4142 y[n-1] + 0.2929 x[n-1]
 */
float filter (float x) {
    static float x1, y1;  // x[n-1], y[n-1]
    float y = 0.4142 * y1 + 0.2929 * x1;
    x1 = x;
    y1 = y;
    return y;
}

A few notes:

x1 and y1 are implicitly initialized to zero. This is common
practice, but a fact you should be aware of. If it doesn't fit your
needs, add an explicit initialization to the definition of the
variables.

If you need multiple instances of the same filter, storing the state
as static locals would not work. Instead, the filter should take a
pointer to a “state object” as an extra parameter. If you want to do
this the “object-oriented” way, the pointer would be called this.

Why use x[n−1] instead of x[n]? This just adds an artificial delay to
the filter without affecting its low-pass performance. When designing
low-pass filters, it is common to prefer short delays, everything
else being equal.


What will happen if I keep my arduino on for 24 hours?

I have several home-brUnos and a genuine Mega 2560 that are now, or have, run 24/7 for periods of weeks to months, powered by either a USB port or a USB-type wall charger. All of them supported (or still do) a string of 2 or 3 DS18b20 digital thermo sensors and a WiFi or Bluetooth radio. None of them slept during those jobs and they all still live and continue work as well as they always have.


Does the VCC Output pin always give out a consistent 5V Voltage supply? What is the current output?

If you power from USB the vcc pin gives you the voltage that USB is providing. Somewhere between 4.75 and 5.25v.

If you use external power it provides 5v since that is what the regulator provides.

The current limit is either the limit of the usb port or the limit of the regulator on your board. Check the datasheet for that regulator (hint: read the schematic to find the model of the regulator).


Storage usage of methods compared to copied code

It.... depends

A call to function involves a few things

Save the context
Move the parameter(s) to the appropriate registers
Enter the function
Execute
Eventually save the return value to a register
Restore the context
Eventually copy the returned value to the variable

As you can see, quite a lot of things. The bold points are the ones executed also if you don't use a function.

Please note that if these functions are "methods", you have also a "hidden" parameter (the object you are applying the method onto)

So why use functions? Well, you will have to write this code in flash only once instead of more times.

What is best? It depends on your application.

You are calling this function only once? Don't use a function
Your function is really short (for instance, a one-liner)*? Don't use a function
You are running out of flash memory? Use a function
You need a lot of speed? Don't use a function (you add overhead)
You are not in one of the previous cases? Do as you prefer

With one-liner I mean something like, for instance, byte sum(byte a, byte b) { return a + b; }; in this case the function also occupies more space, since the call function instruction is compatible with the byte sum

Please note that usually more readability is more important than performances, so maybe using functions should be encouraged. I mean, in your case I'd probably use them unless there is a problem

What to do if you don't want to use a function? Well, there are other techniques:

Mark the function as inline; this is a hint for the compiler not to create a function but to replicate this every time. This is only a hint, so the compiler may ignore this
Instead of a function write a macro. This will be substituted every time, but the code will be maintainable. As a drawback, it is much harder to debug with the usual methods.

Just a remark: usually smart compilers can guess what is the best option (inline or function) on their own also for non-inline functions. So you can also trust the compiler in 90% of the cases


How do I pull up D1-D6 using 10k ohm resistors?

Typical Atmel AVR inputs can “float” when left open, that is, may drift high or low.  The idea of a pullup or pulldown resistor is to give an otherwise-open input a definite value – high if pulled up, low if pulled down.

The values of pullup and pulldown resistor values are a tradeoff:   You can use high values to minimize the current that a sensor device must overcome when it switches values, and to minimize power loss in a battery-powered device.  Or you can use low values to get faster switching when you release the input.

There are built-in pullup resistors on most AVR inputs.  (But A6 and A7 on some models of ATmega328's don't have pullups.)  To use a built-in pullup, initialize the input pin with (for example) pinMode(mypin, INPUT_PULLUP) instead of pinMode(mypin, INPUT).

To sense the state of a simple normally-open switch, you would connect one side of the switch to an input, and the other side to ground.  Initialize the pin to be a pulled-up input: eg, pinMode(mypin, INPUT_PULLUP).  Regard the switch as not-pushed when digitalRead() shows HIGH, and  pushed when it shows LOW.

If you really want to use external pullup resistors, connect the switch as above – one side to ground, one side to a pin – and connect a resistor between +5 V and the pin.  That is, one end of a resistor and one side of a switch will connect to the input pin.  In this case, use either INPUT or INPUT_PULLUP as the pinMode setting; it makes no big difference because the internal pullup resistor has a fairly high value, eg 40 KΩ.


Sending MPU6050 data over serial to Java/C# Program

You may find RXTX java library helpful.

You can format the data (float as calculated at Arduino side) in any mannner that you desire. RXTX library will send the data. It will then up to the Java program (non Arduino side, like PC, etc.) how to interpret the data and extract the values.

http://playground.arduino.cc/interfacing/java

Hope this helps


How to wire and use a L6219 motor driver

If you want an idea of how to connect it there is a nice instruction for the evaluation board complete with a schematic. You will find it here.
https://static5.arrow.com/pdfs/2008/03/06/semi_ap/manual/st/ds/an6219eval.pdf If you go to: https://www.datasheetarchive.com/l6219%20microstepping-datasheet.html
you will find a lot of Links to more information. I believe this was designed originally as an automotive part. This is IC form is not a plug and play, you will need to do more research to better understand it. It looks like it could be a fun project and you could tell us exactly how to use it.  It should work fine with most 5V I/O Arduinos such as the Uno and Nano.


Sending Multiple Information from BNO055 IMU to BridgeClient on Yun

Apparently the solution to my problem was a simple client.println() after my JSON was ready to be printed to the BridgeClient.

Snippet:

root.printTo(client); client.println();

where root is DynamicJsonBuffer from the ArduinoJson library. The client.println() would immediately print \n and this would be read by the readline() python code.


Digital Comparator with ATTiny85 doesn't behave as expected

You have to assign the status of all output pins in each of your "if statement" conditions. Think of it like 'if that happens, I want x, y, & z to be ON, and a, b, & c to be Off'. Unchanging the HIGH status of one output will remain that output HIGH for all conditions. Output pins never change their statuses untill they have an order "your code" to do this. Also you have to replace your code inside a loop function to repeat your code without the need to manually reset your ATTiny.

Assuming LED1 = pinOut1, LED2 = pinOut2, LED3 = pinOut3.
You have to replace "if conditions" in your code by the following:

while( 1 ){
    int a = digitalRead(PinA);
    int b = digitalRead(PinB);

    if ( a == b ) {
        digitalwrite (pinOut1 , HIGH);
        digitalwrite(pinOut2,LOW) ;
        digitalwrite (pinOut3, LOW);
    }
    else if ( a == HIGH ) {
        digitalwrite(pinOut2,HIGH) ;
        digitalwrite(pinOut1,LOW) ;
        digitalwrite(pinOut3,LOW);
    }
    else if ( b == HIGH ) {
        digitalwrite(pinOut3,HIGH) ;
        digitalwrite(pinOut1,LOW) ;
    digitalwrite(pinOut2,LOW);
    }
}

Also according to your application speed requirements, you can add a delay of about 300 ms before reading your digital inputs to allow the user to change the status of these digital inputs.


Arduino is incorrectly reading serial input from C# program

Your Serial receive code is not correct in some ways:

You should only read from Serial, if there is really something to read. For the first read, that is not the problem, since you checked against the return value being -1 (which is the return code for "there is no new data in the buffer). But after that, you read without ever checking, if there is something to read. You need to understand, that the data is really send serially. The bytes come in one after another and there is no concept as messages on the Serial interface (which is actually called UART in non-Arduino environments). More over, there might be small pauses somewhere in the transmission, since you cannot foresee, when exactly the PC will send the data (the PC has a bunch of other tasks to do, too). So it might be, that you have received one byte, which will lead you into the if statement, but the rest of the data will arrive later. All data is then read as -1, since there is no data in the buffer.

You have to check, if there is actually data to read, before reading. This can be done with Serial.available(). It will return the number of new data bytes in the buffer. For example, if you want to read 8 bytes, you should wait, until at least 8 bytes are inside the buffer by using if(Serial.available >= 8).
You are sending the data from the PC as ASCII encoded text. That means, that every number above 9 consists of multiple data bytes. The 4 values, that you are interested in, are all over 200, which means, that you need to read 3 bytes to get them. But you only call Serial.read() once for every value. That will give you the first digit, which is a 2 for all values in the shown data. More over, since you only read 1 byte, where there is the whole number (which may be multiple bytes) plus 1 or 2 bytes for the new line (depending on the chosen line ending \n or "\n\r"), The whole reading gets misaligned to the data structure. Now the read data (if there is any) is also dependent on how much data was send for the values before.

Keep in mind, that with ASCII encoded text, you may need multiple Serial.read() calls to actually read a full number. I will describe the way to go here in the next point.
As I already mentioned above, there is no message protocol on the Serial interface. Lost data would lead to misalignment and thus garbled data. But you can impose an own protocol onto the Serial stream of data. It is a good practice, to first receive a full message (maybe with multiple data values inside it) and then process it. For that I would suggest a new data structure

mode|number of colors|blend speed|beats until color change|Red|Green|Blue|Brightness\n

The new line is here realized only with a newline character (\n). The values are separated with a vertical dash. You should put an if(Serial.available()>0) into your loop function. Then inside that if statement, you read one character and add it to a buffer. If you read the \n character, you start to process the buffer. You can then convert one value after another from the buffer and save them into variables. After that, you clear the buffer. You can see this style in the SerialEvent example, that comes with the Arduino IDE. You should also read Majenko's blog article about reading the Serial interface on the Arduino.

That said, you should be cautious with using String object on the Arduino. Sure, Strings are convenient, but they dynamically allocate the needed memory during the runtime. On microcontrollers, which normally have very limited RAM memory, that can lead to heap fragmentation (heap is the memory area for dynamic memory allocation). When using String objects, the underlying buffer get's often recreated. As buffers get allocated and deleted later, that can lead to small memory areas, which are unused, but to small to actually be used by the buffer. You can fill up your RAM very fast with that.

It is better to not use String, but directly a char array with a fixed length. Majenko also wrote an article about the String problem: The Evils of Arduino Strings


Possible to store variables directly in EEPROM?

Writing and reading EEPROM is possible to do without a library. Take a look at the datasheet of the ATmega328P to find an example: On page 25 / 26 there are example codes for reading and writing both in assembler and C. They do wrap it in a function but as I said in a comment if you only have place in your code where you would like to access EEPROM you can put the code there without duplication. These functions write and read one byte at a time, so if you want to store larger datatypes (a 16-bit integer for example) you already need to call the routines more than once.

Note that the EEPROM has a limited life cycle of at least 100,000 write/erase cycles (cells must be erased before they can be written, reads are unlimited) and it is considerably slower than SRAM (typ. 3.3 ms for writing a byte). You also need to make sure no interrupts interfere with the write process.

However, in the sense of the question it seems this is not what you want: You cannot just create a global variable and have it magically being written to EEPROM.


How to send keystroke with shift modifier?

I never used this library, but in the header file there are this constants for modifiers:

#define MOD_CONTROL_LEFT    (1<<0)
#define MOD_SHIFT_LEFT      (1<<1)
#define MOD_ALT_LEFT        (1<<2)
#define MOD_GUI_LEFT        (1<<3)
#define MOD_CONTROL_RIGHT   (1<<4)
#define MOD_SHIFT_RIGHT     (1<<5)
#define MOD_ALT_RIGHT       (1<<6)
#define MOD_GUI_RIGHT       (1<<7)

and a function

void sendKeyStroke(byte keyStroke, byte modifiers)

so I would use this to send a key with Shift like this

sendKeyStroke(KEY_F2, MOD_SHIFT_LEFT);


Any possible way to stack Motor Driver shield L293D with Xbee Shield v03 on arduino?

Read the documentation for both boards. They should list the pins used. Their associated libraries will define variables to which you can assign non-conflicting pins. Review the sample code provided as well. Usually, the sample code included setting the pins to use, even if the code only sets them to their default.

There is another possibility. I don’t think this is the case, but I’ve run into this issue with different shields. If the shields use I2C, they may need to have jumpers shorted to set an address.


You can send a file, byte after byte, using Serial.
On the Arduino side, you parse serial communication and put bytes inside an array. At the end, you reconstruct the file.


ESPAsyncWebServer how do you escape the % character?

You'd use %% to get a single % as output.

From the source code: double percent sign encountered, this is single percent sign escaped.


Arduino EEPROM retains old data after flashing with a new program

Flash isn't EEPROM. When you reprogram the flash it doesn't touch the EEPROM.

It's controlled by the -U... flag to avrdude:

avrdude ... -Uflash:w:<hex file>

If you want to set the EEPROM to something specific you can use avrdude to program an EEPROM file if the bootloader supports it (not sure it does, so you may need a programmer for it):

avrdude ... -Ueeprom:w:<hex file>


What are the best GPIO pins to use for my project?

NodeMCU and "Wemos D1 R2 and Mini" esp8266 (esp-12) pins and io overview

Serial

RX io3 RX0

TX io1 TX0

boot config pins with pullup or pulldown on board

D3 io0 PULLUP (LOW for boot to flashing mode)

D4 io2 TX1 PULLUP (Serial1 TX. no RX for Serial1)

D8 io15 PULLDOWN (SS pin if esp8266 is SPI slave); TX if Serial.swap()

untroubled GPIOs with optional function for I2C or SPI bus:

D1 io5 default pin for I2C SCL

D2 io4 default pin for I2C SCA

D5 io14 SPI CLK

D6 io12 SPI MISO

D7 io13 SPI MOSI; RX if Serial.swap()

RTC pin for timed deep sleep wake-up (if connected to reset pin)

D0 io16 - optional internal pulldown, internal pullup not available

not useable: on NodeMcu Sx pins io 6 to io 11 connect QIO SPI flash memory
(in a very special setup the SPI bus can be used with other SPI device)
(in other very special setup the QIO pins can be used as gpio)

note: most digital IO start as INPUT_PULLUP


I just found the answer here : https://www.avrfreaks.net/forum/atmega32u4-arduino-leonardo-strange-timer-behavior

It seems that the USB connection generates higher-priority interrupts. I still don't know why the interrupts do work at higher frequency.

Solutions include powering the board from a USB charger or other power source rather than through the computer USB or adding the following code before the interrupt enable :

// Clear usb interrupt flags
USBINT = 0;
UDINT  = 0;
for (uint8_t i = 0; i < 6; i++)
{ // For each USB endpoint
    UENUM = i; // select the _i-th endpoint
    UEINTX = UEIENX = 0; // Clear interrupt flags for that endpoint
}

Thanks to those who helped me !


Can arduino create a file in its memory?

To answer the original question: Basically, yes, you can write libraries to implement a file system using the memories of an embedded microcontroller.
However, if it's feasible highly depends on the controller architecture and its peripherals.
Some of them (e.g. the one on Arduino Due) allow Flash reprogramming while an application is running from Flash.
Others require to have the application running in a special boot block or even in RAM when accessing the Flash for writing (this should be the case on an Arduino Uno)
And others don't allow Flash accesses from application at all.

Anyway:
The use of this for your purpose is very little, because the interface to the PC would also have to support the file system (for example, you could implement a FTP server and use an Ethernet connection...).
Therefore, the SD card approach is surely a very good suggestion.


Serving binary file with ESP8266WebServer

It looks like you can use the send_P function to send raw PROGMEM data:

void send_P(int code, PGM_P content_type, PGM_P content, size_t contentLength);

I.e., (from what I can gather):

PGM_P favicon = {
  0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x10, 0x10, 0x00, 0x00, 0x01, 0x00,
  0x18, 0x00, 0x68, 0x03, 0x00,......... 0x00
};

server.send_P(200, "image/x-icon", favicon, sizeof(favicon));

Incidentally, PGM_P is just a typedef for const char *.


Is volatile qualifier needed if shared variable cannot be changed externally during complete function call?

Declaring a variable as volatile tells the compiler, that it always has to read the real variable and that it cannot use a cached value. Also the compiler cannot optimize this variable, since it is unknown, when the variable will change. For this it is irrelevant, how you actually read the variable in the main sketch, it only matters, that it get's read. Also this has nothing directly to do with doing the read atomically (with noInterrupts()) (though you only garantee correct values, when doing it)

So yes, you need to declare it volatile, or the compiler might think, that the value doesn't change and optimize it out in some way.

  What is the context in which the compiler expects a variable to not be changed externally if it is not declared volatile?

Externally here means outside of the main routine. This covers variables, that get changed in ISRs and also registers, that are changed by hardware (so the register definition in the used core are also volatile). The compiler cannot know, when these changes happen, because they are triggered by the hardware, not by the code. It will try to optimize your sketch (which is a rather complex procedure), and might see, that your variable is never changing in the code (the ISR does not get called from the main sketch, thus the compiler does not see it getting called) and will try to optimize it. To ensure, that your sketch works properly, it is your task to tell the compiler, that this variable can change at any time (so that it does not think the other way). You are doing this by declaring it as volatile


Can Arduino Sketch be used for production

There's a lot of controversy on this issue, but if it works for your needs, absolutely do it!
Basically, there are 2 questions you have to answer:

Should I use actual Arduino boards in production?
The answer is generally "no", simply because you need to customize the boards to add components to support your project, and to make them more robust, and cheaper, if possible. So, use an Arduino schematic as a guideline, then modify it to suit your needs.
One big exception to this, however, could be if you create a "mother board" onto which you will plug in a "daughter board" such as an Arduino Nano, Pro Mini, Pro Micro, or similar. You could make the Nano removable by soldering male headers onto it, and female headers onto the main "mother board", then you just plug in the Nano into the headers on the main board. Or, you could make it permanent by soldering male headers onto the Nano and then also solder that straight onto the "mother board" directly into the holes where female headers would otherwise be soldered. Both of these are great options, and this vastly simplifies your design and assembly process as you learn to get started manufacturing. Legal Arduino Nano clones are ~$1~$4 each, with shipping, on Ebay, and Pro Minis (not as good--here I recommend the Nano) are about the same, so buying a pre-made Nano is generally cheaper than buying just the raw chips on the Nano anyway, oddly enough. And again, this vastly simplifies your design and makes designing and assembling boards and products much much easier for the beginner/entry-level manufacturer (you) or micro business. It also allows you to make hand-made boards using perf-boards or proto (prototyping) boards, as I show in my other answer here.
For designing your own board, I recommend KiCad, which is Free and Open Source, and no cost ("free" == "free to modify"; "free" != "no cost"!), and actively developed by a volunteer team of about 6 people on a daily basis (I'm on their mailing lists and see this daily). It is a great product and is highly-capable. It is used by hobbyists and professionals alike, and has been used on many professional products world-wide. CERN, Arduino, and DigiKey have all contributed to KiCad in one way or another (see the list here: https://kicad-pcb.org/about/kicad/). The CERN Open Hardware Repository states here:

We think that KiCad can do to PCB design what the gcc compiler did to
software: ensure there are no artificial barriers to sharing so that design and
development knowledge can flow more freely.

That's an incredibly exciting mission!
There is also Autodesk Eagle, which is also popular among hobbyists and small businesses. It is a paid product, but has a no cost version for hobbyist, non-commercial use. It is also actively developed, by a tiny team of paid software developers on a pier in San Francisco. I've been to their office, and they are very excited about their work on it. They are doing a great job at making it a more-professional product. They've made some great improvements to Eagle over the last few years, hence why its price has gone up. It is also a great product.
Both products work on Windows, Mac, and Linux.
The Arduino board schematics are open-source hardware, so follow the licenses and provide attribution to where your design stemmed from. Ex: here's the Uno schematic. It shows the CC BY SA license logo at the bottom. I don't see a license version, but if it's 1.0, here's that license in plain terms. So, if you copy parts of the original schematics, release your design under the same license, and give credit to the original design.
You can NOT, however, use the Arduino logo or name. Those are trademarked and copyrighted, respectively. Arduino clones which do NOT use the Arduino name or logo are legal, and any clones which DO use the Arduino name or logo are illegal. There's no excuse for making an illegal Arduino clone. The schematics are intentionally open-source.
See also: Since Arduino uses Creative Commons licenses, do I also need to do that on my product?

Deriving the design of a commercial product from the Eagle files for an Arduino board requires you to release the modified files under the same Creative Commons Attribution Share-Alike license. You may manufacture and sell the resulting product.

And: Can I design my own Arduino board and sell it?

Since the hardware designs of Arduino are open source it is allowed to copy and further develop them. However this is not the same thing as making an Arduino board, only the company Arduino can design and produce Arduino products.
Your finished product is a product compatible with Arduino which should have its own name and brand. In case a copy uses the Arduino name and/or logo on it, this board is no longer a copy but a counterfeit which is illegal to manufacture and produce.

Should I use the Arduino software (build system and core libraries, and my program / "sketch") in production?
The answer is generally, "yes". This may be using the IDE for building or using the Arduino CLI command-line build interface.
The Arduino core and build system works great and has tons of internal and 3rd-party library support. The Arduino IDE itself is released under the GPL license (see below), and the core libraries are LGPL-licensed, which means if you modify them for your project, and put your project result into someone else's hands, you MUST release your modifications you made to the core code and libraries to those who have your project in their hands. See the main license file here:

this file includes licensing information for parts of arduino.
first, the gnu general public license, which covers the main body
of the processing/arduino code (in general, all the stuff inside the 'app'
and 'core' subfolders).
next, the gnu lesser general public license that covers the arduino core
and libraries.

But, you can keep your programs/"sketches" and main bits of project closed-source if you wish. Your programs are your own. They are copyrighted solely by you and you can license, use, and/or sell them however you wish. This includes the right to sell your Arduino/C and C++ programs as software or as firmware within a commercial product.
As a matter of fact, the GPL and LGPL licenses on the Arduino IDE and source code even allow you to sell the Arduino IDE and source code itself if you wish! This is really important, and is a fundamental right that "free and open source" software grants you. The Free Software Foundation, which is the owner of the copyrights on the license text itself, and the author of the GNU GPL and LGPL and other free and open source licenses, has this official guidance about selling and even reselling free software (they strongly encourage it!) (italics added):

Selling Free Software
Some views on the ideas of selling exceptions to free software licenses, such as the GNU GPL are also available.
Many people believe that the spirit of the GNU Project is that you should not charge money for distributing copies of software, or that you should charge as little as possible—just enough to cover the cost. This is a misunderstanding.
Actually, we encourage people who redistribute free software to charge as much as they wish or can. If a license does not permit users to make copies and sell them, it is a nonfree license. If this seems surprising to you, please read on.
The word “free” has two legitimate general meanings; it can refer either to freedom or to price. When we speak of “free software”, we're talking about freedom, not price. (Think of “free speech”, not “free beer”.) Specifically, it means that a user is free to run the program, study and change the program, and redistribute the program with or without changes.
Free programs are sometimes distributed gratis, and sometimes for a substantial price. Often the same program is available in both ways from different places. The program is free regardless of the price, because users have freedom in using it.
Nonfree programs are usually sold for a high price, but sometimes a store will give you a copy at no charge. That doesn't make it free software, though. Price or no price, the program is nonfree because its users are denied freedom.
Since free software is not a matter of price, a low price doesn't make the software free, or even closer to free. So if you are redistributing copies of free software, you might as well charge a substantial fee and make some money. Redistributing free software is a good and legitimate activity; if you do it, you might as well make a profit from it.
Free software is a community project, and everyone who depends on it ought to look for ways to contribute to building the community. For a distributor, the way to do this is to give a part of the profit to free software development projects or to the Free Software Foundation. This way you can advance the world of free software.
Distributing free software is an opportunity to raise funds for development. Don't waste it!
In order to contribute funds, you need to have some extra. If you charge too low a fee, you won't have anything to spare to support development.

This is only the first portion of their stance on the topic. Read the rest of the Free Software Foundation's encouragement to sell free software here.

That's the gist of it.
I am not a lawyer, and even if I was, none of my words herein are official legal advice.
When words come from the Free Software Foundation, who authors the GPL and LGPL licenses, however, those words are automatically extra legitimate.
Related:

Using Arduino for Industrial process
LGPL and Arduino in Commercial Products


All prices in USD w/ free shipping.

FT232RL breakout board:

Aliexpress: $1.55
eBay: $1.81

They are probably counterfeit. A Windows driver update (AKA "FTDIgate") at one point "bricked" them but I'm not sure that's an issue anymore. Even if it is it's Windows only and easy enough to work around. I've used these for years on Windows and they work fine for me.

If that's still beyond your budget there are a few other common options. I haven't used these breakout boards but I do have quite a few boards that use the CH340G and they work perfectly once you install the driver. There's a decent chance some of these will also be counterfeit. Some didn't break out the DTR/CTS pin for auto reset but if you're on such a low budget maybe it's worth it to you to press the reset button on every upload to save a few cents. They may not have the standard FTDI header pinout and if so would require you to use jumpers to connect them to the Pro Mini rather than plugging directly into the header.

PL2303 breakout board:

Aliexpress: $0.50
eBay: $0.74

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

CH340G breakout board:

Aliexpress: $0.72
eBay: $0.93

These don't appear to break out the DTR or CTS pins so they won't do auto-reset.

CP2102 breakout board:

Aliexpress $1.00
eBay: $1.31


How to keep warm arduino uno board with 12v dc supply

See Can I use arduino's 3.3 V output directly to esp8266?

From that page:

  The specs for the Uno say that it does not provide as much current on the 3.3V line as the specs for the ESP8266 requires. You will need to provide another regulator that can supply enough current.

Also, putting 12V into the barrel jack is making work for the on-board voltage regulator (located near the barrel jack) because it has to convert 12V to 5V (making heat in the process). You would be better off putting a lower voltage into the barrel jack, ideally around 7V (but not lower).

Alternatively, just power through the USB port as you have been, and plug the USB cable into a USB charger.

To summarize, both the 5V and 3.3V voltage regulators are probably working very hard, thus getting hot.


Why is dtostrf() not working for this one value?

What is happening is that the variables you declared for mqttTemp etc are stored in memory something like this

variable   memory address
mqttPres @ 1000-1004 (5 bytes)
mqttHum  @ 1005-1010 (6 bytes)
mqttTemp @ 1011-1015 (6 bytes)

For a start, you only have enough room (with the mandatory NUL byte string terminator) for 4, 5 and 5 characters

When you convert pressure, the NUL byte is being placed as the first byte in mqttHum, therefore, when printing mqttHum you get an empty string output (since the first byte is NUL)

To really see what's happening, here's some code that illustrates the issue

char mqttTemp[6] = "TTTTT";
char mqttHum[6] = "HHHHH";
char mqttPres[5] = "PPPP";
void setup() {
  float temp = 25.57;
  float hum = 40.15;
  float pres = 97684.39;

  Serial.begin(74880);
  // put your setup code here, to run once:
  delay(100);
  Serial.println("before");
  printThem();
  dtostrf(temp, 4, 2, mqttTemp);
  Serial.println("converted temp");
  printThem();
  dtostrf(hum, 4, 2, mqttHum);
  Serial.println("converted hum");
  printThem();
  dtostrf(pres, 5, 0, mqttPres);
  Serial.println("converted press");
  printThem();
}
void printThem()
{
  Serial.print("mqttPres ");
  Serial.print((unsigned long) &mqttPres, DEC);
  Serial.print(": ");
  for (int i = 0; i < 5; i++) {
    Serial.print((int) mqttPres[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttHum  ");
  Serial.print((unsigned long) &mqttHum, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttHum[i], DEC);
    Serial.print(' ');
  }
  Serial.println();

  Serial.print("mqttTemp ");
  Serial.print((unsigned long) &mqttTemp, DEC);
  Serial.print(": ");
  for (int i = 0; i < 6; i++) {
    Serial.print((int) mqttTemp[i], DEC);
    Serial.print(' ');
  }
  Serial.println();
}

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

}

The above outputs the following:

before
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 84 84 84 84 84 0
converted temp
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 72 72 72 72 72 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted hum
mqttPres 1073644748: 80 80 80 80 0
mqttHum  1073644753: 52 48 46 49 53 0
mqttTemp 1073644759: 50 53 46 53 55 0
converted press
mqttPres 1073644748: 57 55 54 56 52
mqttHum  1073644753: 0 48 46 49 53 0
                     ^ ======== note the leading 0
mqttTemp 1073644759: 50 53 46 53 55 0

The simplest fix, of course, is to declare your variables with the correct size

char mqttTemp[7]; // because -10.00 takes 6 characters + 1 for NULL
char mqttHum[7];  // because 100.00 takes 6 characters + 1 for NULL
char mqttPres[6]; // because 97684 takes 5 characters + 1 for NULL - if pressure can reach 100000 then use 7 here as well

and then use dtostrf correctly, i.e. the second argument is the total width, including . and a possible -

dtostrf(temp,6,2,mqttTemp);
dtostrf(hum,6,2,mqttHum);
dtostrf(pres,5,0,mqttPres);


I would like to add a RGB led strip to my arduino alarm system

An interesting problem with the Arduino paradigm is that not only do you need basic programming knowledge but you also need basic electronics knowledge.

On the plus side, there are plenty of good tutorials where you can over look these issues if you follow the tutorials step by step.  That is, get exactly the same parts and wire them up exactly the same way.  Later, if you like, you can go over the tutorial, ask questions here and discover how and why what you did works.

In your diagram:

You are implying you are using ordinary Red, Green & Blue LEDs and are going to vary their brightness using the Arduino's Pulse Width Modulation feature.

Possible problems:

You are powering the LEDs from the 9 volt pin of the Arduino.  And the LED strip in the diagram is clearly marked 12 volts.  This may work.  But is out of specification.

Also, this setup makes the assumption you are powering your Arduino with a 9 volt wall power supply.  Are you?  You could also power the Arduino with 5 volts using only the USB cable.  There would then be no 9 volts available at the 9 volt pin.  (I would avoid plugging in both power sources at the same time.  I think the Arduino design has changed over time.)

You are using a strip of Red, Green & Blue LEDs.  Which implies more than 1 of these Red, Green & Blue LEDs.  There is an upper current limit on the outputs of the Arduino.  More LEDs means more current.  Too many LEDs will damage the Arduino.  I would stick to 1 LED until you research the amount of current 1 LED takes verses the upper current limit of an Arduino output pin.


Put the address in EEPROM. It's still "on the chip" but it can be programmed independent of the flash, and can be changed on the fly if deemed appropriate.


You may not want to hear this, but the cheapest option would be an SD card, or a micro-SD card. You could solder it into place, thus making it quite hard for the end user to take it out and plug it into a reader.

Imagine you had this micro-SD card glued onto your board (making it hard to remove in the first place):

It isn't particularly obvious what it is, unless you recognize the shape. You could cover it with a blob of plastic to hide that. Then with the SPI wires soldered to the contacts, removing would be even harder.

That gives you gigabytes of storage, a file system, the works. And all for a few dollars.

A technically sophisticated user could probably prise it loose and get at the data (although if you used strong glue this could be quite hard) but they could also get at the contents of another storage chip too.


Will Intel Atom Processor laptops support cloned a Arduino with CH340 driver?

The processor in your laptop is irrelevant. It is the operating system you should be thinking about, not the processor.

If the operating system has drivers for the CH340 chip, and Windows does, as you already know since you are using it already, then you already know that the answer is a big fat yes.

The only time you need to worry about if the processor will support something is when you are switching to a completely different archetecture such as ARM.


The nRF8001 can not run custom code, so you need an external microcontroller to use it. However, the nrf5 series (for example nrf51822) has a microcontroller and can run custom code.

Nrf5 is Arduino compatible thanks to sandeepmistry's nrf5 arduino core.

You will need a programmer though, since the nrf51822 uses swd programming. References to recommended programmers are available here.


I think I managed to make a little circuit that should prevent you from burning up your Arduino.

From what I read you shouldn't connect MOSFET directly to Arduino. Imagine that MOSFET has a little capacitor inside it, and in the beginning that capacitor can take such high current that actually can burn the Arduino pin. Instead you use a simple NPN transistor (with 100kohm resistor) as a "switch". The NPN can survive much higher current, and it will not strain the Arduino pin.

When I simulated this setup using the default "blink" sketch the light bulb was lit when PIN13 was HIGH. Just note that there always is a small voltage drop (think of it as a resistor inside the MOSFET) and it can make the MOSFET get a little warm. In your setup it should not be a problem, but in some cases it's nice to screw a radiator on the MOSFET.


AccelStepper Library: How do I go to a position without decelerating?

AccelStepper, as hinted by the name, uses acceleration always. By setting the acceleration high, you reduce the amount of time spent accelerating to the set speed.

setAcceleration() sets the rate in steps per second per second. If your MaxSpeed is 200 steps per second, then setting the acceleration to 200*10 means all acceleration is over in 1/10 second. You can go higher, etc.


Can I use a GPS from old Garmin with an Arduino?

The short answer is NO, unless you have solid experience with microelectronics.

Finding documentation for a module you take out of a commercial device is hard to impossible. Chances are, that module is specific to Garmin, and even if it isn't, it's certainly EOL by now, with no support whatsoever.

Even if you do find the spec, there is a high chance that you'll have to write a software library to support it on Arduino. Don't expect the supplier to share the code they gave to Garmin.

Finally, to put together and debug this project, you will need quite some equipment:

oscilloscope to debug the electrical interface
soldering station to solder small pins properly

Like people said in comments, this equipment alone will cost much more than a brand-new GPS receiver.


Nick Gammon correctly points out a problem due to an extra semicolon, but you should also note what the construct else(s < n) is doing.  When the if condition that this else gives an alternative to is false, the statement   (s < n) gets executed.  That statement is an expression statement, and its value is the evaluation of s<n, either true or false.

If the semicolon after (s < n) weren't there, you'd get a compile error because (s < n) serial.println("north") is not a valid statement.  You may have meant to say else if(s < n) instead of else(s < n).

Note, in the sequence

if (e > w)
   Serial.println("west");
else if (e < w)
   Serial.println("east");
else if (s > n)
   ...

that last else typically is reached only rarely, because the only condition to get to it is e and w being equal.  Due to sensor noise and signal processing noise, the chance of e and w being equal is probably at most a few percent.

If your north/south test sequence is supposed to be independent of your east/west test sequence, leave out the second if and second else .  That is, instead say:

if (e > w)
   Serial.println("west");
else
   Serial.println("east");
if (s > n)
   ...


bitClear doesn't work on most significant bit

uint32_t data = 0xFFFFFFFF;
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 30);
Serial.println(data, BIN);
data = 0xFFFFFFFF;
bitClear(data, 31);
Serial.println(data, BIN);

On my mega outputs:

11111111111111111111111111111111
10111111111111111111111111111111
1111111111111111111111111111111

Are you sure you aren't mistaking the fact that println doesn't print leading 0's for the number being nothing but 1's? Try printing as hex, then all the numbers will be the same width:

FFFFFFFF
BFFFFFFF
7FFFFFFF


Disable interrupts when doing critical things?

John Romkey provided you an excellent answer. I am adding this just to
provide another perspective, hopefully complementary.

Interrupts are meant to handle the most time-critical tasks. Those tasks
that cannot wait for the next loop() iteration, such as counting a
pulse from an encoder, or getting a byte out of the UART receive buffer.
If you delay them too much, they may miss their deadline, resulting in
unreliable operation of the whole program (counter missing pulses, UART
missing bytes...).

Sometimes you have a piece of code that cannot afford being interrupted.
Maybe it is extremely time-critical, like the generation in software of
a pulse that is exactly 0.5 µs wide. More commonly it will be
reading data from memory that is being modified by an interrupt handler,
and you don't want that data to be modified in the middle of the read
operation. Such pieces of code are called critical sections, and you
keep them safe in between noInterrupts() and interrupts(). If an
interrupt request fires while the program is running a critical section,
the request is put on hold and serviced only when the critical section
is done. This adds some latency to the interrupt which, if
excessive, can lead to the interrupt missing its deadline. This is the
reason critical sections should be kept as short as possible.

You have been told that interrupt handlers should be kept as short as
possible, but I am not sure you know why it is so. The fundamental
reason is that interrupt handlers are themselves critical sections.
While a handler is running, other interrupts are blocked. On some
architectures (notably not AVR, I don't know about the ESP), only
interrupts of lower priority are blocked, but it is still an issue. The
rationale for keeping those handlers short applies equally to any
critical section.

Now, just to provide an example of the sort of bad things that can
happen if you block interrupts unnecessarily, consider this piece of
code:

noInterrupts();
Serial.println("Inside critical section.");
interrupts();

What this does is put the string "Inside critical section." in a
software buffer. Not a huge task you may say. Actually pushing the bytes
out to the UART is the job of an interrupt handler, triggered by the
UART when it is ready to accept a new byte. But then what happens if
there is not enough free space in the buffer for the string? In this
case, Serial.println() waits in a busy loop. It waits for the
interrupt to move bytes out of the buffer and make space for the new
string. But wait, we have just disabled interrupts... See the problem?
This is the reason it is generally advised to never Serial.print()
inside an interrupt handler. The same applies to any critical section.

Edit: As Juraj points out in a comment, the HardwareSerial code
now implements a workaround against this problem: if it
detects it has to wait with interrupts disabled, it takes care of
calling the interrupt handler itself. This is a (relatively) late
addition to the HardwareSerial code. Their authors presumably
witnessed too many beginners doing debug prints from interrupt handlers
and being bitten by this issue. Note that it is a workaround, not a
solution: it will often make the critical section last for an
unreasonably long time.

I wouldn't rely on similar APIs, or even on other cores, systematically
implementing this kind of safeguards though: some library authors just
trust the user to not do silly things.


status whether the switch is connected to arduino or not?

The simplest way, as @jsotola has said, is to put a resistor across the terminals of the SPST push-button and read the voltage using an ADC input of the MCU.
However, the resistor needs to be bonded to the push-button (or inside the push-button housing) to ensure that when, for example, a vandal rips the push-button out of your switchboard, the resistor is certain to go with it so that the MCU can tell the difference between HIGH, LOW, and MISSING as @EdgarBonet pointed out. You also need to consider the continuous current draw of the extra resistor for low power/battery devices. You could increase the resistor values, but that tends towards weak pullup/pulldown. If you increase the value of only the extra resistor, it shifts the output voltage closer to the rail voltage reducing the margin for error.

Figure 1 – SPST Push-Button AWOL Detector.
Perhaps a better, but more expensive way, is to use a SPDT push-button. This push-button requires no modification, but is more expensive than a SPDT push-button and requires an extra wire and resistor. This circuit draws less continuous current and has stronger pullup/pulldown.

Figure 2 – SPDT Push-Button AWOL Detector.


What's the difference between DDRB and pinMode?

DDRB

is a register. Exactly: Port B Data Direction Register. See datasheet for ATtiny, chapter 10.4. Register Description and 10.2.1 Configuring the Pin. This part will explain why

  DDB0

value was used.
Using this way of setting direction of a pin is much faster than  pinMode(0, OUTPUT);
The possible problem is when you want to use same code to program different Arduino. In this case you have to remember to check all direct registers operations.


Combining 2 IF statements, getting nowhere and pulling hair out! ;)

If you want to do something when two or more conditions meets , use an and operator (&&), like this:

if (h < humLowTrigger && now.hour() == 15 && now.minute() == 5) {
... do something ...
}

If you have a lot of conditional statements, you can simplify:

if (h < humLowTrigger) {
   if (... other conditions 1 ...) {
     do something 1
     }
   ...
  if (... other condition n ...) {
     do something n.
     }
}

In your specific case:

if(h < humLowTrigger) {
  if (now.hour() == 15 && now.minute() == 5) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 8) {
    digitalWrite(A2, LOW);
  }
  if (now.hour() == 15 && now.minute() == 10) {
    digitalWrite(A2, HIGH);
  }
  if (now.hour() == 15 && now.minute() == 12) {
    digitalWrite(A2, LOW);
  }
}

Better version

But there is a problem with the previous code, beacuse the mister must turn off no matter what the humidity level is.

// Turn on only if humidity below threshold.
if (h < humLowTrigger && now.hour() == 15 && (now.minute() == 5 || now.minute() == 10)) {
    digitalWrite(A2, HIGH);
  }
}
// Turn off always.
if (now.hour() == 15 && (now.minute() == 8 || now.minute() == 12) {
    digitalWrite(A2, LOW);
   }


invalid conversion from 'char' to 'const char*'

What do your prototypes look like? I suspect that the compiler thinks that it is calling the first instance of functionA() and is trying to cast '0' to a 'const char *` and that isn't going to work…

If you don't have prototypes for both signatures, then adding the second one may solve your problem. If you do, I'm puzzled.


You should always connect something to an input to pull it high or low when no signal is present.  The simplest thing is to activate the built-in pullup resistor, which will result in the input returning HIGH when there is nothing connected.  If that's not compatible with your particular use, add a resistor from the input to ground (10k-100k is fine) so that it will return LOW when nothing else is connected.  If the input is just floating, it is susceptible to noise causing random state changes. The input impedance is very high (100 Meg) so it can pick up static and other mischief.


Without an ethernet shield or some kind of other internet connectivity shield/circuitry you cannot communicate directly with the internet through the arduino. However, if having a computer as the internet communicator isn't a problem you could try a setup like:

arduino->serial (usb)->processing->internet

This way you create the internet packet in processing using the temperature information received through serial from arduino.

see also https://processing.org/


SoftwareSerial esp8266(0,1)

You can't use pins 0 and 1 for software serial since they are the hardware serial Serial than you use for communication with the PC.

Pick two other pins to use.


Use ESP8266 as WiFi client connected to Arduino Pro Mini

Ditch the Pro Mini.  Upload your Arduino code to the ESP directly. There's a GitHub repo with the details. ESP for Arduino IDE has a ton of libraries. I'm sure you'll find it there.

But if you're bent on using the Pro Mini,  you'll have to use AT commands over serial to control it or flash a custom firmware into the ESP using Lua or something. And Pro Mini can use its hardware serial just like a Uno does.


Adding button which resets to top of void

As currently written, your changeLights() function, which is repeatedly called over and over again by the Arduino loop() function, runs a timed sequence of lights.

Red light is on for 3000 ms
Amber is on for 3000 ms
Green is on for 3000 ms

This sequence could also be implemented using a state machine, but as it is right now, it's just a simple sequence of operations.

So now you have a new feature request (heh, this happens all the time in pro software development):

hardware will include a momentary switch to ground
when the switch is pressed, the changeLights() sequence will skip to the next Red light
we might also want to do other kinds of sequence change, not just reset

The simplest way to code this would be to use digitalRead() to test whether the switch is pressed. You could test just after each of the delay(3000) calls. Technically this would work, but it would only sense the switch state just at the instant that digitalRead() is called. So for most of your 9-second sequence, it will ignore the switch, and only briefly test. The user will have to hold the button for 3 seconds to be sure the program senses the switch press.

There are some better ways to make this work. The delay(3000) actually makes the program do nothing else but watch the clock for the full delay interval, it doesn't do anything else during this time. So instead of delay(3000) you could use a for loop, and test whether the button has been pressed.

// Spend 3 seconds waiting; exit the function if BUTTON1 is pressed.
for(int count = 300; count > 0; count--) {
    delay(10); // test the button every 10 ms
    if (digitalRead(BUTTON1) == LOW) {
        return; // skip out of the changeLights() function
    }
}

(Just saw Edgar Bonet's comment about the blink without delay Ardino example, which is another valid way to do the same thing. You could also use the millis() function and calculate the time when the next state transition should happen.)

Since this is an educational example, it's worth looking into how you would implement this as a state machine. (The traffic lights controller is often used as an introduction to state machines.) There's two types of state machines, Mealy and Moore, the difference is that one kind the outputs are determined only by the internal state, and the other kind, the outputs are a function of the internal state and the inputs.

A simple traffic light controller state machine might look like this:

state 0: initialize; next state=1
state 1: Red light on, timer=5 seconds, next state=2
state 2: Green light on, timer=3 seconds, next state=3
state 3: Amber light on, timer=1 seconds, next state=1

Use a timing countdown like in the example above, and when the countdown reaches 0, advance to the next state.

const int S0_INIT = 0; // state 0: initialize
const int S1_RED = 1; // state 1: Red light on
const int S2_GREEN = 2; // state 2: Green light on
const int S3_AMBER = 3; // state 3: Amber light on
int state = S0_INIT;
int stateTimer = 0;
// void setup() not shown; configures input and output pins by pinMode(...)
void loop()
{
    if (stateTimer < 0) { stateTimer = 0; state = S0_INIT; return; }
    if (stateTimer > 0) {
        stateTimer = stateTimer - 1;
        delay(10); // 10 ms interval
        return;
    }
    switch(state) {
    case S0_INIT: // state 0: initialize; next state=1
        stateTimer = 0;
        state = S1_RED;
        break;
    case S1_RED: // state 1: Red light on, timer=5 seconds, next state=2
        // digitalWrite(... etc.) Red light on
        stateTimer = 500;
        state = S2_GREEN;
        break;
    case S2_GREEN: // state 2: Green light on, timer=3 seconds, next state=3
        // digitalWrite(... etc.) Green light on
        stateTimer = 300;
        state = S3_AMBER;
        break;
    case S3_AMBER: // state 3: Amber light on, timer=1 seconds, next state=1
        // digitalWrite(... etc.) Amber light on
        stateTimer = 100;
        state = S1_RED;
        break;
    }
}

A more advanced traffic light controller (that responds to input) might look like this:

state 0: initialize; next state=1
state 1: Red light on, next state=2 (unless SWITCH1=HIGH, next state=4)
state 2: Green light on, next state=3 (unless SWITCH1=HIGH, next state=4)
state 3: Amber light on, next state=1 (unless SWITCH1=HIGH, next state=4)
state 4: Red light on, next state=5 (unless SWITCH1=LOW, next state=2)
state 5: no lights on, next state=4 (unless SWITCH1=LOW, next state=2)

An external input SWITCH1 switches this traffic controller between Red-Amber-Green sequence (states 1-2-3) and flashing-Red sequence (states 4-5). Adding constants for S4_BLINKING_RED=4 and S5_BLINKING_RED=5 and replacing the switch(state):

    switch(state) {
    case S0_INIT:
        stateTimer = 0;
        state = S1_RED;
        break;
    case S1_RED:
        // digitalWrite(... etc.) Red light on
        stateTimer = 500;
        state = S2_GREEN;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S2_GREEN:
        // digitalWrite(... etc.) Green light on
        stateTimer = 300;
        state = S3_AMBER;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S3_AMBER:
        // digitalWrite(... etc.) Amber light on
        stateTimer = 100;
        state = S1_RED;
        if (digitalRead(SWITCH1) == HIGH) {
            state = S4_BLINKING_RED;
        }
        break;
    case S4_BLINKING_RED:
        // digitalWrite(... etc.) Red light on
        stateTimer = 50;
        state = S5_BLINKING_RED;
        if (digitalRead(SWITCH1) == LOW) {
            state = S2_GREEN;
        }
        break;
    case S5_BLINKING_RED:
        // digitalWrite(... etc.) no lights on
        stateTimer = 50;
        state = S4_BLINKING_RED;
        if (digitalRead(SWITCH1) == LOW) {
            state = S2_GREEN;
        }
        break;
    }

(Remember to define the SWITCH1 pin, and configure pinMode(SWITCH1 ) in setup().)

Of course a real traffic light controller has more lights, say Northbound-Red, Northbound-Amber, Northbound-Green, Westbound-Red, Westbound-Amber, Westbound-Green, etc. Not to mention left turn arrows and maybe even "vehicle present" sensors. For a smart traffic light controller like that, the state is named by what traffic flow is authorized during that state:

state 1: northbound-southbound traffic green, 5 seconds, next state 2
state 2: northbound-southbound traffic amber, 2 seconds, next state 3
state 3: all lights red, 0.5 second, next state 4 (unless no vehicles waiting west-east lanes, then next state 6)
state 4: westbound-eastbound traffic green, 5 seconds, next state 5
state 5: westbound-eastbound traffic amber, 2 seconds, next state 6
state 6: all lights red, 0.5 second, next state 7 (unless no vehicles waiting N-W nor S-E left turn bays, then next state 9)
state 7: north-to-west left turn and south-to-east left turn green, 3 seconds, next state 8
state 8: north-to-west left turn and south-to-east left turn amber, 2 seconds, next state 9
state 9: all lights red, 0.5 second, next state 10 (unless no vehicles waiting W-S nor E-N left turn bays, then next state 12)
state 10: west-to-south left turn and east-to-north left turn green, 3 seconds, next state 11
state 11: west-to-south left turn and east-to-north left turn amber, 2 seconds, next state 1
state 12: all lights red, 0.5 second, next state 1 (unless no vehicles waiting north-south lanes, then next state 3)

The power of using state machines is that they all use the same basic "engine", just with more states, more outputs, more inputs. If the traffic engineer wants to adjust the timing to improve the flow of traffic, that only requires adjusting some of the data, which is much lower risk than rewriting code.  ... and of course state machines apply to more than just traffic lights, it's a very generally useful design technique.


Controlling Dynamixel Ax-12 With Arduino Mega

With Dynamixel library you can use servo this easily:
#include <DynamixelSerial.h>

void setup(){
   Dynamixel.begin(1000000,2);  // Inicialize the servo at 1Mbps and Pin Control 2
}

void loop(){
    Dynamixel.move(1,0);
    delay(2000);
    Dynamixel.move(1,500);
    delay(2000);
    Dynamixel.move(1,1000);
    delay(2000);
}

Example moves servo and makes pauses of 2 sec.
Installation is easy:

Installation:
Copy the files from DynamixeSerial to your IDE libraries folder.

DynamixelSerial folder can be found here: https://sourceforge.net/projects/dynamixelforarduino/files/?source=navbar


Communication between Arduinos using USB Host Shield

Have you tried this lib's documentation? It looks like just doing init() and then checking the task state is not enough.

Looking at the source code makes me think you might want to add a call to the main task/state machine, e.g. add a call to Usb.Task(); to your loop, before your if statement.