Check contents of buffer after serial read

After a serial.read();, the data [as far as I can tell] is pretty much destroyed. You have two main options to accomplish this:

Store the data in a string when read and then reference this later. I'd do this with a global variable, that is declared outside of a method and accessible throughout your whole sketch.
I haven't read throughout your whole code, but, if you only need to read one character, you can use serial.peek();. This only works if you need the first character of the buffer.

Most likely, your only option would be the first bullet. I'd implement this by adding a method something like this:

String buffer_string_serial;

void setup() { //code here }

void loop() { //code here }

int serial_read_buffer() {
  while(serial.avaliable() > 0) {
    buffer_string_serial = buffer_string_serial + serial.peek();
    return serial.read();
  }
}

Then, just use serial_read_buffer();. That will act similar to serial.read();. The only difference is it will fill up the buffer_string_serial string. You'll have to clear that out after you used all the data so it doesn't get full.


Arduino with NRF24L01. Getting correct data from unkown transmitter

Don't have full details yet. But the VAC8010F uses modbus RS485 protocol.
My research shows that the NRF24 just transmitts and receives the MODBUS protocol to and from master/slave. I have found modbus libs and samples of code on the net. There is a command driven program to communicate with MODBUS free for linux, which is the o/s I use. I don't know about win. Anyway, once I receive the MAX485TTL interface for my ARDUINO MEGA I will write code for data  logging to p.c. then modify to use the NRF24, as I should be able to extract the ADDRESS, and CHANNELS etc, and packet construct.
Hope this is of some help.
Patrick


Need help with the syntax for a function that takes a closure

I suggested in a comment that a functor may be a viable alternative to a
capturing lambda. This answer is mostly meant to answer the OP's request
to elaborate on that suggestion.

Let's define a ButtonCallback as an object that can be called like a
function taking a single boolean parameter:

class ButtonCallback {
public:
    virtual void operator()(bool) = 0;
};

To break down the syntax:

void operator()(bool) declares a method that allows the object to be
called as if it were a function taking a bool argument and returning
nothing. In other words, if you issue a call such as
my_object(true), that method will be called.
virtual _method_declaration_ = 0; says that the method is not going
to be defined for this class (it's a “pure virtual method”), but it
can be defined by derived classes. A class with such a method is
called an “abstract class”: it defines an interface, it cannot be
instantiated, and it's meant to be used as a parent for classes that
do implement the missing methods.

Now the Button class can be defined like this:

class Button {
public:
    Button(uint8_t pin, ButtonCallback &callback)
    : pin(pin), callback(callback) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true);
        Serial.print("release: "); callback(false);
    }
private:
    uint8_t pin;
    ButtonCallback &callback;
};

Notice that the callback is stored as a reference to a
ButtonCallback object. The object itself cannot be stored because it
has an abstract type. Alternatively, a pointer could be used, which
would practically be equivalent.

For using this class, you first have to create the callback as a
concrete class that inherits from from ButtonCallback. Any data you
wish to capture should be stored as class data:

class CapturingLambda : public ButtonCallback {
public:
    CapturingLambda(int data) : some_data(data) {}
    virtual void operator()(bool pressed) {
        if (pressed)
            Serial.println(some_data);
        else
            Serial.println(0);
    }
private:
    int some_data;
};

With all this in place, the following test:

void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    CapturingLambda callback(data_to_capture);
    Button the_button(2, callback);
    the_button.push();
}

void loop(){}

outputs:

press: 42
release: 0

Did you said you “find the syntax of C++ pretty obtuse”? I can only
concur with you!

Addendum: Another alternative is to define the callback using the
good old C idiom: a “lambda” is the combination of a function pointer
and a generic data pointer. The function pointer looks like this:

typedef void (*ButtonCallback)(bool, void *);

The second argument is used to provide the callback whatever data it is
supposed to have “captured”. It is a generic pointer (a void *)
because the library does not know what kind of data its client may need.
Now the Button class has to store both the function pointer and the
data pointer, and always provide the data pointer to the callback:

class Button {
public:
    Button(uint8_t pin, ButtonCallback callback, void *callback_data)
    : pin(pin), callback(callback), callback_data(callback_data) {}
    void push() {  // for testing only
        Serial.print("press: ");   callback(true, callback_data);
        Serial.print("release: "); callback(false, callback_data);
    }
private:
    uint8_t pin;
    ButtonCallback callback;
    void *callback_data;
};

The user would have to decide what kind of data it needs, and do
explicit pointer casts to/from the proper pointer type and void *. For
example, assuming we need an int, the callback may be:

void callback(bool pressed, void *data) {
    int *actual_data = (int *) data;
    if (pressed)
        Serial.println(*actual_data);
    else
        Serial.println(0);
}

Here is the test, with the exact same output as before:

void setup() {
    Serial.begin(9600);
    int data_to_capture = 42;
    Button the_button(2, callback, (void *) &data_to_capture);
    the_button.push();
}

void loop(){}

Notice that, syntactic differences apart, this solution does essentially
the same as the previous one. The main difference is that the data is
given to the callback as an explicit pointer instead of the implicit
this pointer. If you have to choose between these two solutions, I
would suggest going for whichever syntax you find easier to work with.

Beware also that in both cases it is the programmer's responsibility to
manage the storage of the callback data and make sure the corresponding
reference (or pointer) remains valid throughout the lifetime of the
Button object.


Please help me read this Schematic Diagram

They are not poorly described.

All capacitors need to be put from the VCC to GND directly (this will not cause a shortcut).

The left 3 are related to the motor; as it uses a lot of current, it can take the current from the capacitors instead of flowing all the way to the power supply, causing problems of a voltage reduction that can cause other components to fail (temporarily).

The middle two are for the ultrasonic sensor as it also uses some current.
0.1 uF capacitors (the one for the ultrasonic sensor) is typically used for ICs and are called bypass capacitors. These needs to be placed as close as the VCC of the IC (in this case ultrasonic as possible).

And the right two for the power supply itself to remove noise/ripple.

For all capacitors, place them close to where the power is needed (for the motor/ultrasonic) and for the power supply close to the VCC input.

EDIT

Below I added the capacitors for the motor, sorry for using MS paint, having no better option right now. I assume the two red wires from the L293D other than going to the breadboard are the 9V lines (VDD).

Also don't put the capacitors in the same pin as the L293D IC pins, but I didn't want to obfuscate the picture. This might destroy your breadboard or IC pins as there is too less space for both.


Global array doesn't get assigned the space it would take up in memory

There is no problem here. Only the compiler is a bit smarter than you anticipated. It sees, that you are not using arr anywhere, so it just optimizes it out.
There are two ways to prevent that, if you really want to:

I think you can use flags to tell the compiler, that this shouldn't be optimized out. I'm no expert in this, others might know more about this and add their own answer
You can just start using it.


Do the libraries of the Arduino Uno work with the Arduino Mega?

Are the libraries that work with the Uno compatable with the Arduino Mega?

Sometimes.

They have a higher chance of being compatible, due to them both using the same AVR core, but since internal peripherals differ slightly there is a chance that, depending on what the library does, it won't work right.

You just have to try it and see.


Visual Studio's web server is restricted to only servicing clients on the machine it is running on.
To do what you want to do there are a number of things you can do.

Get a full licensed copy of IIS. (Please stop laughing)
Get a version of Apache (might affect your server code and will take a while to setup)
Write yourself a 'proxy server'.  I think if you write a program to run on you PC that creates a socket that listens to port 8080 and forwards any messages on to the VS Web Server (use "C:\Program Files (x86)\Common Files\microsoft shared\DevServer\10.0\WebDev.WebServer40.EXE" /port:6666 /path:C:\WebServer\Root to start it on a fixed port) and forward any replies back to you client.


Replacing several pinMode() and digitalWrite() pins with an array

the correct way to store the pins as an array

Your array initializers are almost right; you just need to separate the values with commas:

digitPins[] = {13, 12, 11, 10};
segPins[] = {2, 3, 4, 5, 6, 7, 8};

You will need to call pinMode() in a loop; it doesn't accept arrays as arguments.

  How about for digitalWrite() where its a mix of HIGH and LOW?

There are (at least) two ways: Make arrays of HIGH and LOW values, matching the digitPins[] and segPins[] arrays one-for-one, respectively. Or for easier maintenance, declare a data structure (struct) of a pin # and a value; make an array of those. It's a bit more complex but also more useful. So, for example:

typedef struct {
    uint8_t pinNum;
    bool pinVal;
} pinInit_t;

pinInit_t digitPins[] {
    {13, HIGH},
    {12, LOW},
    {11, LOW},
    {10, HIGH}
};

void setup() {
  // put your setup code here, to run once:
}

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

struct is short for "data structure"; it lets you combine data of different types into a single named and addressable unit. typedef declares a new data type, and says "Don't allocate any memory just now; this (pinInit) is just a description. I'll use it later on." It makes pinInit a named data type, usable wherever you can use a native data type AND a multi-valued data type (such as an array) is permissible.

Thus, we can make an array of pinInits (pin-# / boolean-value pairs) just by using the name of the new type.

Then your initializing code might look like:

uint8_t i;
for( i = 0; i < sizeof(digitPins)/sizeof(pinInit_t); ++i ){
   pinMode(digitPins[i].pinNum, OUTPUT);
   digitalWrite(digitPins[i].pinNum, digitPins[i].pinVal);
}

The expression sizeof(digitPins)/sizeof(pinInit) evaluates to the number of initializers (# of bytes in the array / # of bytes in one array member).

The expression digitPins[i].pinNum means: "in the pinInit array digitPins, get the i-th element..." (remember, this is a pair of values), "... and take value of the member "pinNum". A little more complex, the first time we think about it, but look at how easily the array reads. And a hint about reading that expression: I read it backwards: "the pinNum member of the i-th element of the digitPins array."

Tomorrow, or next month, when we need another pin, no need to update 2 arrays (remembering of course, to keep them in sequence with each other!); just add another 2-valued element to the one digitPins[] array.


readBytes is blocking until the determined length has been read, or it times out (see Serial.setTimeout()). Where read grabs what has come, if it has come in. Hence available is used to query if it has.

Note that it takes time for a message to go out and to receive either the echo or response. So simply checking the RX buffer immediately after sending something, is expected to be empty for some time. That is where readBytes sites and waits. And I bet the default setTimeout of 1s is sufficient, to get the response.

This is why you see the Serial.read() inside a while or if Serial.available. Hence I typically employ something like the following: Which emulates readBytes (for the most part).

    #define TIMEOUT = 3000;
    loop {
        char inData[20];
        unsigned long timeout = millis() + TIMEOUT;
        uint8_t inIndex = 0;
        while ( ((int32_t)(millis() - timeout) < 0) && (inIndex < (sizeof(inData)/sizeof(inData[0])))) {
            if (Serial1.available() > 0) {
                // read the incoming byte:
                inData[inIndex] = Serial.read();
                if ((c == '\n') || (c == '\r')) {
                    break;
                }
                Serial.write(inData[inIndex++]);
            }
        }
    }

Above code was quickly written and untested. But gets the idea across.


Have you tried other baud rates? Could you paste a link to the manual or upload the manual itself? From what i could find quickly, the module supports 3 modes: RS232, RS485 and Wiegand 26/34. So the manual should provide some means of selecting a particular mode (perhaps the CS pin?). I suspect you arent actually using the RS232 mode, which is why you are getting strange results. If you can't find a way to select a mode, you could try brute-forcing it and try the WG26 mode next. This code from seeedstudio seems to do the job http://www.seeedstudio.com/depot/datasheet/RFID_630_WG.pde or you could look at the Wiegand protocol on Wikipedia and write your own code, since its relatively straight forward. Also a google image search turned up this link to Aliexpress: http://www.aliexpress.com/item/Waterproof-Security-Door-Access-Control-Wiegand-26-125KHz-RFID-ID-Card-Reader-EM4100-102A/1362129655.html; this is your reader, right?


How to automatically reset the nrf24l01+ with code?

I found the problem occurs because the transmitter is expecting acknowledgment from the receiver which is getting lost somehow, while transmission and the transmitter still waits for ack for the last transmitted data (which it never gets) so it keeps on transmitting the last packet again and again. I saw on forums that its because of the TX buffer getting full after 3 retries or something. I don't exactly know why it happens.

I first tried resetting just the transmitter through code but it was not enough (as already mentioned in the question). So I now reset both the TX and RX using the below code. I have a separate 1 byte reset-counter in the first byte of the array (you may use a single byte variable) which acts as an id for the packet (you may use the internal PID as well).

The below code resets  the TX if transmission fails by checking the return value of write function and resets the RX when it receives the same ack or packet (with the same reset-counter value) more than 2 times (I use a condition to check if the last counter value is different from the current one or not). To reset it using code I use the below algorithm :

Power Down the NRF using powerDown() function.
Re-initialize the nrf for the MCU.
Power Up the NRF using powerUp() function.

Note: I am using TMRH20 RF24 Library.

TX Code

void radio1_init()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  myRadio1.begin();
  delay(100);
  myRadio1.setChannel(96);
  myRadio1.setPALevel(POWERLEVEL);
  myRadio1.setDataRate(DATARATE);
  myRadio1.setAutoAck(1);
  myRadio1.enableAckPayload();
  myRadio1.enableDynamicPayloads();
  myRadio1.setRetries(2, 10);
  myRadio1.setCRCLength(RF24_CRC_8);
  myRadio1.openWritingPipe( addresses1[0]);
}

void loop()
{
  dataTransmitted[0]++;
  if ( myRadio1.write( &dataTransmitted, sizeof(dataTransmitted)))
  {

    if (myRadio1.isAckPayloadAvailable())
    {
      myRadio1.read(&ack, sizeof(ack));
    }
  }
  else
  {
    myRadio1.powerDown();
    \\Serial.println(" 1 Tx1 problem end");
    radio1_init();
    myRadio1.powerUp();
  }
}

RX Code

void radio2_init()
{
  pinMode(9, OUTPUT);
  digitalWrite(9, HIGH);
  pinMode(10, OUTPUT);
  digitalWrite(10, HIGH);
  myRadio2.begin();
  delay(100);
  myRadio2.setChannel(96);
  myRadio2.setPALevel(POWERLEVEL);
  myRadio2.setDataRate(DATARATE);
  myRadio2.setAutoAck(1);
  myRadio2.enableAckPayload();
  myRadio2.enableDynamicPayloads();
  myRadio2.setRetries(10, 10);
  myRadio2.setCRCLength(RF24_CRC_8);
  myRadio2.openReadingPipe(1, addresses2[0]);
  myRadio2.startListening();
}

void loop()
{
      if (myRadio2.available())
      {
        myRadio2.read( &dataReceived, sizeof(dataReceived));
        myRadio2.writeAckPayload(1, &ack2, sizeof(ack2));
        if (prevack2 == dataReceived[0])
        {
          \\Serial.println("RX 2 problem");
          c2++;
        }
        prevack2 = dataReceived[0];
        if (c2 > 2)
        {
          myRadio2.powerDown();
          radio2_init();
          myRadio2.powerUp();
          c2 = 0;
        }
      }
}


According to sources at c:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial* (on Windows platform), you can use pointer to Stream class (because Serials are inherited from Stream).
So, your function could look like this:
void writeToSerial(bool useSerial1)
{
   Stream* serialPortObject;

   if (useSerial1)
   {
      serialPortObject = &Serial1;
   }
   else
   {
      serialPortObject = &Serial2;
   }

   serialPortObject->write("test123");
}


Why map Arduino pins 2 and 3 to Rx and Tx instead of using the build in Rx and Tx pins?

SoftwareSerial lets you add an additional serial port using "bit banging" to read/write to the port. This lets you connect up another serial device (eg. GPS, RFID reader, MIDI device, LCD) to this extra port, and still use the hardware serial interface (pins 0 and 1) via the USB port to send messages and/or debugging to the connected PC.

  Is there any special wiring needed to send messages to the connected PC? Or is it enough that they just not be in use?

Pins 0 and 1 are connected to the Atmega16U2 USB interface chip. If it gets what looks like serial data it will forward it to the PC.


Arduino String class provides method c_str(). So you don't have to convert it to C string, as it's already stored as a C string internally.

And as mentioned in comments, the second parameter of strtoul is:

  endptr
      Reference to an object of type char*, whose value is set by the function to the next character in str after the numerical value.
      This parameter can also be a null pointer, in which case it is not used.

Basically you can reduce whole foo to the:  return strtoul(time.c_str(), NULL, 10);


Update Variable via Arduino to Arduino I2C

I see now what the issue was. But to answer my questions:

Wire.available(); will not work if called outside of an event handler. I confirmed this while reading through the Wire.cpp source code and it explicitly states that the function should only be called from an event handler.
It is as simple as only a matter of updating global variables. I feel quite silly for not realizing that simply declaring variables outside of a function gives ANY function access to it rather than only the main function.

I see that the other answer mentions applying the volatile modification to the variables, but this is only necessary when the function in question is attached to an interrupt handler.


Making Laser Tripwire with Phone Messaging

As with any project, where you don't know where to start or what to use, there are a number of steps you should go through.

First define exactly how you want your system to work.  There are many many different ways of achieving what you talk about in your question, and most (if not all) of them can be performed using an Arduino of some form with extra hardware to do specific jobs.

Only when you have defined such things as:

What distance must your trip wire be effective over
How long will it be interrupted for typically
Will it be a permanent installation or a mobile battery operated system
What kind of messaging do you want on the phone
Must the message be receivable anywhere on the planet or just within a certain range of the tripwire system

For instance, for the communication, would you want to send a text message via the mobile phone network (SMS), or an email through the internet, or connect to a custom app using Bluetooth, etc., - there are a myriad of different possibilities.

Once you know exactly what you want it's then time to break the project down into little blocks.  Each block can then be tackled separately and you can research what is available to help you perform that specific task within the bounds of what you have specified in your requirements list.

Each of the blocks of your project are quite simple to create and there are generally examples and tutorials for most things on the web that can help you.


Defining an NFC tag as NDEF using the Arduino Uno and the PN532 NFC module

I found the answer to my own question right after posting it, while going through the examples included in the library above:

The library contains an example named "FormatTag" which does exactly what I was looking for.


Is this the right command to check? Why is it always with the same value?

The only way that size can change is if you desolder the can from the top of the ESP32 module, then desolder the flash chip, and replace it with one that has a different capacity.

The free space is not a function of the flash chip. It is a function of the filesystem you are using to store your data - be that SPIFFS or FAT.

You should check the manual for the filesystem you are using to find what functions there are pertaining to space usage.


\r returns the cursor to the start of the current line. You can't use it to go back up to previous lines.

Instead you need to learn ANSI escape sequences to move the cursor around.

For example Serial.print("\e[2J"); will clear the entire screen. Serial.print("\e[1;1H"); will move the cursor to the top left corner of the screen (the coordinates are \e[{Y};{X}H by the way).

You can also add colour and all sorts of other nice things, none of which the Arduino IDE's "Serial Monitor" can do.

You can find a good reference of ANSI escape codes here.


Generating two 1MHz, 33% duty cycle PWM signals

#include <PWM.h>

This is a library meant to abstract the details of the timers, so you
don't have to directly access the hardware registers. If you do access
the hardware directly, you have no use of this library: just remove this
line.

  pinMode(3, OUTPUT);

This is a program instruction (technically called a “statement”). You
cannot have instructions at the top level of the program: they must all
be within a function. Since you want all that follows to be executed
only once when the program starts (as this is just a one-time
configuration), you have to put it in setup(), as:

void setup() {
    pinMode(3, OUTPUT);
    pinMode(11, OUTPUT);
    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS22);
    OCR2A = 76;
    OCR2B = 76;
}

Note that a valid Arduino program also needs a loop() function, with
all the stuff that has to be executed repeatedly. In your case, there is
nothing to be executed repeatedly, but you still have to define an empty
loop() function:

void loop() {
}


How do I use the Arduino Mega as a 16-bit SPI slave?

You might need to check the Arduino Mega/ATmega2560 product description and SPI slave mode.

  In SPI Slave mode, the control logic will sample the incoming signal
  of the SCK pin. To ensure correct sampling of the clock signal, the
  minimum low and high periods should be: Low period: longer than 2 CPU
  clock cycles. High period: longer than 2 CPU clock cycles.

This implies the maximum SCK in slave mode. 16 MHz SCK would be too fast for an Arduino Mega (at 16 MHz).

Also there is a significant latency to the ISR. To achieve higher slave mode clock frequency:

Time between slave mode chip select and clock must be stretched to compensate for the ISR latency.
The ISR will need to busy wait for all data (as the Arduino SPI transfer() is implemented).

Cheers!


From the bottom to the top of the RAM, you have:

the .data section (statically allocated initialized variables)
the .bss section (statically allocated non initialized variables)
the heap (dynamic allocations with malloc() and new)
free space
the stack (return addresses and automatic local-variable allocations)

See the memories of an Arduino for a more lengthy
discussion.

The sizes of the .data and .bss sections are known at build time. This
is the “Global variables” memory usage reported at the end of the
compilation. The rest of the RAM is available for the heap and the
stack. This is the amount reported as “leaving 1852 bytes for local
variables”, where “local variables” is a slight oversimplification.

Your example program doesn't use heap allocation. It does use some
static allocation, mostly for the Serial buffers, and a lot of stack
for:

the return addresses from the calls to main() and setup() (4
bytes)
the local arrays a and si (N+4 bytes)
the memory needed by sprintf() or Serial.print() (unknown)

Even ignoring the last item, you can see that the whole RAM will be
consumed when 4 + N + 4 = 1852, i.e. N = 1844. As you make N larger than
this value, the stack bumps into the .bss section, and you start
corrupting your global variables. The behavior you describe is
consistent with the program corrupting the internal data structures of
the Serial object.

  How should I debug, measure, dimension, or prevent this situation

There is no easy way to determine beforehand the amount of heap and
stack your program will consume. The usual solution is to measure and
report it at run time. See for example the MemoryFree library
(there are many similar to this).


Is it possible to charge a battery using a water flow sensor?

No, it is basically a hall-effect sensor that requires power and generates a low effect pulse.

Look for a generator. Something like this; https://netram.co.za/1199-36v-micro-hydro-generator.html

Cheers!


There is a new command for the ESP8266 in AT version:0.50.0.0 - SDK version:1.4.0 that lets you explicitly set the full UART configuration:

AT+UART_CUR – set the current UART configuration
This command sets the current UART configuration; it does not write to the flash. Hence there is no change in the default baud rate.

For example:

AT+UART_CUR=9600,8,1,0,0


Voltage divider for 6 non intrusive current sensors

I assume you refer to a circuit like this:

simulate this circuit – Schematic created using CircuitLab

The "reference" you speak of is not a reference - it is a virtual ground. A ground reference that is at a different potential to the Arduino - in this case 2.5V higher.

Since it is just the ground for the circuit you can use the same one for all the current transformers without problems.

If the offset voltage were applied to the output (as is often done for active devices that create an AC waveform, such as audio signals) then you would require a separate offset voltage for each one, since otherwise you would be connecting all the outputs together, which would be bad.

You can also "reverse" your thinking. The "offset" voltage you apply is ground, and the Arduino's "ground" is 2.5V below that. It's all relative.


The Arduino Uno and Arduino Nano are fairly compatible.

Problems:

The board layout isn't the same, Nano's won't wield a classic "shield".
Nano's don't have a barrel jack.
Nano's (usually) have a micro USB connector. While the Uno has another one.
But, Nano's are smaller, withouth leaving out the USB connection.

But wait!

Microcontrollers of the same family are quite scaleable, Nano and Uno might even have the same micro on it! Be sure your Nano has the same Atmega328(P?) chip as your Uno.
Check if the pins you're using, are accessible on the Nano. Then you should be fine.

There is a little problem with cheap Arduino Nano's, I've bought 2, from 2 different vendors. They we're about 3$.

The first one featured a counterfeit FTDI chip. By installing the latest FTDI drivers, my FTDI actually got bricked. I had to undo this by using M_PROG or some EEPROM flashing tool to unbrick the chip, and install older drivers (which didn't corrupt it).
The second one featured an CH340G usb-serial chip. I had to download and install the drivers from a chinese website. But Windows wouldn't install unsinged drivers that easily. You have to go into advanced boot options mode and allow installing unsigned drivers.

Getting these Nano's working took me an reasonable amount of time. But they now are working quite well :)
It's something to take into account when buying cheap.

I wouldn't really bother for the alternative crystal, as long as they're 16Mhz. For time-critical behaviour, I wouldn't rely too much on your crystal.


Random data sending integers between two Arduinos

You are being too impatient.

The receiver needs to wait until there is some data available.  if (mySerial.Available() > 0).  So before every read add that line and it should work.


Arduino wrap or subclass print() to work with multiple Serial

You can create a class derived from Print that forwards its output to
either or both Serial and Serial1. The only method you need to
implement for this to work is write(uint8_t):

class DualPrint : public Print
{
public:
    DualPrint() : use_Serial(false), use_Serial1(false) {}
    virtual size_t write(uint8_t c) {
        if (use_Serial) Serial.write(c);
        if (use_Serial1) Serial1.write(c);
        return 1;
    }
    bool use_Serial, use_Serial1;
} out;

You would use it like this:

out.use_Serial = true;
out.println("Printed to Serial only");
out.use_Serial1 = true;
out.println("Printed to both Serial and Serial1");
out.use_Serial = false;
out.println("Printed to Serial1 only");

Note that with this approach, unlike yours, printing number will format
them as text only once, and the underlying Serial and Serial1 will
only handle the resulting characters.

Edit: To answer the question in OP's comment, the construct

class ClassName
{
    ...definition...
} classInstace;

is a shotcut for

class ClassName
{
    ...definition...
};
ClassName classInstace;

A very similar construct exists in plain C:

struct struct_name {
    ...the struct fields...
} struct_instance;


Cannot understand why this code work but this not

Your problem is that you are doing integer maths.

mr = (130-20)/(1023-205)

reduces to:

mr = 110/818

Which normally equates to:

mr = 0.135

But since all those numbers are integers the result is an integer, and is truncated at the decimal point, which means that mr is assigned:

mr = 0

You can force floating point maths by either including a decimal point in one of the numbers, or adding the suffux f:

mr = (130-20)/(1023-205.0)

or

mr = (130-20)/(1023-205f)

Or casting a portion of the sum to a float as your other code does.


Unexpected output for simple code involving calculating a time interval of 10ms

The problem is, that you are filling up the Serial buffer rather fast, because you try to send ASCII numbers every 10ms at only 9600ms. When the buffer is full, Serial.println() will wait, until there is enough space free in the buffer for the current data. That makes your loop lasting significantly longer.
In that case the time, where the time is exactly 10 is missed. Thus the code does nothing at that point, until time rolls over and gets 10 again (48 days I think).
While you can mitigate the problem by using a higher baudrate, the main problem is still
if(time==10){

You have only provided an example code. Your real code might sometimes take longer than 10ms out of some other reason (actually this already gets critical, when the loop takes longer than 1ms, since it then might already miss the one moment, where time is 10). To futureproof your code and make sure, that you don't hunt down the same bug again and again, you should do, what you were told in the comments, and use
if(time>=10){

Depending on your code the event will still happen after 10ms the absolute most of the time. But this variant also doesn't break, if the loop takes longer than 10ms sometimes.


According to the datasheet (page 5) the "Input High Level Voltage" is 3.25V.  That means that any voltage over 3.25V will count as a HIGH.

That is kind of borderline for 3.3V logic which can drop below 3.3V for a HIGH depending on load and other circumstances.

So while it might work off 3.3V I would say for reliable operation you should use some form of level shifting in your circuit, yes.

A simple, cheap, MOSFET-based logic level shifter will do the job - there is no need for anything fancy.


Weight: marginal as the difference between one board (with everything on it) and two boards (Uno plus DOF) may be - for model airplanes every bit counts.

Size: the traditional "Uno" is much larger than the ArduIMU integrated boards.

Power: the integrated board PROBABLY will use less and thus get away with a smaller (lighter) battery.


No, this is not an acceptable solution.  The RC522 needs in excess of 100mA to operate, and an ESP8266's GPIO pin can only supply 12mA maximum.  You will damage the ESP8266.

You need to use a P-channel MOSFET with the gate pulled HIGH as a high side switch.

simulate this circuit – Schematic created using CircuitLab

Set the GPIO to LOW to turn on the MOSFET. Set it HIGH or to INPUT to turn off the MOSFET.

Note 1: Set the communication IO pins to INPUT before powering off otherwise they could back-power the target device through the ESD diodes in the IO pins.


So why you don't just ignore it?

if(directionN >= 32){   //check if char is readable ascii character
  Serial.print("direction is:");
  Serial.println(directioN);
}


Can I emulate Arduino in a headless CI/CD setup?

The problems with this kind of software is:

always behind the recent releases of cores/ hw variations.
reliable only for simple programs/tasks
Imho all the products I tested (mainly on Win) are actually a (somewhat crippled ) teaching and visualization help.
if you look into the emulators you mostly see only support for different chips and not the whole micro computer, which is far more complex to create

Due to the low cost of the hardware it is easier to run real HW setups with HW diagnostics (and get also feedback for thermal/electric issues) So this kind of SW is for the low cost avr/esp HW and its hundreds of variants (even between production batches from one manufacturer) hard to develop and mantain. So you'll only find nice "play around" emulators which won't fulfill any professional requirement (even if some claim it)


Nano-like Board - Programmer Not Responding

That is a Chinese NANO clone, using the notorious CH340G chip.

macOS does NOT have a driver, and it is difficult, if not impossible to get a driver which 1. macOS will let you install, and 2. Actually works.

I do not know the state with current Windows.

In my experience, in addition to poor support the chips are unreliable and fail to respond.

You could try using a Uno as ICSP, bypassing the boot loader, or (untried) use an external USB serial interface. Both of these approaches are documented on the Arduino site.


NodeMCU v2 with MH-Z19B CO2 sensor UART read problem

It says in your description that you have the Rx connected to Rx and the Tx connected to Tx.  That's backwards.  What one transmits the other needs to receive.  When you have a conversation with someone, do you talk into their mouth and listen to their ears?  You should have Rx-Tx and Tx-Rx.

You also need to be sure that it is OK to feed a 5V Tx into that Rx pin.  On some ESP8266 boards it is and on most it isn't.  If you don't have one of the boards that specifically has circuitry built in to handle 5V inputs then you will fry your NodeMCU


How to read long value sent by Arduino in C

char b[1];  // read expects an array, so we give it a 1-byte array

No, it expects a pointer to a destination to store the data. You don't need a 1-entry array - you can simplify your code with:

char b;
...
int n = read(fd, &b, 1);  // read a char at a time
...
buf[i] = b;
... etc ...

  Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

C has the function strtoul() which is far more efficient that sscanf.

uint32_t val = strtoul(buf, NULL, 10);

The 10 is the base to convert from, so you could convert hexadecimal (base 16), octal (base 8), etc using it.

  Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

You're defining the variable until to contain \n, yet passing the variable newLine to your function. Maybe that has something to do with it?

  Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

You can send a 32-bit value using just 4 bytes. However it's not reliable without implementing a whole protocol around those 4 bytes which, for just 4 bytes, is a bit of a waste. Simplest just to stick to ASCII encoding your data.


A good way to avoid display flicker is to only update the display when needed.  The display update is what causes it to flicker.  If you change your main loop as below, the display will only update when needed (when the current reading is different than the last reading).  It's probably also a good idea to only read the temperature every 2 seconds or so which can be controlled with a simple delay().

float temp, last_temp = 0;

void loop() {
    temp = dht.readTemperature();
    if (temp != last_temp)
    {
        sevseg.setNumber(temp,1);
        sevseg.refreshDisplay();
    }
    last_temp = temp;
    delay(2000);
}


Why does SoftwareSerial::read() return int?

The documentation on Arduino's website shows SoftwareSerial::read() as returning a char.

No it doesn't. There is nothing in the documentation that tells you the return type. There is only an example where the returned value is assigned to a char variable. That doesn't mean that it returns a char - it just means that whatever data type it does return can be invisibly cast to a char by the compiler.

  The header shows that the method returns an int.

Indeed it does. That is because that is what it returns.

  The cpp definition shows SoftwareSerial::read() returning the value from a buffer array of uint8_t values.

Yes, because the valid data that it deals with is 8 bits in size. Just because it handles 8 bit "valid" data doesn't mean that that's all it ever wants to return.  The "no data available" return value of -1 is obviously not something that is stored in the data. It's a status, not data.

  Why would the interface return an int instead of a uint8_t?

Because a uint8_t cannot encompass all the functionality stated in the "Returns" section:

  the character read, or -1 if none is available

You can't return -1 in a uint8_t.

  Why do the Arduino docs show it as returning a char?

It doesn't - as I mentioned above. It makes no claims at all about the returned data type.

  Is it safe to send/receive 8-bits at a time using this library?

Yes. It performs serial data transfers using 8-N-1 by default. That's 8 data bits, no parity, and one stop bit.

It's this kind of confusion with return types and bytes and integers and things that make people ask why they keep getting ÿÿÿÿÿÿ on the serial monitor. That's -1 cast as a char. I.e., "no data available" but they ignore that and treat everything returned as a char - most probably because the Arduino documentation shows an overly simplified example that ignores the possibility of a -1 being returned and treats everything as a char.

IMHO much of the Arduino documentation is somewhat sub-par and should not be taken literally - only as a rough guide for what is available. The same goes for much of their example code and projects.


Usually you should set Enable (A and B) pins on L298 to LOW, effectively turning off the driver.


How much can I recurse? How much can I recurse? How much ca!@#QFSD@$RFW

If you really want to recurse (and as @jippie said it is a bad idea; subliminal message:  don't do it) and want to know how much you can recurse, then you will have to perform some calculation and experiments; also you generally will have only an approximation of it as it depends a lot on the memory state at the time your recursive function will be called.

For this, you should first know how SRAM is organized inside AVR-based Arduino (it won't apply to e.g. the Arduino Galileo by Intel). The following diagram from Adafruit shows it clearly:

Then you need to know the total size of your SRAM (depends on Atmel MCU, hence what kind of Arduino board you have).

On this diagram, it is easy to find out ths size of Static Data block as it is known at compile-time and won't change later on.

The Heap size can be more difficult to know as it can vary at runtime, depending on dynamic memory allocations (malloc or new) performed by your sketch or the libraries it uses. Using dynamic memory is quite rare on Arduino, but some standard functions do it (type String uses it, I think).

For the Stack size, it will also vary during runtime, based on the current depth of function calls (each function call takes 2 bytes on the Stack to store the address of the caller) and the number and size of local variables including passed arguments (that are also stored on the Stack) for all the functions called until now.

So let's suppose your recurse() function uses 12 bytes for its local variables and arguments, then each call to this function (the first one from an external caller and the recursive ones) will use 12+2 bytes.

If we suppose that:

you are on Arduino UNO (SRAM = 2K)
your sketch does not use dynamic memory allocation (no Heap)
you know the size of your Static Data (let's say 132 bytes)
when your recurse() function is called from your sketch, the current Stack is 128 bytes long

Then you are left with 2048 - 132 - 128 = 1788 available bytes on the Stack. The number of recursive calls to your function is thus 1788 / 14 = 127, including the initial call (which is not a recursive one).

As you can see, this is very difficult, but not impossible to find what you want.

A simpler way to get the stack size available before recurse() is called would be to use the following function (found on Adafruit learning center; I have not tested it myself):

int freeRam ()
{
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

I strongly encourage you to read this article at Adafruit learning center.


I suspect the problem is that your hardware-debounce capacitive circuit isn't working well enough to accurately debounce the contacts, and that invalid transitions are occurring on the quadrature lines as read by the program.

Note that use of Serial.println() within your clkRise() interrupt handler is problematic, because Serial.println() uses interrupts itself. As far as I know, println() is not reentrant, ie cannot be used correctly from the multiple interrupts that may start before previous println() calls finish their background processing.  The bits of extra delay introduced by LCD code may merely be exposing a problem.

There is no need for either hardware or software debouncing on quadrature inputs.  A correctly-implemented state machine will reject invalid conditions that arise during bounce, or will immediately follow any extra up-tick by a corresponding down-tick, or vice versa.

For some state machine code, see for example answer 16420/3917 and also see answer 18221/3917.  Also see answer 19109/3917.


I suppose you're referring to the HC05 module, already soldered on a board, with the 6-pin header. The regulator is on that board.

Online you'll find several versions of that board, therefore you should check the schematics, to find which you need to mount. For instance, on some board, a R1114-33 is used.

Changing the regulator is not the hardest task on earth, however, other components are very close to it (capacitors).

Still there are 2 things to consider:

Is it worthy to change the regulator? That module will cost few
bucks.
As you can see from the datasheet, the regulator is short-circuit protected (yes, it does not mean that it will be indestructible). I think, instead, you destroyed one of the two ICs of the bluetooth module soldered on board. And those one, beside of being quite difficult to find and expensive in small quantity, they are very hard do replace.


Did I overheat my Arduino while soldering to perfboard?

I would like to clarify that my only question in ENTIRE post was: "Is that enough to break the board?"

The answer to that narrow question is that heat from soldering with an iron is extremely unlikely to have done this.  IC's are in practice (vs data sheet) quite heat tolerant, and further the pins you are soldering on are not even the pins of the IC or any electronic components, but rather those of the module headers.  You'd be more likely to melt the plastic web between those headers pins, but even that won't be a great problem since they are already in place. Or if you were soldering directly on the board, lifting a pad or trace - but you were not doing that.

Your actual problem is something else, what that might be is presently unanswerable due to the lack of detail in your question.


Probably you need two SP10T switches, where you can programmatically decide which of the SPI pins will be sent to which of the 10 outputs which are connected to the 10 pin bus.


Arduino should check the same way like a USB keyboard or a USB mouse, if turned on notebook is connected

With Arduino Nano, you don't have control over the USB, because it is handled by the USB-to-TTL-Serial chip on the board. The MCU is to this adapter connected only with RX and TX of the Serial interface.

With Arduino Micro you could retrieve the state of the USB connection, because he MCU ATmega32u4 has a build in USB support an handles the USB connection from application (sketch).


Teensy 2.0 MIDI: Number of notes in a chord limited to 6?

@Majenko pointed me to the root cause of the problem: I was sending MIDI notes via Ableton's feature of using the computer's keyboard. It seems that the OS (or the keyboard) cannot send/receive more than six simultaneous keystrokes.


Think about it "logically" (pun intended...):

You read a character.  Say it's "A".  You then compare it to both '\r' and '\n'.

char c = Serial.read();
if (c != '\r' || c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR or A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR or CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  If it's OR, then if either part is true then it will be true.  So since CR is not LF it will add it.

Now:

char c = Serial.read();
if (c != '\r' && c != '\n') { // <- This line interesting
    mAnswer[mAnswerLength] = c;
    mAnswerLength++;
}

That is saying "If A is not CR and A is not LF then add it".  Since it's A and not LF or CR then it's going to add it.  Now imagine it's CR.  "If CR is not CR and CR is not LF then add it".  CR is CR, so the first part will be false.  But CR isn't LF, so the second part is true.  Just as before.  However, if it's AMD, then if BOTH parts are true then it will be true.  So since CR is CR it won't add it.

In summary, the first one will ALWAYS be true since one half is always going to be true.  The second one will ONLY be true if BOTH parts are true.  So the first one just plain isn't going to do what you want.


You need to implement hysteresis. Set two temperature points around set_temp. One a little higher to be a limit for turning the heater off and a one a little lower then set_temp to turn the heater on.

You only need to change your if else condition a little

if (current_temp < set_temp - HYST_VALUE) {
  digitalWrite(ssr_u, HIGH);
} else if (current_temp > set_temp + HYST_VALUE) {
  digitalWrite(ssr_u, LOW);
}

you could start with

int const HYST_VALUE = 1;


Using 2 piezo buzzers to emit the same tone with phase difference

Since the frequency is so low, you can generate the signals in software.
That would not be as clean as timer-generated signals, but it will be
much easier. And probably clean enough for the intended purpose.

In order to generate a tone, you have to repeatedly switch the pin
connected to the piezo. This is very similar to blinking an LED, only
somewhat faster. Blinking an LED is the very first thing you learn to do
with an Arduino, but you may notice that blinking two LEDs is a
little bit trickier. The problem – and the solution – is
discussed in the Arduino tutorial Blink Without Delay. Building on
that tutorial, here is an example program that generates two 100 Hz
signals in quadrature:

const uint8_t PIN_A = 8;
const uint8_t PIN_B = 9;
const uint32_t HALF_PERIOD = 5000;  // 5000 us
const float PHASE_SHIFT = 0.25;     // 1/4 period

uint8_t state_A = LOW;
uint8_t state_B = LOW;

uint32_t last_A_toggle = 0;
uint32_t last_B_toggle = - 2 * HALF_PERIOD * PHASE_SHIFT;

void setup() {
    pinMode(PIN_A, OUTPUT);
    pinMode(PIN_B, OUTPUT);
}

void loop() {
    uint32_t now = micros();
    if (now - last_A_toggle >= HALF_PERIOD) {
        last_A_toggle += HALF_PERIOD;
        state_A = !state_A;
        digitalWrite(PIN_A, state_A);
    }
    if (now - last_B_toggle >= HALF_PERIOD) {
        last_B_toggle += HALF_PERIOD;
        state_B = !state_B;
        digitalWrite(PIN_B, state_B);
    }
}

If you compare this with the above mentioned tutorial, there are a
couple of differences worth noticing:

The timings are measured using microseconds rather than milliseconds,
for getting a better accuracy
The variables holding the times of last toggle are updated like
last_A_toggle += HALF_PERIOD rather than last_A_toggle = now (the
equivalent of previousMillis = currentMillis). This is needed to
keep an accurate average frequency. Otherwise the time taken to
execute the code would make the frequency slightly off.

There is a little trickery in the initialization of last_B_toggle,
which is an unsigned number initialized to a negative value. The
initialization is valid and works modulo 232. Using a small
positive value would have the ill effect of now - last_B_toggle
overflowing to a very large positive number on the first run of
loop(), putting last_B_toggle effectively in the distant past.


Can't Upload Sketch, Atmel SDM Chip Overheating

u need to cool down the chip for a few minutes and it will work the uploads use a heatsink or something small enough to cover it


Send/receive data from/to Raspberry Pi to/from Arduino with HM-10 (Bluetooth LE module)

HM-10 is a BLE device. You'll need to understand BLE programming, which is quite different than classic Bluetooth.
There is no standard BLE service for serial communication.
The best way on a Pi to use BLE is with the

noble and bleno modules for node.js.
Or start by playing with gatttool.

If you are fit in Phyton:
The HM-10 style device will send notifications that the Pi's BLE device can read. Basically you need to
attach a 'delegate' call-back function to the Peripheral object,
and then wait for notifications.
The call-back can then process the received data.
You'll have to install the bluepy lib on the PI. This sample code writes to an Arduino HC-10 device

import bluepy.btle as btle

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
s = p.getServiceByUUID("0000ffe0-0000-1000-8000-00805f9b34fb")
c = s.getCharacteristics()[0]

c.write(bytes("Hello world\n", "utf-8"))
p.disconnect()

Here is some code for reading from an Arduino HC-10 device

import bluepy.btle as btle

class ReadDelegate(btle.DefaultDelegate):
    def handleNotification(self, cHandle, data):
        print(data.decode("utf-8"))

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
p.withDelegate(ReadDelegate())

while True:
    while p.waitForNotifications(1):
        pass

p.disconnect()


First you make 4 parallel H-Bridges, http://en.wikipedia.org/wiki/H_bridge then you attach it to an external powersource ( or attach directly to the battery to prevent burning your arduino )

Attach every up to a pin, making it high makes the motor running, you need 8 pins for this, eg pin 1 makes motor 1 go forward, pin 2 makes motor 1 go back and so.

This is by far the most practical solution, but it is the easiest, and can be done with 8 PNP and 8 NPN transistors.

If you don't know how transistors work i suggest https://www.youtube.com/watch?v=-td7YT-Pums collins lab, it is both educational and entertaining.


Can I have more than 1 pin "activated" at the same time?

If you change each led in order they will change fast enough that you cannot tell. The lag between changes will be on the order of microseconds.

If you want to dive into direct port manipulation you can change multiple leds at the same time. Though not all at the same time instead they are grouped.


Arduino Uno serial communication using USB-to-TTL converter

How to send data(Hello World) from Arduino Uno to PC using USB to TTL/UART(PL2303 4 wires)?

Serial.print("Hello World");

That is, assuming it's connected to pins 0/1. Otherwise you would have to use SoftwareSerial.

  why I need to press the reset button during upload a program using PL2303?

Because it lacks a DTR signal to press the reset button for you (resetting runs the bootloader).


Change From One State Machine To Another

If you think you need two finite state machines, where only one of them
is running at any given time, then it is trivial to combine them
together: draw them side by side, and add the required transitions
between them. The set of states of the combined FSM will be the union of
the states of the initial FSMs. For example, if you have:

FSM 1 states: STATE_A, STATE_B, STATE_C
FSM 2 stages: STATE_D, STATE_E
global states: FSM_1_RUNNING, FSM_2_RUNNING

Then the combined FSM will have the states STATE_A, STATE_B,
STATE_C, STATE_D and STATE_E, and all the transitions of both
initial FSMs.


Whatever your power supply voltage is. If you run it from 5V you get 5V IO. If you run it from a 3V coin cell you get 3V IO.


Why is my arduino acting like a radio? And is there a way to abuse this?

I did something like that a while ago. Hardware:

Code:

const byte ANTENNA = 9;

void setup()
  {
  // set up Timer 1
  TCCR1A = bit (COM1A0);  // toggle OC1A on Compare Match
  TCCR1B = bit (WGM12) | bit (CS10);   // CTC, no prescaler
  OCR1A =  9;       // compare A register value to 10 (zero relative)
  }  // end of setup

void loop()
  {
  pinMode (ANTENNA, OUTPUT);
  delay (500);
  pinMode (ANTENNA, INPUT);
  delay (300);
  }  // end of loop

The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 KHz, since one toggle turns the output on, and second toggle turns it off.

If you hold the Arduino near an AM radio tuned to around 800 KHz you should hear a hissing toggling on and off (like Morse code) as the carrier is turned on and off for 0.5 / 0.3 second intervals.

  would there be a relatively easy way to pick up the signal using just an arduino and cheapo components?

I think you might find making a receiver a bit harder than a transmitter.


Getting different results from function. How to retrieve values correctly?

A PI controller has “state”: it has to remember the sum of all the
previous errors. If you want several controllers you have to
independently store the state of each one.

The traditional solution used by C programmers is to write a controller
function that takes an extra parameter which is a pointer to the state.
In C++ you can use a reference instead:

// PI controller.
float PIController(float &sum, float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

You would use it like this:

void loop()
{
    static float sum_1, sum_2;  // State of the controllers.
    // ...
    vi_1 = PIController(sum_1, r_o_1, y_o_1);
    vi_2 = PIController(sum_2, r_o_1, y_o_1);
}

The C++ language provides a nicer way of writing the same thing: you can
use a class to wrap the state and the controlling method together under
the same name:

// PI controller.
class PIController {
public:
    PIController() : sum(0) {}
    float operator()(float r, float y);
private:
    float sum;
};

float PIController::operator()(float r, float y)
{
    const float kp = 2.00;
    const float ki = 10.00;

    float e = r - y;  // error
    sum += e;         // integral of error
    return kp * e + ki * sum;
}

Which you would use like this:

void loop()
{
    static PIController pi_1, pi_2;  // Controller instances.
    // ...
    vi_1 = pi_1(r_o_1, y_o_1);
    vi_2 = pi_2(r_o_1, y_o_1);
}

The generated assembly should not be much different. Note that in both
cases the static variables of loop() could be globals if you prefer.


Storing data on AT24C02 EEPROM chips with Arduino

You wire your chips on a breadboard, with the +/- left rail for Vcc/GND, and the right +/- rail for SCL/SDA, plus a little acrobatics to connect everything.

Your chips can have 8 addresses, 0x50 to 0x57, set up with the A0/1/2 pins: all low = 0x00, all high = 0x07. The you read and write to the EEPROM of your choice with:

char i2c_eeprom_read_char(int deviceaddress, unsigned int eeaddress) {
  char rdata = 0xFF;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.endTransmission();
  Wire.requestFrom(deviceaddress,1);
  if (Wire.available()) rdata = Wire.read();
  return rdata;
}

void i2c_eeprom_write_char(int deviceaddress, unsigned int eeaddress, char data) {
  int rdata = data;
  Wire.beginTransmission(deviceaddress);
  Wire.write((int)(eeaddress >> 8)); // MSB
  Wire.write((int)(eeaddress & 0xFF)); // LSB
  Wire.write(rdata);
  Wire.endTransmission();
}

If you have more than 8 chips (well throw them away and get larger ones, but anyway, for completeness sake): wire all of them with A1/A2 to GND, and each A0 to a different digital pin. When you need to access a chip, set all A0s to LOW, except the one you want to HIGH, and use 0x51 as the address. By doing this you're setting all chips except the one you want to address 0x50 (which doesn't matter) leaving only one at 0x51. That enables you to have as many chips as you have free digital pins...


It has vfprintf_P and stdout is a FILE. Why would you want to waste time and space with implementing vprintf_P as well?

If you really want it, you can make your own:

#define vprintf_P(...) vfprintf_P(stdout, __VA_ARGS__)

Incidentally, the source code to vprintf looks like this:

int
vprintf(const char *fmt, va_list ap)
{
    return vfprintf(stdout, fmt, ap);
}

That does exactly the same job as a preprocessor macro - just forwards your request on to the FILE-based function.

It is actually more efficient to use a preprocessor macro than needlessly nesting functions like that - less stack usage, less calls, etc (unless the compiler happens to choose to inline that function, which since it is in a library it likely won't).

The non-FILE based functions can be considered simple wrapper functions to the FILE-based ones. They are mostly provided for convenience, but are actually completely redundant and can all be replaced with direct calls to the FILE-based variant.  They mostly still exist purely for historical compatibility. And since _P is specific to AVR libc there is nothing historical for it to be compatible with.


As most of the people have posted, the values for the pipe are arbitrary, but must follow the rules per the API:

  Pipes 1-5 should share the first 32 bits. Only the least significant
  byte should be unique, e.g.

Before I answer your question, I think an explanation on Hex and Decimal values are needed.

The 40 bit hexadecimal is a number representation of base 16. A decimal is of base 10. So you can convert a Hex Value to Decimal. As this is out of scope for the question, you can google on how to convert from one to another. There are some online converters:

Hex to Decimal Converter

You will see when you convert the Hex value to decimal, that its just a number representation. When you convert, you drop the 0x and LL. As stated the 0x indicates the value is a hex value and LL means type Long Long.

So to answer your question, use the a converter to find a hex number like:

F0F0F0F0A1
F0F0F0F0A2
F0F0F0F0B4
F0F0F0F0E9

Just change the last 2 digits (least significant bit):

Pipes 1-5 should share the first 32 bits. Only the least significant byte should be unique, e.g.
   openReadingPipe(1,0xF0F0F0F0AA);
   openReadingPipe(2,0xF0F0F0F066);

Add the 0x and LL

0xF0F0F0F0A1LL
0xF0F0F0F0A2LL
0xF0F0F0F0B4LL
0xF0F0F0F0E9LL

All should work.

I am no expert on hex, as I am learning, so if I am incorrect, then please someone correct me.

Finally, the nRF24L01 datasheet makes the following point that the choice of address is not completely arbitrary:

  Note: Addresses where the level shifts only one time (that is, 000FFFFFFF) can often be detected in noise and can give a false detection, which may give a raised Packet Error Rate. Addresses as a continuation of the preamble (hi-low toggling) also raises the Packet Error Rate.


Connecting to Alexa with FAUXMOESP library not detecting the device

If you are using fauxmoESP library version 3.0 and above your device will not be detected by alexa, i dont know why this is.
You may degrade fauxmoESp version to 2.4.0 so that your issue ie. .onSetState will be resolved.

Are you able to connect wifi?


Can an interrupt function call a regular function?

Yes, you can. You just have to make sure your function is reentrant.
If it accesses no memory beyond its parameters and (non static) local
variables, you should be fine. If it accesses global variables, hardware
registers, or static locals, it is unlikely to be, and only detailed
analysis will tell you for sure.

Beware also of the library functions you call: some of them are not
themselves reentrant and should therefore be avoided. See for example
the manual of strtok(), which explicitly addresses the
reentrancy problem.


It's normal that the L-LED is steady on after the USB connection is established. However, after pressing and releasing Reset it should flicker for a second, then go back to on again.

Check https://www.arduino.cc/en/Guide/Troubleshooting#toc1 for reasons why you can't upload.

On http://www.arduino.org/products/boards/4-arduino-boards/arduino-uno I've found:

  The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

I haven't found out so far, how to read the current values of the fuses.


Change operational mode of CAN transceiver

Transmitting this "wake signal" does not "wake" the transceiver.  What it's actually doing is the transceiver, when in "standby" mode, only allows through signals that have a dominant or recessive state that is longer than the filter time (5.5µs). Any transitions in the bus after a stable period of 5.5µs or more will get passed through.

The transceiver does not enter "normal" mode at that point. It is down to the CAN device to activate the transceiver through setting the STB pin LOW.

  When pin RXD goes LOW to signal a wake-up request, a transition to Normal mode will not be triggered until STB is forced LOW.

Exactly what you send is of no consequence to the transceiver - only whether it has D and R states that are longer than 5.5µS.  It's up to the CAN device to interpret them and know if it should wake up the transceiver and place it in NORMAL mode.

And the MCP2515 also doesn't care what it receives.  When the WAKEIE bit is set it will cause the MCP2515 itself to wake from its sleep mode when anything is received - at which point it signals to the Arduino through its INT pin that it's woken up.

However your chosen library has no ability included in it to control the WAKEIE bit of MCP_CANINTF - only the TXxIF bits are supported.  So you will have to expand the library to provide that facility.

The general idea of operation is:

The transceiver lets through a "slow" signal (like transmitting 0b00110011)
The MCP2515 receives "something"
INT pin goes LOW and the Arduino reacts to it
The Arduino drives STB LOW and reception can proceed normally.

Note that it is the Arduino that will be controlling STB, not the MCP2515.


Arduino Yun RFID-RC522 module not working

According to the link you provided, we can see that the RFID-RC522 uses SPI to communicate with Arduino.

On Arduino UNO, the SPI pins are located as follows:

pin 11: MOSI,
pin 12: MISO,
pin 13: SCK

On the Arduino YUN, this is different though; as stated there (bold highlight is mine):

  SPI: on the ICSP header. These pins support SPI communication using
  the SPI library. Note that the SPI pins are not connected to any of
  the digital I/O pins as they are on the Uno, They are only available
  on the ICSP connector. This means that if you have a shield that uses
  SPI, but does NOT have a 6-pin ICSP connector that connects to the
  Yún's 6-pin ICSP header, the shield will not work.

Hence you can not wire the RFID-RC522 module the same on UNO and Yun.
For the Yun, you'll have to follow this wiring picture:

Pin 1 in image above is the pin that is marked with a dot on the Yun PCB.

Also see the ISP-header layout, at the lower-right corner of the yun_by_pighi Yun pinout diagram.


Understanding ArduinoJson capacity calculation assistant

If you look at the details of the numbers reported, you should see:
Data structures     112
Strings             0
Total (minimum)     112
Total (recommended) 128

As you see, there are exactly zero bytes allocated for the strings. This
means that the library does not copy the strings, and instead references
them from the character array you provide as an input.
If you instead configure the library for Stream input, it will have to
store the strings, and the capacity is then very different for these two
documents.


Only specific Digital Pins marked with ~PWM can generate a PWM signal. In the case of arduino Uno the pins 3,5,6,9,10,11 are all hardware PWM driven, and are marked on the Uno with a ~ or something.
Others can be driven with software PWM(though I wouldn't recommend it). As the Arduino Uno uses the ATMEGA328P, the number of pins is same with other boards using same processor.

On the other hand if you want to run 16pins for PWM, its best if you use Arduino MEGA 2560 because its processor supports more than 6 Hardware pins for PWM. Also you get the advantage of a higher memory storage for your code


How Atmel Studio 7 compile Arduino code?

It is almost always the case that a high-level environment like an IDE provides an interface to an existing tool-chain rather than being truly an all-in-one mega-application, which would a maintenance nightmare. Atmel Studio 7 is no exception, and according to Atmel, uses and includes (quite likely by downloading it during the install process) the GCC tool-chain.

  Why Atmel Studio asked about Arduino IDE path when I try to import Arduino sketch?

Probably for the Arduino libraries, which are contained within the Arduino IDE executable.


How can I set two PWM at two different frequencies?

The ATMega PWM hardware underlying the Arduino primarily supports changing the duty cycle; the frequencies can only be selected from a few fixed choices.  Typically the timers run from 0 to 255 or 65535 and loop back to 0, and you can select where within that full cycle the output changes on and off.

Since what you want is a simple 50% duty cycle with fine control of frequency, the PWM functions are not very useful.  What you want is tone or frequency control.  The ATMega timers support this too, but it's a different function than PWM. For frequency control, the timer will cycle from 0 to your choice of upper limit.  So for example, you might count up to 200 instead of 255; or to 201 - so you get much finer control of frequency.

Unlike PWM, on the ATMega328p used in the Uno, you can only get one frequency per timer (you can get two PWM outputs per timer - both at the same frequency).  And if you want millis() and microseconds() and delay() to continue to work, you don't want to mess with timer 0 for frequency control (you can get PWM from timer 0 if you accept the default frequencies).

So that leaves you with two frequency controllable timers - timer 1 (16 bit resolution) and timer 2 (8 bit resolution).

See the tone() function in the Arduino library for examples of a single tone at a time.

For multiple simultaneous frequencies (on different pins) see this library: https://code.google.com/p/rogue-code/wiki/ToneLibraryDocumentation.  You can have two tones at a time, or three if you don't need millis() etc.


How to map PID output to actuator control?

I don't think you would need to use a PID library (or any control loop for that matter) to control a radiator. You could use a simple threshold code, like this:

Pseudocode:

Check temperature
If radiator is off and temperature > (ideal temp - threshold)
  turn radiator on
If radiator is on and temperature > (ideal temp + threshold)
  turn radiator off


H11L1 opto isolator does not pass signal to Arduino (correctly)

simulate this circuit – Schematic created using CircuitLab

I'm not sure I can help much with the MIDI problem but I can help with the schematic. I've reorganised it for clarity. Since the opto-isolator has an open-collector output any loads it is driving should be connected to supply + rather than common.


The reason why "Arduino WiFi Dev Ed" USB upload sometimes doesn't work, is the esp8266 connected to UART of Atmega for the OTA upload. If esp8266 doesn't boot, it doesn't set pin 4 to disconnect from Atmega UART and the connection to UART stays and disturbs the upload from IDE.

The esp8266 hangs sometimes, because it has pin 2 floating on this board, but there is a trace and a soldering point on the bottom of the board for pin 2. If it is touched or otherwise grounded the esp8266 doesn't boot until the potential on the pin rises.

More about Uno WiFi Dev Ed hardware here.


The code you show will toggle the SPKR pin at a 1 Hz rate.  If you have an ordinary speaker attached, you will hear it click twice a second, but it won't generate an audible tone.

To generate a tone, use tone(pin, frequency) calls, or tone(pin, frequency, duration) calls.

For example:

void loop() {
   tone(SPKR, 400, 500); // 400 Hz tone for half second
   delay(500);           // no tone for half second
}

Note, ordinary speakers are low-impedance devices, eg 4 Ω, 8 Ω, etc.  You can use an audio transformer for impedance matching – this helps produce an adequate output volume – but lacking that, should put a resistor (eg 220 Ω) in series with the speaker to avoid over-current conditions.  AVR pins can deliver 25 mA without too much stress, and typically are rated at an absolute max of 40 mA.


I would isolate the two devices using opto-isolators.

simulate this circuit – Schematic created using CircuitLab

Turning the output ON will illuminate the infra-red LED in the opto-isolator which turns on the photo-transistor connecting the input to GND. Both devices are then completely galvanically isolated (unless of course you take power from the C64 for the Arduino).

Another option, if you don't care about galvanic isolation, is to just use a simple transistor (small signal NPN or logic level N-channel MOSFET) to make an Open Drain output:

simulate this circuit

Again, set the output HIGH and the transistor will turn on connecting the C64 input to ground.


Looking at Adafruit's website I'm confused which wallcharger I should get

This website looks like a pretty official answer for you.
http://playground.arduino.cc/Learning/WhatAdapter

  Since you'll probably be connecting other things to the Arduino (LEDs, LCDs, servos) you should get an adapter that can supply at least 500mA, or even 1000 mA (1 ampère). That way you can be sure you have enough juice to make each component of the circuit function reliably.

And

  The Arduino's on-board regulator can actually handle up to 20V or more, so you can actually use an adapter that puts out 20V DC. The reasons you don't want to do that are twofold: you'll lose most of that voltage in heat, which is terribly inefficient. Secondly, the nice 9V pin on the Arduino board will actually be putting out 20V or so, which could lead to potential disaster when you connect something expensive to what you thought was the 9V pin. Our advice is to stick with the 9V or 12V DC adapter.


How do I activate emulation in the Coddeblocks Arduino IDE

I have not done extensive testing with the simulator but here is what you do open code blocks start a new project. Then under the target choose simulator. See the picture for details.

I just tested it out for the simple program but this looks pretty cool.


How to power an Arduino Uno with 3 1.5V batteries?

The Arduino doesn't require 5V.

The Atmel chip on the board requires somewhere between 1.8V and 5.5V, the Arduino just happens to have chosen 5V as a good common widely used voltage to run at.

If you provide a voltage within that range to the +5V pin the board will operate.  There's a couple of caveats though:

Anything below about 4V will mean the 3.3V regulator won't be working right, so the 3.3V pin won't be functioning properly
At lower voltages the Atmel chip can't operate reliably at higher frequencies, which is why 3.3V Arduino boards operate at 8MHz instead of 16Mhz.

So 3 x AA batteries is a perfect power source for running the Arduino, direct into the 5V pin.  Just make sure that you don't power it any other way at the same time or you'll be pumping 5V into your batteries.  You may want to add a Schottky diode in series with your battery + (between battery + and the 5V pin) to stop that ever causing a problem.  Choose one with a very low forward voltage drop though, otherwise you could end up dropping too much of your precious voltage over the diode.

By the way, when you're powering it from USB the 5V could be anywhere between 4.75V and 5.25V.


How can I run multiple programs on an Arduino?

In addition to the other answers, I have a few ideas:

1.) Instead of doing variable prefixes, have them wrap all of their code inside a namespace! Please note that you can't wrap "setup" or "loop" in that namespace. Example

setup() {
  if(conditionIsTrue) {
    aGroup::setup();
  } else {
    bGroup::setup();
  }
}

loop() {
  if(conditionIsTrue) {
    aGroup::loop();
  } else {
    bGroup::loop();
  }
}

namespace aGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

namespace bGroup {
setup() {
  // Code
}

loop() {
  // Code
}
}

2.)

Please note you'll have issues with a student tries to access an analog pin and doesn't prefix it with A. For example, if I wanted analog pin 5, I should do analogRead(A5);, not analogRead(5);. That could cause some major issues.


General rule is, the lower the frequency, the longer the range (but lower bandwidth). So both should have a better range at 433Mhz and 137MHz instead of the 2.4Ghz of the NRF. Antennas also affect the range.

The "over the hills" part I think will be problematic. The RF won't be able to penetrate through the hill. So the signal has to bounce of the ionosphere to get over the hill, which is to long a distance. So you probably have to have some kind of repeater on top of the hill to accomplish this.


The simplest way to get more decimal places to print is this:
Serial.println(val,NUMBER_OF_DECMIAL_PLACES);

This will print out any number of digits after the decimal place. Regular print without the number of digits specified will default to 2 decimal places. for example, here is some code and the result that gets printed:
float val = 23.459;
Serial.println(val);
Serial.println(val, 4);
Serial.println(val, 10);

23.46
23.4590
23.4589996337

You may notice that with 10 decimal places printed you can start to see how much the actual value of 23.459 needs to be approximated to fit within a floating point number. This is similar to how 1/3 can not be represented 100% accurately in a finite number of decimal digits; 459/1000 cannot be represented 100% accurately in a finite number of binary bits, so it is approximated.
Also, note that for non-floating point numbers the optional second argument to print and println is the base it should be printed in (dec, hex, oct, ...) and has nothing to do with precision.


Doing several things at the same time with functions, objects or interrupts?

An RTOS may be a good option for running a complex application on a
quite powerful Arduino. Many Arduinos (the AVR-based ones), however, are
too limited to run complex applications, and the overhead of an RTOS is
quite significant for them. In this case you end up with two options:

non-blocking programming
interrupts

Whichever is best depends on the specific tasks you are managing.
Non-blocking programming
This is best exemplified by the Blink Without Delay Arduino
tutorial. The general principle is to break down you code into small
non-blocking tasks, and perform each one only when it is the right time
to do so. Breaking down the program logic into a set of non-blocking
tasks is not always completely trivial, but you can use a Finite state
machine, which is a very powerful and general concept for doing so
in a systematic way.
Once all task are non-blocking, the main program loop then looks like
this pseudo-code:
void loop() {
    if (task_1_should_be_performed_now()) {
        perform_task_1();
    }
    if (task_2_should_be_performed_now()) {
        perform_task_2();
    }
    // etc...
}

Most of the time, all conditions are false, and the program swifts
through the tests completing the loop in a very short time.
Occasionally, it performs one of the tasks, which makes the loop longer
but, since the tasks never block, not very long anyway. Typical loop
time is highly dependent on the specifics of your code, but I would
expect it to be no more than one millisecond most of the time.
This is probably the most common pattern for multitasking on the
Arduino. You can encapsulate this logic in functions, objects,
libraries, etc. This is the approach I would recommend provided none of
your tasks is so urgent that it cannot wait for one loop iteration.
Interrupts
Occasionally, you may have a task that is so urgent that it cannot wait
for the next loop iteration. It has to be performed right now. Or maybe
the loop takes a very long time because of a blocking call in a library
you have no control over. In those situations, an interrupt may be the
best option.
Interrupts come with some tricky programming issues, which require some
precautions on the part of the programmer:

they block other interrupts, increasing their latency → interrupt
service routines should be as short as possible

they can cause problems with non-reentrant library functions → those
functions should be avoided in interrupt context

they can interact badly with the optimizer → variables used in both
interrupt context and normal context should be qualified as
volatile

they can cause synchronization issues with the data shared with the
main code → access to that data in normal context should be protected
in critical sections.

For all these reasons, it is best to use interrupts only when needed,
i.e. only when a task cannot wait for the next iteration of loop().


You can't do complex tasks (or anything that relies on the Arduino API in any form) in your constructor. Simply because that all gets called before the Arduino API initializes, and in so doing the serial port gets disabled.

Instead you should do your complex operations and API-based operations in .begin(), which is why 99.99% of all libraries (including HardwareSerial) have a .begin() method.


In you Arduino Sketch folder there is a folder called Libraries, create a folder there and put your header file in that folder and restart the Arduino IDE.

For example (PC):

Documents/Arduino/Libraries/ultrasonic/ultrasonic.h

You can now use it in all your projects.

If you only want to use with a particular sketch, place in in the same folder as you  sketch and restart Arduino IDE.


It is much better to store string literals in the FLASH only. In Arduino there is __FlashStringHelper class and F() macro ensures that correct version of print method is used and that the string literal is not copied into the ram before it's printed.

Basically if you don't have enough memory, using lots of string literals results in stack overflows, coruption and/or returning to random adresses and it looks like crashes/resets.


How to implement an alternating current using only two PWM pins on STM32 Nucleo L053R8?

It's quite hard to understand what you want from your question, it's quite "woolly".

However, I will note:

It's not possible to output a negative voltage from a normal microcontroller.
Getting a specific voltage (accurately) from PWM requires good filter design and a feedback system to keep the voltage within bounds.

I say it's not possible to output a negative voltage - that is with respect to ground. Depending on what you are feeding this voltage into you may not need to reference to ground. In this case it is possible to reference the voltage to another IO pin (steady state, output, not PWM). With it set HIGH the PWM pin's filtered voltage will be below that IO pin's voltage and thus appear, with respect to that IO pin, to be negative.  With the IO pin LOW it will appear, with respect to that IO pin, to be positive.

Once you have filtered your PWM signal you will need the output voltage from it to be monitored by an analog input. That can measure the voltage and make sure that your PWM is set to the right duty cycle. Note that the required duty cycle for any one specific voltage will depend largely on the filtering and the load on the output at the time. You will most likely need some form of PID algorithm to constantly adjust the PWM duty cycle. Also remember that your measured voltage will always be with respect to groud, so you will need to subtract your output reference voltage (the output state of your reference IO pin - high or low) from your measured voltage to get the voltage as seen with respect to the IO pin.


Read/write data from 2 Arduinos simultaneously with Python

I wrote a simple sketch to read a KY-040 encoder with an Arduino UNO (or nano) board and to display the output in the Arduino IDE serial plotter (CTRL + SHIFT + L).

Here is the pinout:

ENCODER            ARDUINO UNO
====================================
GND            ⇒   GND
+              ⇒   +5V
SW  (button)   ⇒   pin D4 (PORT D4)
DT  (encoder)  ⇒   pin D3 (PORT D3)
CLK (encoder)  ⇒   pin D2 (PORT D2)

Here is a screenshot of the output in the serial plotter:

Here is the picture of a project I am doing now (you need only the Arduino and the encoder for the sketch to work):

And here is the code :

/*
LECTURE D’UN ENCODEUR ROTATIF KY-040
====================================
# DESCRIPTION DU PROGRAMME
Lecture d’un encodeur rotatif KY-040 pour affichage dans le traceur
série de l’IDE Arduino (CMD-SHIFT-L).
La rotation du bouton est détecté avec des interruptions sur les
broches 2 et 3 du port D.
Ce programme implémente un filtrage des rebond en deux étapes (voir
la procédure “lectureEncodeur”).
Ce programme est basé sur celui d’Oleg Mazurov
https://www.circuitsathome.com/mcu/reading-rotary-encoder-on-arduino
Pour la gestion des interruptions, voir
https://sites.google.com/site/qeewiki/books/avr-guide/external-interrupts-on-the-atmega328
# RÉFÉRENCE DE L’ENCODEUR
http://www.banggood.com/5Pcs-5V-KY-040-Rotary-Encoder-Module-For-Arduino-AVR-PIC-p-951151.html
# CONNEXIONS DE L’ENCODEUR KY-040 SUR ARDUINO NANO
    GND            ⇒   GND
    +              ⇒   +5V
    SW  (bouton)   ⇒   pin D4 (PORT D4)
    DT  (encodeur) ⇒   pin D3 (PORT D3)
    CLK (encodeur) ⇒   pin D2 (PORT D2)
juin 2016, ouilogique.com
*/

#define ENC_A 2
#define ENC_B 3
#define ENC_C 4
#define ENC_PORT PIND
#define BtnRead  ! bitRead( ENC_PORT, ENC_C )

bool encodeurTourne = false;
byte ENC_PORT_VAL = 0;

// Modifier ici la sensibilité de l’encodeur pour qu’il ne réagisse
// pas trop vite. Cette valeur représente le nombre de millisecondes
// avant un changement sur la sortie.
static const long sensibiliteEncodeur = 10;

// Gamme de sortie de l’encodeur. À modifier en fonction de l’application.
static const int8_t minVal = 0;
static const int8_t maxVal = 10;

void setup()
{
  pinMode( ENC_A, INPUT_PULLUP );
  pinMode( ENC_B, INPUT_PULLUP );
  pinMode( ENC_C, INPUT_PULLUP );

  PCICR  |= ( 1<<PCIE2 );
  PCMSK2 |= ( 1<<PCINT18 );
  PCMSK2 |= ( 1<<PCINT19 );
  PCMSK2 |= ( 1<<PCINT20 );
  PCMSK2 |= ( 1<<PCINT21 );

  encodeurTourne = true;

  Serial.begin( 115200 );
}

void loop()
{
  static int8_t compteur = 0;

  // Lecture et affichage des valeurs de l’encodeur
  // dans le traceur série de l’IDE Arduino (CMD-SHIFT-L)
  if( encodeurTourne )
  {
    int8_t encodeurVal = lectureEncodeur();

    // Si le bouton est pressé, on remet le compteur à 0.
    if( encodeurVal == 2 )
    {
      compteur = 0;
      Serial.println( 0 );
      while( BtnRead ){ _delay_ms( 1 ); }
      _delay_ms( 20 );
    }

    // Sinon on met le compteur à jour en le gardant dans la gamme minVal..maxVal.
    else if( encodeurVal != 0 )
    {
      if( compteur < minVal || ( compteur == minVal && encodeurVal < 0 ) )
        { compteur = minVal; }
      else if( compteur > maxVal || ( compteur == maxVal && encodeurVal > 0 ) )
        { compteur = maxVal; }
      else
        { compteur = compteur + encodeurVal; }

      Serial.println( compteur );
    }
    encodeurTourne = false;
  }
}

/*
  lectureEncodeur() retourne
  -1 pour une rotation dans le sens anti-horaire
   0 pour une valeur impossible (rebond)
  +1 pour une rotation dans le sens horaire
  +2 si le bouton de l’encodeur est pressé
*/
int8_t lectureEncodeur()
{
  // Si le bouton est pressé, on quitte en retournant 2.
  if( ! bitRead( ENC_PORT_VAL, ENC_C ) )
  {
    return( 2 );
  }

  // Lecture des signaux de l’encodeur et comparaison
  // avec les valeurs possibles dans le code de Gray.
  // Ceci permet de filtrer la plupart des rebonds de l’encodeur.
  // Les valeurs à 0 représentent les transitions impossibles
  // et qui doivent être supprimées (resultat = 0).
  // Les valeurs à 1 représentent les transitions dans le sens horaire.
  // Les valeurs à -1 représentent les transitions dans le sens anti-horaire.
  static const int8_t enc_states[ 16 ] PROGMEM =
    { 0,-1, 1, 0, 1, 0, 0,-1,-1, 0, 0, 1, 0, 1,-1, 0 };
  static uint8_t old_AB = 0;

  old_AB <<= 2;
  bitWrite( old_AB, 0, bitRead( ENC_PORT_VAL, ENC_A ) );
  bitWrite( old_AB, 1, bitRead( ENC_PORT_VAL, ENC_B ) );
  uint8_t resultat = pgm_read_byte( &enc_states[ ( old_AB & 0x0F ) ] );

  // On accumule “maxVal” résulats dans un sens ou dans l’autre
  // avant de bouger. Ceci permet de supprimer les derniers rebonds
  // de l’encodeur qui n’ont pas été filtrés ci-dessus.
  if( resultat != 0 )
  {
    static int8_t resultatCumul = 0;
    const int8_t maxVal = 2;
    resultatCumul += resultat;
    if( resultatCumul >= maxVal )
    {
      resultatCumul = maxVal;
      resultat = 1;
    }
    else if( resultatCumul <= -maxVal )
    {
      resultatCumul = -maxVal;
      resultat = -1;
    }
    else
      { resultat = 0; }
  }

  // On rejete quelques lectures pour limiter la sensibilité de l’encodeur
  // et éviter ainsi qu’il ne tourne trop vite.
  static long lastT = millis();
  if( millis() - lastT < sensibiliteEncodeur )
    { resultat = 0; }
  else
    { lastT = millis(); }

  // On retourne le résultat.
  return( resultat );
}

ISR( PCINT2_vect )
{
  ENC_PORT_VAL = ENC_PORT;
  encodeurTourne = true;
}


You have two copies of your program sharing one physical resource, the serial port input to the Arduino.  It is by chance which of the two copies will receive and process the input data.  So this approach will not work dependably.

Semiphoras are often used when sharing hardware among several programs.  However you are not only sharing hardware, but also the data being sent to the Arduino.  And the data will only be sent once.

In this case, you need to handle the data once in code that is separate from the 2 instantiations of the ESP class.  That is, you need to process the received data once and pass that processed data to the appropriate instantiation of the ESP class.


This is an analog servo, so there is no endpoint calibration on the servo side. This type of calibration is for digital servos (which can be tuned) and controllers.
On the servo description page, they talk about a stretcher. This is a translation tool to help with old controllers:  usually servos have a narrower band: 1000us to 2000us for 0° to 180°. Therefore old controllers can only do 1000us to 2000us, and would fail to achieve full range with this servo, which requires 600us to 2400us

Also, note that RC servo input signal isn't really a PWM: duty cycle doesn't matter, only lengh of the pulse does.

Your servo doc says: 600us to 2400us for -90° to +90°, which correspond to what the Servo lib does by default according to its documentation. You should be fine. What are the results of a super simple sweep-like code? eg:

loop() {
  myServo.writeMicroseconds(600);
  delay(2000);
  myServo.writeMicroseconds(2400);
  delay(2000);
}


Is it possible to measure the velocity of a Unmanned Aerial Vehicle using only accelerometer?

Not with any measure of accuracy, no.

You're basically asking about Dead Reckoning which is problematical at best - and when doing it with just a low-grade accelerometer it can't be anything more than a rough "It's moving quick" or "it's moving slower now" accuracy.


Dragino lg01-p problem with serial monitor

Found it so i will share my problem here to help someone else!
Apparently Bridge funcions work better for this device if you include Process.h rather than Bridge.h.


Expanding on my previous comment...

  I need a way to keep an array of memory ignored by the C initializer

You can achieve this by instructing the compiler to store the array in
the “.noinit” memory section:

int my_array[ARRAY_LENGTH] __attribute__((section(".noinit")));

Your array will end up sitting somewhere between the .bss and the heap
(if any), and will not be touched by the __do_clear_bss routine from
the C startup code.

  my question is whether it would instead stupidly try to keep the core
  running when power is disconnected

Most likely. In order to avoid that, I suggest you enable the brown-out
detection by setting the BODLEVEL fuses. This feature of the
ATtiny is specifically meant to prevent the CPU core from running if the
supply voltage is below some configurable threshold.


Your declaration of char buffers is done like so:

char* move1 = "N/A";

This will only allocate 3 characters with an additional one for null termination i.e. not long enough to hold the name.

You need to do:

char buffer[16];

Where the length is long enough to hold your string.


What would be the right way to connect 2 fsr resistors, jumper wire cables and 2 10khm resistors onto the breadboard

From this Adafruit tutorial:

  The easiest way to measure a resistive sensor is to connect one end to Power and the other to a pull-down resistor to ground. Then the point between the fixed pulldown resistor and the variable FSR resistor is connected to the analog input of a microcontroller such as an Arduino (shown).


Is there a way to add external RAM (let's say 100 MB or 200 MB) in this audio buffer mixing context?

There are SRAM ICs / boards, however, don't expect 100 MB, more like 1 MB (with the pin numbers and connectivity / protocols that an Arduino offers).

With Flash you can get much further, but it can only be written a number of times; not sure if that suits your requirements.

Beyond that, I'm afraid the real problem is in the processing speed. Mixing 100 samples with 48 KHz stero would mean (48000 * 2) = 96 KSamples/s. Since the Arduino is only 16 MHz you have just 16e6/96e3 = 166 clock cycles to mix all those 100 samples. Probably way too less.

Update

Winbond is a brand that is supported by Arduino libraries and the biggest supported IC is e.g. W25Q128FVSSIG, which is 128 Mbit, thus 8 MB. For 200 MB you need 25 of them which is quite a lot, and not sure if there will be issues using so many (let alone the cost). For this you do not need a file system, however you need to write it per page (if you want to do it efficiently). Which should be ok, since the SD card also is read per page (maybe not the same page size though).
However, you still have to copy the Flash memory into SRAM to be able to process it, so it's not the same as SRAM. Getting 200 MB SRAM will be very costly.


How to determine which pins_arduino.h file is used?

In the boards.txt file for the core in question you have a line for each board:

xxxx.build.variant=yyyy

where yyyy is the name of the folder in variants for the board.

For instance, the Uno, has:

uno.build.variant=standard

which relates to:

variants/standard

with the pins_arduino.h file in it for that board.


How are HIDs (keyboard,joypad) created and mapped?

When the Arduino sends data to the computer using the HID protocol it sends what is called a HID Report. That is basically an array of numbers in a pre-defined format that correspond to what the computer is expecting.

In the case of keyboard events it sends a HID Keyboard Report

It can send events for up to 6 keys at once along with up to 8 meta keys.  How those key events are interpreted are down to the Keyboard Mapping used on the computer.  This is the setting (usually in the Language or Regional settings of the computer) that defines the layout of your keyboard - UK, US, French "AZERTY", etc.

While it is possible to create custom key mappings in many operating systems it is usually a very difficult and involved task. Also the mapping takes effect for every keyboard attached to the system, including the one you type on. So changing the mapping at will is probably not a good idea since it could break your normal keyboard usage.

So how would you go about doing what you want to do?  Well, my recommendation is not to do it on the computer, but to do it on the Arduino.  The Arduino has multiple interfaces available at once. As well as the HID interface for keyboard and mouse it also has the CDC/ACM interface for emulating serial. You can use both of these at once quite happily.  So you can use that USB serial interface to configure the way the Arduino works - including what key code to send for any particular event.  You could even write an easy-to-use GUI in Visual Basic or something that communicates with the Arduino over serial to adjust the settings.  How you do that communication (what protocol you come up with) is entirely up to you.

As for the hardware side of things - all you really need is just the switches / buttons and wire.  Just follow the on-line tutorials (there's millions of them) for connecting switches and buttons to the Arduino. Enable the internal pullups, and connect the switch between the I/O pin and ground.  For the rotary switch you will have 4 inputs and 1 output, so connect the 4 inputs to I/O pins and the 1 output to ground.


registers are nothing but pointers to memory addresses. so the best way to "parameterize" them is to do so via pointers.

assuming that ICRi is of 8-bit types - they are NOT to be sure:

uint8_t *ICRs[4];  //isr pointers

//initialize the icrs
ICRs[0]=(uint8_t *)&ICR0;
ICRs[1]=(uint8_t *)&ICR1;
...

*ICRs[i]=icr; //assign value to ICRi

note: that piece of code isn't operable in reality. The way to go is to use a pointer to void. But I'm sure you can figure that out.


I want to make my stepper motor work for 1 hour

The problem you have is you are treating minutes and hours separately. That won't work - they need to be combined.  As it stands your "on" time is:

Minutes greater than W, and
Hours greater than X, and
Minutes less than Y, and
Hours less than Z.

Or, to rearrange that:

Hours between X and Z, and
Minutes between W and Y.

You can see that won't work. You will only get "on" for the block of minutes between W and Y for each hour in your "ON" period.

For example, if you want ON from 9:30 to 12:45, you get:

If hours greater than or equal to 9 and less than or equal to 12, and
Minutes greater than or equal to 30 and less than or equal to 45

So, that's 9:30 to 9:45, 10:30 to 10:45, 11:30 to 11:45 and 12:30 to 12:45

Even worse if you want 9:30 to 12:00...  the second part of the IF above becomes:

Minutes greater than or equal to 30 and less than or equal to than 0.

That can never happen. There is no number that is both greater than 30 and less than 0.

So you have to combine the two values together, to create a "minutes since midnight" value. Then your ON time is decided by the number of minutes, not the hours and the minutes separately.  It's simple enough:

int minutesSinceMidnight = myRTC.hours * 60 + myRTC.minutes;

Your ON time then becomes, for 9:30, 9 * 60 + 30 = 570, to 12:00 = 12 * 60 + 0 = 720.

So:

if (minutesSinceMidnight >= 570 && minutesSinceMidnight <= 720) {
    // Do your stepping
}