Like Majenko's comments suggested, you must shift the UTC time to your local time.  The Time library can help you do this.

There are some other problems:

You cannot wait 10 seconds without processing the characters. The Arduino receive buffer only has room for 64 characters. The GPS device could have sent 10000 characters during that time, so most of them will get dropped. This prevents the GPS library from parsing a GPS data successfully.  It will eventually "see" a complete set of data, sometime after the 10 seconds.  You may see data once every 11 seconds, not 10.
You are printing the several values even though they may not be valid.  For example, if you are not moving, or you do not have good satellite reception, the GPS device may not provide a speed.
The Arduino millis() clock will not be synchronized with the GPS clock. You could use the GPS updates as an exact 1-second clock. Simply count 10 fixes as they arrive, and this will mean that 10 seconds have elapsed.
You should use a different serial port and/or library. This answer describes the various choices: HardwareSerial (i.e. Serial on pins 0 & 1), AltSoftSerial (8 & 9 on an UNO) or NeoSWSerial (any two pins).

Here is a NeoGPS version of your sketch that addresses these issues:

#include <NeoSWSerial.h>
#include <NMEAGPS.h>

NMEAGPS gps;  //Declaramos el objeto GPS
gps_fix fix;  // all GPS fields, including date/time, location, etc.
uint8_t fixCount;
NeoSWSerial serialgps(10,11);

void setup()
{
 Serial.begin(9600);  //Iniciamos el puerto serie
 serialgps.begin(9600); //Iniciamos el puerto serie del gps

 //Imprimimos en el monitor serial:
 Serial.println( F("Test") );

}

void loop()
{
 // Check for GPS characters and parse them
 if (gps.available( serialgps ))
 {
  // Once per second, a complete GPS fix structure is ready.  Get it.
  fix = gps.read();

  // Count elapsed seconds
  fixCount++;

  if (fixCount >= 10)
  {
    fixCount = 0; // reset counter

    // adjust from UTC to local time
    if (fix.valid.time)
      adjustTime( fix.dateTime );

    printGPSdata();
  }
 }
}

void printGPSdata()
{
  Serial.print( F("Latitud/Longitud: ") );
  if (fix.valid.location) {
    Serial.print( fix.latitude(), 5 );
    Serial.print( F(", ") );
    Serial.print( fix.longitude(), 5 );
  }
  Serial.println();

  Serial.print( F("Date: ") );
  if (fix.valid.date) {
    Serial.print( fix.dateTime.date  ); Serial.print('/');
    Serial.print( fix.dateTime.month ); Serial.print('/');
    Serial.print( fix.dateTime.year  );
  }

  Serial.print( F(" Time: ") );
  if (fix.valid.time) {
    Serial.print( fix.dateTime.hours ); Serial.print(':');
    if (fix.dateTime.minutes < 10)
      Serial.print( '0' );
    Serial.print(fix.dateTime.minutes); Serial.print(':');
    if (fix.dateTime.seconds < 10)
      Serial.print( '0' );
    Serial.print( fix.dateTime.seconds );
    Serial.print('.');
    if (fix.dateTime_cs < 10)
      Serial.print( '0' );
    Serial.print( fix.dateTime_cs );
  }
  Serial.println();

  Serial.print( F("Altitud (metros): ") );
  if (fix.valid.altitude)
    Serial.print( fix.altitude() );
  Serial.println();

  Serial.print( F("Rumbo (grados): ") );
  if (fix.valid.heading)
    Serial.print( fix.heading() );
  Serial.println();

  Serial.print( F("Velocidad(kmph): ") );
  if (fix.valid.speed)
    Serial.print( fix.speed_kph() );
  Serial.println();

  Serial.print( F("Satelites: ") );
  if (fix.valid.satellites)
    Serial.println( fix.satellites );
  Serial.println();
  Serial.println();
}

//--------------------------

void adjustTime( NeoGPS::time_t & dt )
{
  NeoGPS::clock_t seconds = dt; // convert date/time structure to seconds

  // Offset to the local time
  const int32_t          zone_hours  = +8L;
  const NeoGPS::clock_t  zone_offset = zone_hours * NeoGPS::SECONDS_PER_HOUR;
  seconds += zone_offset;

  dt = seconds; // convert seconds back to a date/time structure

} // adjustTime

If you want to try it, NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries. NeoGPS is smaller, faster, more reliable and more accurate than all other GPS libraries.

Even if you don't use it, there are many suggestions on the Installation and Troubleshooting pages.


How can Arduino's 8 bit Microcontrollers handle C++

It's a misconception that using constructors or C++ in general requires lots of RAM. Plus, to be clear, the AVR processors like the Micro and Uno have separate RAM and PROGMEM (program memory). So, code for functions does not, in itself, use RAM.

As an example, this small program for the Micro:

int main ()
  {
  }

That uses only 206 bytes of PROGMEM and 0 bytes of RAM (according to the IDE).

Sketch uses 206 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 2,560 bytes for local variables. Maximum is 2,560 bytes.

Adding in a class, with a constructor, and using that class, increases the memory a bit:

class foo
  {
  public:
  int bar;  // some class variable

  foo ()  // constructor
    {
    bar = 1;
    }
  };  // end of foo

foo nick;  // a global variable
int main ()
  {
  PORTD = nick.bar;
  }

That uses 2 bytes of RAM, and 278 bytes of PROGMEM. Hardly a lot.

Sketch uses 278 bytes (0%) of program storage space. Maximum is 28,672 bytes.
Global variables use 2 bytes (0%) of dynamic memory, leaving 2,558 bytes for local variables. Maximum is 2,560 bytes.

Of course, the more things you do, the more RAM and PROGMEM it takes, however the compiler generates quite efficient code, and the linker strips out things that are not needed by your code.

  Is it that Arduino's library does not contain or utilize features such as constructors or objects (of C++) ...

A lot of libraries use classes and constructors (for example the Serial library, the Print class, and a lot of others). There is nothing inherently RAM-intensive about a constructor. It's just a function that does something, with an implied this pointer to the current instance of the class.

  do lambdas work? (from a comment)

Yes you can use lambdas:

// array of function pointers
void (*doActionsArray []) () =
 {
 [] { Serial.println (0); } ,
 [] { Serial.println (1); } ,
 [] { Serial.println (2); } ,
 [] { Serial.println (3); } ,
 [] { Serial.println (4); } ,
 };

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  doActionsArray [3] ();
  }  // end of setup

void loop () { }

  as long as you don't (extensively) use: the standard library, exceptions, templates ... (from a comment)

Templates can certainly simplify doing things like writing to, or reading from EEPROM and similar. For example:

#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

The standard library? There are implementations for the Arduino. We have to bear in mind that RAM is limited, however if you are going to do something anyway that involves linked lists, etc. then the Standard Template Library will probably do what you want as efficiently as you could if you coded it "by hand".

The bottom line is you need to be aware of what you are coding on. I have seen examples like this:

float foo [1000];  // hold my readings

That blows the available RAM on a Uno straight away. Nothing to do with C++ per se.

The other thing to be aware of is some tricks you can usefully employ. One common one is to replace:

Serial.println ("Program starting.");

With:

Serial.println (F("Program starting."));

The first example causes the compiler to copy the string "Program starting." from PROGMEM into RAM, using some of your valuable RAM. The second example doesn't.


Arduino eeprom_put sketch writes data in two locations?

What is probably happening is aliasing.  Let's say your processor has a 16 bit address bus.  16 bits can count up to 2^16 = 65536 = 64k memory addresses.  Each address is a byte (B) so your processor has 64k-Bytes of address space.  It can physically address 64kB of memory.

What happens if you only have one memory chip with 4KBytes of memory, with  only 12 address lines?  Well, if the designer was lazy (or cost-conscious), the first 12 address lines on the processor will be connected to the 12 lines on the memory chip.  The other 4 lines on the processor will be ignored.

So it doesn't matter what the processor does with address lines 13-16 -- they're not connected to the memory chip.  Therefore the contents of the memory chip appears where you expect, starting at address 0, but also again at address 4096, and again at address 8192 and so on.


How to keep track of if data is outdated

OK, so you have three possible states for your values:

No valid data (-1, or 0xFFFF in 16-bit 2's complement)
Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

If you first check for invalid data before thinking about "old" data (invalid data is never considered "old") then you just have two states:

Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

As you can see the highest 6 bits of the stored value aren't used at all except for storing -1 for invalid data (hence checking for that first). So you could utilize those 6 bits to store all sorts of things. In 6 bits you can store the values 0 to 63. That could be the number of seconds since the last time you got some data.

By masking and shifting you can separate out the two values:

val = data[x] & 0x3FF;
sec = data[x] >> 10;

Every second add one to the seconds count of each and every data entry that is less than (say) 60.

val = data[x] & 0x3FF;
sec = data[x] >> 10;
if (sec < 60) sec++;
data[x] = val | (sec << 10);

Now each entry in your array knows how old it is (up to 1 minute), and if it's older than a certain threshold (30 seconds? 45 seconds? you choose) then you consider it "old" and display it as such.

You can make it easier to program by using a union/struct combination:

typedef union {
    int16_t rawval;
    struct {
        unsigned value:10;
        unsigned seconds:6;
    } __attribute__((packed));
} data_t __attribute__((packed));

If your data array is now made up of that type instead of integers:

data_t data[500];

you can now access:

data[x].rawval as the raw 16 bit signed value (to look for -1).
data[x].value as the unsigned 10 bit value from 0 to 1000.
data[x].seconds as the unsigned 6 bit value from 0 to 63.

Updating the seconds then becomes as simple as:

if (data[x].seconds < 60) data[x].seconds++;

When you store a new value using

data[x].rawval = sensor.getValue();

the seconds is automatically overwritten with 0 which resets the count for you.

And both methods give you data ageing without using a single byte more memory.


Code Optimization: Interrupt when a value reaches 0

You did not specify the kind of Arduino you are using but, based on
another recent question of yours, I will assume it is an AVR-based
Arduino.
You cannot have an interrupt automatically triggered by a variable
reaching zero. What you can do, instead, is trigger an interrupt by
software, by toggling a pin that is configured both as an output and as
an interrupt source:
const uint8_t int_pin = 2;  // pin used for interrupt

void setup() {
    digitalWrite(int_pin, LOW);
    pinMode(int_pin, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(int_pin, reset, RISING));
}

static inline void trigger_interrupt() {
    digitalWrite(int_pin, HIGH);
    digitalWrite(int_pin, LOW);
}

// Within loop():
if (!amp) trigger_interrupt();

However, if you do that, you will discover that interrupts are slow.
Awfully slow compared with a simple if test:

digitalWrite() itself is awfully slow. This can be overcome by
using direct port access, but that is still two cycles for toggling
the pin in each direction.

You will loose an extra cycle in the pin synchronizer.

Once the IRQ is raised, the CPU needs four cycles to prepare itself
for servicing it.

The interrupt vector is a jmp instruction, which takes 3 cycles.

The ISR then has to save every single register it is going to use,
including the status register. That takes two cycles per register.
And there are quite a lot of registers to save...

This ISR, which is provided by the Arduino core, will then look for
the interrupt handler you provided with attachInterrupt(). This
also involves checking that the pointer to the handler is not zero
(the kind of test you seem to be worried about). It then has to
call (4 cycles) your handler, which will have to return
(4 cycles) to the ISR. You could avoid this indirection by defining
the ISR yourself instead of relying on attachInterrupt().

Once the job is done, all the saved registers have to be restored
(2 cycles times many register), and the reti instruction (4 cycles)
is issued in order to restore control to the interrupted program.

Last but not least, since amp will be modified in interrupt
context, you will have to qualify it as volatile. This keyword
prevents the compiler to perform optimizations that are unsafe in
this situation, and you will loose a lot of time to these missed
optimization opportunities.

In contrast, this line:
if (--amp == 0) amp = 10;

would be translated by the compiler into something like this:
   dec  amp     ; --amp, as amp is likely already in a register
   brne 1f      ; if (amp != 0) skip the following
   ldi  amp, 10 ; amp = 10
1:

The whole sequence takes 3 cycles, irrespective of whether the if
condition was true or false. That is at least one order of magnitude
faster than the interrupt-based solution.


5 bytes = more than 1 million million unique addresses, although not all addresses (as the nRF24L01 datasheet points out) are advised, for instance because they mimic the nRF's preamble packet.

So what is the purpose of addresses?
The purpose is to ensure that radio transmissions are received at the intended radio module.  Consider a radio network where you have 1 transmitter (TX) and 3 receivers (RXs) within range of one another, all using the same radio frequency (channel).  Now all receivers will detect a message sent by the transmitter, but only act upon it, such as raising an interrupt flag, it if the TX and RX addresses match.  To avoid chaotic communication, failed packets or on-air collisions you need each receiver to have a unique address.  Consider these like a postal address.  You should have an intuition of what would happen to your mail if both you and your neighbor had the exact same address.  Since the 2.4 GHz band can be extremely busy in public places with WiFi and Bluetooth traffic (which as an aside, Bluetooth is based on the nRF protocol), having 40 address bits seems quite sensible, as the probability of matching addresses by chance is almost zero.

So what are pipes?
If you read the nRF datasheet, you will see that in TX mode the radio can only send on using one address.  In RX mode, the radio will listen for messages on up to 6 different addresses.  Why 6?  This is likely arbitrary - a balance between register memory allocation, most probable number of nRF modules being used simultaneously and the likelihood of more efficient network topologies (such as star/tree networks) that do not require huge numbers of pipes.  A pipe represents one of these 6 addresses that a radio can receive the message and send and an ACK packet if requested.  That's all.

I hope this answer clears any confusion you had between nRF addresses and pipes.


Wiring Multiple MPU 6050 to Micro/Lenardo

Buttons are just buttons. You can have them "active high" with pulldown resistors as you have there (10K is fine. The actual value doesn't really matter, just don't have it too low or excess current will be drawn), or "active low" without resistors and connecting to ground when pushed instead of VCC and use INPUT_PULLUP. The choice is yours. There's no real benefit in this situation to either way of doing it.
The critical part is your AD0 connection. Whether you connect one to ground and leave the other unconnected, or connect one to VCC and leave the other unconnected, depends entirely on the design of the breakout board. It should have a resistor on the AD0 pin internally that either connects it to GND or to VCC. If it connects to GND then you need to link that pin to VCC to override it. If it connects it to VCC (or more likely 3.3V) internally then you need to connect it to GND to override it.
To find out which you will have to either consult the documentation or schematic for the board or measure the voltage at the AD0 pin. If it measures 0V (within a few mV) then it connects to ground and you will have to connect it to VCC to override it. If it measures more (probably nearer 3.3V) then connect it to ground to override it.
Because those chips are 3.3V and the board contains a 3.3V regulator (if your boards are the same as you picture in your wiring diagram) the chances are that the AD0 is pulled up to 3.3V so you just need to connect one to ground.
So it looks to me like your wiring diagram is most likely suitable and correct, pending confirmation of the pullup/pulldown in the AD0 pin.


How to change baudrate of ESP8266 (12e) permanently?

Depending on how recent a version of the AT Instruction Set interpreter your chip has, the two instructions you tried may not be valid ones; they are not listed in Espressif's ESP8266 AT Instruction Set document. Searches for either "CIOBAUD" or "IPR" in the current document (version 1.5.3) return no results.

The baud rate commands are now "AT+UART_CUR" and "AT+UART_DEF" which configure the entire UART for the current session or the current and future sessions, respectively. The manual's prototype for the command is:

AT+UART_DEF=<baudrate>, <databits>, <stopbits>, <parity>, <flow control>
Example:
AT+UART_DEF=115200, 8, 1, 0, 3

I have used these and can confirm that they work.

What I've found using software serial is that it can push 115200 baud well enough to send commands to the device (though I wouldn't build an application that depends on it) but it can only read reliably up to 9600 baud. I've been able to change my devices' baud rates from 115200 baud to 9600 over software serial; you just have to expect garbage coming back and ignore it:

// Set ESP8266 baud rate to 9600. You only need to do this once per device
set software serial baud to 115200;
send "AT+UART_DEF=9600,8,1,0,0";
set software serial baud to 9600;
// From now on, communicate with your device at 9600 baud.


What are the connectors used in the arduino mega?

Look for male pin header strip, with 0.1 inch (2.54mm) pitch.

In single and dual row form.

Specifically they are:

8x1 ADCL
8x1 ADCH
8x1 PWML
8x1 PWMH
8x1 Communication
6x1 Power
18x2   digital IO (on the side)

Source: Schematics


The answer is simple. Just pass a negative number of steps as an argument to motor.step();.

Another note: You forgot a semicolon on your second to last line. IIRC this doesn't matter in C, but it's just bad practice to do this. If you add a line of code below that, then it won't work.

Example code:

#include <Stepper.h>

int in1Pin = 22;
int in2Pin = 23;
int in3Pin = 24;
int in4Pin = 25;

Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin);

void setup()
{
    pinMode(in1Pin, OUTPUT);
    pinMode(in2Pin, OUTPUT);
    pinMode(in3Pin, OUTPUT);
    pinMode(in4Pin, OUTPUT);

    motor.setSpeed(25);
}

void loop()
{
    int steps = 360;
    motor.step(steps);
    delay(100);

    steps = -360;
    motor.step(steps);
    delay(500); //Semicolon added
}


One time execution of a variable incrementation

See http://www.gammon.com.au/switches.

Basically you need to detect the transition between the switch not being pressed before, and now being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.

  Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?

To clarify, you increment once on a transition, note when you did this (eg, by calling millis() ) and then ignore any further transitions for, say 10 ms.


Is there a manometer available to use with Arduino?

Bruno, there are a number of sensors available, try an Ebay search, to do what you want.  However, you need to determine what pressure range you are looking at.  As you mention manometer I assume you are working in the mBar range but to me that would be at odds with the pressure typically seen in whole building systems.  An Ebay search on 'Pressure transducers' will yield a good range of devices, likely to be primarily industrial types and some using wheatstone bridge type outputs.  you may need an op-amp circuit to buffer / amplify the output signal but virtually all sensors can be interfaced to an Arduino with the correct conditioning cicuitry.  As you are aware to measure pressure all sensors will need to be invasive into the pipework.


In microcontrollers, the GPIO pins have a multiplexer to select what the pin is used for.  When you use the Arduino SPI library, the initialization function will set the multiplexer to MOSI for that pin.  You should be able to run your own initialization for that pin and overwrite whatever the SPI initialization function did.  Just make sure to call your initialization after SPI.begin().  This is the simplest solution.

If that doesn't work for some reason then you can dig into the source code for the Arduino SPI library.  This isn't too hard either.

Bitbanging is the hardest solution and shouldn't be necessary for your application.


Is it possible to accept multiple web requests at once?

It can be done. The Arduino is a single tasking environment so you have to make sure your code is non-blocking.

BlinkWithoutDelay is a good starting point (thanks @Majenko) but you should also look at the Timer1 library.

Basically your programs needs to do all the steps it can right away and whenever it does something that could block, it must do it asynchronously and during a later loop() run check if it's finished and continue with the next task. The alternative (if you know how long your task will take) is to use the timer interrupt with the library mentioned above.


Why can't this C++ program read my arduino's Serial.write()?

The problem is in your C++ program at the other end of the line (not the Arduino side):

char* c = "";
int len = strlen(c);
while(c == "")
{
    serial.ReadData(c, len);
}

Here, len is zero because that is the length of "" , the empty string! Thus, in your loop, you ask ReadData to read 0 bytes. Hence, the condition of your while loop is always true as, c never changes.

Also, the while condition seems incorrect as it is not recommended in C++ to compare 2 strings (defines as char * or char [...]) with ==. In your situation, what is important is the number of characters read by ReadData:

char c[LEN + 1];
int numBytes = 0;
while(true)
{
    numBytes = serial.ReadData(c, LEN);
    if (numBytes != -1)
    {
        // Terminate the string if we want to use c variable as a string
        c[numBytes] = 0;
        break;
    }
}

in the code above, LEN is the number of characters you want to read at one time, in you example it should be set to 1, either as a #define or as a const variable:

// either:
#define LEN 1
// or:
const int LEN = 1;

The code above also ensures that c can be used as a normal string, by adding a 0 at the end. This is mandatory only if you want to use string functions on c such as strlen, strcpy, strchr... otherwise numBytes is enough to manage the number of characters read into c.


Pin definitions in your code seem to be mixed up. If Adafruit example works fine with your setup, you should keep the pin definitions Adarfruit uses:

#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

Also, you are using a deprecated constructor. It is recommended to use a constructor which explicitly specifies display size.


And I am wondering if I could control this port with my Arduino (NODE-MCU) and a module like this one?

Yes, you can, though choose a board based around the MAX3232 for a 3.3V MCU board.

  How could I then control the TV? This is the Manuel for the TV at page 124 there are the commands how to control it, but how can I send them?

Exactly as they show in the manual. For example:

Serial.print("ka 0 01\r");

That would turn on every TV connected to the serial bus.

  My last question is, how long can the cables from the arduino to the module be? They have to be about 2-3m long! Is that possible without any other hardware?

You can get away with no more than maybe 1 meter between the Arduino and the RS232 board. Keep that as short as possible. However between the RS232 board and the TV you can have up to 15 meters of cable.


Ok, as @IgnacioVazquez-Abrams suggested: the configuration files for the plugins can be found in the Arduino ide preferences directory. Click the menu Arduino->Preferences (under macosx) at the bottom of the window there is the clickable path of the preferences.txt file. In the same folder as that file you will find a packages folder, where the plugins are downloaded.


Can a KCPI-3101 be replaced with an Arduino?

An Arduino's ADC cannot sample fast enough to sustain 225ksps over 16 channels. That equates to a total of 3.6Msps.  The Arduino can manage something like 120ksps in total.

That's not to say there aren't microcontrollers that can't do that kind of speed - there are.  The PIC32MZ, for instance, can run at 15Msps (although it's somewhat buggy still) and there are many other microcontrollers.

The main bottleneck though is in the communication between the microcontroller and the computer.  Regardless of the sampling speed of an Arduino the serial interface is too slow for high speed sampling. Even at its practical maximum of around 2Mbps it gives you 200000 bytes per second, which with 2 bytes per sample would be 100ksps maximum throughput, not taking into account any protocol overheads.

So that's where having a PCI card is a big advantage. A 32-bit (or even 64-bit on PCI64) 66MHz direct channel to the CPU means you can shift considerably more data. And having the computer perform DMA access means that smooth data transfers without the CPU needing to be involved can be performed.


Programming Questions / Capacitive Soil Moisture Sensor

Thanks to all for the advice,
I have chosen to divert the whole system and rather make use of a 555 timer to sent a frequency to the measuring pins. It has been tested and seems to resolve the issue completely.


Is my Arduino board defect? No matter what program I upload the pin 13 turns on and off 3 times and that's it

The best way to check if Arduino is working or not is to install Firmata. Here's the necessary steps:

1) Download Firmata application from the official website.

2) Connect Arduino to the computer

3) Open the Arduino IDE and burn the example Standard Firmata [File - Examples - Firmata - Standard Firmata]

4) Open the application, leaving the Arduino connected.

5) Chose the right serial port and debug every pin =D


The OP has likely solved this problem by now, but I know that others will be in the same position, so I am answering for them.

I routinely record ten channels of biological sensors including one of 16-bit sound at 8 kHz (plus the associated FFT data) to an SD card using arduino-compatible systems, so I doubt very much that the SD card writing per se is the problem.

Throughput to an SD card is a function of several variables.

To maximize write throughput you need to write full blocks of data at
the correct block size, since partial blocks take the same amount of
time as full blocks.
You also need to be ready with more data as soon as the SD card is
ready to take more, otherwise precious cycles slip away from you.
You need to ensure that your writes are non-blocking (don't try to
write more than the buffer can receive) so your loop can process and
queue up new data while the SD card is doing its thing.
You need to read any timing-sensitive sensors using interrupt service
routines that write their data either to a circular buffer or to one
of a group of two or three buffers that are cycled between being
filled and being emptied.

Printing debug statements to the serial port can take many tens of milliseconds in a loop that otherwise may take only a few microseconds. If you write more than the serial port buffer can hold, the call will be blocking and you will be at the mercy of the PC that's reading the serial port. This will always be bad enough to mess up the program you're trying to debug... I've encountered situations where this introduced delays of up to 10 seconds (the PC was misbehaving, but still...).

A quick improvement to printing debug statements is to maintain a loop counter and only print a debug statement every N loops.

The program in the original question uses a naive strategy in the sense that it acquires some amount of data and then immediately tries to write it to the SD card, waiting until the write is complete before trying to acquire new data. This will never work at high data rates for the reasons given above. If you use this approach, you are likely wasting 90% of your program cycles in waiting for the SD write and the Serial port write. If either one takes too long, you will miss the next data acquisition window.

My advice: your first step is to research and find or write a circular buffer library.

Then set a timer to call an interrupt service routine that acquires data and puts it into the circular buffer.

Write a loop routine that checks to see whether the SD card is available for writing, and then takes just enough data out of the circular buffer to fit in a single block write for your SD card (look at the documentation for the card adaptor and the card).

At that point you will know whether your system can keep up with your needs.

It's possible that your SD card writing itself is OK but your Arduino is having trouble keeping up either because it's too slow or because you don't have enough room for a sufficiently large circular buffer. I doubt this because I've recorded and played back audio at 8 KHz on the Uno, but then I don't know what else you need to accomplish in your program.

If you do determine that the Arduino itself is too slow or has insufficient memory, take a look at the Teensy series of boards [https://www.pjrc.com/teensy/index.html]. They are entirely compatible with Arduino libraries and IDE but they run hundreds of times faster than the Uno at a larger data width, plus they have oodles of RAM and a gazillion pins. They're also much smaller than the Arduino form factor and the community that uses them is very knowledgeable.

If it turns out that SD card write throughput is OK but that it requires more buffering than you have on-board, you can add an SPI ram breakout board for more fast buffering space.

Finally, if the amount of data you need to collect is so large and so continuous that you simply can't buffer it long enough to get it written out to SD, or if the SD card truly can't keep up, or if the data is larger than any available SD card, you may consider sending your data off the board in near-real-time. I send 10 hours of nightly data from a Teensy over a USB virtual serial port to the PC at about 3Mbps, and others have done better. Ethernet output is also available and can be at least an order of magnitude greater.

glhf!


Compiling Error - exit status 1 for DHT11 using Arduino UNO (code/process/connections same as website given bellow)

I didn't download the "Adafruit Sensor Library"
https://github.com/adafruit/Adafruit_Sensor
It ran after I added it.


parse intel hex into SPI commands for arduino ICSP AVR

I have some code that does exactly what you want on GitHub.

Amongst other processors, it supports the At90USB162 chip. The code reads from an SD card in Intel hex format and writes to the chip at the press of a switch. This effectively is what you are trying to do.

Arduino forum moderator "Crossroads" (who has recently also joined Stack Exchange) has made a board to do the programming, hold the SD card, and have some status LEDs:

Here is my code to write to the flash:

// execute one programming instruction ... b1 is command, b2, b3, b4 are arguments
//  processor may return a result on the 4th transfer, this is returned.
byte program (const byte b1, const byte b2 = 0, const byte b3 = 0, const byte b4 = 0)
  {
  noInterrupts ();
  BB_SPITransfer (b1);
  BB_SPITransfer (b2);
  BB_SPITransfer (b3);
  byte b = BB_SPITransfer (b4);
  interrupts ();
  return b;
  } // end of program

// write a byte to the flash memory buffer (ready for committing)
void writeFlash (unsigned long addr, const byte data)
  {
  byte high = (addr & 1) ? 0x08 : 0;  // set if high byte wanted
  addr >>= 1;  // turn into word address
  program (loadProgramMemory | high, 0, lowByte (addr), data);
  } // end of writeFlash

Your loop looks a bit strange, the page size (before you need to commit) is 128 bytes (64 bytes), not 2 bytes.

See the datasheet:


There is indeed a race condition in your code: if an interrupt fires
while you are reading one of the counters, you might read garbage. If it
fires between reading and resetting the counter, you loose one count.

The way to prevent the race is to block interrupts while the main thread
(everything that does not run in interrupt context) accesses the
counters. BTW, do not forget to make the counters volatile.

The portions of the code that run with interrupts disabled are called
“critical sections”, and you should keep them as short as possible in
order to limit the interrupt latency they introduce. Typically, within
those critical sections you do nothing more than access the shared
variables. Example:

void loop()
{
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;
    noInterrupts();  // start of critical section
    int counter1Copy = counter1;
    counter1 = 0;
    interrupts();  // end of critical section
    Serial.print("A");
    Serial.println(counter1Copy);
    noInterrupts();  // start of critical section
    int counter2Copy = counter2;
    counter2 = 0;
    interrupts();  // end of critical section
    Serial.print("D");
    Serial.println(counter2Copy);
  }
}


The unit measures a maximum voltage of 25v. When the measured voltage is 25v it divides it by 5 to present a maximum of 5v to the Arduino.  That is measured as a value of 1023 by analogRead(). If you divide 1023 by 40.92 you get 25.


Arduino Mega 2560 ADC sampling instant and other timings

does that mean that this is the instant from which the actual ADC
  conversion start, and so 1.5 ADC clock cycles from here, my analog pin
  value is set on hold?

Yes. After between 3μs and 5μs. This is because conversion start at the following rising edge of the ADC clock cycle. This rising edge might have just happened, which means you need to wait 31 (main) clock cycles.

  how can I know how much time passed before that sbi function call is
  issued?

You could copy the original code and create your own analogRead2 function that measures the time before setting ADSC.

  I saw that a single instruction on arduino won't take more than 4
  microseconds (but micros() function has that resolution so I don't
  exactly know!)

A single instruction will take 1 or 2 clock cycles (if I remember correctly). So at 16Mhz that will mean 62.5ns (nano seconds) per clock cycle. Not 4ms

  Now, considering the so called "first" conversion, which take 25 ADC
  clock cycles

  does this conversion happen just the first time I call analogRead
  since I powered on Arduino? or does it happen even after some time ,
  because the ADC module gets powered off? (of course, I consider the
  case when Arduino remains powered on all the time)

  Judging by the timings I measured it seems like that the former is the
  one really happening, even if I don't use ADC for some time, but can
  anyone confirm?

This first conversion is after the ADEN bit changes from 0 to 1. If you don't unset this bit, all further conversions will take the shorter time.

PS on the first conversion, the sample-and-hold takes place after the extra 12 ADC clock cycles, so between cycle 12 and 13.5.

PPS this info is actually based on the ATMega328, but should be pretty similar in the 2560.


Arduino secure two way communication over radio

You may want to take a look at my RC4-with-diffusion algorithm RC4D which is very resource friendly as it takes less than 500 bytes of flash space (when encrypting inplace) and is much faster than AES128 on an Arduino.


RFID reader code to identify more than one tag

here's how I'd do it ... allowing for 4, 7 and 10 byte uid's (which are all possible apparently)

struct tagInfo {
  byte len;
  byte uid[10];
};
struct tagInfo tag[] = { // add your tags here
  // the len is 1, 2 or 3, for lengths 4, 7, and 10
  // you could just use 4, 7, 10 here and not bother
  // with the len * 3 + 1 calculation later
  // the choice is yours, really
  {1, {0x01, 0x02, 0x03, 0x04}},
  {1, {0x02, 0x03, 0x04, 0x05}},
  {2, {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}},
  {1, {0x02, 0x02, 0x02, 0x02}}
};
const int numtags = sizeof(tag)/sizeof(struct tagInfo);

Then, your loop

void loop() {
  if (!mfrc522.PICC_IsNewCardPresent()) { return; }
  if (!mfrc522.PICC_ReadCardSerial()) { return; }
  int i; // declare before the loop because we want to check the value after the loop ends
  for (i = 0; i < numtags; i++) {
    byte len = tag[i].len * 3 + 1;
    if(len == mfrc522.uid.size) { // 4, 7, 10?
      if(!memcmp(mfrc522.uid.uidByte, tag[i].uid, len)) {
        break; // found an exact match so stop the loop
      }
    }
  }
  if (i == NUMTAGS) { return; } // no matches
  // all good here - run the rest of your code
}


Arduino Sending faster/more data to a web server

Option 1.
Send a single message from the client to the server.  This message should contain all 150 points of data.

Option 2.
Send the data in a format other than as a string.  Base64 encoding of the raw numeric values would be ideal, but its going to add extra load to the CPU.  Depending on the range of the data (0-359) and the resolution (use 2 DP) you might be able to use just 4 bytes for each data point.  Because you are using a fixed length value to represent each point you no longer need separators in you data so a single reading goes from 21 bytes to 12 bytes.

Option 3.
Hand off the data to a second processor that is dedicated to sending the data.  The Yun would write the data into a shard circular buffer and the other processor (possible another Yun or an ESP8266) would read the data from the buffer, convert it and write it to the server.

I can't say which is best, because I don't know enough about you system, but if you could expand on your details we should be able to narrow it down.

After reading you answer above.  If you ranges are 0-10 with two DPs then I would look at option 2 first.  If each reading can range from -9.99 to +9.99 you take the absolute value and multiply by 100 and write that as a 2 digit hex number to your message body.

uint8 number = ((reading < 0) ? 0x80 : 0x00);  // Set the high bit for negative.
number += (abs (reading) * 100);
messageBodyString += String (number, HEX);

That will give you 2 bytes per point, and a 300 byte (+overhead) message should be transferable within 5 seconds.

Here is some quick code to explain the encoding and decoding

unsigned int Encode(const float& value)
{
    unsigned int result = (value < 0) ? 0x80000000 : 0x00000000;// Work out and set the sign bit
    result |= (unsigned int)abs(value * 100.0);             // Get the absolute value (ignore sign) and multiply
    return result;
}

float Decode(const unsigned int& value)
{
    const bool isNegative = ((value & 0x80000000)  != 0);       // Get the sign bit
    float result = (float)(value & 0x7FFFFFFF);                 // To remove the sign bit
    result /= 100.0;                                            // Divide to return to the original number of dps.
    if (isNegative)
        result = 0 - result;
    return result;
}


How to copy files from local computer to Yun with scp?

Try ~/Documents/index.html

The ~ represents the current user's home directory, so ~/Documents is the Documents folder for the current user.  It means you don't have to make sure you have spelled the user's home directory exactly right.

Other options are:

$HOME/Documents/index.html
Documents/index.html (if you are in your home directory)
cd ~/Documents then just use index.html

... the list goes on ...


Why is my CNC shield smoking? Is it safe to keep on for long periods of time?

Those NEMAs are big ones - i suspect too big for the little A4988 chips - which can only provide 2A when actively cooled and generally only for short periods. I wouldn't try to push more than 1.7ish Amps for any length of time.
You will also need to set the vREF correctly for the motors you are using - if this is not set you will either provide too little current or too much current.
Look up the specifications for the NEMAs you have - and upgrade the Stepper controller to something more like a TB6600 that can handle greater current.
Also when the Steppers are not being used - disable (if you dont need them to hold) this will turn off the drivers and let them cool between runs/moves.


Yes, perfectly possible. Just provide two separate CS pins to select between the two devices.


One approach is to look at the assembly listing of the program.

After compiling the program (via the Verify or Download button) locate the directory where the .cpp, .hex, and .elf files for the program have been stored.  (If you have trouble finding them, briefly turn on verbose compile options in the arduino IDE and look at the directory names in the output.)
In that directory, run avr-objdump -S fn.cpp.elf > listing.txt where fn.cpp.elf is the name of your sketch with .ino taken off and .cpp.elf added on at the end.  For example, with sketch serialecho.ino:

avr-objdump -S serialecho.cpp.elf > listing.txt
View the listing.txt file, and subtract each function's starting address from its ending address, using hex arithmetic.  For example, with setup code

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

in the listing we will see

00000144 <setup>:
...(6 lines snipped)...
 144:   26 e0           ldi     r18, 0x06       ; 6
 146:   40 e8           ldi     r20, 0x80       ; 128
 148:   55 e2           ldi     r21, 0x25       ; 37
 14a:   60 e0           ldi     r22, 0x00       ; 0
 14c:   70 e0           ldi     r23, 0x00       ; 0
 14e:   80 e1           ldi     r24, 0x10       ; 16
 150:   92 e0           ldi     r25, 0x02       ; 2
 152:   db c1           rjmp    .+950           ; 0x50a <_ZN14HardwareSerial5beginEmh>

00000154 <loop>:

The calculation 0x154–0x144 = 0x10 shows this portion of setup is 16 bytes long.

These examples were generated on a linux system.  I think the approach is the same on a MSWindows system except you may need to say avr-objdump.exe instead of avr-objdump, and may need to specify its path.  See, eg, the Assemler results, where? thread at forum.arduino.cc.


Here, below is updated version of your code.

Before running this code, you have to download DHT library. Just click on Click Here and you find good explanation & library of DHT11 Sensor. Becuase this library I usually preferred for my code. So, please download it and then run my code.

Click Here

And two void() loop never used. Put your all logic in one void() loop.

Note: This is not tested code. So if you face any problem then update me.

#include <dht.h>                // DHT library
#include<LiquidCrystal.h>       // LCD library

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

dht DHT;

#define DHT11_PIN 12

#define pwm 9

float temp;

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

  pinMode(pwm, OUTPUT); //Pin as OUTPUT
}

void loop()
{

 int chk = DHT.read11(DHT11_PIN);
 temp = DHT.temperature;
 Serial.print("Temperature = ");
 Serial.print("\t");
 Serial.print(temp);
 delay(1000);

 lcd.begin(16, 2);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Fan Speed");
 lcd.setCursor(0, 1);
 lcd.print("Controlling");
 delay(2000);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Circuit Digest");
 delay(2000);
 lcd.clear();
 lcd.setCursor(0, 0);
 lcd.print("Temperature:");
 lcd.setCursor(10, 0);
 lcd.print(temp);

 lcd.setCursor(0, 1);

 if(temp < 26 )
 {
    analogWrite(pwm, 0);
    lcd.print("Fan OFF");
    delay(100);
 }
 else if(temp == 26)
 {
    analogWrite(pwm, 51);
    lcd.print("Fan Speed: 20%");
    delay(100);
 }
 else if(temp == 27)
 {
    analogWrite(pwm, 102);
    lcd.print("Fan Speed: 40%");
    delay(100);
 }
 else if(temp == 28)
 {
    analogWrite(pwm, 153);
    lcd.print("Fan Speed: 60%");
    delay(100);
 }
 else if(temp == 29)
 {
    analogWrite(pwm, 204);
    lcd.print("Fan Speed: 80%");
    delay(100);
 }
 else if(temp > 29)
 {
    analogWrite(pwm, 255);
    lcd.print("Fan Speed: 100%");
    delay(100);
  }
}


The HM-10 is a BLE-only device.

Android phones do not normally transmit BLE advertisements, so there is normally nothing about an Android phone for it to discover.

The exception would be if you have software on a late Android version with the capability, which you have set up to intentionally transmit BLE advertisements, or else if software you put on your Android phone is actively responding to advertisements you had the HM-10 transmit.

Essentially, you are expecting something that his not normal behavior, but will only be achieved by adding your software on both devices.


You can use:

AT+ CWJAP?

or

AT+ CIPSTATUS

to see if you're connected to wifi. (The first will tell you access point status, the second will tell you IP address.)


I have to say that I do not have any experience with the ws2812 led strip but basically it is used with the Adafruit_Neopixel library where you have the function pixel_obj.setPixelColor(pixel_number,pixel_obj.Color(R,G,B)
and the function pixel_obj.show().
Now you basically want to make the code in void loop() clean and there is a wide choice of possibilities and techniques to use. The simplest is not to do it, but if you want you can write a library to do it or write a function that takes the number of the pins and light 'em up (all with the same color), like this
void light_pixel(int pixels[],int Red,int Green,int Blue){
    for(int i=0;i<NUMPIXELS;++i){
        pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
    }
    pixel_obj.show();
}
This works assuming you have declared pixel_obj in the outermost scope, and you will call the function like this:

#include <Adafruit_NeoPixel.h>
#define PIN //Whatever you pin is
#define NUMPIXELS //Thenumber of the pixels in your strip
Adafruit_NeoPixel pixel_obj = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
// You may have to modify the third parameter Rationale: You didn't
// specified anything about your led strip
void setup(){
pixel_obj.begin();
pinMode(PIN, OUTPUT);
}
void light_pixel(int pixels[],int Red, int Green, int Blue){
for(int i=0;i<NUMPIXELS && pixels[I]!=-1 ;++i){
    pixel_obj.setPixelColor(pixels[i],pixel_obj.Color(Red,Green,Blue));
}
pixel_obj.show();
}
void loop(){
int my_pixels[NUMPIXELS]={1,3,5,7,-1}; // Using -1 as terminator
// Initialize the array . Disclaimer: this is not optimised and you might use
// new opearator or better pass the reference of a vector to the function so
// that you can modify the range of the vector and have a more concise function
light_pixel(my_pixels,255,255,255);
delay(1000);
light_pixel(my_pixels,0,0,0);
}

Then you can change the number of my_pixels with a smile array assignment
This function is just a sample to get the job done but I'd recommend you to study further the C/C++ programming language in general in order to write better code
Good Luck!


The Core is the software API for a specific group of chips.

For instance, the AVR core supports the AVR chips found on most Arduino boards. The SAM3X core supports the Arduino Due. Etc.

It is the code that provides things like digitalRead(), analogWrite(), millis() etc.

Since each family of chips works differently that abstraction layer between your sketch and the physical hardware of the chip needs to be different.

In your default IDE installation the Arduino AVR core can be found within the hardware/arduino/avr/cores/arduino folder.

Cores are usually installed as part of a "boards" bundle in the boards manager. This includes definitions for the boards ("variants"), the core and, equally importantly, the compiler and firmware uploading software for the chip on the board.


BOTTOM UP

The arduino Zero uses an Atmel samd21 µController. This video explains how to program the samd chips in a bottom up fashion, or at least how to gather all required information to do so. In case the video doesn't work anymore, i'll briefly rephrase it here. The main steps are:

Figure out the required registers by reading the data sheet
Consult the Atmel Software Framework(ASF) to figure out the corresponding data structures
Setup your sketch inside the arduino IDE

The bottom up process can be very time consuming, because you are searching a needle out of an haystack like, the datasheet and the ASF. So you need to tackle all the tiny bits before building the whole thing.

TOP DOWN

For some situations it is better to look for a working example program and try to figure out how its done. For this i recommend the arduino github repository. It is a very good resource for figuring out how arduino uses the ASF and helps me tune certain functions.

The top down process therefore allows to decompose a large working function into its smaller parts and dig into the interesting parts. However, it requires something to work with at the start which is not always available.

INDECIPHERABLE

Some code examples aren't understandable from the start. Once you know what the code is doing, i recommend splitting up the large pieces like this register and bit modification section into smaller ones. Extract these sections into functions with self explanatory names, and if done correctly you can get rid of the comments.

Hope this helps ;)


Streaming sensor data over UDP using an Arduino Yún - how to do it and how fast could it be?

The Yun is really two different computers (one AVR and on Linux) connected by a serial link. Basically the AVR is connected to a serial console on the Linux machine, so you can "type" commands into Linux by sending strings out the serial port from the AVR.

The serial link normally comes up at 250,000 buad, so that should not be a bottleneck for your application.

Typically, the AVR will "type" a command to run a Python program on the Linux side (called the Bridge) that will then communicate with AVR code using a high level protocol. Unfortunately, this "bridge" connections tends to be slow and flaky.

But you could do what you want very easily by just pumping netcat commands into the Linux machine from the AVR machine every time you wanted to send a UDP packet out. The overhead would only be a few serial bytes per packet (you'd send "nc -u   \r" where everything but data is likely the same for every packet).

Here is an example of a program that runs on thew AVR and periodically reads some data from temperature sensors connected via 1-Wire, and then runs a "curl" command on the linux console to record  the readings to a server...

https://github.com/bigjosh/SimpleTempLoggerYun/blob/master/Arduino/SimpleTempLoggerYun/SimpleTempLoggerYun.ino

In your case, your replace the 1-Wire reading code with SPI reading code, and replace the "curl" that sends HTTP data command with an "nc" command that would send a UDP packet (using the "-u" parameter).

With this technique, I think you could get something working very very quickly and likely easily meet your data rate requirements.

Note that while this is a great technique for getting a proof-of-concept working quickly, I would not use a setup like this in production. Instead consider something like a BeagleBone Black where you could read the SPI data and send the UDP pack in a single C program that ran as a normal Linux process.


Getting sensor data wirelessly from arduino to PC

Xbee costs about 1000INR. They are really expensive. You should buy HC-05 module, which costs about 320INR.
You can easily interface them with Bluetooth of your Laptop using Processing Application.

You can even use ESP8266 ESP-01 Wireless Module. They Cost about 3$.
Wireless module gets connected with your router. this tutorial will help you to start. You can by this module from here.

nRF24l01+ modules can not be interfaced with Laptop...


L293D driver DC motors need help to start rotating

The L2978D is a terrible motor driver (I really wish people wouldn't use it!). It is "bipolar" which means that both the high and low side switches of the H-bridge are Bipolar Junction Transistors. This means that you get about 1.4V voltage drop in total between the inputs and outputs.
To counter that you must provide at least 1.4V more than your motors need for them to operate properly.


Sanity check with potential project. IoT with a dishwasher

If connecting to the wiring, using an opto-coupler will ensure that your Arduino's days will be long on the face of the land. If it is an LED indicator you may be able to connect the opto-coupler LED  input directly across the existing LED, but use of an appropriate series resistor would be wise. Optocoupler LEDs may have about 2 V forward operating voltage which is in the same range as a red LED. Some use lower forwards voltage LEDS (probably IR).

If your opto coupler has low input current requirements then connecting it via a series resistor across the existing LED will allow the indicator to still operate.

R series = (Vsource - V_opto_LED) / I_opto.
eg 12V source, 2V opto_LED (typical), 1 mA (should be enough for logiclevel signal.)
R = (12-2) / .001 A = 10/.001 = 10 k Ohm.

For direct connection across an existing red LED a 100 Ohm series resistor should avert disaster.
V drop in resistor at 1 mA:
V = IR = 0.001 x 100 = 0.1 V
= liable to be OK.

Ask if more information wanted.


Very sorry!  But I actually figured this out on my own.  I needed to reset by briefly bridging the reset pin with ground near the USB connector.  Then typed

sudo dfu-programmer atmega16u2 erase

and I'm happy again.


What is the most memory-friendly way to declare integer literals?

I'm not familiar with the Atmel megaAVR microcontrollers or Arduino.  But generally speaking, your memory optimization ideas are misguided.

For example, it's likely that the compiler implements local loop variables within a register so that they don't consume any RAM at all.

And the integer literal constants, such as 16 from your example, also likely don't consume any RAM.  The compiler likely incorporates these constants into the code.

Whenever you optimize something it's best to go after the big fish first.  You're focusing on the tiniest fish.  To find the big fish, look at the *.map file produced by the linker.  The map file should show how much RAM and Flash memory is used by your program.  The RAM sections might be labeled "bss" and "data" in the map file.  Hopefully the map file will also detail how much RAM is used by each compilation unit.  Find the compilation units that are using the most RAM and focus on them.  Maybe there are large buffers or arrays defined in those compilation units that can be reduced in size or redesigned.

The map file is also where you could check to see if your optimizations have made any difference.  For example, try some of the optimization you described and see whether the map file changes significantly.


I have seen this error numerous times before. I think the possibilities could be that either some external device is connected on RX, TX pins of arduino mega or mega is not getting sufficient power. Some connection from your board is trying to pull more than the limit current.

and off course the answers suggested above are also right. check out every possibility.


Control Speed of DC FAN Using Arduino PID Library

Two thing that may be helpful.
First make sure you have a common ground. For instance for you transistor you are using separate power from the arduino and 12 volt source. Connecting the two ground of the arduino and the power supply may resolve this for you.
The other thing is it is often times helpful to put a capacitor across the DC motor to help with voltage fluctuations.


My DS18B20 is reading high. How can I get it to return the correct temperature?

I've put a lot of DS18B20 sensors in place now on various sensor nodes - maybe 50 or so. I've learnt a bit about the readings returned from them. I know you have isolated some of these as not being the cause, but it is good to confirm that they are issues.

I don't know if you are using Celsius or Fahrenheit, so the degree of the problem isn't clear.

Localised heating

I don't think of Arduino as a "hot" chip, but putting a DS18B20 in an enclosure with an Arduino and LCD caused me to see readings 2-3°C higher than expected.

Moving it outside the enclosure fixed this.

Heating from high Vcc/frequent conversions

If you supply the chip with a high Vcc and perform frequent conversions (i.e. as frequently as you can), the chip does warm up. I have seen this increase readings by 1-2°C.

I haven't seen the problem with high Vcc alone, but I operate most DS18B20 in parasitic mode and convert at most once every 10s. The ones operated in active mode generally have the powered turned off when not being used.

OneWire and DallasTemperature do support parasitic mode.

Not all temperature sensors are created equal

I had a number of temperature sensors before I started playing around with DS18B20. Almost without exception, these under-read. Most of them are based on thermistors and calibration is poor. I thought the DS18B20 were over reading, but when I used a good thermocouple and meter, I could validate that they were correct.

This was about learning to trust the DS18B20.

Heat conducted along wire

If you have the sensors on a wire, the wire conducts a surprising amount of heat. This can be an issue when running wiring along pipes.

Fake DS18B20

These sensors are very popular, and this seems to have caused fakes to appear. I have a batch of stainless steel waterproof sensors that over-read and the timings were out. They worked with the OneWire library, but not a DS2482 OneWire master. I have heard of the normal TO-92 cased ones being fake as well.


Servo motors not working when called upon using I2C

If you are using Servo library, which uses timer (and so interrupts) for manipulating the servos then you may have the problem, that from loop it works (as interrrupts are enabled), but from interrupt (ISR) it does not work, because while serving interrupt (from I2C) all other interrupts are (temporary) disabled.

In receiveEvent() you are inside interrupt serving, so other interrupts are disabled and so anything, what depends on interrupts does not work, until you leave the function.

So it is the more probable cause, why your servo does not move, while called from receiveEvent(), while it moves, if called from loop()

And you wait inside the interrupt routine, until all Wire input is read fully and then while the (slow, as it probabely involves mechanical components like motors or servos) movement(from,to) ends (if it can even end with interrupts disabled).

The solution would be to do all movement(..) in the loop and int the receiveEvent() just store the already aviable values and put them into some static volatile variables, when transfer ends together with mark, that some change was done.

static volatile int from;
static volatile int to;
static volatile int changed;

void loop() {
int my_from,my_to;
  if (changed) {
     noInterrupts();  // critical, time-sensitive code here
       my_from=from;
       my_to=to;
       changed=0;
     interrupts(); // enable interrupts, so I2C, servo and such can work again
     movement(my_from,my_to);
  }
}
void receiveEvent(int howMany)
{
  if(Wire.available())
  {
    char c = Wire.read();
    from = readInteger();
    to = readInteger();
    changed = 1;
  }
}

Not totally perfect (mainly reading the Wire, which I would just tak as much as is ready to some buffer and decode it only when buffer is sufficiently full and syntactically correct, but if would make the idea here more complicated), but should work much better, than the current version.

Better version of `receiveEvent can look like this:

char buf[20];
int buf_pos;
void receiveEvent(int howMany)
{
  while (Wire.available()) {
    buf[buf_pos] = Wire.read();
    buf_pos++;
    if (buf[0] == 'f') { // starts with known command
      if (buf_pos>= sizeof(char)+2*sizeof(int)) { // have all data already collected
        from=0;
        for (i=0;i<sizeof(int);i++) from=from<<8+buf[sizeof(char)+i];
        to=0;
        for (i=0;i<sizeof(int);i++) to=to<<8+buf[sizeof(char)+sizeof(int)+i];
        changed = 1;
        buf_pos=0;
        } // end of buf_pos>= ...
     } else { // not started with 'f' (or anything it should know) - throw all transfer away as bad
        while (Wire.available()) Wire.read();
        buf_pos = 0;
     }
}


Getting error invalid conversion from 'const char*' to 'const uint8_t*

In the library ESPAsyncWebServer.h are these two possible function variants defined

  void send_P(int code, const String& contentType, const uint8_t * content, size_t len, AwsTemplateProcessor callback=nullptr);
   void send_P(int code, const String& contentType, PGM_P content, AwsTemplateProcessor callback=nullptr);

So  when using

const char index_html[] PROGMEM = R"rawliteral(<YOUR HTML here>)rawliteral";

give the compiler the explicit instruction

ap_server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
  request->send_P(200, "text/html", (const uint8_t*) index_html, getWifiHotspots());
 });

The code compiles error free on ArduinoIDE 1.8.12/ESP8266 2.71/ NodeMCUv1 (as not having your definition of getWifiHotspots() I defined it as char)


Return value of 0 if value is less than zero

The scope of each of the two different and unrelated voltadj variables that your code (as below) declares is limited to within its enclosing set of braces.

if (voltage-.47 < 0)
{
    float voltadj = 0;
}
else
{
    float voltadj = (voltage-.47);
}

Instead perhaps say

float voltadj = voltage-.47;
if (voltadj < 0) voltadj = 0;

or perhaps

float voltadj = voltage < .47? 0 : voltage-.47;

or

float voltadj = constrain(voltage-0.47, 0.0, 5.0);

or

float voltadj = max(0.0, voltage-0.47);

Also see max() and constrain() reference pages at arduino.cc.


Make little task using millis function.
// GLOBAL VARIABLE
uint32_t taskMillis = 0;

....

// IN LOOP
if (taskMillis && millis() - taskMillis >= 5000)
{ /* SWITCHES DIRECTION */ }

With that code you can make two tasks(one to switch direction, second to move Servo by X deg).
Here is video about this topic.
https://www.youtube.com/watch?v=v5SpPXMmHJE
I hope this anwser will help you.


Code hangs with SPI, and OLED labraries (Possible conflict between Adafruit SSD1306 and hardware SPI libraries)

I used the same code provided by you and uploaded it in the arduino uno and it was working fine for me. I am attaching the image for reference. I guess there might be some other issue


Is this Bluetooth module cool for Arduino?

From skimming that post, I believe that your linked pcb is not a full bluetooth module (note how there is no bluetooth chip or antenna of any kind). This is simply a "base board," which is why it is so cheap1.

You will need something like this that actually has the components you want.

To answer your questions:

The bluetooth library for arduino sets the discoverale name to ARDUINOBT by default, but that can be changed in the setup() method.
"scan around" is a little ambiguous—AFAIK, bluetooth can only connect to one device at a time, but I'm not sure if that's totally true. You may want to look into using radios instead of BT, as they can communicate more freely with one another, are extremely cheap, and have extensive arduino libraries availible. I'm currently working on a project that uses the nRF24L01, and I'd be happy to answer any questions you have about it.

1: It also has a draw of 6v VCC, which is more than the Uno can output.


How to read data from a rotary encoder with ATmega328

You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.

Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A & B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.

Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.

This code goes at the start of your sketch, right before setup() function:

const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
volatile long encCount = 0;

It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.

Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 & 1 (hardware pins pins 2 & 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder_interrupt function immediately.

pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
attachInterrupt(0, encoder_interrupt, CHANGE);
attachInterrupt(1, encoder_interrupt, CHANGE);

Last you will need the actual interrupt function that reads the encoder and updates the counter value.

void encoder_interrupt() {
  static unsigned int oldEncoderState = 0;
  oldEncoderState <<= 2;
  oldEncoderState |= ((PIND >> 2) & 0x03);
  encCount += encoderDirections[(oldEncoderState & 0x0F)];
}

First this defines a variable that holds the previous encoder value that was read from the pins 2 & 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.

The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.

The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 & 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 & 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.

On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.

And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.

If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:

const int LINE_COUNT = 400;

Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.

float getAngle() {
  long curCount = encCount;  // Store the current count.
  while(curCount < 0) {
    curCount += LINE_COUNT;
  }
  while(curCount >= LINE_COUNT) {
    curCount -= LINE_COUNT;
  }
  return (curCount / LINE_COUNT * 360.0);
}

First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.


Is there a practical way to broadcast and receive ascii payloads over ethernet or wifi?

The magical trick you are looking for is Ethernet UDP Broadcast. By chance there is an example sketch in the Arduino Tutorial. I cannot say if it is up to date but this will help you get started.

Cheers!


Servomotor losing its connection right after being connected to Arduino

Your code is correct. Check the following:

Arduino works from 5V, but most servos need 6V.
Even if your servo works from 5V, don't ever connect your servo power directly to Arduino pins. These pins are not able to provide adequate power for servo.
Check that grounds of both power supply for Arduino and power supply for servo are connected together.


// Following devices could be helpful in you case.

Power BJT as a switch (check datasheets if it comes on your required range).
Solid state relay is obviously, but cast is little high in this case.


Is there a relationship between RSSI and Power? If so, how are they connected and does it have a formula to extract one from the other?

Is there a relationship between RSSI and Power?

Yes

  If so, how are they connected and does it have a formula to extract one from the other?

RSSI is in relation to the square-root of the power. See below references for the actual formula.

Holiday extra: RSSI for an RF433 module can be estimated by the time from end of transmission and noise. This is the time for the AGC circuit to increase gain from the received signal to the noise level. Please see Cosa RF433 library for an example.

References:

https://en.wikipedia.org/wiki/Received_signal_strength_indication
https://en.wikipedia.org/wiki/Signal_strength_in_telecommunications


Get board.vid and board.pid value in code

The preprocessor will sub in the values for the names "USB_PID" and "USB_VID"

this line in "platform.txt" grabs them and makes build flags for them:

build.usb_flags=-DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'

the -D* option in the build is equivalent to the following lines being in the code

#define USB_VID /*value of build.vid*/
#define USB_PID /*value of build.pid*/
#define USB_MANUFACTURER /*value of build.usb_manufacturer*/
#define USB_PRODUCT /*value of build.usb_product*/

If you are curious, they are used by the libraries in "USBCore.cpp". Also, they will never be defined for devices they don't apply to.


Difference between Arduino IDE giving me headaches

To get RF24 working:

Download the latest IDE (not 1.0*)
Use the library manager to download the
latest RF24.
See https://github.com/TMRh20/RF24/issues/236#issuecomment-205354077
about what core to use.
Don't forget to define ATTiny in the sketch
Ex: #define __AVR_ATtiny84__
(84, 44, 24 are the choices)

ATTiny* do not have SPI, that's why it can't find SPI.h (SPI library).


My stepper motor connected to a driver and an Arduino is not working

For those who missed the comments, what I made a mistake in, as @JRobert pointed is that I was suppose to have connected the stepper motor to a separate power supply as the Arduino was not capable of so much resources. I also altered the code as I think I had gotten the steps-per-revolution wrong which is needed in the Stepper function in the Arduino Code. One needs to check this with the datasheet or somewhere online for the respective stepper motor model. The final code that got it working is here. All thanks to @JRobert for helping me figure out the solution :)


Read BLE Characteristic Value in Arduino Uno

I was able to communicate Arduino UNO and HM-10. Whenever one writes a characteristic on BLE using Android application, the exact bytes are transmitted to Tx/Rx channel to Arduino and can be read using SoftwareSerial Arduino library.

CurieBLE library works on Genuino/Arduino 101 board which has Intel Curie Module.


Can I compile c/c++ code on the linux part of the Arduino Yun?

The Yun's OS (Linino) is based on OpenWRT, and the official toolchain from OpenWRT does not appear to have changed much. It could probably be done, the question is if you'd really want to though.

The limited resources (storage, RAM, CPU) means you would most likely not fit all the parts of the toolchain for C/C++ compilation (perhaps with the exception of very basic programs without many dependencies). The YUN's package manager (opkg) should contain pre-built packackes if they exist, but given that even the list of packages is only kept in RAM to conserve space, I doubt the entire toolchain with libraries needed to compile useful stuff would fit.

The official way to build things for OpenWRT appears to be cross-compilation on a much beefier machine, if only because it takes a fraction of the time needed by a native compiler. All in all, you're also very likely to save time and resources by cross-compiling and have more resources left on the YUN itself.


Where can I find magnetic declination lookup table?

No, the North pointed by GPS coordinates are extracted using the velocity heading which would represent the true North. If you get the ECEF (earth centered earth fixed) coordinates from the GPS you can convert it to a local ENU (east north up frame) and calculate the heading from the velocity vectors (take a look here if you need the formulas for that).

However, this site http://www.magnetic-declination.com/ can provide you a estimate for magnetic declination at your location.

EDIT
From the comment I came across this topic which lead to this

you can play with the code provided and take it as a template for your needs to create a lookup table. The software used for creation of the files is the one present in the site you pointed. Just downloaded the linux zip file and tested it with the sample txt coordinates provided and all seems ok.

For the record the command used was (yes for some reason the extension exe is present but this is linux binary):

./wmm_file.exe f sample_coords.txt out.txt

which created a out.txt equal to sample output file provided. Now this file can be used by the function void build_lookup_table() (present on grab60_char.c) to build the lookup table you need.


In that ancient version of the IDE? You don't.

You download and install the latest version of the IDE from the Arduino website, then use the Boards Manager to install the packages that include the Ardiuno 101.


Any type of communication protocol uses pull-up resistors (not 100% sure that all of them do but still, it's a rule of thumb) so using the serial trick on the attiny enables the internal pull-up resistors on PB3 and PB4. I can bet the ADC value is near 1023 isn't it? Disabling the serial communication should in theory fix your problem.


Programming an ATmega328P by holding it on an Uno's

It's easy enough to use a Uno to program a bootloader onto another chip. I describe this process here.

The idea of holding one chip on top of another is likely to fail for various reasons. Both chips will try to respond to the programming attempt at slightly different times, probably making them both fail to be programmed.

See my post about making a breadboard Arduino. It only takes a few wires to program the target chip.

However this isn't just "paralleling the pins" - it is using one chip to program another, in the way it is designed to do.


SoftwareSerial mySerial(0, 1);

try changing pin0 and pin1 with some other pins. (lets say with pin2 & pin3)

pin0 and pin1 are used by default Serial.


The other answer mentioned some general ideas; here are a couple of more-specific notes.

• You can direct your writes of single bytes through a routine that reads the EEPROM cell before writing to it, and if its value isn't changing, doesn't write.

• For load-leveling, you can divide the EEPROM address space into k buckets, where k =⌊E/(n+1)⌋, with n = data array size and E = EEPROM size.  Initialize a directory, an array of m bytes all set to k, with m = E-n·k.  When your device starts up, it reads through the directory until it finds current entry, a byte not equal to k. [If all directory entries equal k, initialize the first to 0, and go on from there.]  If the current directory entry contains j, then bucket j contains current data.  When you need to write new data, you store j+1 into the current directory entry; if that makes it equal to k, initialize the next directory entry to 0, and go on from there.  Note that directory bytes get about the same amount of wear as bucket bytes because 2·k > m ≥ k.


Look at the following pinout diagram (from telecnatron.com):

The right-hand diagram above shows the USBASP-board pin-header pin assignments, when you are looking into the pin-header.  The header shell will have a triangle marking pin 1.  Note that pin 1 is on the same side of the connector as the key (the ridge on the cable connectors, the slot on the pin-header shell).  Each socket on the cable also will have a triangle marking pin 1.


How to run background music while the code for a game is executed


NodeMCU burned, did I something fundamental wrong?

Yes, you did something fundamentally wrong.

The component that blew up is a diode.  It is designed to protect the USB from voltage being injected into the board.

That diode can handle an absolute maximum of 1A.

Any fault on your LED strip connection (a short to ground) will cause that diode to vacate the premises. As yours did.

The purpose of the VIN pin (as the label suggests) is as a voltage input. It's not really designed to provide power to other devices, especially as the ESP8266 itself can take more than half that 1A power budget when communicating.  You should not use VIN for powering anything more than maybe a couple of low power sensors. LED strips are a big no-no.


What you need is an edge detector. As long as the PIR output is hight, the ESP stays in reset mode.

You can use a capacitor to do the trick, as shown in the following schematic.
You'll probably want to get rid of the pull-down resistor R1 since you're using an open-collector output.

If the voltage at the collector is the blue curve, then the resulting voltage at the output of the circuit will be similar to the yellow curve. (Note that this simulation used an ideal square wave as input, produced by a push-pull output from a CMOS chip, for example. An open-collector output will have slightly different characteristics, the high peak won't be as high.)

At the instant when the collector voltage drops to (almost) zero, the voltage across C1 will be 0V, so the output is close to 0V as well. Then the capacitor immediately starts to charge through R2, so the voltage on the reset pin rises exponentially.

To prevent a high voltage peak when the PIR turns off, a diode is used to discharge the capacitor more quickly. If the resistor at the collector is large enough, this might not be an issue at all.

The same principle is used in the Arduino UNO, for example, to reset the ATmega when DTR goes low.


The simplest way is just to plug the Arduino in to the BBB.

The BBB has USB.  The Arduino has USB.  Connect the two together and you have both power and data immediately available.

Depending on the Arduino and its version it will either be there as /dev/ttyAMA0 or /dev/ttyUSB0

You can even use avrdude to upload new software to the Arduino direct from the BBB.


Determine what size power supply I need to run stepper motors

You can't run these off the Arduino board for several reasons:

the Arduino board does not provide 7.4V on any pin, only 5V (model dependent, but never 7.4 V)
the Arduino board can provide about 20mA per pin, never 1A or higher
even if the board would only need to pass the voltage on, the total current were >2A. This would possibly fry the board.

So, what you need is: a power supply with constant 7.4V or a regulated one where 7.4V is within the range. From this power supply you will power 3 devices only:

one arduino board via the Vin pin (accepts 7 to 12 V, so 7.4V is ok)
two Dual Channel DC Motor Drivers (accepts 4 to 16V, so 7.4V is ok)

From each motor driver, you will power

one Planetary Gear Unipolar Stepper Motors (designed for 7.4V)

Now, let's sum of the currents:

Arduino Uno board without any peripherals: ~45 mA
two Stepper motors: 1000 mA each
two motor drivers: hard to say. In theory, the motor driver would not consume power by itself, just forward it to the motors. In practice, it cannot forward everything. The driver will get hot and thus consume some power itself. The datasheet is not specific about the power consumption. Let's assume a 70% efficiency = 30% loss. 30% of 1000mA is 300mA each.

The total current needed for this setup is 2645mA. Depending on your budget you could buy a 3A or 5A power supply. At constant 7.4V, that's 23W or 37W. For a regulated 0V to 20V power supply, go for 60W or 100W.

A cheap regulated one should be at ~50 USD. Expect those to be loud because of bad cooling / fan noise.


Trying to create a beats per minute monitor but having diffuctly with the coding? coding wont print any values

There's two basic methods of measuring a frequency, which is basically what you are trying to do.

There is Frequency Counting and Frequency Timing. The latter involves measuring the time between successive pulses and calculating the instantaneous frequency from that. Good for rapidly changing frequencies where you need to know the frequency right away.

Frequency counting is what you are attempting, and is basically counting the number of edges that occur within a certain timeframe.

However your method is slightly flawed: chiefly because you forgot to actually count the edges. You wrote some reasonable code for finding an edge, but failed to actually do anything with that edge.

Also your code is blocking for 10 seconds, which may be fine in this scenario, but is not a good habit to allow yourself to get into.

Instead you should consider something more like this:

void loop() {
    static int count = 0;
    static bool counted = false;
    static uint32_t ts = millis();

    int val = analogRead(sensorPin);

    if ((val > 550) && (counted == false)) {
        counted = true;
        count++;
    } else if (val < 500) {
        counted = false;
    }

    if (millis() - ts >= 10000) {
        ts += 10000; // You could assign ts the millis() value, but
                     // by adding 10 seconds it cancels any drift
                     // caused by other delays in your sketch.
        int BPM = count * 10;
        count = 0;
        Serial.print("BPM: ");
        Serial.println(BPM);
    }
}


Problem using an array inside a switch statement

One big problem is that you forgot the break statements for those cases.  So if it compares in the first one and finds it, you'll still get null because it is going to go look for the third one afterwards.


I found this reference for Wifi.beginAP() in the Wifi101 library, which I hope is the correct one - apologies if it's not.

It says that beginAP() returns either WL_AP_LISTENING or WL_CONNECT_FAILED, so checking for WL_CONNECTED is not sensible.

Try this:

if (WiFi.beginAP(ssid) != WL_AP_LISTENING) {
  Serial.println("Creating access point failed");
  while (true);
}


everything works independitly but not together. Piezo not generating a tone

You connected the piezo to pin 1? Chose other pin. Pin 1 is Serial TX. You 'pump' PWM to USB.

tone() function will make sound no matter if you have a delay there. You set 1 sec with 1000 as third parameter. It will sound 1 sec and the turn of. You do not need the delay() and noTone().

500 is low frequency. If it sounds only one second, can you catch it?

try tone(TONE_PIN, 4500, 500). with speaker it is a nice beeeep


I think, that -1%10=-1, not 9 as you would like. I use

if (tempC<0) {print'-';tempC=-tempC;};
print tempC as usual for positive numbers


Burn bootloader on custom ATmega 2560 board

To burn a bootloader you have to use some external device. That can either be another Arduino or a hardware programmer, like an USBASP or something similar.

You can't just magic the bootloader on there through the USB and a dose of wishful thinking. To use the USB you first have to have the bootloader on there.


RTClib now() within while loop does not update

See the documentation of DateTime::toString():

The buffer parameter should be initialized by the caller with a
string specifying the requested format. This format string may contain
any of the following specifiers: [...] The specifiers within buffer
will be overwritten with the appropriate values from the DateTime.
Any characters not belonging to one of the above specifiers are left
as-is.

The important thing to realize is that the buffer parameter is used
both as input (for the format description) and as output (for the
formatted date and time). You initialize it with a format description
("YYYY/MM/DD-hh:mm:ss\n"). Then, after the first call to toString(),
the same buffer contains the formatted date and time. It does not
contain the format description anymore. On the second call to
toString(), as per the rule “Any characters not belonging to one of
the above specifiers are left as-is”, the buffer is not modified.
Solution: Put the buffer initialization within the same while loop
as the call to toString().


Cannot compile code from Arduino WIFI shield example

Those kinds of errors are usually caused by the selection of an incorrect hardware in the IDE.

Choosing a correct board in the IDE will solve the compilation issue.

Since you said that you used the Arduino.cc online editor, I pasted your code into the editor.

You did not say which Arduino board or which WiFi module you are using, so I chose Arduino Uno WiFi board as a starting point.

Compiling the code produced the same errors as in the post.

Next I chose Arduino Uno WiFi Rev2 board, and compiled without errors.


Use an Arduino as a user interface for the computer

For the sake of completeness, on the more traditional boards where the USB interface is not implemented from the main "sketch" processor, there are three other potential possibilities:

Use the (USB) serial data interface, and have software on the host computer which accepts commands over that.  Obviously, the downside is requiring installation of something on the host system - installation which may require admin privileges or even disabling code signing requirements in some cases (especially if it is to inject the data into the host operating system as if it came from a keyaboard)
On boards such as the Uno and comparable-generation Mega which use a secondary ATmega "u" series part as a USB-serial converter, this chip can be reprogrammed to act instead as a keyboard.  That could make loading sketches tricky - though it might be possible to come up with a dual-mode firmware that could switch roles under control of an external hardware or software signal.
The main ATmega "sketch" processor can generally implement a "not quite compliant, but workable" approximation of a low-speed USB interface in software on arbitrary I/O pins with some external matching/protection componenets.  A USB keyboard is a common demo application of that.


Bluetooth connection to HC-05 paired but not connected (in Linux)

you can try this website for more information

http://wiki.micropython.org/official-accessories/Bluetooth-module-HC05


Setting timer3 in CTC mode - conflict with servo library

Unfortunately, The Servo library reserves output compare A (OCR*A) on timers 1,3,4, and 5 when loaded on an arduino mega. Each can only have one ISR, so you will not be able to define your own TIMER*_COMPA_vect while you use Servo without modifying the library.

However, each hardware timer is equipped with 2 output compare registers. Servo does not claim any TIMER*_COMPB_vect interrupts, so those are free to use, and work exactly the same.

You should watch out for the Servo libraries activities, it could change the configuration of your timer. The default order is on megas is 5,1,3,4 and to give each 12 servos. It only configures the timer once it needs it, so you should be fine using timer 3 until you add that 25th servo.

To change your code, use OCR3B instead of OCR3A (the Output Compare Registers) and set bit OCIE3B instead of OCIE3A in TIMSK3 (the Output Compare Interrupt Enable bits). Then you to change your ISR function to  ISR(TIMER3_COMPB_vect){}

CTC mode only works with OCR3A, but if you set TCNT3 to 0 in your interrupt function you can get similar behavior. Remember to remove the line that turns CTC mode on using WGM12.


How to record steps a stepper motor takes and how to rotate it backward and forward with analog input?

I analyzed your code written in the comment and assuming that it works I prepared a modification that should prevent the motor from moving when the sensor is pressed the same way all the time. The noise values you have to adjust yourself. Make it as low as you can.

I cannot test this code, because I don't have your hardware. Treat it as pseudo code.

#include <Stepper.h>
// change this to the number of steps on your motor
#define STEPS 200
#define NOISE 0.1

Stepper stepper(STEPS, 8, 9);
int previous = 0;
void setup() {
  // set the speed of the motor to 30 RPMs
  stepper.setSpeed(100);
}

void loop() {
  // get the sensor value
  float val = analogRead(A0);

  float difference = previous - val;

  if(difference < -NOISE || difference > NOISE)
  {
    stepper.step(val - previous);
    previous = val;
  }
}


Listen for USB "TX signal received" response on RX

If an MCU which has a built in USB interface (such as the ATmega32u4 on a Leondardo) is properly configured and connected to an operating USB host, it will receive a "Start of Frame" packet every millisecond.  I'm not very familiar with the details of the USB engine on that particular chip, but generally you can detect this as an interrupt, or as a change in a peripheral status register bit.

Going a step further, in the Arduino API an if (Serial) test will determine if the board is connected to a host which is in an active CDC-ACM "serial" session with it, ie, one that has a serial terminal or other program talking to it.  Again, this only applies to those that implement USB within the chip on which the sketch is running.

Chances are your problems can be fixed by enabling the AVR watchdog timer at one of its longer limits and resetting it in the USB ISR found in USBCore.cpp Then if the the USB goes down (ie, the usual every millisecond SoF interrupt fails to happen for several seconds) your Arduino will reset.  In the simple case, it will keep resetting as long as it has power and the USB is down, but you can put some startup logic to wait for the USB while resetting the watchdog if that bothers you.  See for comparative example the implementation details behind the if (serial) and create something similar for your chosen USB mode.


As already stated, your problem is in the use of delay(), which
blocks the program until the delay is over. When your program needs to
be responsive, you have to write everything in a non-bloking manner.
The basics of non-blocking management of time are covered in the
Blink Without Delay Arduino
tutorial, which I
strongly encourage you to read. Applying the technique of the tutorial
to your printing of the distance gives something like this:

static uint32_t last_time_printed;
uint32_t now = millis();
if (now - last_time_printed >= 1000) {
    Serial.println(Distance);
    last_time_printed = now;
}

I think the code is quite straightforward: you record the last time you
printed the value and, if it has been one second since last time, you
print it again.

You also have some other blocking calls in the section where you operate
the sonar. I would not worry too much about delayMicroseconds(): these
are really tiny delays, and your robot does not need to be that
responsive. I would worry about pulseIn() though: this function blocks
until it sees the end of the pulse, or until it reaches a timeout. The
default timeout is one second, which is way too large for this
application. Instead of relying on the default, you should specify a
timeout as a third parameter, as in

duration = pulseIn(echoPin, HIGH, 50000);  // timeout: 50 ms

This would limit the range to about 8 m, which I think should be
more than enough.

Reading the sonar pulse in a completely non-blocking fashion is
possible, by using either an input capture unit or an interrupt, but I
guess it is not worth the trouble, as your robot can probably cope well
with being blocked for 50 ms.


Error using SD card module: no matching function for call to

The function is defined as

// Methods to determine if the requested file path exists.
boolean exists(char *filepath);

Source: https://github.com/adafruit/SD/blob/master/SD.h#L90

You call it with a File object, not the filename. You probably mixed up the variable names:

File myTest;

void setup()
{
  //
  char myTestName[] = "MyTest.txt";

  //[...]
  if (! SD.exists(myTest)){
     myTest = SD.open(myTestName, FILE_WRITE);
     myTest.println("My 1st Line of Data");
     myTest.flush();
  }
//..

Just exchange myTest for myTestName in the SD.exists() call.


Cannot pass objects of non-trivially-copyable type 'class String' through '...'

The basic problem here is that you're trying to pass a String object to sprintf(). That isn't possible because String is a C++ class, and sprintf() is a C variadic function. The only way to pass a string to it is as a char *.

The rest of your call to sprintf() doesn't seem to make sense either, although I suspect it's not what you actually want here. You'd normally use sprintf() if you want to format several values into a string.

As you've suggested in the comments, adding the contents of nospace to data_current character-at-a-time would be the sensible approach. You could do it something like this:

for (int i = 0; i < nospace.length(); ++i) {
    data_current[data_index++] = nospace[i];
}

Note that strlen() won't work on nospace because it's a String object not a char array.

This is all assuming that there's enough space in data_current though. Without seeing the rest of your code, I can't tell you if it will definitely work or not.

Update:
As an alternative, you could use memcpy() to do a block transfer:

memcpy(data_current + data_index, nospace.c_str(), nospace.length());
data_index += nospace.length();

I'm not sure there's much benefit to doing that though. It's hypothetically more efficient, but it probably won't make a noticeable difference unless your string is moderately long and it's being called very frequently. (It's trading-off the loop overhead against a function-call overhead.)