text:
Updating ATmega16u2
I have the UNO Mini Strong from www.diymore.cc.
I am having the issue of keyboard.h not being recognized.
I have been trying to find the firmware mentioned in https://www.arduino.cc/en/Hacking/DFUProgramming8U2 from here https://github.com/arduino/Arduino/tree/master/hardware/arduino/avr/firmwares/atmegaxxu2 but, page is gone!
Does anyone know where the firmware can be found and should this work on the board I am trying to use?

I tried to make a little research and it looks that the hardware folder was cleared (see here).
The json file made me think that now this is shipped like libraries, so through a dedicated package which gets downloaded later.
Consequently I checked in the installation folder and... there it is!
In the folder <arduino install dir>\hardware\arduino\avr\firmwares\atmegaxxu2 you will find a lot of hex files (e.g. Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex)
I checked on my portable installation of arduino 1.8.5, but it should be there also for installed versions

Great. I found the file. I'll update later on the outcome. Thank you.

While I was researching the DFU programming, I found this, https://github.com/NicoHood/HoodLoader2/wiki which I believe is exactly what I need. Check the example for Serial Keyboard. I will not be able to set this up until next week. I'll post an update.


text:
Turn off power to a moisture sensor except when reading values
I have an Arduino Uno and a moisture sensor (looks like a YL-69 clone) submerged in water. I need to read the sensor's (analog) value every 3 min or so. The problem is: the sensor is always powered by the Arduino (GND and VCC), i.e. the current passes through it at all times. Because of this, one of the sensor's electrodes (presumably containing copper) grows a cyan residue. I'd like to NOT supply any power to the sensor except for the brief moment when I need to read the value. How can I do this?
EDIT: I've just noticed a related question (link below). The user decided to intermittently power the sensor via a digital pin, rather than VCC. Is this reasonable?
Does a moisture sensor need warm-up time?

If your sensor draws less than 40mA to operate, then you can safely "power" it from an GPIO pin.
The related question also asks how long the sensor must be powered in order to get a stable reading. For a sensor such as this one, it appears to be a simple resistive voltage divider, with the moisture sensor itself providing one leg of the divider circuit. The active component appears to be a comparator to provide a digital HIGH/LOW output as an alternative to the analog output.
Most schematics show a capacitor between ground and the voltage divider output, presumably to reduce noise. You need to allow for this capacitor to charge up and become stable before you take a reading. The time for this depends somewhat on the value of that capacitor and the supply voltage you are using.
Safe to assume, however, that a wait time of 1 second is more than enough.

I built a project very similar to this last winter to monitor moisture levels in the soil of plants that I was keeping over winter in my basement.  I used GPIO pins to power the sensors similar to what jose can u c described above and  performed testing to determine the minimum on time to get readings.  I found that 150ms was enough to get stable readings in soils varying from completely saturated and with standing water to very dry (plant leaves starting to show signs of drying out).

Here are other anti-corrosion measures for moisture sensors I found:
A moisture sensor with gold-plated electrodes:
https://www.dfrobot.com/product-599.html#.UhflOL-N_H0
Replacing metal electrodes with graphite:
http://tuxgraphics.org/electronics/200908/eth-flower-watering.shtml
Capacitive (i.e. not resisitive) moisture sensor:
https://www.amazon.com/DFROBOT-Gravity-Capacitive-Corrosion-Resistant/dp/B01GHY0N4K/ref=cm_cr_arp_d_product_top?ie=UTF8
Non-corrosive high quality sensor ($$$):
https://www.vegetronix.com/Products/VH400/

I use in my project the fully waterproof sensor SMT50 (see http://www.truebner.de/en/smt50). It is specified from 3.3V to 30V power supply with a current of around 3 mA, so that should be possible to supply it from a GPIO. Please not that the GPIO output voltage decreases with current (see AVR datasheet pin driver strength).

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How to produce multiple DC voltages for a single project
So the title pretty much says it all, but for an example, I have an arduino board, 5-12 V, an LED bank 18 V, and an ultrasonic mister 24 V.
I know some brute force methods to power them from one outlet, but I was wondering if there is a more elegant way to get the voltage for each device with only one transformer instead of three. The solutions I've come up with are less than elegant, and only moderately compact.
I was just wondering what solutions you guys have employed and hoped I could find something helpful.

First you want to take a regulated 24V supply. To that you want to add a switch-mode ("Buck") regulator to drop you down to 5V.  You don't want to try using an LDO for this unless you are happy to have a heat sink the size of a small car. A good cheap choice is a "UBEC" that can take 24V in and give 5V out (I use these).
That 5V can then be fed direct into the Arduino.
Depending on what the "LED bank" is you may get away with an 18V (or adjustable) LDO, or an adjustable buck regulator. Or a simple (though high wattage) resistor may be all that is needed. You will have to provide more detail on this to get more help.

Typically you'll only have a single transformer in this sort of design, to get you down to your highest DC voltage. Then you'll create lower voltage rails from that. You can use any number of approaches depending on your needs, e.g. capacitive dropper (on the 24Vac output of the transformer), resistor divider (on your rectified 24Vdc).
But, most typically for hobbyist projects you'll want to be using a regulator IC, either a linear regular/LDO (low noise but poor efficiency) or a separate onboard SMPS IC (good efficiency but typically noisy).

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
RX and TX pin in Arduino Uno
I have LED Cube Project, and I want to activate the LED with My Android apps (Bluetooth). The LED Cube used A0-A5 and D0-D13 Pins, and the Bluetooth need RX and TX (D0, D1).
Where I can put the RX and TX (for Bluetooth HC-05) while D0, D1, and all analog and digital pins are used by the LED?

buy a Mega. perhaps a mini version

is there no other way except buy a new device?

You can't magic more pins out of thin air. If you have used all your pins you have used all your pins. You are already multiplexing, so you can't use that to reduce your pin usage. You may be able to use charlieplexing to free up some pins. We'd need to see your schematics to know what is possible. Or just get a bigger board. Get one with more power while you're at it - and multiple UARTs, so you can use hardware serial for bluetooth and debug over USB at the same time.

my schematics just like LED Cube 4x4 in youtube https://www.youtube.com/watch?v=4pzxR-ZhbJA&t=548s

4x4x4 is 64 leds. You can do that with 8x8, which is only 16 pins. The software should be changed, but that would be a good programming exercise.

You can't magic more pins out of thin air.

Yes you can!
You can have as many output (and even input) pins as you want. I managed to build 8x8x8 LED cube using ATTiny13 with just 6 output pins (using only 5 of them)
All it takes is a little extra coding and "shift registers". (For extending outputs use the one with "latch", but for LEDs normal one is enough)

You can use three (for example CD4094) 8 bit shift registers. You connect three Arduino pins to "DATA" (a.k.a. SERIAL DATA INPUT) pin of each register. Then one Arduino pin to three "CLOCK" pins and one Arduino pin to three "OUTPUT ENABLE" pins.
Then in the code you send a sequence of bits into the registers simulating the clock signal and when that's over just set output enable to make the registers output a value on their 8 output pins each.
This way you use just 5 pins, and when you chain the registers together (last "Q8" pin of one register can go to "DATA" pin of second one) you can theoretically have as many outputs as you need at the cost of output update speed.
This way you can free most of your Arduino pins including TX and RX.

Using shift registers as extra parts is not "magic more pins out of thin air", but nontheless this is a valid answer how to get to the desired result.

It's just semantics and abstraction, but I think using the shift registers in this particular fashion is called "extending number of outputs" of microcontroller. Thinking about it this way allows you to mentally "blackbox" the microcontroler  with shift registers and just treat them as a single IC when designing rest of the circuit.


text:
How to write a library that support both HW and SW Serial communication and allow user to chose which one to use?
I'm working on a library for Arduino/ESP8266/Teensy that use serial to send AT commands. I want to make it as customizable as possible, so I avoided to hardcode the serial and I ask for a reference in the startup method:
void MyClass::init(HardwareSerial* hwSerialPtr)
{
   _serialPtr = hwSerialPtr;
   ...
}

On some devices, it will be useful to use SoftwareSerial instead of the HW one, due to only one serial is available and so keep it for debugging purposes or other features.
So my question is: how can I accept both types? I read both HW and SW serial have Stream as base-clase, but it does not have methods like begin() etc.
A possible solution I though is so have two pointers (one for HWSerial and one for SWSerial) then wrap some methods like begin(), println(), ... in my class and, ond the base of which pointer has been set, use one or the other.
Something like this:
class MyClass{
   public:
      void init(HardwareSerial* hwSerialPtr);
      void init(SoftwareSerial* swSerialPtr);

   private:
      HardwareSerial* _hwSerialPtr;
      SoftwareSerial* _swSerialPtr;

      void begin(long baud);
      void println(const String &s)
};

then
void MyClass::begin(long baud)
{
   if( _hwSerialPtr != null ){ _hwSerialPtr->begin(baudrate); }
   else if( _swSerialPtr != null ){ _swSerialPtr->begin(baudrate); }
}

...etc...

but this solution seems to me very tricky and not optimized.
Any better ideas?

and the way WiFiEsp library examples use is not good?  https://github.com/bportaluri/WiFiEsp/blob/master/examples/WebClient/WebClient.ino

why do you want to handle begin in the library? and alternative software serial implementations exist

The trick here is to go "up a level".  Both HardwareSerial and SoftwareSerial inherit from the Stream class.  It is that class that provides the majority of the interface that you actually use.
So you can provide a constructor with a Stream object alone and use that:
class Foo {
    private:
        Stream *_dev;

    public:
        foo(Stream *dev) : _dev(dev) {}
        foo(Stream &dev) : _dev(&dev) {}

        void begin() {
            _dev->println("I am ready");
        }
};

Foo myFoo(Serial1);
SoftareSerial btSerial(11,12);
Foo myOtherFoo(btSerial);

What the Stream class doesn't provide, though, is .begin() for setting the baud rate. It has to be left to the user to configure the port before using it.
Serial1.begin(115200);
myFoo.begin(); // --> "I am ready" on Serial 1

or:
btSerial.begin(9600);
myOtherFoo.begin(); // --> "I am ready" on Software serial pins 11/12.

This is known as polymorphism, where an object is seen as one of the parent classes in the inheritance chain and is one of the most powerful aspects of object-oriented programming.
Not having begin in your library is no big deal really. It increases the flexibility (a user can more easily select their baud rate), and it means you don't force them to include SoftwareSerial if they don't need it.
There are other things that inherit Stream, as well, such as a networking Client. So instantly you class can be used with network connections as well as just serial.
So stick to using Stream. It's the accepted way of doing things, and perfectly normal. For example, it's how my ICSC library handles serial objects.  (I used to use the multiple pointer method, but it really really got messy when trying to support other platforms. I ended up with HardwareSerial, SoftwareSerial, USBSerial, Client... a real mess. So much simpler to just use Stream.)

BTW, before you ask, I have two constructors with very slight differences so that you can construct an object either by passing a Stream object by reference (as I do in the examples) or as a pointer (which can be great if you want to use this in another class which itself has a pointer to a Stream object).

Another option is to combine the Stream pointer with a dynamic_cast to try and identify the type of object being passed.
void Foo::begin(int baud) {
    if (HardwareSerial *hs = dynamic_cast<HardwareSerial *>(_dev)) {
        hs->begin(baud);
    } else if (SoftwareSerial *ss = dynamic_cast<SoftwareSerial *>(_dev)) {
        ss->begin(baud);
    } else {
        // We don't know what to do here
        // so do nothing?
    }
}

In this way dynamic_cast is being used like Java's instanceof operator to work out what kind of object it is that is being used.
Of course, that then means that you're really restricting the library to only working with those two types of object, but it is still possible to pass other class types as long as the user pre-configures them before calling your begin function. Which gets confusing - which type does the user need to .begin() and which types have .begin() called for you? It's just cleaner to always have it as the user must call .begin() themselves - there's no ambiguity then.

I second Majenko's advice: inherit from Stream and let the user handle
the call to begin() if at all possible. However, if you really insist
in calling begin() from your class, then I suggest you make your class
a template, like this:
// T is the type of the serial port, typically HardwareSerial or
// SoftwareSerial.
template<class T> class MyClass {
    public:
        MyClass(T& port) : port(port) {}
        void begin(unsigned long baud) { port.begin(baud); }
    private:
        T& port;
};

Your user would then instantiate it as
MyClass<HardwareSerial> myObject(Serial);
MyClass<SoftwareSerial> myOtherObject(mySerial);

Of course, it doesn't look nice, and it may confuse your users, but it
has the advantage that it can work with anything that remotely looks
like HardwareSerial, e.g. AltSoftSerial or other alternative
software serial implementations.


text:
Arduino Mega upload issue
I have made my own version of an Arduino Mega and I am encountering some issues. Whenever I try to upload any sketch to the Mega, I get the following error message:
avrdude: stk500v2 ReceiveMessage(): timeout
I can upload just fine to the 16u2 as well as the 2560 using ICSP and Nick Gammons Atmega_Board_Programmer sketch. I have the correct board and COM port selected, and the cable, computer, and USB(2.0) port can upload to other Arduino boards just fine.
I have had some other troubles with the board that have been solved, but this issue remains. Please see my Arduino forum post for more details on these issues.
My current guess is that there may some sort of issue with the transmission lines between the 16u2 and the 2560. Here is a picture of the pcb traces. Can anyone look them over to see if there are issues with the traces?
If the traces seem fine, can anyone think of another reason why the upload does not work?

Comments are not for extended discussion; this conversation has been moved to chat.

So as of right now the problem has been solved. The issue was that the decoupling capacitor on the reset line near the 2560 was designed to be a 22pF capacitor, but I had put a 100nF capacitor, which increases the time constant by a factor of 5000, prohibiting the auto-reset circuitry from operating correctly. Removing the 100nF and putting in the 22pF seems to have solved the issue of only being able to upload once after burning the bootloader.
Thank you everyone for your support.

Can you elaborate? A decoupling capacitor is usually between Vcc and Gnd, so it wouldn't be "on the reset line". The capacitor in series with Reset (and usually going to RTS on the FTDI header) should work fine as 100nF. If you really have a decoupling capacitor on Reset (between Reset and Gnd) then you shouldn't have it.

Example schematic, which has always worked for me (this is the Atmega328P but it is the same concept).

Sorry for delay. For the reset connection between the 16u2 and the 2560, I have a 10k pull-down resistor on the 16u2 side, then a 100nF capacitor in series from the 16u2 to the 2560, a 10k pullup resistor on the 2560 side, and a 22pF shunt capacitor (shunt is a better word than decoupling). The shunt capacitor was a 100nF and that was causing the auto-reset to not work correctly.

Whatever word you use, you don't need that capacitor between Reset and ground. The schematic I linked to above shows a diode between Reset and Vcc which should suppress any inadvertent pulses which might put it into high-voltage programming mode, but that probably won't be required unless you have problems with it not resetting.

So there are some issues. I made three boards. One of them works correctly, the other two do not. I can manually program each chip (16u2 and 2560) with FLIP, Arduino as ISP, and your board programmer sketch. The circuitry is the same in each of the three boards. I have checked the resonators of each chip and they are functioning at 16MHz. Is the capacitor in question the culprit? The capacitor is populated on genuine Mega boards so I made sure to have it in mine. I have also noticed that when I program the blink sketch to the 2560 using ArduinoISP, The LED will stay on for 1s and off for 0.5s

OK, I see what you mean. The schematic has the 22 pF capacitor on the main chip but not on the Atmega16U2. On my schematic I see that PD7 on the Atmega16U2 goes to Reset on the Atmega2560 via the 100 nF capacitor. I would be more doubtful of the 100 nF capacitor than the 22 pF capacitor.

Am I correct in thinking that the 100nF series capacitor is to only allow a low to high or high to low signal transition from the 16u2 to the 2560 and that a capacitor with too low or too high capacitance can adversely affect the time constant, causing the 2560 to reset before or after the data is ready to be sent?

What data? It's purpose is to allow RTS to be pulled low (and stay low) by the USB interface. Initially that will activate Reset because it will go low temporarily, but then the pull-up resistor on Reset will charge the capacitor again, taking Reset high, and allowing the chip to run. I don't think the value is particularly critical. Too low, and the Reset pulse could be too short. Too high and the bootloader data will be sent while the processor is still reset. Still, the bootloader protocol should handle anything other than an egregiously long time.

Yes the line is to control the auto reset and the RC circuit timing can adversely effect the bootloader not starting on time or ending too quickly, but yes only with a drastic difference. The data is sent over the UART lines, but the reset line lets the 2560 reset and run the bootloader, which looks for the data. If the bootloader ends too quickly the, 16u2 will spit out the ReceiveMessage timout error since no data is being received since the bootloader on the 2560 is done with its process(es)


text:
Cannot use radio transmitter after switching to LowPower library
My Arduino Mini board has DHT22 temperature sensor and 433MHz radio transmitter modules. I'm using DHT and RCswitch libraries to make use of them. Code looks like this:
void setup() {
  tempSwitch.enableTransmit(RADIO_PIN);
  dht.begin();
}

void loop() {
  float temp = dht.readTemperature();

  unsigned long message = createTemperatureMessage(SENSOR_ID, temp);
  tempSwitch.send(message, 32);

#ifdef MY_DEBUG
  unsigned int sleepCount = 1;
#else
  // 3600s / 2 / 8s == 225
  unsigned int sleepCount = 225;
#endif
  for (; sleepCount > 0; sleepCount--) {
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
  }
}

So I'm reading temperature and sending it using RCswitch library. Initially I just had delay(1000); instead of fancy LowPower sleep loop but I wanted to make my "device" more battery-friendly so I switched to low-power sleep.
The problem is that now Arduino is only sending data first time and after sleeping 30 minutes (in "release" mode) it does not send anything anymore. If I reduce 30 minutes to 8 seconds it is capable of sending data as well as if I replace sleep with delay(30*60*1000);.
From beyond it looks like something is not caching up after the sleep. Do I need to "wake" radio module in any special way? How to fix that?

I've never tried this, but if you are putting the Arduino to sleep I would expect it to cut power to the devices (does it?) if it does then after a 30 minute sleep I would expect the devices to come back up in the initial state.  Guessing by your code the initial state of the radio is Tx Disabled, so try moving the
tempSwitch.enableTransmit(RADIO_PIN);

to before the
float temp = dht.readTemperature();

line.
I'd also be concerned that the DHT22 is not in the correct state after you wake up.
Can you try doing a 1 second LowPower sleep in debug mode, I suspect it would work more often.

You idea kind of worked (I just called setup() instead) but with addition of delay(1000); after power-down sleep itself.


text:
Hex/Byte Reversing and Conversion
I'm working on an RFID system using a MFRC522 with this Library : https://github.com/miguelbalboa/rfid
Here's the code I have right now:
int A=(mfrc522.uid.uidByte[0]);
int B=(mfrc522.uid.uidByte[1]);
int C=(mfrc522.uid.uidByte[2]);
int D=(mfrc522.uid.uidByte[3]);

Serial.println("UID is %x %x %x %x", A, B, C, D);

This results in the following output:
UID is 35 C5 5A 59

My issue is - how do I first reverse that UID : from 35 C5 5A 59 to 59 5A C5 35
- and second convert and print the corresponding decimal value of that reversed UID. In this case, it would be 1499120949.
I should mention that I need it as a string at the end to add it to the end of a POST command.

Already has an answer on Arduino.cc  http://forum.arduino.cc/index.php?topic=561413.0

A standard way to convert individual bytes to a number is to use bit
shifts and bitwise OR, as shown in chrisl's answer. When doing this,
however, one has to take care not to overflow the bit shifts. On the
AVR-based Arduinos, an int is 16 bits long. Shifting it by
24 bit positions to the left is guaranteed to overflow, which in
C++ leads to undefined behavior.
The solution, as explained in Majenko's comment, is to cast to the final
type before shifting, like this:
uint32_t uid = (uint32_t) mfrc522.uid.uidByte[0] << 0
             | (uint32_t) mfrc522.uid.uidByte[1] << 8
             | (uint32_t) mfrc522.uid.uidByte[2] << 16
             | (uint32_t) mfrc522.uid.uidByte[3] << 24;

Note that I got rid of the useless intermediate variables A through
D.
Once you have have the numerical value, you may try to use it without
explicitly converting to a string. Instead, you rely on the print()
or println() methods to implicitly do the conversion only when needed,
as in
Serial.print("UID = ");
Serial.println(uid);

or even, on a network connection:
client.print(uid);

This will save you the memory needed to store the string. If you really
need to have the converted string in memory, which could happen if you
need to provide a Content-Length before sending the data, you can do so
with the function ultoa() from the avr-libc:
char uid_str[11];  // max = 10 digits + terminating NUL
ultoa(uid, uid_str, 10);  // convert to base 10

Please note that ltoa() is not appropriate here, as calling it
will implicitly convert the value to a signed long, which has the
potential to overflow and yield a negative result.
This “C string” – a NUL-terminated character array – can then
be converted to a String object if needed, but I advice you against doing so
if at all possible. String objects are more convenient to manipulate,
but they are absolutely not memory friendly, which can quickly become an
issue on most Arduinos.

Your UID has 4 bytes, which correspond to 32 bits. To get a decimal value from these bytes, you have to put them together in one variable. For this you can use an unsigned long. To put the bytes together, you can shift the values to the byte boundaries:
unsigned long dec_value = (D << 24) | (C << 16) | (B << 8) | A;

<< shifts the bits of the byte by the specified amount of bits to the left; The bitwise OR | puts the now not overlapping bytes together in one value. I have reversed the order of the bytes in this code, as you wrote, that this is necessary.
To convert this unsigned long to a string you can use the function ltoa():
char buf[50];
ltoa(dec_value, buf, 10);  // 10 is the base value not the size - look up ltoa for avr

If you want to use a String object (which should be avoided because of heap fragmentation), you can contruct the String directly from the long value:
String my_UID = String(dec_value);

Fantastic! I tried printing the result just to test with Serial.println("%s\n", my_UID); but I'm getting an error: no matching function for call to 'HardwareSerial::println(const char [4], String&)'

Serial.println() does not work like sprintf(), so you can't use that syntax there. But you should be able to get the correct result by simply writing Serial.println(my_UID);. There is really no need to format the string again (also because println already adds a line break at the end, so that you can ditch the extra "\n").

Ah. Managed to get it to print - but I'm getting 4294952245 as my decimal answer. An online converter said that 595AC535 = 1499120949. I'm testing it using fixed hex bytes - https://pastebin.com/i2NPjv60

You need to use "unsigned long" instead of "int" for your A,B,C and D - otherwise the shifting overflows.

dec_value is a poorly chosen variable name, as it implies there is something “decimal” about it. It's not decimal: it's just a number, internally stored in binary, just as any other numerical variable is stored in binary.

To add a bit to the whole hex and decimal story:
Those are just representations of numerical values your computer/microprocessor does not really care about.
int x = 0
int y = 0b0
int z = 0x0

these are all the same value and internally stored as binary, just like any other number.
You specifically told the println function to display said number(s) in hexadecimal representation with the format specifier %x
Serial.println("UID is %x %x %x %x", A, B, C, D);
using %d or %i(for integer) will print out decimal values for each number.
Converting byte array to larger data type
If you actually want them to be reversed, you could simply cast the array variable (which is nothing but a pointer) to an uint32_t pointer:
uint32_t dec_value = *(uint32_t*)mfrc522.uid.uidByte

Note the *s
We first cast the pointer to a pointer of a different type (uint32_t*)
and then access it's value, by prepending another *, which is then stored in dec_value, equaling 1499120949 now.
This works because in C/++ data structures in memory are guarenteed to be in the order you specified.
 Therefore, you essentially tell the computer to 'see' these very 4byte (32bit) as a single value rather than a independent bytes.
Usually, when converting byte arrays to larger data types, you will find the values you receive are not what you would expect. This is because they are stored in a different order (depending on the machine) known as endianness
Here is a function that addresses this issue (similiar to the other answers)
uint32_t bytearray_to_uint32(unsigned char *buffer)
{
    uint32_t value = 0;

    value |= (uint32_t)buffer[0] << 24;    // cast to target type before
    value |= (uint32_t)buffer[1] << 16;    // shifting to avoid overflow
    value |= (uint32_t)buffer[2] << 8;     // no parentheses needed due to operator precedence
    value |= buffer[3];

    return value;
}

Applying this function to your case would result in 902126169 (0x35c55a59) instead of the desired 1499120949 (0x595ac535).
Also check out ntohl when dealing with endianness still puzzles you.

As already stated in Majenko's comment to chrisl's answer, and restated in my own answer, buffer[0] << 24 will overflow on most Arduinos. 2. ntohl() is not be available on most (maybe all) Arduinos.

I referred to ntohl for educational purposes only. Shifting an 8 bit value by > 8 will not overflow unless the target is too small (WinAVR). Again, the function utilizing shifting is just included for educational purposes, as it is not suited for OP's application in it's given form.

This may be just my personal opinion, but I don't think “educational purposes” excuses undefined behavior.

Behavior depends on target architecture and used compiler. Any decent one will either cope or throw a shift-count-overflow instead.

I think this does what you need.  You already have the data in an array so to reverse it you go backwards through the list and assemble the number.  To fit 4 bytes into 32bits you need to multiply each byte by (256 * its position), which is what the left shift << does.  So by placing the code in a small loop you get some compact code that should do the job.
int A=(mfrc522.uid.uidByte[0]);
int B=(mfrc522.uid.uidByte[1]);
int C=(mfrc522.uid.uidByte[2]);
int D=(mfrc522.uid.uidByte[3]);

Serial.println("UID is %x %x %x %x", A, B, C, D);
// ^ Your code
uint32_t reversed = 0;
for (int x = 3; x > -1; --x) // go backwards through the array
{  // Take the existing value and multiple by 256 (left shift by 8) then add the latest byte on.
   reversed = (reversed << 8) + mfrc522.uid.uidByte[x];
}
String decValue = String (reversed);  // Covert the number to a string


text:
Why do COM port numbers between Arduino and Processing not match?
I have a Processing program that reads data sent to the serial port by an Arduino. When I go to device manager it shows that the Arduino is plugged into COM 4, however in order to get Processing to read the data the number I need for the COM in the following line is 2:
String portName = Serial.list()[2]

Why do the numbers not match?
Thanks!

what numbers are you talking about?

Serial.list()[2] can easily refer to COM4 as well.

If you print out portName it should be COM4 it seems you must have 3 COM ports on your machine otherwise you would use index 0; Serial.List() appears to return an array or list which you are taking the third item located at index 2.

Indeed. The numbers do match. But you are trying to match a number with a name, and those do not match. Or are you Number 6?


text:
Posting TinyGPS++ co-ordinates as paramaters with GPRS
I'm able to view my co-ords on the Serial Monitor using Serial.println(gps.location.lat(), 6);
I believe the data type returned by gps.location.lat() is double. I need to pass this value to a webservice with AT commands over GPRS.
double latitude = gps.location.lat()
Later in my code I execute AT commands to begin HTTP POST. I would like to know how to pass these double values in my paramaters.
gsm.println("AT+HTTPPARA=\"URL\",\"http://webservice/service1\"");
 gsm.println("AT+HTTPDATA=192,10000");
 gsm.println("latitude=" + latitude); < This is not allowed.
How can I pass this parameter to my web service.

One solution may be to split the commands:
gsm.print("latitude=");
gsm.println(latitude);

I'm not sure how you should pass multiple parameters; if it is the usual syntax you can write something like
gsm.print("latitude=");
gsm.print(latitude);
gsm.print("&longitude=");
gsm.println("longitude);

If I have the time I'll research into this a bit.
To check what is the problem, you may try to send "static" messages, like
gsm.println("latitude=12.345");

To check if this format is the correct one
EDIT: after a very quick research
It looks like the AT commands are a bit more complicated. In order to send the parameters, at least on a SIM800L, you should:

send the HTTPDATA command (the first parameter is the length of the payload)
wait for the board to send you the command DOWNLOAD
Send the body of the request, which is formatted as a JSON object. This means you have to send something like { "latitude" : 12.345, "longitude": 98.765 }

After all, it is much faster to use a library already developed for this, for instance ArduinoSIM800L (check a library available for your GPRS modem, or modify this one)

Seperating the values in individual print commands was the trick. Thanks!


text:
Connecting Arduino and Processing, how do I know what COM to read?
I'm using Processing to read data from the serial port that the Arduino sends. When I go to device manager it shows that the Arduino is in COM 4, but in order for Processing to read from the Arduino the COM I need to type in is 2:
String portName = Serial.list()[2]

Why do the numbers not match?
Thanks!

Because the two numbers are completely different types of numbers.
The number 4 for COM4 means that it is the fourth serial communications port as defined by which I/O ports are used to communicate with the actual hardware. I.e. you'll have COM1, COM2, COM3 and so on. It doesn't matter if the hardware is actually there or anything is connected - the names are the same.
The number 2 in Serial.list()[2] means that you're selecting the third (!) element of the array returned by Serial.list(). I.e. in this case we're counting from 0 instead of 1.
In addition to that, Serial.list() only returns available ports. I.e. if the hardware for COM3 is not installed physically, it will not be returned by Serial.list(). Also the list is not guaranteed to be sorted in any specific order.
You'll want to print out the contents of the array returned by Serial.list() and let the user select which of the ports he wants to use.


text:
MemoryFree library showing Irregular Behaviour..!
I simply burned the code written below but it is showing me irregular behaviour.. as in output's last paragraph, free memory increases after a runtime allocation, how it is possible? The output is attached :
#include <MemoryFree.h>
String str="rajat";
int flag=0;
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}

void loop()
{
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    str=str+"rjt";
    Serial.println(str);
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    Serial.println("");
      delay(1000);
}

Free memory can be found in two forms:

The free space between the heap and the stack. This is usually the
main chunk of free memory.
Heap “holes”, i.e. pieces of unallocated memory within the heap. The
presence of these holes is called “heap fragmentation”.

There are various versions of the MemoryFree library. The simplest ones
only report the main chunk between the heap and the stack. The more
sophisticated ones walk the malloc()'s free list in order to also count
the heap holes. Which approach is better? I would argue that the naive
version is fine, as heap holes is something you should not count on,
because it is never guaranteed that a particular allocation will fit in
any of those holes.
You are visibly using one of the naive versions. As you grow your
string, the object calls realloc(), which in some cases copies the
string's character array and frees the original one, potentially
creating a heap hole. Eventually, small holes can coalesce into a
larger one big enough for the next allocation, and
realloc() can end up using this large hole and freeing the chunk at
the top of the heap. When this happens, the heap shrinks, and the main
chunk of free memory gets larger, which is what freeMemory() is
reporting to you.
In summary, it's normal and expected behavior. If you want something
less surprising, use a version of the library that does count the holes.
But then you may run into a more displeasing surprise: a heap–stack
collision, or an out-of-memory condition, can happen even with loads of
memory buried inside heap holes.


text:
freeMemory() function from memoryfree library not returning decreased value in arduino UNO
I burned the code written below, I expect that as we declare the local variable in the loop, freeMemory() function should return decreased value. But it remains constant..! please explain why..?  The output is attached :
#include <MemoryFree.h>
void setup()
{
  // put your setup code here, to run once:

  Serial.begin(9600); Serial.println(freeMemory(), DEC);  // print how much RAM is available.
  Serial.println("Lets Start");
}
void jack();
void loop()
{
    char c=0;
    c++;
    Serial.println("");
    Serial.println("Rajat0");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat1");
    int x=0;
    x++;
    Serial.println("Rajat2");
    Serial.println(freeMemory(), DEC);
    Serial.println("Rajat3");
    jack();
    Serial.println("");
    delay(1000);
}
void jack()
{
    Serial.println("jack0");
    int x=0;
    x++;
    Serial.println(freeMemory(), DEC);
    Serial.println("jack1");
}

Given your recent track of similar questions that turn around how the compiler manages memory, I very strongly recommend you start to learn the basics of AVR assembly, and then read the assembly generated by the compiler. I promise this will enlightening.

Thanks @Edgar for your kind suggestion..! :) It will be a great help if you can recommend me with some strong reference.. i.e. links, books etc.

You are assuming that, just because you created a variable, it will be stored in memory. That is often not the case.
The compiler is reasonably intelligent. And there are lots of CPU registers in the AVR core. If there is a free register available for a temporary local variable like that, why would it waste time and effort putting it into memory when it can just keep it in a register?
Also, since you don't really do anything with the variable, chances are the compiler is just throwing it away.
Marking a variable volatile will remove both those problems, and you may see different results.

Suppose CPU chooses memory to store variable..Does'nt stack variable will occupy space after they are declared..? And free memory should be decreased in the jack function w.r.t available memory before calling jack function..?

The CPU doesn't choose anything. The compiler makes that decision. If it decides the variable is only used for a short time and there is a spare register it will choose to use that register instead of allocating space on the stack. Your view of the language and compiler is too naïve.

Sorry..! I am a UG fresher.. still learning.. :).. but let say compiler chose.. ! my query if it chooses memory to store variable..Does'nt stack variable will occupy space after they are declared..? And free memory should be decreased in the jack function w.r.t available memory before calling jack function..?(& Of course if those variables will be used in some conditional operations)

If the compiler chooses to allocate memory then there are two possible scenarios. Either the memory will be allocated on the stack at the point the function is entered, or it will be allocated when the variable is first used. You should look at the assembly language the compiler produces.

Function 'jack' also does not show any difference in allocation. Since jack() is called only within this one module (known, because the program only consist of one module), and only once, the compiler can replace the function-call with the actual code of the function, saving both the space and time of a call and return.
That optimization is called "inlining" (usually only useful for instructional purposes but learning appears to be the whole point of your sketch). You can suppress the inlining by prefixing both the function and its declaration with __attribute__ ((noinline)). (Note that this attribute is specific to the gcc compilers; other compilers may provide a different way to do it, or none at all):
__attribute__ ((noinline)) void jack();

...

__attribute__ ((noinline)) void jack(){
   ... etc ...
}


text:
Include in different file make different compiling error
I'm have problem compiling a code.
ardutest.ino:

#include "mylib.h"
#include <SD.h>

void setup() {

}

void loop() {
  fn();
}

mylib.h:
#ifndef mylib_h
#define mylib_h

#include "Arduino.h"

void fn(File &_file);

#endif

mylib.c:
#include "mylib.h"

void fn(File &_file)
{
  _file = SD.open("LOG.TXT", FILE_WRITE);
  _file.println(42);
  _file.close();
}

When checking code in Arduino IDE I have this error:
In file included from sketch/mylib.c:1:0:
mylib.h:7: error: expected ')' before '&' token
 void fn(File &_file);
          ^
mylib.c:3: error: expected ')' before '&' token
 void fn(File &_file)
          ^
Multiple libraries were found for "SD.h"
 Used: /home/mario/Arduino/libraries/SD
 Not used: /home/mario/Programs/arduino/libraries/SD
exit status 1
expected ')' before '&' token

But if I put SD.h in mylib.h (other files are the same):
#ifndef mylib_h
#define mylib_h

#include "Arduino.h"
#include <SD.h>

void fn(File &_file);

#endif

I have this error:
In file included from /home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:26:0,
                 from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:29,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:423:14: error: unknown type name 'pin_map_t'
 static const pin_map_t digitalPinMap[] = {

              ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:447:69: error: 'pin_map_t' undeclared here (not in a function)
 static const uint8_t digitalPinCount = sizeof(digitalPinMap)/sizeof(pin_map_t);

                                                                     ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'getPinMode':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:455:32: error: request for member 'ddr' in something not a structure or union
     return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1;

                                ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:455:58: error: request for member 'bit' in something not a structure or union
     return (*digitalPinMap[pin].ddr >> digitalPinMap[pin].bit) & 1;

                                                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'setPinMode':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:464:26: error: request for member 'ddr' in something not a structure or union
       *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit;

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:464:57: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].ddr |= 1 << digitalPinMap[pin].bit;

                                                         ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:466:26: error: request for member 'ddr' in something not a structure or union
       *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit);

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:466:59: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].ddr &= ~(1 << digitalPinMap[pin].bit);

                                                           ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'fastDigitalRead':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:475:32: error: request for member 'pin' in something not a structure or union
     return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1;

                                ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:475:58: error: request for member 'bit' in something not a structure or union
     return (*digitalPinMap[pin].pin >> digitalPinMap[pin].bit) & 1;

                                                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h: In function 'fastDigitalWrite':
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:484:26: error: request for member 'port' in something not a structure or union
       *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit;

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:484:58: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].port |= 1 << digitalPinMap[pin].bit;

                                                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:486:26: error: request for member 'port' in something not a structure or union
       *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit);

                          ^
/home/user/Arduino/libraries/SD/src/utility/Sd2PinMap.h:486:60: error: request for member 'bit' in something not a structure or union
       *digitalPinMap[pin].port &= ~(1 << digitalPinMap[pin].bit);

                                                            ^
In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:29:0,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
Multiple libraries were found for "SD.h"
 Used: /home/user/Arduino/libraries/SD
 Not used: /home/user/Programs/arduino/libraries/SD
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h: At top level:
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:70:1: error: initializer element is not constant
 uint8_t const  SD_CHIP_SELECT_PIN = SS;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:79:1: error: initializer element is not constant
 uint8_t const  SPI_MOSI_PIN = MOSI;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:81:1: error: initializer element is not constant
 uint8_t const  SPI_MISO_PIN = MISO;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:83:1: error: initializer element is not constant
 uint8_t const  SPI_SCK_PIN = SCK;

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:176:1: error: unknown type name 'class'
 class Sd2Card {

 ^
/home/user/Arduino/libraries/SD/src/utility/Sd2Card.h:176:15: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 class Sd2Card {

               ^
In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:30:0,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/FatStructs.h:405:1: error: initializer element is not constant
 uint8_t const DIR_ATT_FILE_TYPE_MASK = (DIR_ATT_VOLUME_ID | DIR_ATT_DIRECTORY);

 ^
In file included from /home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:27:0,
                 from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:31,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:25:1: error: unknown type name 'class'
 class Print;
 ^
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:33:1: error: unknown type name 'class'
 class Printable
 ^
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Printable.h:34:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 {
 ^
In file included from /home/user/Arduino/libraries/SD/src/utility/SdFat.h:31:0,
                 from /home/user/Arduino/libraries/SD/src/SD.h:20,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:37:1: error: unknown type name 'class'
 class Print
 ^
/home/user/.arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino/Print.h:38:1: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 {
 ^
In file included from /home/user/Arduino/libraries/SD/src/SD.h:20:0,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:39:1: error: unknown type name 'class'
 class SdVolume;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:55:1: error: initializer element is not constant
 uint8_t const O_RDONLY = O_READ;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:59:1: error: initializer element is not constant
 uint8_t const O_WRONLY = O_WRITE;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:61:1: error: initializer element is not constant
 uint8_t const O_RDWR = (O_READ | O_WRITE);

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:63:1: error: initializer element is not constant
 uint8_t const O_ACCMODE = (O_READ | O_WRITE);

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:94:1: error: initializer element is not constant
 uint8_t const FAT_FILE_TYPE_MIN_DIR = FAT_FILE_TYPE_ROOT16;

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:137:1: error: unknown type name 'class'
 class SdFile : public Print {

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:137:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
 class SdFile : public Print {

              ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:431:1: error: unknown type name 'class'
 class SdVolume {

 ^
/home/user/Arduino/libraries/SD/src/utility/SdFat.h:431:16: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 class SdVolume {

                ^
In file included from /home/user/Arduino/libraries/SD/src/SD.h:21:0,
                 from sketch/mylib.h:5,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'FreeRam':
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:7: error: 'reinterpret_cast' undeclared (first use in this function)
   if (reinterpret_cast<int>(__brkval) == 0) {

       ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:7: note: each undeclared identifier is reported only once for each function it appears in
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:43:24: error: expected expression before 'int'
   if (reinterpret_cast<int>(__brkval) == 0) {

                        ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:45:36: error: expected expression before 'int'
     free_memory = reinterpret_cast<int>(&free_memory)

                                    ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:49:36: error: expected expression before 'int'
     free_memory = reinterpret_cast<int>(&free_memory)

                                    ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'SerialPrint_P':
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:62:52: error: 'Serial' undeclared (first use in this function)
   for (uint8_t c; (c = pgm_read_byte(str)); str++) Serial.write(c);

                                                    ^
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h: In function 'SerialPrintln_P':
/home/user/Arduino/libraries/SD/src/utility/SdFatUtil.h:72:3: error: 'Serial' undeclared (first use in this function)
   Serial.println();

   ^
In file included from sketch/mylib.h:5:0,
                 from sketch/mylib.c:1:
/home/user/Arduino/libraries/SD/src/SD.h: At top level:
/home/user/Arduino/libraries/SD/src/SD.h:26:1: error: unknown type name 'namespace'
 namespace SDLib {
 ^
/home/user/Arduino/libraries/SD/src/SD.h:26:17: error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token
 namespace SDLib {
                 ^
/home/user/Arduino/libraries/SD/src/SD.h:119:1: error: unknown type name 'using'
 using namespace SDLib;
 ^
/home/user/Arduino/libraries/SD/src/SD.h:119:17: error: expected '=', ',', ';', 'asm' or '__attribute__' before 'SDLib'
 using namespace SDLib;
                 ^
/home/user/Arduino/libraries/SD/src/SD.h:123:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
 typedef SDLib::File    SDFile;
              ^
/home/user/Arduino/libraries/SD/src/SD.h:124:14: error: expected '=', ',', ';', 'asm' or '__attribute__' before ':' token
 typedef SDLib::SDClass SDFileSystemClass;
              ^
In file included from sketch/mylib.c:1:0:
mylib.h:7: error: expected ')' before '&' token
 void fn(File &_file);
              ^
mylib.c:3: error: expected ')' before '&' token
 void fn(File &_file)
              ^
exit status 1
expected ')' before '&' token

If I use SD.h function in mylib, I need this in mylib.h file. Why is it happens?
The first error is about passing object as function argument. I'm following sample I found in others forum, then I don't know why it isn't working.
[SOLVED]
I rename mylib.c to mylib.cpp and solved the problem.

in first case you have SD.h included after mylib.h so File is not known

SD.h defines class File. Without that definition, 'File' is taken to be the name of an untyped argument (which will be assumed to be an int). Given that assumption, '&_file' is unexpected.

Firstly, there are different strategies for organizing header file structure. I don't know which one you follow. Within the popular approach that strives to keep all header files in self-sufficient state, mylib.h should include <SD.h> since mylib.h uses File type.
Secondly, when you actually included <SD.h> into mylib.h, you ran into a different problem. SD library is written as a C++ library. Its header files will not compile as C code. Meanwhile, you are trying to compile <SD.h> in C mode by indirectly including it into a mylib.c file, which is what causes the errors.

This library's header files contain many bizarre coding patterns that might create an impression as if someone was trying to make these headers compatible with C code (static const? static inline? Etc.), but this is an illusion. The code is exclusively C++, not C.


text:
How to change the default Slave Select pin (Digital pin 10) on Arduino UNO R3 for SPI communication?
Currently I am working on an Arduino based project. My project require interfacing 6 servo motors and an SD card module to my Arduino UNO.
The problem is that I need all the six PWM pins for six servos (Including pin 10) which happen to be the default Slave Select Pin for SPI communication. I don't want to use software based PWM on a digital pin. I could not find any resource on how to change the default SS pin to any other pin. Any help in this regard will be highly appreciated. Thanks!

Other than passing a different argument to SD::begin()?

Hmm, I though any GPIO pins could be used for slave selecting.

pin 10 is CS if Atmega 328 is a SPI slave. if Atmega is master pin 10 must be output otherwise the chip switches to slave. pwm is output

Just declare it and use it:
byte ssPin = 7; // or any other pin, stay away from 0,1, leave those for Serial()
byte defaultSS = 10; // 53 on a 2560

pinMode (ssPin, OUTPUT);
digitalWrite (ssPIN, HIGH); // typical slave select OFF state
pinMode (defaultSS, OUTPUT);  // 10 MUST be an output for device to be SPI master (328P)
SPI.begin(); // default is 4 MHz speed, MSBFIRST
// takes care of SCK, MISO, MOSI, don't need define/declare those

digitalWrite (ssPin, LOW);
SPI.transfer (ledData, 0xAA); // example data going to a device
digitalWrite (ssPin,  HIGH);

" The problem is that I need all the six PWM pins for six servos" The Servo.h library can drive 12 Servos on an Uno, and on any pin,not just PWM pins. Check it out. Servos need a 1-2mS (1000 to 2000  uS) wide pulse occurring every 20mS (50 Hz), which is not really PWM. (1mS =  full turn one direction, 1.5mS = centered, 2mS =  full turn the other direction, give or take a few uS).  I bet that could be created using Blink without Delay technique even, 50 Hz is pretty slow.


text:
LED does not light when inserted into round Lilypad board
Title: LED does not light when inserted into round Lilypad board.
very simple goal here: i want to plug in a blinking LED [or 10] into a round circuit board [then solder them], then power those LEDs. when i touch the - and + battery wires to the loose LED it lights. as soon as i insert the LED into the Lilypad round prototype board, those same battery wires will not light the LED. of course when i solder the LED in, then touching the battery - and + to two of the outer board contacts, nothing lights. the board is, "LilyPad Prototype Board ProtoBoard by AMX3d - Round Prototype Board for all DIY Electronics project", and the LEDs are, "100pcs 3mm Flat Top Water Clear Fast Rainbow Flash RGB flashing LED Diodes USA". it is like the board thwarts conductivity. thoughts?
board - https://www.amazon.com/gp/product/B01L9B9RSY/ref=oh_aui_detailpage_o03_s00?ie=UTF8&psc=1
LEDs - https://www.ebay.com/itm/121752435838

and the resistor? https://www.arduino.cc/en/Tutorial/Blink

How is it actually wired?

wow glad u can get ur "eyes" on this. i have no resistor, why would i need one? one per LED? i literally hold the LED, touch black and red wires to the short and long LED legs, it lights. i then insert it into the board, then w the wires still on the legs, as it is lit, when it goes into the board, it stops lighting. i had soldered a tiny dab on the same edge as where the outer pwr pads show circuit paths going towards center of board, so i think it's soldered on the right side. but then i discovered, merely inserting the LED stops the conductivity. i thought it could NOT be simpler lol.

https://arduino.stackexchange.com/questions/54771/what-happens-if-you-supply-too-much-voltage-to-an-led?answertab=oldest#tab-top

That board looks to me like every pin is connected to every other pin. You will have to isolate the pins you want to use. I have never seen a board like that before...

the question remains ....  @dcparham, why do you not see that all the pads are connected together on that board?

well, being an uber noob, i am only now tuning into the context of how the boards work. Majenko below highlighted what i had just found when going back to RTM.

Your board has every pin directly connected to every other pin.
As it states in the description:

10 mil traces connect holes, cut the ones you do not need to create a breadboard with infinite possibilities

(Highlighting by me).

hah, NOW it's making a micron of sense.... so need to use a razor or clippers to isolate away the holes i will not be using; then the board will look strange, parts of it being cut away, right? my original goal was to have a bank of LEDs in a circle, beneath a 1" circle hole in wood, to produce a sparkling effect. i had thought the board would remain circular. anyway, thx much!

You don't need to cut the board - only the thin tracks that join the holes. Just scape them with a craft knife until they break.

ah i see, isolate the row and column that lead to their respective outer pad [one -, the other +], by breaking the other connections. new to this, thx much! [but of course let me know if i misinterpreted your notes]

Sounds right, yes. If you look at the rear you can see that there are 4 traces coming from each pad, north, south, east and west. Should be easy enough to cut them.


text:
Help me determine the power consumption/rating of the circuit below?

Please help me determine the circuit's power consumption from the battery and help me outline the steps to calculate?

Battery power consumption is a tricky engineering problem.  Many estimate then find them selves to be way off.  Especially when using ultra low current processors (processors which support sleeping features).  Added complexities may result when assumed features are unavailable in various levels of sleep mode.  Like, for instance, an accurate clock.  Further, special considerations are necessary when designing for low power consumption.   Simple things like not using pull up or pull down resistors can spell the difference between an extra hour to extra days of operation.

Use a multimeter to measure it in its different states (relay on/off; MCU in sleep mode, etc)

Why the frog are you using a TIP122 to switch the gate of a MOSFET?!?!

You can use higher values for r5 and r6, for example 100k and 10k. Don't connect aref to vcc. The crystal requires two 22pf capacitors. pd5 to q1 is missing a resistor. The buzzer might be inductive. Are those soil moisture sensors resistive or capacitive? If they are the resistive type, they will become useless very quick. What kind of battery is it? Are you relying on your programmings skills to prevent that the battery will be charged too much? The omih-sh-124l is a 24V relay and requires a minimal voltage of 18v.

It's not a simple matter of "calculating the power". Instead you need to:

Calculate (or obtain) the current consumption of each individual sub-module or component
Calculate (or obtain) the current consumption of the main MCU for each power state it operates in
Calculate the current consumption of static items such as voltage dividers and power LED

Then:
For each unit examine the percentage of time it spends in different power states. From that create an hourly average current for the unit.
And finally:
Sum up all the average hourly usages to get a final AH value for the whole circuit.
Most of the current values can be obtained either by calculation (e.g., Ohm's Law for resistive dividers and LEDs, etc), or from the datasheets for the devices you have attached.
Note that this will still only be an approximation, because (amongst other things) you have multiple power sources which will cause different drains on the system depending on which source is being actively used (different monitoring circuitry and components switched it), and that (I assume) is influenced by the weather.


text:
What's the maximum number of keys in Yun Bridge?
The Yun has a Bridge for communicating between the Arduino and Linux processors via a key/value hash. The docs say this is actually stored on the Linux side, but it doesn't say what the limit is.
How many key/value pairs can the Bridge store? What are the practical limitations?

I think that the limit is the memory in the atmega32u4 and the speed limit for the python script on the linux side. About 20 values should be no problem, but when you have 20 different values, all the updating and controlling those 20 values via the bridge can be a problem. When you need 1000 values, perhaps you can try to control everything on the linux side and start a linux-script from the arduino side now and then. The best solution is stop using the yun right now, before you spend too much time struggling with it. Have a look at the mkr wifi boards, or the esp32 or the raspberry pi.

The data is just stored in an array within the Python daemon. The ATMega32U4 just sends commands to set / get the values, so there is no limit imposed by the ATMega side of things.
The only limit is the size of the array in Python, and that is restricted by:

The amount of available memory in Linux, and
Whether or not you have swap space set up on the Yun

Since both those are very much variable (it depends what processes you have running, what your configuration is, etc) the answer can only really be:

Quite a few.

Putting memory aside for a moment, an answer to this question on SO states:

According to the source code, the maximum size of a list is PY_SSIZE_T_MAX/sizeof(PyObject*) . On a regular 32bit system, this is (4294967295 / 2) / 4 or 536870912. Therefore the maximum size of a python list on a 32 bit system is 536,870,912 elements.

So you have the smaller of:

The maximum you can fit in Linux's memory, and
536,870,912

Majenko, google translate has troubles with the expression "quite a few". It can understand "quite a lot" or "a few" and also "quite a few beer", but it gets confused with just "quite a few". It is "many", right? Have you used the arduino yun? Every idea that pops into my mind turns out to be very hard to implement on the arduino yun.

GT often struggles with idioms. Quite A Few = A Lot, but not a huge amount. More than a few, less than a massive amount. I have a Yun, but all it is doing at the moment is being a router to connect my sky box to the WiFi. The Yun was a nice idea when first thought up, but MCU technology has moved on since then, and it's pretty redundant now.


text:
Every so often ESP8266 hangs... WifiClient seems to be at fault
This code works fine without any freezes:
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  /*if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }*/

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

While this code (with the wificlient bit commented out) freezes every so often:
#include <ESP8266WiFi.h>
#include <Servo.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>

Servo turn;

ESP8266WiFiMulti wifiMulti;

const char* host = "192.168.1.148";
WiFiClient client;

int turnPos = 90;
unsigned long ts = 0;

void setup() {
  startWiFi();
  turn.attach(14);
  turn.write(90);
}

void loop() {

  if (millis() - ts > 500 && millis() - ts < 1000) {
    turnPos = 160;
  }
  else if (millis() - ts >= 1000) {
    ts = millis();
  }
  else {
    turnPos = 20;
  }

  if (client.connected()) {
    }
    else {
    if (!client.connect(host, 3000)) {
    }
    }

  turn.write(turnPos);
  yield();
}

void startWiFi() {
  wifiMulti.addAP("DVW3201BE8", "###");   // password is filled in on mny version
  while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
    delay(250);
    Serial.print('.');
  }
}

Only difference is in the working one the WifiClient bit of code is commented out.   How would WifiClient cause this problem?

fun with esp8266. try new core package 2.4.2

I see you're using String in a terrible way. If this snippet is anything to go by you're probably doing the same thing elsewhere, and making swiss cheese of your heap.

The problem still occurs without the String bit -- I have edited my question to include all of my code.

yes and this is fixed in latest version of arduino esp8266 core

Are you sure?   How can I check the version?   Because I think I have the most updated version.

It is a bug and it was fixed in Arduino esp8266 core package 2.4.2 published 2 days ago.
see first line in ESP8266WiFi section of the changes list

2.4.2 ESP8266WiFi:
  Fix memory leak when reusing WiFiClient object (#4497, #4516, #4549)


text:
Safely powering a relay from same source as attiny/arduino?
My project involves using ATTINY to control a 5v relay (specifically JZC-11F and will be ground triggered) in an automotive setting.
I keep seeing the warnings of powering a relay from the same source as the ATTINY (or arduino), everything I can find says you need a completely separate source.
I'm still working on a 12~v to 5v power circuit that is safe from the issues that arise from being in an automotive setting (load dumps, noisy, reverse polarity protection..etc) but saying I have that figured out and I have a clean 5v source for power, do I have to duplicate that circuit just for the relay? or are there a ways of preventing the relay from eventually shorting out the ATTINY?
Plan B:
What if I scratch the whole 5v relay and set it up to trigger an external standard 12v automotive relay (this is probably more ideal)? Is the ATTINY capable of triggering a 12v relay via ground? if not what are the recommended ways of making this happen?
side note: I'm know code I don't know EE but I'm trying. The end goal is to combine everything onto a custom pcb, so any suggestions about the 12v-5 using an off the shelf car usb adapter or a premade board are unnecessary (seems to be the go-to answer on that subject). I have a separate post regarding that circuit so if at all possible please stick to the relay questions.

This question may be more appropriate for EE stack exchange. It will all depend on how beefy is your 5 V power source, on how much current the relay uses, and on your supply decoupling capacitors.

Why not use a solid state relay? Often they work on 5V/the output pins of a microcontroller.

@Paul: most solid state relays are for AC (triac-based) and won't work in automotive application. a MOSFET or MOSFET-based SSR designed for DC would work.

@EdgarBonet shooting for 5v 500mA, the relay I mentioned has a coil draw of 40mA and attiny is around 13mA

do I have to duplicate that circuit just for the relay?

No, not really, no.

Is the ATTINY capable of triggering a 12v relay via ground?

The ATTtiny is capable of triggering a transistor - the transistor is capable of triggering a 12V relay.
Unless your relay is incredibly high powered and the coil takes (and generates through back-EMF) massive amounts of current, there really is no problem running it alongside a small microcontroller. Just be sure you have the flyback diode, and maybe a damping capacitor as well to absorb noise.
TBH you're probably going to be getting more noise from contact spark than you are from the relay's coil.

Decided to drop the onboard relay and go with an external 12v relay w/ built in diode (301-1C-C-D1)


text:
Button Matrix Code and Wiring

Bear with me here, I'm new to arduinos, so what I'm saying might only make sense in my own mind.
I'm trying a button matrix and I not completely sure on my wiring and I have a few questions.

Is the diagram correct?
I wire D2 to D3 and set them to output and input respectively. In the code I digital write to D2 a HIGH, will D3 then read high?
What is the best way to read the state of each button? Is there a Library that can simplify it?

I'm sorry if this is all just confused gibberish.
EDIT: I got the idea from this video, which explains some of it, but no code. He however uses an arduino micro.
EDIT #2: I realized I wired the buttons incorrectly.

Is this what you are looking for: https://playground.arduino.cc/Code/Keypad

you are using 4 wires to read 4 switches .... you could just use one pin for each switch ..... enable internal pullups on the pin and connect the switch between the pin and ground

@Jot commented to use the Keypad Library. Which I got to work using the tutorial. Took a few minutes to set up.


text:
How to convert byte *payload to String
I would like to convert a byte *payload to a String, because I want to compare the content of payload to another String.
void mqttCallbackHandler(char *topic, byte *payload, unsigned int length) {
  String payloadstr = ???
  ...
}

Depending on what is setting the message on the topic, payload may, or may not be, a NULL-terminated string.  This is why they provide the length parameter.
You could consider comparing the data with memcmp() which is like strcmp() but doesn't look for a NULL termination - instead it takes a length parameter.  This is good if you may have NULL bytes in your payload.
An alternative is strncmp() which both looks for a NULL termination and also limits the length using a length parameter. Better for payloads you know are strings, but you aren't sure if they have NULL termination or not.
Here is a callback (for PubSubClient on ESP8266) I have in one of my projects which uses strncmp():
void callback(char *topic, byte *payload, unsigned int length) {
    if (!strcmp(topic, SUBTOPIC)) {
        if (!strncmp((char *)payload, "on", length)) {
            digitalWrite(POWERPIN, HIGH);
            powerState = true;
            client.publish(PUBTOPIC, "on", true);
        } else if (!strncmp((char *)payload, "off", length)) {
            digitalWrite(POWERPIN, LOW);
            powerState = false;
            client.publish(PUBTOPIC, "off", true);
        }
    }
}

Simply casting your payload to (char *) is enough for the functions to take it as a string, and the length parameter will prevent looking past the end of the payload if there is no NULL termination.
It's not perfect - a single byte payload of o will falsely match the first on, but if that is a critical problem I am sure you can find a way to work around it by checking what length equals.

strncmp is good for internal comparison, what if I want to send the data to a rest API?

This is an old post but probably somebody can use this info:
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
  String topicStr = topic;
  String recv_payload = String(( char *) payload);

  Serial.println( "mqtt_callback - message arrived - topic [" + topicStr +
                  "] payload [" + recv_payload + "]" );
}

Thanks for answering the actual question.  But how does the String constructor know where the end of the char array is ?

Consider simply using the returned pointer.
Payload is a pointer of type byte.  You can compare each byte in a string to the byte the pointer is pointing at. Then increment the pointer to the next byte and repeat the process. You don't need to allocate more memory for new string.
If a type string is necessary.  For example, if you were using a complex library method which requires a string to be passed to it, you could copy what the returned pointer is pointing at byte by byte into a locally defined string.

For comparing a byte array to a String object, you could convert the
byte array to another String object, but this involves dynamically
allocating memory for a whole copy of the string. This is memory
unfriendly, and preferably avoided on small microcontrollers.
The cheapest way to achieve what you want is to compare them as
character arrays :
if (strcmp((char *) payload, theReferenceString.c_str()) == 0) {
    // the strings are equal
}

strcmp() is a standard C function that does the byte by byte
comparison, exactly as suggested by st2000.

what if the payload string is not terminated with zero?

@Juraj: then memcmp().

Marco's answer worked for me, but worked better with:
payload[length] = 0;
String recv_payload = String(( char *) payload);

Therefore, the full code would be:
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
  String topicStr = topic;
  payload[length] = 0;
  String recv_payload = String(( char *) payload);

  Serial.println( "mqtt_callback - message arrived - topic [" + topicStr +
                  "] payload [" + recv_payload + "]" );
}


text:
Read frequency of input in digital pins
This is a somewhat theoretical question:
Let's say I have some sensor that sends digital signals to one of Arduino's digital ports.
Now, I don't know the frequency it sends those signals in.
For example, the frequency of the sensor output could be 100Hz, so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one), but it could just as well be 200Hz.
Would Arduino be able to faithfully read the digital signal regardless of its frequency? Or is there a conventional frequency that digital devices usually use for output?
Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs?
For: (1 0 1 0 0 1...) wouldn't it see: (1 1 0) - that is skip every other input because it's sampling rate would be too slow by half?
Thanks kindly for your help..

What do you mean by “digital signal”? Some kind of synchronous serial transmission protocol? SPI maybe? Or I2C? Or maybe an asynchronous one, like logic level UART? Or is it a custom protocol? Your question will start to make sense only once you specify how the data is supposed to be clocked in your protocol.

so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one), - are you asking about measuring voltages or frequencies?

@Nick, let's assume that the 1 voltage is high enough (but not too high) for Arduino to register a 1, and the 0 voltage is also within the threshold for Arduino to register a zero (say 5V for HIGH and 0.5V for LOW). It's the frequency of the signal I'm concerned with.

@Edgar, I have in mind just a generic digital sensor - let's say one that measures temperature and sends a digital signal to Arduino at some unknown frequency.

A “generic” digital sensor doesn't mean anything. Digital sensors usually come with either SPI or I2C interfaces. Sometimes asynchronous serial. All those are well defined communication protocols. There are rules stating how the sender should notify the receiver about when precisely the data line is to be sampled. The Arduino has hardware support for these protocols, but other protocols have to be implemented in software (e.g. one wire). So forget about your meaningless “generic” and tell us what serial protocol you intend to use.

100 Hz is pretty trivial. See my page about timers.
This sketch can detect frequencies up to about 5 MHz:
// Timer and Counter example
// Author: Nick Gammon
// Date: 17th January 2012

// Input: Pin D5

// these are checked for in the main program
volatile unsigned long timerCounts;
volatile boolean counterReady;

// internal to counting routine
unsigned long overflowCount;
unsigned int timerTicks;
unsigned int timerPeriod;

void startCounting (unsigned int ms)
  {
  counterReady = false;         // time not up yet
  timerPeriod = ms;             // how many 1 ms counts to do
  timerTicks = 0;               // reset interrupt counter
  overflowCount = 0;            // no overflows yet

  // reset Timer 1 and Timer 2
  TCCR1A = 0;
  TCCR1B = 0;
  TCCR2A = 0;
  TCCR2B = 0;

  // Timer 1 - counts events on pin D5
  TIMSK1 = bit (TOIE1);   // interrupt on Timer 1 overflow

  // Timer 2 - gives us our 1 ms counting interval
  // 16 MHz clock (62.5 ns per tick) - prescaled by 128
  //  counter increments every 8 µs.
  // So we count 125 of them, giving exactly 1000 µs (1 ms)
  TCCR2A = bit (WGM21) ;   // CTC mode
  OCR2A  = 124;            // count up to 125  (zero relative!!!!)

  // Timer 2 - interrupt on match (ie. every 1 ms)
  TIMSK2 = bit (OCIE2A);   // enable Timer2 Interrupt

  TCNT1 = 0;      // Both counters to zero
  TCNT2 = 0;

  // Reset prescalers
  GTCCR = bit (PSRASY);        // reset prescaler now
  // start Timer 2
  TCCR2B =  bit (CS20) | bit (CS22) ;  // prescaler of 128
  // start Timer 1
  // External clock source on T1 pin (D5). Clock on rising edge.
  TCCR1B =  bit (CS10) | bit (CS11) | bit (CS12);
  }  // end of startCounting

ISR (TIMER1_OVF_vect)
  {
  ++overflowCount;               // count number of Counter1 overflows
  }  // end of TIMER1_OVF_vect

//******************************************************************
//  Timer2 Interrupt Service is invoked by hardware Timer 2 every 1 ms = 1000 Hz
//  16Mhz / 128 / 125 = 1000 Hz

ISR (TIMER2_COMPA_vect)
  {
  // grab counter value before it changes any more
  unsigned int timer1CounterValue;
  timer1CounterValue = TCNT1;  // see datasheet, page 117 (accessing 16-bit registers)
  unsigned long overflowCopy = overflowCount;

  // see if we have reached timing period
  if (++timerTicks < timerPeriod)
    return;  // not yet

  // if just missed an overflow
  if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 256)
    overflowCopy++;

  // end of gate time, measurement ready

  TCCR1A = 0;    // stop timer 1
  TCCR1B = 0;

  TCCR2A = 0;    // stop timer 2
  TCCR2B = 0;

  TIMSK1 = 0;    // disable Timer1 Interrupt
  TIMSK2 = 0;    // disable Timer2 Interrupt

  // calculate total count
  timerCounts = (overflowCopy << 16) + timer1CounterValue;  // each overflow is 65536 more
  counterReady = true;              // set global flag for end count period
  }  // end of TIMER2_COMPA_vect

void setup ()
  {
  Serial.begin(115200);
  Serial.println("Frequency Counter");
  } // end of setup

void loop ()
  {
  // stop Timer 0 interrupts from throwing the count out
  byte oldTCCR0A = TCCR0A;
  byte oldTCCR0B = TCCR0B;
  TCCR0A = 0;    // stop timer 0
  TCCR0B = 0;

  startCounting (500);  // how many ms to count for

  while (!counterReady)
     { }  // loop until count over

  // adjust counts by counting interval to give frequency in Hz
  float frq = (timerCounts *  1000.0) / timerPeriod;

  Serial.print ("Frequency: ");
  Serial.print ((unsigned long) frq);
  Serial.println (" Hz.");

  // restart timer 0
  TCCR0A = oldTCCR0A;
  TCCR0B = oldTCCR0B;

  // let serial stuff finish
  delay(200);
  }   // end of loop

Or is there a conventional frequency that digital devices usually use for output?

No.

Wouldn't it be the case that if Arduino expects 100Hz signal, but the signal is 200Hz it would miss half the inputs? For: (1 0 1 0 0 1...)

No.
Why would it "expect" a frequency? It isn't a person expecting a chocolate cake on its birthday.

So whatever frequency the sensor sends its data in - be it 100Hz or 5Mhz - Arduino is smart enough to read all the voltage signals faithfully?

I'm not quite sure what you mean by "read all the voltage signals" which seems to imply you want to measure the voltage.

so every 1/100 of a second it varies the voltage (or keeps the old voltage if the next signal is the same as the previous one)

But then you say:

let's assume that the 1 voltage is high enough (but not too high) for Arduino to register a 1, and the 0 voltage is also within the threshold for Arduino to register a zero (say 5V for HIGH and 0.5V for LOW). It's the frequency of the signal I'm concerned with.

The voltage levels for 0 and 1 are documented in the datasheet. For the Atmega328P for most pins they are as follows:

You can see that if Vcc is 2.4V or above then LOW is -0.5V to 0.3 * Vcc, which if Vcc is 5V then a LOW is -0.5 to 1.5V.
Similarly a HIGH is 0.6V * Vcc to Vcc + 0.5, so if Vcc is 5V then a HIGH is 3V to 5.5V.
In between 1.5V and 3V then the digital status would be undefined.
So, if your LOW and HIGH are in those voltage ranges, yes you can detect the frequency of the signal.
I'm not sure about the bit where you said "keeps the old voltage if the next signal is the same as the previous one". That seems to imply that if the signals stay the same (eg. for a second) then the voltage won't change at all, and thus the frequency will be zero.

Thanks @Nick. So whatever frequency the sensor sends its data in - be it 100Hz or 5Mhz - Arduino is smart enough to read all the voltage signals faithfully? If that's the case, that's encouraging news.. One additional question pls: can you determine the frequency of the sensor from the code - i,e. determine if the sensor is 100Hz, 200Hz etc.

See amended answer.

thanks @nick for all the info. About the last paragraph: wouldn't it be the case that if there's a stream of 1s and not 0s for a whole second, then the voltage graph would look like a horizontal line of 5V (basically like DC of 5V) for that 1 sec.)?

Yes, absolutely.

Another method if it's helpful to the world:
Using inspiration from https://forum.arduino.cc/t/how-to-read-frequency-with-arduino/528143/2
I am just measuring the seconds using micros() between each up or down portion of the waveform, multiplying the time by 2 to get the full period (assuming a duty cycle of 50%). And then inverting the full period to calculate the frequency.
I was using a Teensy 4.1 for this.
// READ FREQUENCY FROM A DIGITAL INPUT PIN SKETCH

// this cannot be used when the FreqMeasure.h toolbox is used if on teensy
// https://www.pjrc.com/teensy/td_libs_FreqMeasure.html

// define your digital input pin
#define inputPin 22

// initialize variables for the frequency reading function
boolean inputState = false; boolean lastInputState = false;
long lastTime; long period; double freq;

// the frequency reading function
double readFrequency(){
  inputState = digitalRead(inputPin);

  if (inputState != lastInputState) {
    period = micros() - lastTime; // in microseconds
    freq = 1/(2*period*pow(10,-6)); // conversion to Hz

    lastInputState = inputState;
    lastTime = micros();
  }
  return freq; // always return frequency even if it hasn't changed state...
}

// label the pin
void setup() {
  // Serial.begin(115200); // uncomment & adjust for Arduino - I was using a Teensy.
  pinMode(inputPin, INPUT);
}

// call the function and print the output at full speed
void loop() {
  Serial.print("Frequency:"); Serial.println(readFrequency());
  // works even if I put a delay in here (e.g., delay(1) millisecond)
}


text:
Text send via HC-05 is broken up by first character on the receiving end?
On the receiving end, I have an mit app inventor app which acts like a client.
In arduino, I check for connection status and do a serial write to send the text. The code for that is below:
#include <SoftwareSerial.h>

#define D2 2
#define D3 3
#define BT_STATE_PIN 4

SoftwareSerial BTSerial(D3, D2);
long lastMark;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(38400);
  BTSerial.begin(9600);
  pinMode(BT_STATE_PIN, INPUT);

  int counter = 0;
  lastMark = millis();
}

bool isBTConnected() {
  return (digitalRead(BT_STATE_PIN) == HIGH);
}

void sendText(char* message) {
  Serial.println("SEND: " + String(message));
  if(isBTConnected()) {
    BTSerial.write(message);
  }
  else {
    Serial.println("did not send");
  }
}

int msgCount = 0;
void loop() {
  long now = millis();

  if(now - lastMark > 2500) {
    msgCount++;
    String msg = "This is a really really long MSG" + String(msgCount);
    sendText(msg.c_str());
    if(msgCount == 5) {
      msgCount = 0;
    }
    lastMark = millis();
  }
}

This is how the device is wired currently:

simulate this circuit – Schematic created using CircuitLab
On the app inventor side of things, I have a very simple app that connects to the bluetooth module; it listens for anything received, and then just receives the text.
aia file

Here is a pic showing the issue I am facing currently:

Sometimes the breaking up happens randomly at some other place. Hoping someone can help sort this issue.

Without having experience in AppInventor, I see the following problem:
In your app you are outputting the received data regularly with a timer in form of distinct messages. This code can naturally only display text, that was already received. You seem to think, that only because you use a single line oft code on Arduino for sending the message data, the data would be send in one big chunk. For Serial that is not the case. Actually the write() function only fills the libraries buffer and the actual data will then be send serially (thus the name). There is nothing like a chunk of data or a message on a serial interface, unless you yourself impose this principle on the data stream. All the bytes in the libraries buffer are the same and are being send in the order of the buffer. Moreover Bluetooth does consist of packages of data, but they will be automatically packed; in a way that will not correspond to your messages.
So in the end, arbitrary parts of your message will be received by the phone at arbitrary times, that highly depend on timing conditions. In your code you should constantly receive the data and only display a message, when you have received an \n character, which is the delimiter of a message. It is a very common and helpful technique to first receive a full message and then processing it, when the message is complete.

I did something similar (multiBT) using HC-05 and PC BT, with the same App.
Results: all the incoming data from the PC_BT to the phone are right, but with the HC-05 sometimes is chunked as @deostrol show. I think is a bug with the HC-05 firmware.
To correct this, I've implemented StartBegin and StopFinish character in the received string before use.


text:
Ethernet socket impedes adding shields
I just bought a KEYESTUDIO W5500 Ethernet Arduino without realizing that the Ethernet socket on the board impedes adding any additional shields to the device because:

Horizontally the socket runs right up next to the shield connector sockets
Vertically the socket is a good 1/4 inch higher that the shield connector
sockets

Is there a good solution for extending the shield connector sockets vertically so that they clear this Ethernet socket?

what shield do you want to put up? you do not have much free memory for more libraries

@Juraj The main shield I want to add is a screw terminal I/O card. But it's the mechanical clearance I am concerned about, not the memory

Reverse the order of the shields: Uno | Terminal I/O | Ethernet?

@JRobert The board has built in Ethernet - there is no Ethernet shield

Oops, missed that. Back to extra headers!  :)

Plug some of these into the Arduino headers to add extra space.
They come in different lengths and can be cut to the required number of pins.
They also come in different pin lengths.
Google long tailed pin headers.

After googling a bit I found Arduino Stackable Header Kit which is more descriptive of what I want.


text:
Software Gate on a PWM port
I'm using a PWM port and outputting a freq. Is it possible to pulse the PWM port using software to simulate a pulse gate. For example, I'd like to output a freq of 111hz, but would like to gate that freq at .5-7hz. Is this possible to do all in software without external hardware. I'm using a Teensy board which is similar to an Arduino, but has 3 independent PWM ports. Any ideas on whether this possible?

PWM is not for outputting different frequencies, but for outputting a square wave of a fixed frequency with different duty cycles. And it's not clear, what do you mean by "gate that freq at .5-7hz" What exactly you are trying to achieve?

You could use one timer for the 111Hz and another timer with interrupt. In the interrupt turn the other timer on and off. It is even possible to use the tone() for 111Hz and millis() in the loop() to create that .5 to 7Hz. Can you explain what this is for? Is it a modulated 111Hz? How accurate should it be?

Yes, I understand fully what the PWM port does and how it works and have been using it for years =) What I’m trying to achieve is how to change the shape of the freq by adding a controllable gate on the PWM port in software. I can do this by outputting the PWM freq into a collector of an 2N3904 transistor and drive the base of the transistor w/ another PWM acting has the gate freq and the emitter will have the newly shaped freq which seems to work, but would like to do it all in software using a timer on the PWM port. Is this possible?

btw, this is for a brain tuner circuit I'm building. The brain is stimulated at freqs of 111Hz and 1110HZ, but pulsing the freq slightly w/ a controllable gate will alter the shape to create different types of stimulation modes. This is what I'm trying to achieve using the freq gate on the PWM port. The accuracy should be as close as possible. Once the wave form is created, it will be put through another circuit that includes a transformer to create the final output signal. If I can do the gating in software that would be really cool =) Tnx for your help.

Jot 23, do you know of any good code examples using a timer interrupt on a PWM port to achieve what I'm looking for? Currently, I have 2 PWM ports 1 at running at 111Hz and 1 running at 1110Hz and both need a controllable gate of 5. to 7Hz applied to it. If the timer interrupt would be fast enough to work, that would be neat since I'd like to do this all in software if possible. In theory it should work. The Teensy v3.2 is a fast processor.

If you can configure the PWM to run at 111 Hz (I don't know how
this is done on the Teensy), then “gating” it is as simple as turning
the PWM on and off at the desired frequency:
uint32_t half_period;  // half the gating period in microseconds

void set_gate_frequency(float freq_in_hz)
{
    half_period = (1e6 / 2) / freq_in_hz;
}

void loop()
{
    static uint32_t last_toggle = 0;
    static bool pwm_is_on = false;
    if (micros() - last_toggle >= half_period) {
        if (pwm_is_on) {
            digitalWrite(PWM_PIN, LOW);
            pwm_is_on = false;
        } else {
            analogWrite(PWM_PIN, 128);  // PWM with 50% duty cycle
            pwm_is_on = true;
        }
        last_toggle += half_period;
    }
}

Thank you, I will try that. I assume this is possible to put into a timer interrupt routine as well, is that correct? So I can separate it from the loop function.
For reference on a Teensy this is how you would configure a PWM port to output a frequency.
analogWriteResolution(8); // 187500Hz resolution
analogWriteFrequency(pwmPin,FreqHz);
analogWrite(pwmPin,dutyCycle);

@Wildview: Yes, you could use an interrupt. However, for such low frequencies, you don't need to. Doing this in loop() should work just as well, and you can add whatever else you want to the same loop(). That is, it will work well unless you do something wrong like using delay()...

Thanks. I noticed in looking at the waveform running your example. There is no change to the frequency even w/ a gate freq of 50hz. It appears the digitalWrite is not working correctly to set the pin low. If I changed the digitalWrite to this analogWrite(PWM_PIN_PIN, 0)  it looks like it's pulsing now. I have a 1K pull up on that port a well. Does the analogWrite(PWM_PIN_PIN, 0) have the same effect as the digitalWrite would?

On the AVR core, digitalWrite() turns off any ongoing PWM. Maybe it doesn't do that on the Teensy, I don't know. analogWrite(PWM_PIN, 0) should do the same. If it works for you, keep it.


text:
How to automatically reset the nrf24l01+ with code?
I have two separate nrf24l01+ connected to two different Arduino UNOs, one as TX and the other as RX. The problem is the connection stops after a while between them.
On the Arduino COM screen I have noticed these things:
TX Side: Completely Frozen (Transmission Stops).
RX Side: Continuously receives the last data repeatedly.
The problem is solved temporarily when the TX MCU (hence the nrf) is restarted .Sometimes even after restarting the TX MCU the RX stops responding and I have to restart the RX as well. Therefore I am trying to find a way to reset my nrfs automatically using software when this situation occurs.

What is connected on pin9 and pin10 ?

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;
        }
      }
}

If you use standard arduino pin cables, then they do not provide stable connectivity for NRF24L01+. Try to solder pins instead (not kidding).
Another reason could be that one of your modules has bad power supply. Power it with perfect 3.3 volts (from another power source, not from Arduino), or use "base module" for the NRF24L01+ (connect this "base module" to 5V pin on Arduino)
http://www.yourduino.com/sunshop/index.php?l=product_detail&p=467

If the NRF24L01 truly locks up, as can happen with an inadequate power supply, then the powerDown(), init(), powerUp() method wont work as the NRF wont receive SPI commands.
In this situation, which seems to be the most common form of lockup, a physical power cycle is the only option.