text:
My Arduino IDE won't compile even simple sketches suddenly... How can I fix that??? this is the error message I get... I did work well at first!
private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/arduino-builder -dump-prefs -logger=machine -hardware /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware -hardware /Users/daniellecomte/Library/Arduino15/packages -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/daniellecomte/Library/Arduino15/packages -built-in-libraries /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/libraries -libraries /Users/daniellecomte/Documents/Arduino/libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=0X2341_0X0042 -ide-version=10805 -build-path /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660 -warnings=all -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.1.1 -prefs=runtime.tools.avrdude.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2 -verbose /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/untitled1415726107.tmp/sketch_may19a/sketch_may19a.ino
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/arduino-builder -compile -logger=machine -hardware /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware -hardware /Users/daniellecomte/Library/Arduino15/packages -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/tools-builder -tools /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/hardware/tools/avr -tools /Users/daniellecomte/Library/Arduino15/packages -built-in-libraries /private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/8AC1112E-019A-430D-A268-5BEDD561B4FC/d/Arduino.app/Contents/Java/libraries -libraries /Users/daniellecomte/Documents/Arduino/libraries -fqbn=arduino:avr:mega:cpu=atmega2560 -vid-pid=0X2341_0X0042 -ide-version=10805 -build-path /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660 -warnings=all -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/arduinoOTA/1.1.1 -prefs=runtime.tools.avrdude.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino9 -prefs=runtime.tools.avr-gcc.path=/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2 -verbose /var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/untitled1415726107.tmp/sketch_may19a/sketch_may19a.ino
Using board 'mega' from platform in folder: /Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21
Using core 'arduino' from platform in folder: /Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21
Detecting libraries used...
"/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR   "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino" "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/variants/mega" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660/sketch/sketch_may19a.ino.cpp" -o "/dev/null"
Generating function prototypes...
"/Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics  -flto -w -x c++ -E -CC -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=10805 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR   "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/cores/arduino" "-I/Users/daniellecomte/Library/Arduino15/packages/arduino/hardware/avr/1.6.21/variants/mega" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660/sketch/sketch_may19a.ino.cpp" -o "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_880660/preproc/ctags_target_for_gcc_minus_e.cpp"
fork/exec /Users/daniellecomte/Library/Arduino15/packages/arduino/tools/avr-gcc/4.9.2-atmel3.5.4-arduino2/bin/avr-g++: no such file or directory
Error compiling for board Arduino/Genuino Mega or Mega 2560.

What update did you do just before it broke?

avr-g++: no such file or directory

Try downloading the IDE again. It looks like it has lost sight of where the compiler is. Preferably not a nightly build but one of the stable versions.

This indicates something has gone wrong with your Arduino AVR Boards installation. To make sure it has been fully uninstalled you need to take some drastic action. Be aware this is somewhat advanced and will remove all boards you have installed via Boards Manager:

Click the link on the line following File > Preferences > More preferences can be edited directly in the file. This will open the /Users/daniellecomte/Library/Arduino15 folder.
Delete all files and folders under the Arduino15 folder except for preferences.txt. Please be very careful when deleting things from your computer. When in doubt, back up!
Restart the Arduino IDE

Verify that you can now compile for your board before reinstalling any packages via Boards Manager.

You were absolutely correct... it works now...  many many thanks sir!

@DanielLecomte Since you agree this answer helped, please "accept" it so that the Stack Exchange software does not keep prompting for a good answer.

recommended is to install Arduino AVR Boards newest version through this simple steps, go to Tools -> Boards -> Board Manager -> Install "Arduino AVR Boards (X.Y.Z).


text:
How to send IR data from Arduino to USB-TTL
I have a led receiver KY-022 and led emitter KY-005, I also have a PL2303 (USB-TTL). This is the code of the issuing LED:
#include <IRremote.h>
IRsend irsend;

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

void loop()
{
   for (int i = 0; i < 50; i++) {
     irsend.sendSony(0xa90, 12); // Sony TV power code
     //Serial.print(0xa90,HEX);
     delay(40);
   }
}

The following is the connection scheme:

The output of the KY-022 I have connected to the pin RXD of the PL2303 which has a led that indicates that it receives data, however when using the HyperTerminal program to see the data I receive nothing appears.
I found similar information but they use another LED model, however I think it should work the same. What can I do?
I'm also testing with node js using the node js package, but in the console I only get non-readable characters, or something like this Buffer 00 e0 e0 e0 e0 if I do not apply toString () to the data.
This is my code in node JS.
var SerialPort = require('serialport');
var io = require('socket.io').listen(3000);

var serialPort = new SerialPort("COM9", {
    baudRate: 9600,
    parser: new SerialPort.parsers.Readline("\n")
});

io.sockets.on('connection', function(socket){
    socket.on('message', function(msg){
        console.log(msg);
    });

    socket.on('disconnected', function(){
        console.log('disconnected');
    });
});

var clearData = "";
var readData = "";

serialPort.on('open',function(){
    console.log('open');
    serialPort.on('data', function(data){
        console.log(data);
        readData += data.toString();
        io.sockets.emit('message',data);
    });
});

please post the code that you are using for receiving the IR data

I have no code for the KY-022, it is directly connected to PL2303.  I only have the node code js with which I read what enters the RX pin.

You don't have much of a clue about how IR communication works, do you? IR != serial. You need something between the receiver and your computer that decodes the incoming IR signal and converts it into something more meaningful. At the moment you're pointing a TV remote control at a fish and expecting it to bark.

You are transmitting data by encoding it using one of probably many Sony Consumer Remote Control formats and expecting to decode it using one of many possible RS232 like formats.  You will likely get something between nothing and random values.
Instead, consider sending data using only the RS232 protocols.  This is what is done in this tutorial.  It is recommended you replicate the tutorial before moving on to using a TTL to USB dongle and a computer.  This should validate the transmitter is working.  Note in the tutorial transmitter code example no IR  remote control library is used.  Only the common serial libraries.
A word regarding the tutorial.  Consider using the second of the two examples in the tutorial.  The first does not modulate the IR transmitter and will not work with commonly available IR receivers.  The second does modulate the IR transmitter and discusses how to alter the modulation to accommodate different IR receivers.

source: Stack Exchange

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

sort: votes


text:
Clock generator up to 8 MHz using pin 3 arduino nano
I would like to generate square signal up to 8 MHz using internal timer of arduino, I have done successfully in pin 11, but i want to change it in pin 3, but still stuck. Here is the code
 pinMode(11,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2A0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2A = 1;

from this page here
How can i change the pin to pin 3?
Thank you

The MCU Timer Outputs are hardwired to specific pins. Arduino Nano (ATmega328p) pin 3 is the MCU pin PD3 and may be connected to Timer 2 output logic, OC2B with Output Compare Register 2B (OCR2B). Waveform Generator Mode and Timer Clock prescale are the same as above.
 pinMode(3,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2B0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2B = 1;

Cheers!

You should also set OCR2A, as it defines the TOP value of the counter in CTC mode, which is the mode being used here.

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


text:
Where do I find the enclosures for an Arduino and a bunch of sensors?
I recently started playing with Arduino in order to do several projects, including:

A system which will measure some characteristics of the indoor air and could alert me if something goes wrong (for instance if the percentage of CH4 goes beyond a threshold).
A system I can bring with me on a walk which will measure the pollution and other characteristics of the air outdoors.

While the quantity and the diversity of the sensors for such projects, as well as the ease of use is mind blowing, I'm blocked at one aspect: the casing. Both of the projects require to put the electronics within a plastic case with:

Enough space for not only Arduino, but also the sensors. Some, such as MQ2/MQ5, can be quite large.
Holes for air flow, which are large enough to let small particles, but small enough to keep insects and large dust out of the electronics.
A hole for an USB cable and possibly a hole for the LED.

Unfortunately, the popular sites selling Arduino-related stuff have practically nothing when it comes to the cases. In most cases, the choice is limited to (1) the enclosures for Arduino itself (or other boards), with no holes in them and (2) the multicolored modular systems which look like LEGO bricks.
Outside Arduino-related sites, the only idea I have is to buy somewhere an old smoke detector, throw away the electronics and put Arduino and the sensors inside. For now, most smoke detectors I've seen seem too small for the task, and have to be modified in order to accommodate the USB cable.
Am I missing something? How other people do when they need an enclosure which fits Arduino and sensors and doesn't look geeky?

https://www.shapeways.com/

@IgnacioVazquez-Abrams: I may be wrong, but I suppose that custom-made enclosures would be either expensive, or their quality would be too low (just like with 3D printers).

you can gets lots of them on thingiverse, for not just the boards, but even several permutations of popular modules and boards. if you don't have a 3D printer, you can order the parts from an online printer or find a local fab lab that will let you print for a small donation or fee. I've also taken to small cheap wooden boxes from ebay:  biodegradable, easy to work with a dremel, and under $3usd delivered.

I think your problem is that you are looking specifically for Arduino enclosures. Such a search tends to lead you to boxes for just an Arduino and nothing else - maybe with the headers poking out the top.
Instead, you should be looking more generically. There are thousands and thousands of "project enclosures" from many manufacturers (Hammond is a big name in these).
You take a generic project box of the right size and shape for what you want to create and in a material suitable for your needs, and cut / grind / drill / glue it to be what you want.
Most electronics suppliers will have an "Enclosures and Housings" section on their website. Have a browse through your favourite.
As far as air vents go, one good trick I have used is to simply drill holes (with a steady hand so you get them lined up nice and straight) and glue some fine mesh on the inside.  One good source of fine mesh is to go to your local smoking supplies reseller (tobacconist) and buy some "pipe meshes" (the flat ones, not bowl shaped ones) - also available from low-cost online resellers of any old junk (eBay, etc), which look like this:

(Also available in brass).  They typically come in different mesh sizes to suit your needs.

for many projects i use distribution box like this one:

I just came across your question, and I think this may be useful if you're still interested in project enclosures. I've designed and created stackable, modular and extensible enclosures for Arduino (fits Uno and Mega footprints), Raspberry Pi (three different versions, for A+, B+/4B and Zero (can accommodate up to 4 Zeros), and Breadboard and breadboard-friendly MCUs. All of these enclosures have 4"x2.4"x1.2"(h) space on the inside, enough for one or two shields or hats. They also come with replaceable sides/tops that can allow you to add sensors and peripherals, like a Pi Camera, High Quality Camera, Tripod mount, Ultrasonic sensors (HC-SR04), momentary push button switches, RS232 ports and more. The enclosure is made of acrylic with 6 separate flat pieces, so that means you can also hack it to easily add holes and mounts to customize it yourself.
You can find more details on https://www.protostax.com/
Hope you find it helpful! Let me know if you have any questions.
Cheers, and Happy Making!
Sridhar Rajagopal

Look into "Really Useful Boxes", found online, or at stores like Office Depot.  Lot of sizes available, pretty easy to mount cards & connectors into.
I have several projects lower down on this page where you can see how I used them.


text:
Connect NodeMCU with USB camera
I am trying to connect a USB camera to my NodeMCU v0.9.

VCC  Red             +5V
D-       White           Data
D+       Green           Data
GND  Black           Ground

I dismantled the USB cable and connected the VCC cable to 5 V and the black ground cable to GND.
Now I have a DATA + and DATA - cable from the USB, which I connected to the D5/D6 GPIOs of the NodeMCU. I can now read the digital signal of the camera.
But I am not quite sure how to process the data cable's signal. I am not familiar with the USB data + / - cable concept.
Any ideas on how I can process the video image ?

You can't. USB is complex, and the video data over it even more complex.

https://www.cnx-software.com/2016/08/08/esp8266-gets-usb-support-thanks-to-espusb-software-stack/

A) that's device mode, not host mode. B) that's low speed which means keyboard and mouse only.

no, but you can get a camera that connects by serial or SPI or i2c

You can't. It's as simple as that. To do it you require:

An MCU or MPU with a USB Host or OTG module built in.
Drivers for that module to enumerate the device
Drivers for the specific device you are connecting
Software to deal with the data provided by the device.

The ESP8266 has none of those.
Sounds to me like you want a Raspberry Pi.


text:
String to equation problem
My project is to create a decimal adder via voice recognition. Its like a calculator that only does addition. I am using hc-06 bluetooth module to convert my voice to a string. Let's say for example, I say "21+22" then the lcd would print "21 + 22 = 43". I have no problem in displaying my voice message on the lcd. My problem is that the string can't evaluate the equation. I used toInt() but it only recognizes the first integer. Is there a code to recognize the string and convert numerical values to int separated by + then evaluate it by adding the 2 intergers?

Please show us the sketch you are using.

There is no one single function for performing a calculation from a string like you are after in C.
Instead you will have to parse and split your string up into chunks and convert the two numbers into integers (maybe confirming that there is a + between them) and perform the calculation on those two individual integers.

The standard IO library (sscanf) can help you with that:
String s = "21+22";
int x;
int y;
int items = sscanf(s.c_str(), "%d+%d", &x, &y);
if (items != 2) /* error handling */
int z = x + y;

Cheers!


text:
Connecting to a WNR2000v4 Netgear Router via Serial Connection with an Arduino Uno and a sketch?
I was reading in the OpenWRT wiki that you can indeed connect to the serial TTY console of an Open WRT roouter using the serial console if you're careful aabout the voltages.  https://wiki.openwrt.org/doc/hardware/port.serial.cables#method_b_no_physical_changes_to_arduino_board
However, I don't know anything about the voltages of my particular model of OpenWRT router a Netgear WNR2000v4.  I know that it is accessible via 3 holes on the board but I know nothing of the voltages.  Does anyone know or have experince with this about what voltages / wires to use to access it via the serial console?

3.3V. It's always 3.3V.

You can also find this information about the voltage of 3.3V on the site you linked

Why do you want to attach an Arduino to the UART port in the first place? If you can flash LEDE / OpenWRT on it or just activate the Telnet port, you can also remote-control the router, without having to have a Arduino logging into it over serial.

@MaximilianGerhardt Because the flashing didn't go so well...

@MaximilianGerhardt Will this do it? https://www.hotmcu.com/cp2102-module-usb-to-33v-ttl-p-35.html

@leeand00 I'm not sure if the CP2102 in this design outputs 5V or 3.3V on the TX pin. I'd buy a FT232RL module (https://www.amazon.com/dp/B014Y1IMNM) because there is a jumper to select either 5V or 3.3V output.

The WNR2000v4 serial port is at JP1: 115200 8N1 at 3.3V. Pads are, from left to right with the ethernet ports on right: [GND] [Rx] [Tx] [Vcc]

Source: https://wiki.openwrt.org/toh/netgear/wnr2000, PCB picture: https://wiki.openwrt.org/_detail/media/netgear/wnr2000/wnr2000v1_pcb_detail_small.jpg?id=toh%3Anetgear%3Awnr2000

So it has a mofset in it?

I have some wires that seem like they would work...they have little female ends on them; how am I going to know if the wires are okay for 3.3v?

If you are not connecting to a PC serial port, you do not need the mosfet. You linked Method B in your question, so I was operating under the assumption that was the path you chose forward.
It's not the wires you have to worry about at such low voltages, it's the device on the other end. If your Arduino is one with a atmega16u2, then it will work fine to hook up per your link.

@leeand00 For communication you only need to connect (from Arduino to Router) GND -> GND, RX -> TX, TX -> RX over a voltage divider. 3.3V is high enough to register as a '1' with the Arduino's 5V logic. Don't put your Arduino's 5V TX signal into the router though, use a simple voltage divider (example https://randomnerdtutorials.com/how-to-level-shift-5v-to-3-3v/)


text:
Reading several rotary encoders
Have an upcoming project where user input will be based on spinning a large cog and I have several UNOs available
Since rotary encoders need two pins, only a Mega would be able to handle the 7-8 encoders needed. Unless theres a better method of reading them?
Is it worth using an ATTiny85 per encoder and passing all this data to a mega via 1 pin each? This way, I could extend the project beyond 7-8 later?
Or is this idea out the window, because there's a much simpler way?

An Arduino Mega has 54 input pins, which would yield a whopping 27 encoders? Also, reading rotary encoders can be done using interrupts, which is practically zero-overhead (no polling, CPU is only shortly interrupted when an action occursi i.e. CLK has a rising edge). My point is: 1. A Arduino Mega has enough pins, 2. by using an interrupt-capable I2C GPIO expander (e.g. 16-bit MCP23017) you could also do this more efficiently. Sure the question is right?

I meant UNO when writing Mega, thinking maybe a mega. A fantastic should out for the MCP23017 - I will update the question to reflect

rotary encoders need two pins ... not all  ... what kind do you have?

I have a rotary encoder and a MCP23017 here, I'll build a proof-of-concept and come back with an answer later this day.

See https://hackaday.com/2018/04/15/rotary-encoders-become-i2c-devices/ . This person used one chip per rotary encoder. The position would then be retrieved by the Arduino using I2C. So using only 2 pins you could connect up to 127 encoders. Another advantage is that the device can do the debouncing, so your main Arduino does have to deal with this.

Library and schematics are at https://github.com/maxgerhardt/rotary-encoder-over-mcp23017.
To read a rotary encoder (i.e., detect state changes of the knob), there are two possible implementations:

poll the state of the two output pins and check for changes
set up an interrupt which will be called when an output pin changes, then check for changes

Using interrupts is more efficient than always polling the pins, because an action is only executed when an actual change occurs.
Per rotary encoder you would need two pins on your microcontroller. However, we can use GPIO expanders over e.g. I2C or SPI, such as

Microchip MCP23017 (16-bit, I2C)
Texas Instruments PCF8575 (16-bit, I2C), PCF8574 (8-bit, I2C)

Using a port expander over I2C has the advantage being a bus that only uses 2 pins. This means that there can be multiple (up to 127) devices on the I2C bus, and each I2C device can then e.g. provide 16 GPIO pins.
Using an ATTiny85 per encoder and possibly joining them via an I2C bus is also possible, however more expensive and more work.
I've chosen a MCP23017 here because it is interrupt-capable, has 16-bit and I had it lying around. A PCF8574 would have also worked just fine, since it has the same capabilites.
Tests were made using an MCP23017 and a KY-040.

The written library uses a modified Adafruit MCP23017 library and the Rotary library. The Rotary library also handles debouncing by using a state-machine based approach for decoding. The library is a simple header file which defines a RotaryEncOverMCP C++ object, with which a rotary encoder connected to an MCP23017 device can be easily described and managed. It has an example for the polling method and the interrupt method.
For 1 encoder, one can write down schematic like: (interrupt based)

Since one MCP23017 has 16 ports, we can connect up to 8 rotary encoders to one such device.

However the MCP23017 also has three address pins with which its I2C address can be selected. This means we can have 2^3 = 8 such device on the same I2C bus (i.e., connected to the same SDA and SCL lines).
Thus, with one I2C bus, which uses 2 pins, we can have a maximum of 8xMCP23017 and 64 rotary encoders (assuming no interrupts are used, which would need 1 pin for any number of rotary encoders). At the cost of 2 more pins on the microcontroller, we can create another software bit-banged I2C bus, each of which adds again a maximum of 64 rotary encoders.
Assuming D2 to D13 and A0 to A5 are free, on these 18 pins we can have 9 I2C buses with a total of 72 MCP23017 devices hosting a grand total of 576 rotary encoders. Whatever one might need that for.
I've tested this library with one rotary encoder and a MCP23017, but the code is structured in a way that adding more encoders is just adding an entry in an array.

Fantastic. This is exactly the information I was looking for – I've ordered a handful of MCP23017 to get started. I really appreciate the depth you've gone to here

Started working on this today and i've got a setup that is exactly to the specs of the schematic, but nothing is reading on the  console – did you experience a similar problem when writing the answer? and if so, what part should I be checking for

@AndrewLazarus run the I2C scanner scetch first to make sure you can reach the MCP23017. If not, check that the I2C lines, power and RST are connected properly

Thank you! This was good information!


text:
C# Arduino: How to detect if the needed software is present on the computer
I have a digispark that uses trinket keyboard library to send media keys back to the computer using a rotary encoder. I currently have it configured to send normal media keys but about 2 weeks ago i started needing to change binds on what the rotary encoder does so i needed a driver of some sort. i asked and i got answers that i can't use serial ports but i can use unused keys like f13+ keys so i use the f keys now to communicate to c# software (it listens on these f keys and as soon as they are pressed depending on the configuration it does what it needs to do).
I don't think that code is needed for this demonstration but if u need it i'll be happy to edit this.
So i made the software and now comes a problem of what happens when u plug in the device that doesn't have the driver. its useless, so i need a way for the digispark to find out if there is a software that can "reprogram" what the rotary encoder does and if there isn't use the default functions(the media keys).
Questions:

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in
Is there any way to add my program made in c# to the digispark, i got a usb headset and when i first plugged it in it installed its driver, so when i plug in my digispark can it load the program

Solutions that i think may work but i have no idea how to do them:

using one of these unused keys as Boolean, when its held down lets say by the c# software can the digispark using the trinket or any other compatible Tiny85 library determine if that key is pressed down or not (this may interfere with other software so i don't think its perfect solution)
If anyone here knows any library or custom firmware that allows the digispark(Tiny85) to communicate on serial ports that'd be pretty useful and would solve the whole question.

For the second problem: do i need any other hardware to do this as i only have a Tiny85 digispark and a rotary encoder with a breakout board
If you have a solution please provide me code or links where i may learn how to do this because as of now i have no idea how to do this, i know my way around c# but i'm a noob in arduino programming. I already asked this on stack overflow a week ago but didn't get any comments or answers. I'm sorry if this counts as a duplicate i'll remove the one on stack overflow if needed. thank you for understanding

A usb device can’t check if a key is pressed. What you might be able to check is the status of the capslock key. So my proposed solution would be. On powerup have the digispark send a F17-key press. Then have the c# respond by Turing the capslock on for e.g. 1 second. The digispark will check if the capslock was on for a brief moment, and if so, will know that the C# program is active. (Note that you need a slightly different solution if digispark is already  connected before the pc is turned on)

@Gerben Can it also be done with the scrool lock as i dont find myself using it very often and the problem where your pc isnt loaded can be fixed either by adding a delay on startup like 20 secs to allow the pc and program to start up, or put it in a loop and add a boolean to stop checking everytime it loops if it finds the software

scrolllock would indeed be better.

How big is your software installation package?

And why are you so fixated on such an unsuitable MCU for complex USB work?

you use too many words to ask a question about emulating a USB keyboard using a digispark .... the rotary encoder is not really related to your question ... open another question for the rotary encoder, if you have to  .....  simplify the question text and you may get an answer from more people

@jsotola some people may need the explaining for what keys are sent and received by the program

it is irrelevant what the key presses are for .... the receiving program is also irrelevant ... the question is how to create a keyboard  .... you are losing sight of what you are actually having a problem with

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in

I can't think of any way to do that. That's like asking if a keyboard you plug into a USB port can tell if you have Photoshop installed or not.

Is there any way to add my program made in c# to the digispark ...

No. The Digispark is a tiny computer based on the Attiny85 which has 8k of program memory, some of which is dedicated to a bootloader which lets you upload new code.

Your project is far too ambitious for the level of hardware you are proposing to use. In fact this video which I watched the other day comes to mind:
https://www.youtube.com/watch?v=s7AXskSxxMk

From a comment:

the it refers to the digispark, when connected the digispark checks if the f17 key is pressed down and if it is that means my program is running in the background so use the functions that are compatible with the program

OK, so you want the host computer (not the Digispark) to pretend it is holding down F17, and then when the Digispark is plugged in it checks if F17 is down, and if so it knows that the desired program is running on the PC. Is that your idea?
The problem here is that the Digispark is a USB device (not a USB host). I suppose it would be possible to write a special device driver on the PC that, once the Digispark connects, would send some special code to say whether or not the program is running. However with the Digispark only having 8 KB of program memory, this extra code (on the Digispark) might be hard to fit in. Plus you would need to write your USB device driver. Plus the device driver would need to be able to query what programs are running.
I think a far simpler solution would be to have an On/Off button on the Digispark. If you plug it into a PC which has this special program running you press the button, then the Digispark sends the alternative commands to your C# program.

First of all i clearly stated that the digispark doesn't have serial so i use one of the unused keys, let's say f17 as a boolean. my c# program holds it down so when the digispark connects it should check if f17 is held down or not, if it's not it should default to volume control and if it is held down it should be f13 and f14 for the rotary encoder rotation(this is already done). i need a way to find if that key is pressed and act according to that. for the second thing ik the digispark doesn't have internal memory so that's why i asked what do i buy to get this functionality

@SenaCarbtc There is absolutely no way for a USB device to query what software is installed on your computer - no matter what device you buy. It's just not physically possible. Only software installed in your computer can know what software is installed in your computer.

@SenaCarbtc The only thing you could possibly do is send some custom message from the USB device that the software responds to, sending a message back. If that message never arrives you can assume the software either isn't installed or isn't running.

I didn't mention "serial" in my answer. I am now uncertain if by Digispark you mean the device you plug into your computer, or some software running on the computer (like the IDE). when the digispark connects it should check if f17 is held down or not - what is "it" in that sentence?

@NickGammon the it refers to the digispark, when connected the digispark checks if the f17 key is pressed down and if it is that means my program is running in the background so use the functions that are compatible with the program, i already got an answer to use the scroll lock key but can this be done with the f17 as no program uses it

See amended answer.


text:
Read one value from continuous data stream at a lower frequency
I am working on a university final project and have run into a problem with programming Arduino, after a 3 year hiatus. I have a pressure transducer that is sending pressure data at 10Hz. I have successfully programmed my Arduino Pro Micro to read the data as it is coming in. I'm using the SoftwareSerial library to set digital pins 8 and 9 to RX and TX, respectively. As the pressure transducer is continuously streaming data values, I read each character, store them in an array, and print them to the Serial Monitor. I'm using a start and end-marker to recognize each incoming character and put them into the array. The raw data output from the transducer is in the form:
*000114.2927
*000114.2926
*000114.2927

And this is the code I am using.
#include <SoftwareSerial.h>
#define paroRX 8
#define paroTX 9

SoftwareSerial paroSerial(paroRX, paroTX);

const byte numChars = 16;
char paroChars[numChars];     //array to store received data
char paroToSend[numChars];      //array to transmit
boolean newParoData = false;

void setup(){
  Serial.begin(9600);     //with transmitter radio
  paroSerial.begin(9600);
}

void loop(){
  paroSerial.listen();
  readParo();      //read from Paro and store values in paroChars
  if(newParoData == true){
    for(int i=0; i<16; i++){
      paroToSend[i] = paroChars[i];
    }
    Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
    newParoData = false;
  }
}

void readParo(){
  static boolean receiveInProgress = false;
  static byte index = 0;
  char startMarker = '*';
  char endMarker = '\n';
  char pd;
  while(paroSerial.available() && newParoData == false){
    pd = paroSerial.read();
    if(receiveInProgress == true){
      if(pd != endMarker){
        paroChars[index] = pd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        paroChars[index] = '\0';      //terminate string
        receiveInProgress = false;
        index = 0;
        newParoData = true;
      }
    }else if(pd == startMarker){
      receiveInProgress = true;
    }
  }
}

And this is the output that I get, which is correct. I don't really want that * in front anyways.
000114.2927
000114.2928
000114.2927
000114.2929

But all of this happens at 10Hz, which means I get a constant stream of readings on the Serial Monitor. I want to slow this down to 1Hz, or just one reading per second. The obvious solution that occurred to me was to put a delay in the loop. So I tried to implement this with delay(1000) and using the millis() function as well, but I get strange readings like:
000114.2927
***000114
**2928
***.000114
000114.2928

How can I read at 1Hz from the 10Hz data stream? I want to just store one data value from the stream per second in the form of 000114.2927, then ignore the rest while the Arduino does something else.
Thanks!

How can I read at 1Hz from the 10Hz data stream? ... discard 9 readings

You're thinking backwards. You don't want to read slower (which is what delay does), you want to only send every 10th entry.
That is, count the lines as they come in. When you hit 10 you print one and reset your count.
In other words:
static int count = 0;

if(newParoData == true){

  count ++;
  if (count == 10) {
      count = 0;

      // (Why copy the line just to send the copy...?)
      for(int i=0; i<16; i++){
        paroToSend[i] = paroChars[i];
      }
      Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
  }
  newParoData = false;
}

I would use Stream class timed functions. Serial is implementation of Stream. The property timeout (setTimeout) sets how long will the blocking functions wait for the next byte/character. Default timeuot is 1000 ms.
Timed functions of Stream are find, parseInt, parseFloat, readBytes, readBytesUntil, readString and readStringUntil. (Non blocking read functions are available, read and peek.)

Majenko’s answer is spot on: you just have to count the sentences you
read and repeat one every ten sentences. And you don't need two copies
of the sentence you are reading: one is enough. But I would add that you
don't even need a single copy: you can just echo back the characters you
read, without ever storing them, until you hit a '*':
void loop()
{
    static uint8_t sentence_count;
    if (paroSerial.available()) {
        char c = paroSerial.read();
        if (c == '*') {
            // Increment the sentence count modulo 10.
            if (++sentence_count == 10)
                sentence_count = 0;
        } else if (sentence_count == 0) {
            // This is one sentence we have to repeat.
            Serial.write(c);
        }
    }
}

As a side note, if your program doesn't read input from the computer,
and if it doesn't send anything to the transducer, then you may consider
getting rid of SoftwareSerial and using only the hardware serial port:

the receiver part of the port for reading the data from the transducer
the emitter part to send the data to the computer.

Yes, it is perfectly fine to use the receiver and the transmitter for
different links. The only caveat is that you will have to use the same
port configuration on both sides: if the transducer talks at
9600 bps, then the whole port will have to run at 9600 bps.

Thanks everyone for the helpful responses. I'm asking my question because I actually have two pressure transducers hooked up to my Arduino via the SoftwareSerial implementation, and I need to send the pressure data from one after the other. So far, I've only had luck sending data from one at a time. I read that the Arduino Pro Micro cannot receive from more than one Serial port simultaneously when SoftwareSerial is used, so I was thinking if I could strictly read one data value from the first transducer, then read another one from the second transducer. Maybe I should start a new topic?

@bf109k4: Or you can use the hardware serial receiver and only one software serial.


text:
Decreasing a functions programming size
I have Arduino Code that utilizes the I2CDev library to control an MPU-6050. I am pretty new to coding and copied and pasted most of the code from examples I have found around. I am starting to run out of programming space on my Arduino, and I have found that one line of the code takes up 21%, or 6000 bytes of the programming memory. I found the function that the line related to and I have it shown below.
The link to the I2CDev libarary can be found on Github here as well:
https://github.com/jrowberg/i2cdevlib
Is there a way to decrease it? Ot can someone explain to me why it is taking up so much space? Thanks!
uint8_t MPU6050::dmpInitialize() {
// reset device
DEBUG_PRINTLN(F("\n\nResetting MPU6050..."));
reset();
delay(30); // wait after reset

// enable sleep mode and wake cycle
/*Serial.println(F("Enabling sleep mode..."));
setSleepEnabled(true);
Serial.println(F("Enabling wake cycle..."));
setWakeCycleEnabled(true);*/

// disable sleep mode
DEBUG_PRINTLN(F("Disabling sleep mode..."));
setSleepEnabled(false);

// get MPU hardware revision
DEBUG_PRINTLN(F("Selecting user bank 16..."));
setMemoryBank(0x10, true, true);
DEBUG_PRINTLN(F("Selecting memory byte 6..."));
setMemoryStartAddress(0x06);
DEBUG_PRINTLN(F("Checking hardware revision..."));
DEBUG_PRINT(F("Revision @ user[16][6] = "));
DEBUG_PRINTLNF(readMemoryByte(), HEX);
DEBUG_PRINTLN(F("Resetting memory bank selection to 0..."));
setMemoryBank(0, false, false);

// check OTP bank valid
DEBUG_PRINTLN(F("Reading OTP bank valid flag..."));
DEBUG_PRINT(F("OTP bank is "));
DEBUG_PRINTLN(getOTPBankValid() ? F("valid!") : F("invalid!"));

// get X/Y/Z gyro offsets
DEBUG_PRINTLN(F("Reading gyro offset TC values..."));
int8_t xgOffsetTC = getXGyroOffsetTC();
int8_t ygOffsetTC = getYGyroOffsetTC();
int8_t zgOffsetTC = getZGyroOffsetTC();
DEBUG_PRINT(F("X gyro offset = "));
DEBUG_PRINTLN(xgOffsetTC);
DEBUG_PRINT(F("Y gyro offset = "));
DEBUG_PRINTLN(ygOffsetTC);
DEBUG_PRINT(F("Z gyro offset = "));
DEBUG_PRINTLN(zgOffsetTC);

// setup weird slave stuff (?)
DEBUG_PRINTLN(F("Setting slave 0 address to 0x7F..."));
setSlaveAddress(0, 0x7F);
DEBUG_PRINTLN(F("Disabling I2C Master mode..."));
setI2CMasterModeEnabled(false);
DEBUG_PRINTLN(F("Setting slave 0 address to 0x68 (self)..."));
setSlaveAddress(0, 0x68);
DEBUG_PRINTLN(F("Resetting I2C Master control..."));
resetI2CMaster();
delay(20);

// load DMP code into memory banks
DEBUG_PRINT(F("Writing DMP code to MPU memory banks ("));
DEBUG_PRINT(MPU6050_DMP_CODE_SIZE);
DEBUG_PRINTLN(F(" bytes)"));
if (writeProgMemoryBlock(dmpMemory, MPU6050_DMP_CODE_SIZE)) {
    DEBUG_PRINTLN(F("Success! DMP code written and verified."));

    // write DMP configuration
    DEBUG_PRINT(F("Writing DMP configuration to MPU memory banks ("));
    DEBUG_PRINT(MPU6050_DMP_CONFIG_SIZE);
    DEBUG_PRINTLN(F(" bytes in config def)"));
    if (writeProgDMPConfigurationSet(dmpConfig, MPU6050_DMP_CONFIG_SIZE)) {
        DEBUG_PRINTLN(F("Success! DMP configuration written and verified."));

        DEBUG_PRINTLN(F("Setting clock source to Z Gyro..."));
        setClockSource(MPU6050_CLOCK_PLL_ZGYRO);

        DEBUG_PRINTLN(F("Setting DMP and FIFO_OFLOW interrupts enabled..."));
        setIntEnabled(0x12);

        DEBUG_PRINTLN(F("Setting sample rate to 200Hz..."));
        setRate(4); // 1khz / (1 + 4) = 200 Hz

        DEBUG_PRINTLN(F("Setting external frame sync to TEMP_OUT_L[0]..."));
        setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L);

        DEBUG_PRINTLN(F("Setting DLPF bandwidth to 42Hz..."));
        setDLPFMode(MPU6050_DLPF_BW_42);

        DEBUG_PRINTLN(F("Setting gyro sensitivity to +/- 2000 deg/sec..."));
        setFullScaleGyroRange(MPU6050_GYRO_FS_2000);

        DEBUG_PRINTLN(F("Setting DMP programm start address"));
        //write start address MSB into register
        setDMPConfig1(0x03);
        //write start address LSB into register
        setDMPConfig2(0x00);

        DEBUG_PRINTLN(F("Clearing OTP Bank flag..."));
        setOTPBankValid(false);

        DEBUG_PRINTLN(F("Setting X/Y/Z gyro offset TCs to previous values..."));
        setXGyroOffsetTC(xgOffsetTC);
        setYGyroOffsetTC(ygOffsetTC);
        setZGyroOffsetTC(zgOffsetTC);

        DEBUG_PRINTLN(F("Setting X/Y/Z gyro user offsets to zero..."));
        //setXGyroOffset(0);
        //setYGyroOffset(0);
        //setZGyroOffset(0);

        DEBUG_PRINTLN(F("Writing final memory update 1/7 (function unknown)..."));
        uint8_t dmpUpdate[16], j;
        uint16_t pos = 0;
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 2/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Resetting FIFO..."));
        resetFIFO();

        DEBUG_PRINTLN(F("Reading FIFO count..."));
        uint16_t fifoCount = getFIFOCount();
        uint8_t fifoBuffer[128];

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Setting motion detection threshold to 2..."));
        setMotionDetectionThreshold(2);

        DEBUG_PRINTLN(F("Setting zero-motion detection threshold to 156..."));
        setZeroMotionDetectionThreshold(156);

        DEBUG_PRINTLN(F("Setting motion detection duration to 80..."));
        setMotionDetectionDuration(80);

        DEBUG_PRINTLN(F("Setting zero-motion detection duration to 0..."));
        setZeroMotionDetectionDuration(0);

        DEBUG_PRINTLN(F("Resetting FIFO..."));
        resetFIFO();

        DEBUG_PRINTLN(F("Enabling FIFO..."));
        setFIFOEnabled(true);

        DEBUG_PRINTLN(F("Enabling DMP..."));
        setDMPEnabled(true);

        DEBUG_PRINTLN(F("Resetting DMP..."));
        resetDMP();

        DEBUG_PRINTLN(F("Writing final memory update 3/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 4/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Writing final memory update 5/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
        while ((fifoCount = getFIFOCount()) < 3);

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);
        DEBUG_PRINTLN(F("Reading FIFO data..."));
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Reading interrupt status..."));

        DEBUG_PRINT(F("Current interrupt status="));
        DEBUG_PRINTLNF(getIntStatus(), HEX);

        DEBUG_PRINTLN(F("Reading final memory update 6/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        readMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("Waiting for FIFO count > 2..."));
        while ((fifoCount = getFIFOCount()) < 3);

        DEBUG_PRINT(F("Current FIFO count="));
        DEBUG_PRINTLN(fifoCount);

        DEBUG_PRINTLN(F("Reading FIFO data..."));
        getFIFOBytes(fifoBuffer, fifoCount);

        DEBUG_PRINTLN(F("Reading interrupt status..."));

        DEBUG_PRINT(F("Current interrupt status="));
        DEBUG_PRINTLNF(getIntStatus(), HEX);

        DEBUG_PRINTLN(F("Writing final memory update 7/7 (function unknown)..."));
        for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++) dmpUpdate[j] = pgm_read_byte(&dmpUpdates[pos]);
        writeMemoryBlock(dmpUpdate + 3, dmpUpdate[2], dmpUpdate[0], dmpUpdate[1]);

        DEBUG_PRINTLN(F("DMP is good to go! Finally."));

        DEBUG_PRINTLN(F("Disabling DMP (you turn it on later)..."));
        setDMPEnabled(false);

        DEBUG_PRINTLN(F("Setting up internal 42-byte (default) DMP packet buffer..."));
        dmpPacketSize = 42;
        /*if ((dmpPacketBuffer = (uint8_t *)malloc(42)) == 0) {
            return 3; // TODO: proper error code for no memory
        }*/

        DEBUG_PRINTLN(F("Resetting FIFO and clearing INT status one last time..."));
        resetFIFO();
        getIntStatus();
    } else {
        DEBUG_PRINTLN(F("ERROR! DMP configuration verification failed."));
        return 2; // configuration block loading failed
    }
} else {
    DEBUG_PRINTLN(F("ERROR! DMP code verification failed."));
    return 1; // main binary block loading failed
}
return 0; // success

}

Which line? Put a marker on it and refer to it in your question.

A lot of PLINTLN lines aren’t very useful. Most of them are just comments. Removing them or converting them to regular comments would reduce the size.

There is no magic recipe for reducing the code size. The only general rule is: “remove everything that is not strictly needed”, but you cannot make use of that rule unless you really understand what the program is doing. You can start nevertheless by looking at which functions take up the most space. C.f. Determining which section of code uses the most flash.

i know that you are new to coding ... i am just wondering why it did not occur to you to remove the DEBUG_PRINTLN( commands

@jsotola, that was the first thing I tried but it didn't change the size of the code at all.

It doesn't matter if you use 90% of your program memory, provided your code does all you want it to. Are you in fact likely to run out of program memory?

One line of code doesn't use 6000 bytes of memory. However if it calls a function, which otherwise would not be called, then the compiler has to include the function.
So, for example, if you have a function that takes 6000 bytes, but don't call it, then the compiler can omit the function itself.

Assuming DEBUG_PRINTLN does something, then I count 2480 bytes of string literals there. Therefore your function would at the very least take up 2480 bytes. And that is called 71 times, so if DEBUG_PRINTLN takes (say) 10 bytes to call each time, that is another 710 bytes. We are already up to 3190 bytes. Other stuff (unrelated to debugging) also probably takes quite a few bytes.

I am starting to run out of programming space on my Arduino

That's not a problem until you actually run out of space. Who cares if you use 99% of available memory?

The fact that something causes a jump in memory usage is not, in itself, cause for worry. For example this sketch:
void setup() {
  Serial.begin(115200);
  int a;
  Serial.println (a);
}

void loop() {  }

Compiled for a Uno using IDE 1.6.9 I get:
Sketch uses 2,122 bytes (6%) of program storage space. Maximum is 32,256 bytes.

So, 2,122 bytes. Now change a to be float:
void setup() {
  Serial.begin(115200);
  float a;
  Serial.println (a);
}

void loop() {  }

Now it uses 3,668 bytes:
Sketch uses 3,668 bytes (11%) of program storage space. Maximum is 32,256 bytes. That's another 1,546 bytes just by changing one variable's type.

However it doesn't take another 1,546 bytes if you add a second such variable.
void setup() {
  Serial.begin(115200);
  float a;
  float b;
  Serial.println (a);
  Serial.println (b);
}

void loop() {  }

That only uses another 18 bytes:
Sketch uses 3,686 bytes (11%) of program storage space. Maximum is 32,256 bytes.

In other words, the floating-point library has now been included by the compiler. This is a once-off jump in usage. Of course, if I now do something with I2C there will be another jump as that additional library is loaded.

Yeah sorry for the misconfusion. The single line was in the arduino code. I then opened up the function that that line was referring to and pasted it above. My question is what in this function is taking up so much space?

What in what function? Can you please be more explicit?

What does DEBUG_PRINTLN do? Try to post enough information to enable us to answer your question.

See my amended answer.

You could save a lot of memory by replacing those rather wordy debugging message with something like DEBUG_PRINTLN(F("1")) (and then 2 and so on) and have a spreadsheet that tells you which one each one means. You are working on a microcontroller, not a PC with 20 gigabytes of RAM.

So I tried removing the DEBUG_PRINT lines and it did not change the size of the code at all. Do DEBUG_PRINT have to be enabled somewhere else in the code to work?

It would help to show the code/macro for DEBUG_PRINT so then that could be answered. Quite possibly it is a macro that does nothing unless something (like DEBUG) is defined.

See amended answer about library code only needed to be included once.


text:
Arduino Uno with ESP8266 Wifi transceiver or ESP8266 NodeMCU board?
I already have an Arduino Uno, and I want to learn Internet-of-Things. I'm planning to use an ESP8266 since it's cheap. Should I purchase an ESP8266 Wifi transceiver module to use with my Arduino Uno or just buy an ESP8266 NodeMCU board?
Is there any advantage using an ESP8266 NodeMCU board to using my Arduino Uno with an ESP8266 Serial transceiver module?

don't be "one of those guys", program the ESP8266; it's a million times faster with a billion times more ram and flash (an exaggeration, but true in spirit)

The Uno has its place, but its not an ideal platform for a connected device.  The ESP is bigger, but can connect less hardware, but if you need more hardware connections you can always slave an UNO to the ESP :)

In my opinion, it is more desirable to program the ESP8266 directly. I'm always shivering when I see a Uno (ab)using the ESP8266 as a WiFi bridge when the ESP8266 already has everything needed for the project. Of course, this is highly project specific.
Advantages of programming an ESP8266 directly:

you learn about a new MCU and architecture (XTensa vs AVR)
you learn to use a new Arduino Core (Arduino-ESP8266)
ESP8266 is way more powerful than the Arduino Uno

80MHz (overclockable to 160MHz) vs 16 MHz
~40kB free RAM at startup vs 2 kB
4 MB Flash vs 32kB
can use an RTOS like FreeRTOS
Flash can be used as filesystem (e.g. for a HTTP(S) server)
==> we can build way more complex projects

WiFi radio and stack directly on the processor, no need to get information via a serial bridge

higher speed, more direct control over sockets etc.

you can try out other frameworks and languages, such as

Micropython
esp-open-rtos
the NodeMCU firwmare (Lua language)
Espressif's NON-RTOS / RTOS SDKs

easier to move to its big brother, the ESP32 (Dual-Core XTensa LX6 @ 240MHz, WiFi + BT, 4MB Flash, 520kB RAM (+4MB PSRAM optional), tons of peripherals and accelerators) for even more complex projects

Disadvantages:

only 1 ADC input (vs. 6) with a voltage range of 0 to 1.0V (unlike the normal 5V range on the Uno)

remedy: external ADCs via I2C / SPI (e.g. MCP3008)

3.3V device, must be careful when connecting to existing 5V devices or shields

remedy: logic level shifters, voltage regulators

less number of available digital GPIO pins (9 vs 13)

remedy: external GPIO expanders via I2C/SPI (e.g. PCF8574, MCP23017)

In summary, I think a good way of acquiring a better skillset is to try to explore and program a new board directly vs programming the old board and slapping the new one on top over serial. I hope this gave a rough overview of why an ESP8266 might be better (or worse) for a certain project.

Really good answer +1 isn't enough.


text:
Question about memory allocation analysis
As I'm experiencing weird bugs in a rather lengthy project, I started analyzing my RAM usage on my ATMEGA328P with Arduino bootloader. At least I tried to and wrote the following piece of code. Consider the following written in Arduino IDE 1.8.5:
extern int __heap_start, *__brkval;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(500);
  f1();
  delay(500);
  freeRAM();
}

void f1() {
  int local = 0;
  local = 6;
  freeRAM();

}

void freeRAM() {
  int local = 0;
  local = 5;
  if (*__brkval == 0) {
    Serial.println("The break point is 0,...");
    Serial.println((int)&local - __heap_start);
  }
  else {
    Serial.println("The break point is not 0,...");
    Serial.println((int)&local - *__brkval);
  }
}

And the rather unexpected output:
The break point is not 0,...
2048
The break point is 0,...
2294
The break point is 0,...
2294
The break point is 0,...
2294
The break point is 0,...
2294
The break point is 0,...
2294
The break point is 0,...
2294
The break point is 0,...
2294

I was expecting 2 different values of free RAM because on the second call of freeFram(); the function call and local variables of f1() should already be popped from the stack. Perhaps i misused the external variables (__heap_start, __brkval) or I misinterpreted one of the links I read:
memories-of-an-arduino
Lecture 08: Memory Allocation and Program Memory Layout
Perhaps someone could elaborate on this.
EDIT:
@Gerben: Thx for the hint, didn't change anything though!
@Edgar:
Looking at a snippet of the objdump:
 76e:   0e 94 8e 01     call    0x31c   ; 0x31c <delay.constprop.3>
 772:   1a 82           std     Y+2, r1 ; 0x02
 774:   19 82           std     Y+1, r1 ; 0x01
 776:   1a 83           std     Y+2, r17        ; 0x02
 778:   09 83           std     Y+1, r16        ; 0x01
 77a:   0e 94 5a 02     call    0x4b4   ; 0x4b4 <_Z7freeRAMv>
 77e:   0e 94 8e 01     call    0x31c   ; 0x31c <delay.constprop.3>
 782:   0e 94 5a 02     call    0x4b4   ; 0x4b4 <_Z7freeRAMv>
 786:   0e 94 5f 01     call    0x2be   ; 0x2be <_Z14serialEventRunv>
 78a:   f1 cf           rjmp    .-30            ; 0x76e <main+0xfe>

I realized the compiler was indeed inlining the call to f1(). Changing f1() to:
__attribute__((noinline)) void f1() {
  volatile int local = 0;
  local = 6;
  freeRAM();

}

and results in the following objdump:
 784:   0e 94 8e 01     call    0x31c   ; 0x31c <delay.constprop.3>
 788:   0e 94 94 02     call    0x528   ; 0x528 <_Z2f1v>
 78c:   0e 94 8e 01     call    0x31c   ; 0x31c <delay.constprop.3>
 790:   0e 94 5a 02     call    0x4b4   ; 0x4b4 <_Z7freeRAMv>
 794:   0e 94 5f 01     call    0x2be   ; 0x2be <_Z14serialEventRunv>
 798:   f5 cf           rjmp    .-22            ; 0x784 <main+0xf0>

which therefore results in the desired behaviour:
The break point is 0,...
2294
The break point is 0,...
2288
The break point is 0,...
2294
The break point is 0,...
2288
The break point is 0,...
2294
The break point is 0,...
2288
The break point is 0,...
2294

Thanks a lot!
A question that's on my mind now: Looking at the values of freeRam, shouldn't the value be smaller than 2048? Am I calculating wrong?
EDIT #2: In the meantime it turned out that my "memory"-problem was actually some self induced pointer stupidity :/
But for the sake of completeness, and if someone is on the search for a method for memory analysis like I was, here are my 2 cents.
@Gerben: I'm sry, I realised that I have to declare the function noinline as well as declare some volatile variable in it to stop the compiler from inlining the call. So Edgar and you were both right at the beginning!!
@Edgar you were completly right again, with you and some reading from here:
Official freeRam() command #5289
I came up with the following code:
extern int __heap_start, *__brkval;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

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

}

__attribute__((noinline)) void f1() {
  //String s = "foobar";
  volatile char arr[7] = "foobar";
  reportFreeRAM();

}

void reportFreeRAM () {
  int v;
  Serial.println("-------RAM Report---------");
  Serial.print("__brkval = ");
  Serial.println((int)__brkval);
  Serial.print("FreeRAM: ");
  Serial.println((int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval));
}

which results in the following output:
-------RAM Report---------
__brkval = 0
FreeRAM: 1792
-------RAM Report---------
__brkval = 0
FreeRAM: 1781
-------RAM Report---------
__brkval = 0
FreeRAM: 1792
-------RAM Report---------
__brkval = 0
FreeRAM: 1781
-------RAM Report---------
__brkval = 0
FreeRAM: 1792

and if f1() is changed to:
__attribute__((noinline)) void f1() {
  String s = "foobar";
  //volatile char arr[7] = "foobar";
  reportFreeRAM();
}

we see the following result:
-------RAM Report---------
__brkval = 0
FreeRAM: 1786
-------RAM Report---------
__brkval = 519
FreeRAM: 1773
-------RAM Report---------
__brkval = 510
FreeRAM: 1786
-------RAM Report---------
__brkval = 519
FreeRAM: 1773
-------RAM Report---------
__brkval = 510
FreeRAM: 1786

which is rather interesting, because you see the break-point-pointer getting initialised with the first allocation for the String variable and after that the value jumping back and forth. Which is to my understanding the expected behaviour. For my application I wanted to check if I had allocated any memory dynamically, so I guess an easy check would be to check (int)__brkval for zero. Perhaps someone could elaborate if that is always a good idea or not.
So sry for the lengthy post, I just wanted to show what I found, in case someone stumbles over the same kind of question.
Thx @Gerben and @Edgar!

You simply forgot that the compiler optimizes your code. Looking at the generated assembly should be enlightening.

Try declaring the local variable as volatile

Yes, the amount of free memory can only be less than 2 KiB on the 328P. I think the problem is that you should use __brkval instead of *__brkval and &__heap_start instead of __heap_start.

__brkval may not return to zero once you do any allocation. If you want to know the size of the heap, try: (__brkval ? (int) __brkval - (int) &__heap_start : 0).


text:
making a digital dice
i'm trying to make a digital dice to play catan with, here's what i have so far
#include <LiquidCrystal.h>
#include <DFR_LCD_Keypad.h>

// this is factory config shield initialisation
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// initialise the keypad
DFR_LCD_Keypad keypad(A0, &lcd);
int lcd_key     = 0;
int abc_key_in;
int read_LCD_buttons;
int  diceOne;
int  diceTwo;
#define btnSELECT 4
int read_LCD_buttons()
{
  abc_key_in = analogRead(0);
if (abc_key_in < 790) return btnSELECT;}
const int button = 4;
const int BUTTON4LOW = 400;
const int BUTTON4HIGH = 650;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i
}

void loop() {
  int reading =  analogRead (A0);

  lcd_key = read_LCD_buttons();

 if (reading<BUTTON4LOW && reading<BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

  if (diceOne + diceTwo == 7) {
    lcd.clear();
    lcd.setCursor(7, 0);
    lcd.print("7");
    lcd.setCursor(3, 1);
    lcd.print("The pirate");

      if (diceOne + diceTwo == 3,2,1,5,4,6) {
          lcd.clear();
          lcd.setCursor(7, 0);
          lcd.print("fish");
      }
      }
  }
}
}

and im running into a error code saying
Arduino: 1.8.5 (Windows Store 1.8.10.0) (Windows 10), Board: "Arduino/Genuino Uno"

demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons'
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'int read_LCD_buttons()':
demo_simple:15: error: 'int read_LCD_buttons()' redeclared as different kind of symbol
 int read_LCD_buttons()
                      ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino:11:5: note: previous declaration 'int read_LCD_buttons
 int read_LCD_buttons;
     ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void setup()':
demo_simple:28: error: 'i' was not declared in this scope
   i
   ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: In function 'void loop()':
demo_simple:34: error: 'read_LCD_buttons' cannot be used as a function
   lcd_key = read_LCD_buttons();
                              ^
C:\Users\taran\Desktop\arduino\demo_simple\demo_simple.ino: At global scope:
demo_simple:58: error: expected declaration before '}' token
 }
 ^
exit status 1
'int read_LCD_buttons()' redeclared as different kind of symbol

name your children, like int x read_LCD_buttons(). also, that will play the same game each time, you need to randomize, preferably with micros() after each user input.

You have
int read_LCD_buttons;

int read_LCD_buttons()
{
//..
}

You can't have a variable int read_LCD_buttons at the same time as a function called read_LCD_buttons -- this identifier is already taken. It looks however like you're not assigning or reading anything from this variable, so it probably never should have existed in the first place -- deletion is the solution.
In the case that you wanted to write a function prototype (which you by the way don't have to write in the Arduino IDE because it autogenerates them), the correct form would have been
int read_LCD_buttons();

i.e., the exact same prototype ended by a ;.
In setup() you have a random i which doesn't belong there.
void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 0);
  lcd.print("Press to dice");
  pinMode (A0, INPUT);
  i //delete this line
}

Finally, you have a mismatch of opening and closing curly braces. Always format your code correctly, so that these errors are more easily spotted! You have one final } too much.
void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");

      if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
        lcd.clear();
        lcd.setCursor(7, 0);
        lcd.print("fish");
      }
    }
  }
}
} //This } is too much!

Then you'll also see that the third if statment which checks for a sum is actually within another expression where it was asserted that the sum is already 7. Then the inner if can never become true. You probably meant to move the if to the outer part, i.e. write
void loop() {
  int reading = analogRead(A0);

  lcd_key = read_LCD_buttons();

  if (reading < BUTTON4LOW && reading < BUTTON4HIGH) {
    diceOne = random(1, 7);
    diceTwo = random(1, 7);

    if (diceOne + diceTwo == 7) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("7");
      lcd.setCursor(3, 1);
      lcd.print("The pirate");
    }
    //the line below is still wrong
    if (diceOne + diceTwo == 3, 2, 1, 5, 4, 6) {
      lcd.clear();
      lcd.setCursor(7, 0);
      lcd.print("fish");
    }
  }
}

Next, this expression makes no sense.
if (diceOne + diceTwo == 3,2,1,5,4,6)

I think you meant that "if the sum of diceOne and diceTwo are equal to either 3, 2, 1, 5, 4, or 6 (i.e. within 1 and 6 inclusive), then do something.
Using multiple or statments this would be expressed as
if ((diceOne + diceTwo == 3) || (diceOne + diceTwo == 2) || (diceOne + diceTwo == 1) || (diceOne + diceTwo == 5) ||(diceOne + diceTwo == 4) || (diceOne + diceTwo == 6))

Or using the simpler interval check, assuming both numbers are positive and greater than 1.
if( diceOne + diceTwo <= 6)

Also this expression is suspect
if (reading<BUTTON4LOW && reading<BUTTON4HIGH)

When you have a LOW and a HIGH boundary and you want to check if reading is between these, you would write it as "if reading is greater than the lower boundary and less than the higher boundary", i.e.,
if (reading > BUTTON4LOW && reading < BUTTON4HIGH)

I fixed my errors but I want to be able to press the select button on the LCD keypad shield to generate random numbers, how would I do that (coding)

and I want to press the select button once for the two dice and again for the 1 die

@user46194 This is not a free coding service. Work it out yourself, and, if you have a particular problem on why something you wrote doesn't work, you can ask another question.


text:
Connect two D1 R2 (8266) via SPI with Github SPISlave Library
Problem:
SPI Connection between two D1 (ESP8266) boards does not work properly, only master to slave transfers data correctly.
What I did:
I connected two Wemos D1 R2 via SPI and installed the library from https://github.com/esp8266/Arduino. I connected MISO, MOSI, SCK, SS and ground 1:1. On one D1 I run SPISlaveTest on the other SPIMaster from the examples. The D1 are located directly beside each other, cables are only 15 cm long.
Effect:
While the slave receives strings from the master fine the master seems to get crippeled answers from the slave, they appear as ??? and other characters. If I connect the slaves SS to +3.3V it reacts like expected: The slave receives no more, the master gets no reponses.
What I already tried:

Updated the Libraries to the latest versions
Changed delay to wait for answer
tried SafeMaster.ino
Changed D1 hardware on both sides

Everything unfortunately did not help.
Any tip is very appreciated.
Thanks!

try swapping the master and slave devices

install esp8266 arduino core in IDE board manager and the spislave library is part of that package. you do not need GitHub for that

did you connect ground between D1 R2s?

I connected ground and also opened this connection as they are both connected to the same computer via usb no difference. And yes, I installed the library through the board manager. Also I swapped devices because I have several D1.

If the corruption is unidirectional is there an issue with your MISO line?

I swapped and exchanged hardware, also the wires.


text:
Response from ESP8266 is returning unknown characters
I'm working on a project with Arduino UNO that needs connection with a cloud server, that is why I'm using ESP8266 module.
I'm already connecting to wi-fi and making GET and POST request but my problem is get the response from these requests.
Here is my code:
/* Doing all these steps to make the request
AT+RST
AT+CWMODE=1
AT+CWJAP="MyNetwork","MyPassword"
AT+CIPMUX=1
AT+CIPSTART=0,"TCP","myserver.com.br",80
AT+CIPSEND=0,270
*/

String data = "data=example";

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
comando += "User-Agent: Arduino/1.0\r\n";
comando += "Connection: Close\r\n";
comando += "Content-Type: application/x-www-form-urlencoded;\r\n";
comando += "Content-Length: " + String(data.length()) + "\r\n\r\n";
comando += data;

esp8266.println(command);

delay(2000);

String response;

while(esp8266.available()) {
  response += esp8266.readStringUntil('\r');
}

Serial.print("Request response: ");
Serial.println(response);

When I run this code the only response I can get is something like:
Recv 270 bxt⸮⸮C⸮
SEND OK

+IPD,0.569:HTTP/1.0 200 OK

But I was expecting a JSON.
Can someone tell me what I am doing wrong and how can I resolve it?

Edit.
Ok, after Code Gorilla helps me (Thank you so much) and a lot of research what I did was program Arduino UNO to send some commands that I invented to serial and program ESP8266 to read the serial and, depending of the command that it reads, do requests and stuff.
ESP8266 is a lot easyer to make requests and have a lot of others possibilities, like HTTPS requests, that you can't do using AT Commands.
When I create this ask I didn't know that I could program directly in ESP8266, but when Code Gorilla told me about it and helps me with some articles I could finally continue with my project.

try using the GET method instead of POST

This variable named "data" is the content of the POST

Try posting all your code, not a meaningless snippet.

you expect that after reading a line, the first character of the next line is immediately available

Why are you using an Uno?  Why not just program the ESP8266 directly (using the Arduino IDE and language), much quicker and you don't need to send everything via serial.

@CodeGorilla How can I exactly can do it? You have any article to indicate to me?

See my answer below

String command = "POST /webservice/v1/dispositivo/atualizar_data_requisicao HTTP/1.1\r\n";
comando += "Host: " + SERVER + "\r\n";
...
esp8266.println(command);

I suspect this is just a typo because it shouldn't compile.  But you are adding all the HTTP headers to commando not command.
Usually the ? means that the character is unprintable.  So to help diagnose the issue display the integer value for each character that is returned.  Something LIKE this (I've never used a String before so length() might not be right)
Serial.print("Request response: ");
Serial.println(response);
for (int index = 0; index < response.length(); ++index)
{
   Serial.print (response[index]);
   Serial.print (" ");
}

If you want to program the ESP directly then have a look at these guides, they should give you the general idea.  Its usually as easy as programming an UNO once you are setup.
http://www.whatimade.today/esp8266-easiest-way-to-program-so-far/
https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide
https://www.hackster.io/harshmangukiya/how-to-program-esp8266-with-arduino-uno-efb05f

I'm sorry, I think that I need to make a new question because I am not expressing my question very well. But your answer seems to be correct, the example shouldn't compile. Thank you!

Don't make a new question, edit the one above.  Use diagrams because then the language doesn't matter so much.

Thank you so much! I could not continue without your help. I edited the question with what I did to resolve it.


text:
Breaking out of a while loop using IR remote for neopixel
I've been piecing together various lighting effects. I am wanting to have each lighting effect loop until another button is pressed to trigger another lighting effect.
I've come to a bit of standstill at the moment. I've created a loop that doesn't seem to end. I've had a look around but I can't work out how to fix my code. Sorry in advanced, I'm new to using arduinos but if anyone could help out, it would be much appreciated.
Thanks!

//www.elegoo.com
//2016.12.9

#include "IRremote.h"
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#define PIN 6

Adafruit_NeoPixel strip = Adafruit_NeoPixel(20, PIN, NEO_GRB + NEO_KHZ800);

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

/*-----( Declare objects )-----*/
IRrecv irrecv(receiver);     // create instance of 'irrecv'
decode_results results;      // create instance of 'decode_results'
int Remote = 0;

/*-----( Function )-----*/
void translateIR() // takes action based on IR code received

// describing Remote IR codes

{

  switch(results.value)

  {
  case 0xFFA25D: Serial.println("POWER");
  ArrowRight(strip.Color(25, 0, 0), 100); //Red
  ArrowRight(strip.Color(0, 0, 25), 100); //Blue
//  Remote = 0xFFA25D;
  break;

  case 0xFFE21D: Serial.println("FUNC/STOP");
  ArrowLeft(strip.Color(25, 0, 0), 100); // Red
  ArrowLeft(strip.Color(0, 0, 25), 100); // Blue
//  Remote = 0xFFE21D;
  break;

  case 0xFF629D: Serial.println("VOL+"); break;
  case 0xFF22DD: Serial.println("FAST BACK");    break;
  case 0xFF02FD: Serial.println("PAUSE");    break;
  case 0xFFC23D: Serial.println("FAST FORWARD");   break;
  case 0xFFE01F: Serial.println("DOWN");    break;
  case 0xFFA857: Serial.println("VOL-");    break;
  case 0xFF906F: Serial.println("UP");    break;
  case 0xFF9867: Serial.println("EQ");    break;
  case 0xFFB04F: Serial.println("ST/REPT");    break;
  case 0xFF6897: Serial.println("0");    break;
  case 0xFF30CF: Serial.println("1");    break;
  case 0xFF18E7: Serial.println("2");    break;
  case 0xFF7A85: Serial.println("3");    break;
  case 0xFF10EF: Serial.println("4");    break;
  case 0xFF38C7: Serial.println("5");    break;
  case 0xFF5AA5: Serial.println("6");    break;
  case 0xFF42BD: Serial.println("7");    break;
  case 0xFF4AB5: Serial.println("8");    break;
  case 0xFF52AD: Serial.println("9");    break;
  case 0xFFFFFFFF: Serial.println(" REPEAT");break;

  default:
    Serial.println(" other button   ");

  }// End Case

  delay(0); // Do not get immediate repeat

} //END translateIR
void setup()   /*----( SETUP: RUNS ONCE )----*/
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  strip.begin();
  strip.show();
  Remote = 0;

}/*--(end setup )---*/

void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}/* --(end main loop )-- */

void ArrowRight(uint32_t c, uint8_t wait) {
  while (Remote = 0xFFA25D) {
    for (uint16_t i = strip.numPixels()/2; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
    }
    for (uint16_t i = 0; i < strip.numPixels(); i++) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(wait);
  }
}

void ArrowLeft(uint32_t c, uint8_t wait) {
  while (Remote = 0xFFE21D) { // The j<# determines how many cycles
    for (uint16_t i = strip.numPixels()/2-1; i + 1 > 0 ; i--) {
      strip.setPixelColor(i, c);
      strip.show();
      delay(wait);
    }
    for (uint16_t i = strip.numPixels(); i + 1 > 0 ; i--) {
      strip.setPixelColor(i, 0);
    }
    strip.show();
    delay(wait);
  }
}

what loop runs constantly?

Both of them seem to do it at the moment. I think its because I've got Remote to equal the value that corresponds to the button press on my remote. I think the issue is that I've not been able to implement an "override" as you may say, to switch over to a different loop. Cheers.

both of which ones?   Are you referring to the the while loops in the Arrow functions? And they run forever when you press the corresponding button and release it?

I think you don't need the while loops -- you should take them out & turn them into one-shots and take the translateIR() out of the conditional in loop().  Inside the conditional, if you do get a new message, copy it to from a temp variable into &result instead of updating &result each loop()

while (Remote = 0xFFE21D) You have to use == here, or this will be an assignment

There are a few causes for eternal loops and other things that will go wrong in your code.
As ChrisL noted above you are assigning a value to Remote in the while condition which is almost certainly not what you wanted to do.  On the plus side, every C/C++ programmer ever has also made that same mistake at some time or another.
Now if you change it to while (Remote == 0xcFFE21D) it still won't work, because Remote is always 0.  You have commented out the lines that set Remote, but they are after the call to the function.  To be honest since you know the value before you call the function (because of the switch statement) you don't need to check the value within the function so you could remove the while loop all together.  If you intention is to call this function repeatedly until a different button is pressed on the remote, the way you are doing it won't work.  you need to store the last button pressed value and then pass that into the switch statement.  When a different button is pressed update the 'last button pressed' value.
You for loop conditions need looking at.  I don't think that the number of lights in the strip is going to change while the program is running.  If that's true then your are wasting processor instructions by doing strip.numPixels()/2-1 you might want to look at setting global values in setup.
Also the for loops might benefit from using i >= 0 because then you don't need to do i+1 every loop.

Hi Gorilla, thank you and everyone else for your help.
I'm fairly new to C/C++, as is quite evident. Like you have suggested, I am wanting to call a certain function, repeatedly, until another button is pressed, to switch to another function.
I'm going to have a go at it now but if anyone could help me amend the code that would be very helpful, thanks!

You'll learn more if you do it yourself.:)  You have said what you need to do in the above comment, "... call a certain function, repeatedly, until another button is pressed..." So ensure that the function you call does its think once and then returns.  The code that calls the function is the one that is checking to see if the "until ..." has occurred, because it was that code that decided to call the function in the first place.  You are 90% of the way there.

You might want to tinker with C/C++ programming concepts in an IDE that has a symbolic debugger, including tracing and breakpoints. Debugging Arduino programs is a pain in the butt since you don't have any of those tools. You have to add serial port print statements and do a fair amount of guesswork.

Once you work out your basic logic using normal non-Arduino C/C++, you can re-implement your code on Ardino.


text:
How to check for valid Serial data, then break?
I'm having trouble completing this code for my university final project. I feel like I'm almost there, but I can't seem to find the final buttons to press. I'm using the Arduino Pro Micro.
I have one static pressure transducer connected to the hardware serial pins, RX1 and TX0. I have one differential pressure transducer connected to digital pins 10 (Rx) and 16 (TX), on which I have implemented SoftwareSerial. I'm reading the output data from each of these transducers. Which means technically I don't need to connect the TX pins, because I'm not writing anything to them. They are already programmed to give a continuous serial data stream.
With lots of great help from StackExchange and the Arduino Forums, I'm able to write code to check for a start-marker and end-marker from the two serial ports. I'm storing each character in an array for each of the transducers.
Here is the code I'm using for the static pressure transducer:
const byte numChars = 16;
char paroChars[numChars];     //array to store received data
boolean newParoData = false;

void setup(){
  Serial.begin(9600);     //with computer
  Serial1.begin(9600);     //with Paro transducer
}

void loop(){
  readParo();      //read from Paro and store values in paroChars
  if(newParoData == true){
    Serial.println(paroChars);      //print Paro data with a new line for each value
    newParoData = false;
  }
}

void readParo(){      //reads each character from Paro and stores it in array
  static boolean receiveInProgress = false;
  static byte index = 0;
  char startMarker = '*';
  char endMarker = '\n';
  char pd;
  while(Serial1.available() && newParoData == false){
    pd = Serial1.read();
    if(receiveInProgress == true){
      if(pd != endMarker){
        paroChars[index] = pd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        paroChars[index] = '\0';      //terminate string
        receiveInProgress = false;
        index = 0;
        newParoData = true;
      }
    }else if(pd == startMarker){
      receiveInProgress = true;
    }
  }
}

I do get the correct output on the Serial Monitor from the static pressure transducer when I upload this program to the Arduino:
000114.2927
000114.2928
000114.2927
000114.2929

Similar code goes for the differential pressure transducer:
#include <SoftwareSerial.h>
#define honeywell_RX 10
#define honeywell_TX 16

SoftwareSerial honeySerial(honeywell_RX, honeywell_TX);

const byte numChars = 16;
char honeyChars[numChars];     //array to store received data
boolean newHoneyData = false;

void setup(){
  Serial.begin(9600);     //with computer
  honeySerial.begin(9600);      //with Honeywell transducer
}

void loop(){
  readHoney();      //read from Honeywell and store values in honeyChars
  if(newHoneyData == true){
    Serial.println(honeyChars);    //print Honeywell data with a new line for each value
    newHoneyData = false;
  }
}

void readHoney(){     //read each character from Honeywell and store it in array
  static boolean honeyReceiveInProgress = false;
  static byte index = 0;
  char honeyStartMarker = '?';
  char honeyEndMarker = '?';
  char hd;
  while(honeySerial.available() && newHoneyData == false){
    hd = honeySerial.read();
    if(honeyReceiveInProgress == true){
      if(hd != honeyEndMarker){
        honeyChars[index] = hd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        honeyChars[index] = '\0';      //terminate string
        honeyReceiveInProgress = false;
        index = 0;
        newHoneyData = true;
      }
    }else if(hd == honeyStartMarker){
      honeyReceiveInProgress = true;
    }
  }
}

And this is the output I get on the Serial Monitor for the differential pressure transducer, which is also correct:
01CP=0.0000
01CP=0.0001
01CP=-0.0001
01CP=0.0000

My problem is combining these two programs. Basically, I want to be able to read from the Hardware Serial port first, make sure that the data is valid, store it, then exit the function. After that, read from the SoftwareSerial port, make sure the data is valid, store it, and exit the function. After this I would print both arrays to the Serial Monitor. I don't know how to read from the Serial ports only until the array is filled up with valid characters, then exit. If I combine these two programs, the output is distorted, meaning the values are either bunched together, or there are random characters showing.
I found that these two pressure transducers operate at different frequencies. The static transducer gives serial output at 10Hz, while the differential transducer is about 2Hz. I'm not sure if that factors into the problem.
Basically, I want to get one reading like 000114.2927, then another like 01CP=0.0001, then print both of these to the Serial Monitor. I can't figure out how and where to break out of reading from the serial ports.
Thanks!

read from the Hardware Serial,validate, store, exit function .... read from the Software Serial, validate, store, exit function .... this may cause data loss ...... in loop() check for new data from both devices ... store data and raise flag if data is available ... process data if available

What exactly is the problem? You didn't include the combined code, so we cannot help you with this. Go the way, that is described in the answers of your other questions. Read every value from the serials, but only send every 5th value for one of it. The other can be send everytime a complete value was received


text:
Two SD card interfaces on one ESP8266?
I know it's possible to hook up multiple SPI devices, but how can one access the second drive from a sketch?
Looking at the SDWebServer.ino example, my doubt is with the SD.begin(SS); part. If I call begin() again with the other CS pin, it seems that I would lose a reference to my first volume, or maybe it won't work at all. I would instantiate another SD instance, but the sketch never seems to instantiate that object, it first appears in setup() with SD.begin(SS);
If I copy the lib (sd.h+sd.cpp) and replace all literal instances of SD with SD2, can I then include and use SD2 just like the original (provided the different .begin(pin))? Is there a less hacky way of using two SD cards in ESP8266 Arduino?
In case anyone's wondering, it's for a crypto project where one card will contain one-time-pads of plaintext length and the other contains the XOR'd ciphertext, both are fed by wifi upload, and the max file size must be bigger than SPIFFS, so I really need two SD cards...

Can't you just create another instance of  SDClass SD2 in the sketch?

and of course choose a different pin for slave select signal

Not possible without changing the library code. Because the current library code is written intended for only one SD card, ie not intended for multiple SD cards because it will be complicated to do so. The SPI library also uses FatFS library, which is a bottleneck in this scenario.
Worth a try.
sdfatlib is library written for Arduino. I have never used it, but you can give a try on ESP.
Let us know if it works.

You should (I have not tested it) be able to do it if the library is well coded and doesn't use global variables and you do something like this:
// Don't know what the class name is so replace TYPE with what it should be.
TYPE SDCardOne;
TYPE SDCardTwo;

SDCardOne.begin(CS1);
SDCardTwo.begin(CS2);
....

Thanks for the edit Juraj, it makes a lot more sense now :)

Unfortunately, standard SD.h library is designed as a singleton, so the sketch code does not instantiate card interfaces, as @Devidas pointed out in another answer


text:
360 degree motion of servo with position control
Is there any way I can control the position of servo by changing the value of potentiometer for using it for 360 deg motion?

Rotary encoders are not that expensive, and not really hard to code into a sketch.  Why don't you try that instead of a potentiometer?

A pot doesn't spin all the way around, so you could map hi/lo values, but you can't run more than one lap with it.  You could add a button that silences the pot input, so that you can hold the button and dial back the pot, releasing the button to continue turning the servo with the pot. In that case, you use relative values between samples to turn the servo instead of simply feeding it the ADC value.
A rotary encoder is probably a better fit though, since it can spin 360 just like the servo. You would still want to "gear down" the encoder if you're micro-stepping, so that say, 4 turns of the encoder yields 1 turn of the servo. This allows full 360 and as much arbitrary precision as your project needs.


text:
Wemos D1 doesnt drive Relay
I recently bought a Wemos D1 board and tried to connect a relay and test its connection.
I got an example server from here and executed. I connected D5 to a Relay's data and 5v and GND from Wemos board.
But this does not change the state of relay, it always remains high. I connected a LED for D5, it works perfectly with client's response.
Then I powered relay using an external 5v and ground connection, but the same result.
I have checked for possible solution, but coulnt find an answer.
The relay I am using is this one

Normally it is because people work under the misconception that D5 in the code is D5 on the board, but using the LED means you are using the right port in the code and hardware, so have you looked at it the board can supply enough current to trigger the relay (it only outputs <20mA).

Sounds like the pin cannot provide enough current to drive the relais. Try to use a transistor or MOSFET for it

@chrisl can you provide me an example? I am not good with electronic stuffs. Thanks for the comment.

You may need a BJT transistor to amplify the current. Look at https://electronics.stackexchange.com/questions/220492/safely-pull-5v-to-gnd-on-3-3v-gpio. Do you use a bare-bones relay or a relay board? Which one exactly?

you have a relay module? add a link to it

@chrisl if the relay has separate power and signal pins, I would think that it is a relay module with supporting circuit

Please give a link to the exact relay you are using.

Many of the cheap 5v relay modules i've gotten don't work because the D1 runs on 3.3v, so it's high is not enough to trigger the relay. fwiw, every dual-relay module i've gotten works on 3.3v boards, but there's not reason on paper why that should be the case, it just happens to be true; maybe they use better driving electronics in the dual modules...

the relay you linked has no digital pin. how did you wire it?

The board which you are using is operating on 3v3. Even if you try to run the relay using the D5 or any other pin on the board, you may not be able to run it successfully at all times. In this case, you can go for either MOSFETs or Pull-up resistors so that you can hold the voltage to 5V for triggering the relay. I would personally suggest to go for a PNP type.
As requested by Sachith, here is the circuit suggested for the problem stated. Just note that the voltage source should be +5 V (which is +1 V in the schematic). Also, the MOSFET is not the specific one, it is just for the schematic purpose.

simulate this circuit – Schematic created using CircuitLab

I would expect that a 5 V TTL senses 3.3 V as HIGH. I think he has some other problem.

@Juraj: your expectations are too high for fleabay modules; i have several single-relay boards that work perfect at 5v, but spotty or not at all on 3.3v...

@dandavis, with 5 V power supply  and 3.3 V signal?

@Juraj: yes, with 5v in from usb, 3.3v i/o on ESP, many are sporadic at best

but patching the module's on-board TTL circuit with external MOSFET?  is it a good answer? if I would want to care about electronics details, the I would take a plain relay

@Juraj I understand that it feels awkward to have a TTL with external MOSFET, but the best solution could be possible only when we would be clear with the actual scenario. So, Sachith please let us know which relay you are actually trying in your case. If possible, share a link of the same.

@SumitPanse I have updated the relay I am using.

Okay @Sachith. I saw that update just now. I would need a little time to check and revert back on it.

@Sachith, how did you wire it?

@Juraj https://www.amazon.ca/Indicator-Light-Channel-Module-Arduino/dp/B00P7QDJD2

@SumitPanse Can you give an example of the circuit I need to implement? I do not have a good electronic knowledge.

so, this is a module. it needs 5 V VCC and not specified signal level, where 3.3 V doesn't work. buy one which accepts 3.3 V as HIGH

@Sachith I have updated and modified my answer with the circuit you have requested. Please check it let me know whether it is clear to you or not.

@SumitPanse thanks for the updated answer.  So I should use P1 = D5 and 5v supply to J310 MOSFET.

@Sachith I have taken J310 just for reference. But yes, other connections can be done as per the schematic.


text:
Issue in long ON OFF timer using millis()
I have 3 components: a relay and two LEDs...I want two timers using Arduino... In timer one, relay should be off on; one LED is off; and other is on...In second timer, relay is off; one led is on; other is off...
This is my Code:
//const unsigned long onTime = (2 *3600000); // 2 Hours in miliseconds;
const unsigned long onTime = (3 *1000); // 3 seconds;
//const unsigned long onTime = (5 *60000); // 15 minutes;

//const unsigned long offTime = (0.5 *3600000); // 1/2 Hours in miliseconds;
const unsigned long offTime = (2 *1000); // 1 seconds;
//const unsigned long offTime = (5 *60000); // 5 minutes;

const unsigned long start_delay = (5 *60000);  // 5 minute in miliseconds

// Tracks the last time event fired
unsigned long previousMillis=0;

// Interval is how long we wait
int interval = onTime;

// Used to track if relay should be on or off
boolean relayState = true;

void setup()
{
  pinMode(13, OUTPUT); //Relay
  pinMode(3, OUTPUT); //LED Green for ON
  pinMode(4, OUTPUT); //LED Red for OFF

  digitalWrite(13, LOW);   // Relay Off
  digitalWrite(3, LOW);    // Green LED off
  digitalWrite(4, LOW);    // Red LED OFF

  //delay (start_delay);  // wait for 5 minute
}
void loop()
{
  if (relayState == true)
  {
    // Relay ON
    digitalWrite(13, HIGH);   // Relay ON
    digitalWrite(3, HIGH);    // Green LED ON
    digitalWrite(4, LOW);    // Red LED OFF
  }
  if (relayState == false)
  {
    // Relay OFF
    digitalWrite(13, LOW);   // Relay Off
    digitalWrite(3, LOW);    // Green LED Off
    digitalWrite(4, HIGH);    // Red LED On
  }

  // Grab snapshot of current time, this keeps all timing
  long currentMillis = millis();

  // Compare to previous capture to see if enough time has passed
  if ((unsigned long)(currentMillis - previousMillis) >= interval)
  {
    // Change wait interval, based on current relay state
    if (relayState)
    {
      // Relay is currently on, set time to stay off
      interval = offTime;
    }
    else
    {
      // Relay is currently off, set time to stay on
      interval = onTime;
    }
    // Toggle the relay's state
    relayState = !(relayState);
    // Save the current time to compare "later"
    previousMillis = currentMillis;
  }
}

Now issue is; when I make timer for seconds like OnTime is 3 second and offTime is 1 second... It works perfect... But timer for hours or minutes does not simply works... it does not switch state from on to off... It constantly remains on... What could be  the problem... Thanks!

You declare interval as an integer, while onTime and offTime are unsigned long.
Change int interval = onTime; to unsigned long interval = onTime;
The maximum value of int is only 32767 (215-1), which is only 33 seconds.
An unsigned long can be as high as 4294967296 (232-1). Which is around 49.7 days worth of milliseconds.

He has also an overflow in (5 *60000), which should be 5 * 60000UL

@EdgarBonet you’re right! Nicely spotted.

Just to point out: On PCs and Macs it is very likely that an int is 32 if not 64 bits. You have been surprised by the fact that it is only 16 bits on this platform.

You should not depend on millis() function for long time delays, use an extra rtc chip(DS3231/DS1307) instead.
Theoretically millis() function should produce 1 millisecond time frame, but it is not exactly that. There will always be a difference; and if you multiply that small time difference with a big number, then there will be a significant delay.

No clock is perfect. millis() long term accuracy is typically around 0.1%. An RTC should be significantly better. Whether or not millis() is suitable for the application has little to do with the length of the delays: it only depends on the required accuracy.