text:
Why would anyone use Arduino in 2017?
Sorry for clickbait question but it really bugs me why Arduino is still a thing in the age of ARM based boards like Pine64, Raspberry Pi, Bannana Pi, Whatever Pi etc.
I'm more or less aware of Arduino capabilities as I used to program PLC controllers but I don't really see any rational reason to use Arduino platform over ARM devboards (unless we need mission-critical level reliability however I believe commercial realtime OSes for ARM boards also exist). Even PLC and in general industrial controllers seem to shift towards platforms driven by actual RT OSes underneath running on powerfull hardware.
Getting 30$ quad core 1.2 ghz ARM board with 512M RAM, ethernet, GPIO, I2C, SPI, USB, SD card and actual Linux OS which can do virtually everything whatsoever over 25$ Arduino Uno board with abacus level performance, similar or inferior i/o, capable of only pretty basic stuff sounds to me like no brainer. Arduino sounds to me like extremely cost ineffective solution for almost anything. And I can't seem to find any rational explanation to why people still use such thing now? Maybe as Linux engineer I'm a bit biased towards Unix based solutions because I feel "safe" in this ecosystem but still I think my points are kind of objective no matter if availability of unix itself on platform is considered serious advantage or not.

When's the last time you did hard realtime in Linux? Or even on ARM?

Not necessarily Linux. There are OSes like QNX for example or other commercial RT systems. However RT Linux is also kind of taking off, though I'm aware it's far from RT OS. Not that you really need RT OS at this level of tasks... As long as you're not building medical equipment or industrial controllers using Arduino boards...

You might not need 512M RAM and 1.2 GHz quad ARM core to blink a LED :). 2K RAM and 16 MHz single AVR core might be sufficient. And the learning curve not as high. In any case, what type of GPIO performance (highest pin toggle frequency) can you get using Linux (from user space)? Bare metal has its charm (and fun).

Go to trends.google.com and show the graph for "arduino" worldwide from 2004. It is going up. However, the Arduino organization can not sit still, even if sometimes a bad choice is made. The WeMos is not an official Arduino board, but it should be.

@MikaelPatel I didn't check max PWM freq on ARM boards but I guess after setting FIFO scheduling policy to process so that preemption doesn't occur automatically you can have quite strict control over i/o timings even without strictly RT OS. Also at least how I justify power reserve is that you don't really need to run just one project on such board. With greater reserve you can run multiple projects in parallel on single piece of hardware.

See When Raspberry Pi is preferred over Arduino and Why connect arduino with Rasberry pi?.

@EdgarBonet yeah I've seen plenty of topics like those but I don't really agree with them as ARM board using RT OS (like FreeRTOS for example) is pretty RT and boards other than Rpi (eg. banana Pi, Rpi isn't actually that much i/o oriented ARM board) have plenty of i/o options, quite comparable with Ardu. That's why I created this question to gain more details and boarder cases where it really does make sense to use Ardu over ARM board.

Possible duplicate of When Raspberry Pi is preferred over Arduino

One way to approach answering your question is to look at some specific implementations. Take, for instance. 1-Wire and study how the respective implementations on rpi and arduino are done (and how easy they are to use, understand, etc). Another example is MQTT or some other high level TCP/IP protocol.

This is the ATtiny.

It costs < $1 and is completely capable of most tasks that a hobbyist requires of a chip. Truthfully, it’s more than capable of many tasks a pro requires as well. It’s perfect for adding just a little bit of smarts to a project. Not every project needs an ARM chip, dual cores, or a Linux distro running. In fact, in low power situations, that’s likely the last thing I want. How long does your smart phone battery last? A day? I’ve heard of people powering ATtiny based projects on 3 AAs for over a year!
The Arduino is an excellent little dev board for these micros. For the cost of a few cups of coffee I can have one for my work bench. Heck, I’ve used them at work as dev boards for prototyping. It’s cheap enough to put one on the desk of every dev on a project. We can verify our code works on the target architecture very early in the dev process. That was unheard of just a decade ago.

One year on 3 AAs? I have an ATtiny running since June 2012 on 2 AAs. As much as I love my Raspberry, I'm sure it can't do that.

It's just uC. ARM SoCs are also super cheap but that's not the point. It's not board with meaningful i/o, just single component. You need either custom PCB for that or some of the shelf one as it doesn't even have any form of power delivery (though I can't seem to find off the shelf i/o boards for ATTiny). It's not ready to use platform. I got flushed by Arduino Uno price. Didn't consider it's mostly price of programmer, debugger and whole starter kit rather than uC itself. However like I said I can't seem to find universal i/o boards for ATTiny with something like GPIO

@Lapsio: See the Trinket.

The 328P & 32u4 (most commonly used chips for Arduino) are similar enough to the Tiny to use them as dev boards. Atmel has really done a fantastic job of keeping their libraries portable between their devices.

@RubberDuck My concern about common Arduino dev boards was that they're expensive. Too expensive considering capabilities compared to ARM boards. But with i/o boards like mentioned Trinket it's fair price. 7$ is significantly less than 30$ and this is something I can understand.

You’ve got to be trolling. An arm eval board runs $250 and that’s on the less expensive side.

@Lapsio: If you think the Trinket is a fair price, how about $1.45USD for a Pro Mini (same performance specs as the Uno) at aliexpress.

How about this? http://www.orangepi.org/orangepizero/index.html and the cheapest variant is $6.99 :)

Here is another one $8.99 and comes with Ubuntu preloaded; http://www.friendlyarm.com/index.php?route=product/product&path=69&product_id=132

@RubberDuck it was pretty bad example of really beefy ARM board. 3gb DDR4 RAM is more than most phones have to offer. I didn't even know such overkill ARM boards are widely available. Average price of mainstream ARM boards is somewhere around 30-50$ for ~1Ghz few cores, ~1GM ram and some mainstream i/o. Those 8$ ARM boards are rather ultra compact ones without ethernet and quite poor i/o options in general so I don't think comparing them to more complete Arduino boards is fair either.

An arduino board is really a breakout for a micro processor. Microprocessors you can get separately. A rPi is really a full system without that modularity.
There are also other size factors for that breakout board, many of which are much smaller than a rasberry pi and will have a much better battery life. And very often the abacus-level perf and half a dozen GPIO pins is all you really need.
Also some people enjoy having direct control over the chip in a way that a semi-stripped linux OS on a poorly documented platform just doesn't give. Hard realtime when you don't have full control over the system means you need to trust the RT-OS writers to actually hold to their documented deadlines.

On the other hand from engineering standpoint it doesn't really seem to be wise to trust your own code more than industrial solutions at least as long as you didn't break everything into ASM code and compared against timings of individual instructions for certain uC. It's general rule of thumb to use as much of the shelf stuff as possible while designing RT systems to avoid necessity to prove time limits.


text:
Does a Sparkfun Redboard Arduino Uno have built-in RTC?
I have a Sparkfun Redboard (an Arduino Uno like board based on the Atmega328P and programmed with the Arduino bootloader).
I have been trying to make an accurate clock without an RTC with an LCD screen and it's been hard.
Does the Sparkfun Redboard have built-in RTC?

Sparkfun Redboard is NOT Arduino Uno

the schematic is right on the sparkfun.com website ... have you looked at it?

@jsotola yes I have p.s. it works like an Arduino uno

Sparkfun Redboard and Arduino Uno do not have built-in RTC.

The new "Sparkfun Redboard Turbo" does have an RTC on pins A5 and AREF

source: Stack Exchange

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

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

sort: votes


text:
Create PWM pulses by comparing the cosine wave with AnalogRead potenciometer
I need generate 4 pulses, for the digital outputs, for example 8,9 and 10,11, at this moment I am using an Arduino Mega.
The pulses have these characteristics:
1) 8 and 9 are the same pulses, but I need them to be each going through a digital output. In the same way, 10 and 11 are another equal pair of pulses but different from 8 and 9. Therefore, they are altogether two pulses, only that each one will duplicate it and send it independently in a digital output.
Here is the bulk of the matter with which I need your experiences:
2) The pulses that I need to generate are with the cut of an analog input of a potentiometer that is produced with a trigonometric wave that I generate with a sweep in degrees with the help of a for cycle.
That is to say that the signals Vc and Vd (trigonometric signals) I must compare them with a control signal (Potentiometer) called Vx. That is, for each signal Vc and Vd, it would have a pair of pulses associated each in this way, in 8,9 and 10,11.
I think that this comparison of the signals with respect to the signal status of the potentiometer can be done with an IF arrangement, so I ask for your help because I have already tried it and it has not worked correctly.
3) Something important is that I only need to generate a rising edge that is with the first cut with the cosine wave, the second one that would be the lowering flank is not important, I do not know how I could limit this.

float V1,V2;
float Vc,Vd,Vcc;
float Vx;

void setup() {

    Serial.begin(9600);
    pinMode(A0,INPUT);
}

void loop() {

    Vx = 2.0 * analogRead(A0)/1023.0;      // analog input from potentiometer, range 0 to 2.0

    for (float j = 0; j <= 360; j++) {
        V1 = 1.0 * cos(j * (PI / 180.0));  // cosine wave

        Vd = 1.0 + V1;                     // Signals Vd and Vc
        Vc = 1.0 - V1;

        Serial.print(Vx);
        Serial.print(" ");
        Serial.print(Vd);Serial.print(" "); Serial.println(Vc);
    }
}

Thanks

your question is simple, but the description that you used is too complicated.  i think that all you want is to generate two pulses. each pulse starts when the rising edge of a waveform crosses a preset point. each of the pulses is output through two pins (4 pins are used in total)  .... it is difficult to write the program when the description in your head is complicated. once you make it simple in your head, then it becomes easier to write the program.

one thing that i do not understand:   this is the kind of program that you would use to produce a pulse from an external waveform. ... what is the point of calculating the sine wave internally? ... just calculate time delay to set the outputs to their values .... you will get better PW control when you use the potentiometer value to set a delay value

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


text:
AT Commands HM10 BLE Module - Not working
I got the ble module to work fine following online guide. However when i changed the baud rate: AT+BAUD1 which changed to 19200 however ever since i was not able to get at commands to work.
tried: arduino nano, FTDI programmer, software serial, normal tx, rx
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(8,9); //RX|TX

void setup(){
  Serial.begin(9600);
  BTSerial.begin(9600); // default baud rate
  while(!Serial); //if it is an Arduino Micro
  Serial.println("AT commands: ");
}

void loop(){
  //read from the HM-10 and print in the Serial
  if(BTSerial.available())
    Serial.write(BTSerial.read());

  //read from the Serial and print to the HM-10
  if(Serial.available())
    BTSerial.write(Serial.read());
}

If you set it to 19200, why are you using 9600?

You changed the baud rate that the Bluetooth module uses to communicate with your Arduino but you forgot to change the baud rate that the Arduino uses to communicate with the Bluetooth module. These must match. From consulting the SoftwareSerial library's reference page, you can see that is set by this line of your code:
BTSerial.begin(9600)

That sets the software serial communication rate at 9600 baud. You need to change it to this:
BTSerial.begin(19200)


text:
16x2 LCD showing blocks under text
I have a LCD connected to a Arduino Mega 2560 using the instructions in LiquidCrystal library. It is not the first time I am using a 16x2 LCD but I never have encountered a problem like this. When I first connect the Arduino Mega to PC I see a row of blocks in first row of LCD which looks like normal to me. Then after that there is a block of white under each character.
Now I have searched a little and saw whole blocks which was due to bad soldering or bad wiring or etc. I have checked soldering and wiring twice. used 3 different LCD's and 2 different Mega's and it is still the same.
Any suggestions?
These are the images from when I turn it on:

[SOLVED] Update :
Looks like the POT was broken and did not respond the way it used to. So i replaced V0 with a 2.5k resistor and connected them to GND.
Here is the updated image :

can you please post an update later with adjusted contrast which looks fine?

@user1306322 updated with image

My LCD display shows gibberish character. How do I troubleshoot?

The row of white blocks is what you get before the screen's initialized. It's normal.
The shadow behind the characters is because you have the contrast turned up too high. Adjust it down a little.

If your contrast is not adjustable by a pot, there's a resistor that goes on the contrast pin that controls the level of contrast, which is what is causing the dark blocks.

Some LCD modules also have software contrast adjustment. Read the datasheet


text:
Programmer only uploading with its own power source
Can anyone explain to me why the following occurs (See image below)?
When I connect the pins according to situation 1, everything works fine and I am able to upload my project. However when I connect the pins according to situation 2 it gives me the following error:

wrong direction/command: 0x00 0x08, expected 0x01 0x08 esp8266

Both supply the same constant 3.3V and after the project is uploaded it runs with the pins connected as in both scenarios.
(All the other factors are constant in both scenarios. Think of pulling down IO0 etc.)

This will not work for the same reason you can not measure the voltage of a battery by only connecting the measurement device to the positive battery terminal. You always need a ground reference.
Perhaps you were thinking all grounds, no matter where they come from, are the same. This is only true if all your power supplies are grounded. But this is usually not the case. In fact it can be dangerous and can lead to other problems such a ground loops.
So, connect your grounds together and try your circuit again.

You must always connect the grounds. Without the grounds connected, even when using a separate power supply, there can be no circuit. With no circuit, no electrons can flow.
I cover it in detail in this blog post.

Very nice blog post, made me understand it quite good!

There's no problem with supplying a separate power supply to the ESP8266 but you always need to connect the grounds between the "programmer" and the ESP8266.

Can you also explain why? (Why is the ground of the separate supply not good enough for the esp8266)


text:
Accesing the USART registers by Arduino
I'm having a hard time understanding how the Arduino libraries are defining the address for accessing the registers of the USART modules.
I cant find definition for udr(pointer) as used in the delegated constructor for Hardware Serial. So how does the class gets the underlying address? And what type of declaration is this?
HardwareSerial::HardwareSerial(
  volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
  volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
  volatile uint8_t *ucsrc, volatile uint8_t *udr) :
    _ubrrh(ubrrh), _ubrrl(ubrrl),
    _ucsra(ucsra), _ucsrb(ucsrb), _ucsrc(ucsrc),
    _udr(udr),
    _rx_buffer_head(0), _rx_buffer_tail(0),
    _tx_buffer_head(0), _tx_buffer_tail(0)
{
}

It is handed the addresses when the object is constrcted:
 HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);

&UDR is passed as *udr. That is then assigned to _udr in the initialiser list.


text:
Problem communicating between arduino UNO R3 and Mega 2560 via MAX485
I want to send data between Arduino Uno and Mega via MAX485.
When I set the data Enable pin to HIGH on Mega (to transmit data) and set the same pin on UNO to LOW (to receive data) I can read data from Mega into Uno properly. However, when I want to do it vice versa (send data from uno to mega) can't get any data from Uno into Mega. Tried different pins on both boards but still no answer.
This problem happens when I want to change data Enable pins to low or high inside loop(), I mean when I use for example Uno as permanent master and mega as permanent slave, it works properly but when I try to change them from slave to master on runtime, data cannot be sent from uno to mega!
PS: Im newbie on RS485 and MAX485. Here is my code in MEGA side:
#include <SoftwareSerial.h>'
SoftwareSerial mySerial(2, 3);
String inputS = "";
boolean stringComplete = false;
int i = 0;
bool b= false;

void setup() {
  mySerial.begin(9600);//Using SoftwareSerial Port
  Serial.begin(9600);
  pinMode(8, OUTPUT);//DE/RE Controling pin of RS-485
  digitalWrite(8, HIGH);//DE/RE=HIGH Transmit Enabled M1
}

void loop() {
  mySerial.println("MEGA:Hi");
  Serial.println("Hi Sent");
  digitalWrite(8, LOW);
  CheckAndReceive();
  if(stringComplete)
  {
  stringComplete = false;
  inputS.trim();
  Serial.print(inputS);
  Serial.println(": " + String(i++));
  inputS = "";
  }
  digitalWrite(8, HIGH);
    delay(1000);
}

void CheckAndReceive()
{
  while (mySerial.available()) {
    // get the new byte:
    char inChar = (char)mySerial.read();
    // add it to the inputString:
    inputS += inChar;
    // if the incoming character is a newline, set a flag
    // so the main loop can do something about it:
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
}

This code is supposed to send a string to UNO and listen to it.
UPDATE:
UNO cannot send data to MEGA at all. I think there is a problem with my UNO

Are you waiting for the data to actually send before switching...?

I set the dataenable pin on uno to high and on mega to low and then try to send data. Doesnt that mean switching ?

And what do you do next after sending? Please show your code.

Im far away from my pc, but will show that as soon as i sit behind my pc. After i send data from uno i check serial1.available() on mega. But it never runs

You have forgotten to add mySerial.flush().
mySerial.flush() waits for the transmission of outgoing serial data to complete.
Add it right after you have sent the data and want to change the DE pin status.

Care to elaborate on that? What is the purpose of flush()? What is the effect that it is working around and why does that effect exist?  Teach a man to fish...

When i added this line to my code, it worked properly! Strange!


text:
How to identify RGBW LED pins?
I have a RGBW LED but I don't know how to identify the negative and the colors pins.
I tried different combinations with an Arduino Uno but it never produce light.
I never used it so I am not sure if its name name RGBW LED.

That's not the kind of LED that even wakes up for less than 50mA, which the Arduino can't even reach.

try a battery directly across the pins (with a current limiting resistor of course)

Brand Name: LEDGUHON
Model Number:JH-4RGBW14G

The pin with a + is the anode of one colour. The three next to it are also anodes.
Each anode is connected to one LED. The cathode of that LED is connected to the pin directly opposite the anode.


text:
Serial monitor in Arduino IDE for RobotDyn ESP8266-Pro via CP2102
I bought a couple of "ESP8266-Pro" micro-controllers from a Chinese company named RobotDyn.  There's no real documentation with them, but I've bought a lot of other stuff from them in the past that worked out really well, so I took a chance.
After some work, I am finally able to program the board with the Arduino IDE 1.8.1.
The problem is that I am unable to get the serial monitor working to see what's going on with the code.
What do I need to do to get this to work, or is it simply not possible?  In order to program the board, I need to connect EN to VIN, and both IO0 and IO15 to GND.  I assume I have to disconnect that to actually run the board after programming, but I don't know and haven't gotten anything to work yet.
Here's a photo of the board hooked up for programming.  What do I need to do to restart it with the serial monitor working?

scroll down https://robotdyn.com/catalog/boards/wifi_module_esp8266_pro_8m_flash/

I've seen those before. First place I looked. But none of them answer my question in a way I understand, at least. If one of those three docs explain how to connect serially, I'd appreciate it if you explained, more specifically, what I'm not grokking.

You applied connections like it was a plain esp8266. The board has the necessary pull-ups and pull-downs. Connect it at first only to GND, VCC, TX, RX. The button pulls gpio0 LOW to enter flashing mode at power up.

I'll try just those 4 pins, thanks. But I'm pretty sure I started with that and got nowhere. I'll respond with results later.

As I thought, I had tried this.  Does not work as you expected.  I consistently get the following errors from the IDE when it attempts uploading:
warning: espcomm_sync failed, error: espcomm_open failed, error: espcomm_upload_mem failed, error: espcomm_upload_mem failed. As I say here (https://stackoverflow.com/a/47742473/1480995), I am unable to program unless IO15 and IO0 are grounded and EN is run to VIN, regardless of the use of the button.

So it seems that the trick to being able to monitor serial output on the RobotDyn ESP8266-Pro is to NOT have DTR and CTS from the CP2102 programmer connected to the board's RST and IO12 pins.
With only the four remaining lines connected (VCC, GND, TXO, and RXI), you will see normal serial output on the the Arduino IDE's serial monitor after uploading firmware completes.
This works for me with the board set as "Generic ESP8266 Module" or as "NodeMCU 1.0 (ESP-12E Module)".
This still doesn't get you serial monitoring when you just plug in the device, though.  It only works after firmware has been uploaded.  Still working on that.

without DTR signal the Serial Monitor doesn't restart the board as you know it from Arduino

OK, I'll look into that.  I'm not familiar with these serial devices at all - everything I've used had built-in USB except from an Arduino Pro-Min that worked with the programmer cable I got with my CP2102 out of the box.


text:
WS2811 LEDs have the wrong color unless I touch the data wire
This is an electrical/hardware issue, but for background, here's my setup:
I'm using a Wemos D1 mini
in conjunction with Home Assistant running on a RPi3.  The MQTT setup works fine and the commands are being executed perfectly, but the colors are completely off unless I'm touching the data wire.
For instance, if I request solid blue and am touching the wire, they all turn blue.  If I let go of the wire, the first LED turns red and the rest are a strong green.  If I touch the wire, they go back to blue.
Any colors or patterns requested show likewise confusing changes.
What kind of effect is causing this, and what can I do to fix it?
Using a Tanbaby 5V 60A for power
Lights are Alitove WS2811 5V 12mm RGBs

I am having the same issue, I put a Capacitor in the right place and I also put the resistor in line, and when I put the resistor inline it does not work at all. Any other feedback on this?

It sounds like the bits are getting garbled. There is more than one wire, which one do you mean? Data? Earth? Power?
From the Adafruit NeoPixels best practices guide:

Before connecting NeoPixels to any large power source (DC “wall wart” or even a large battery), add a capacitor (1000 µF, 6.3V or higher) across the + and – terminals.
Place a 300 to 500 Ohm resistor in series between the Arduino data output pin and the input to the first NeoPixel. This resistor must be at the NeoPixel end of the wire to be effective!
Try to minimize the distance between the Arduino and first pixel.
Avoid connecting NeoPixels to a live circuit. If you simply must, always connect ground first, then +5V, then data. Disconnect in the reverse order.
If powering the pixels with a separate supply, apply power to the pixels before applying power to the microcontroller.

I agree that it's an issue of mangled bits, but how does touching the data wire "fix" that.  Skipping the capacitor advise for now, as it's manifesting as a data issue.  Tried adding a resistor, but that eliminates the signal altogether.  The data wire is only 4 inches, soldered into the board and clipped to the led data input.

your body is adding capacitance to whatever it touches

What is supplying the data? The Pi? The ESP8266? What voltage are you running at? The Neopixels require 5V as I recall. If you are running at 3.3V the performance may be marginal.

The ESP8266 is supplying the signal.  The lights are more "christmas light"-style, they're not Neopixels.

Yes, well Adafruit call them Neopixels. They may not be technically the Neopixel "brand" but Neopixels use the WS2811 chip (amongst others).

What voltage are you powering the WS2811 chips at?

And, what is the data voltage? 3.3V or 5V?

The GND on the ESP8266 should be tied to the DC- from your power supply.   With your short signal wire, you can do it at either end; on longer runs, it's recommended to run a twisted pair of GND & Signal and tie GND to DC- at the first pixel.


text:
Do I have to wire up my WS2812 LED strip in "series", if I want to address each LED individually?
Let's assume I want to make an asterisk (*) out of LED strips. I want to control each leg individually, while still being connected to only one GPIO pin. The layout I had in mind, looks like this:

Since it's an LED strip with individually addressable LEDs, I can't just supply 5V, GND, and DATA to the middle and expect it to work (I highly assume).
If I want to do this, I assume I need to keep running them in "series", basically meaning I hook up one of the strips to the Arduino, then at the end of the strip I run a long wire to the start of one of the others and then repeat. Something like this:

but only for the data wire, as I can simply power all of them in the middle. If not, how can I do this? What happens if I hook up 5 strips' DATA to a single GPIO pin on the Arduino? Are all 5 strips shared then, so each strip's first LED is also the first I would turn on?

The LEDs are "addressed" in series; if you address the first LED then you address all connected first LEDs. So yes, you must connect the Data Out of the previous LED/strip to the Data In of the next in order to address all of them individually.

Right, so the second image I put in is basically what I have to do?

Or you can flip every other strip in order to have the shortest data paths. Just keep in mind the direction of each strip if you do.

Right, so something like this? https://i.imgur.com/MusZ8Hc.png

@MortenMoulder: Correct.

Awesome, thanks a lot for the confirmation :-)


text:
Additional Digital Input Pins
I require additional digital input pins for 5 PIR sensors. Can I use the shift register (74HC165) to read these input? And will I be able obtain real time values from all the 5 sensors?

Did you know you can use the Ax (A0, A1, A2, etc.) pins as digital inputs also? Or have you already used all of them?

Yes I have used all if them

Yes, a shift register will work fine if "real time" is on the milli-seconds level. Calculate the time to access the shift register input.

If you don't care about which sensor triggered, you could use an OR-gate.

You could use a GPIO expander (MCP23017 or similar) which could give you 14 extra pins (16-2 for I2C bus), but this is putting extra load on the microprocessor.  (you haven't said which one by the way).
Or another option might be to revisit you design and see if you can split it out to multiple processors.  This is effectively the same as a GPIO Expander, just using an Uno or ESP8266 as the expander.

I will look into the GPIO expander.

I am using an arduino uno by the way. Sorry didn't mention it. Thank you:)


text:
Save a fingerprint to the database of the fingerprint sensor
I'm using the Adafruit Kookye fingerprint module in my project. Since it can only allocate 256 fingerprints I need to make a program to free the memory and add additional users. I have made the following function at the library:
uint8_t Adafruit_Fingerprint::downloadModel(uint16_t id, uint8_t packet_1[], uint8_t packet_2[], uint8_t slot) {
  uint8_t packet[] = {FINGERPRINT_DOWNLOAD, slot};
  writePacket(theAddress, FINGERPRINT_COMMANDPACKET, sizeof(packet)+2, packet);
  uint8_t len = getReply(recvPacket);

  if ((len != 1) && (recvPacket[0] != FINGERPRINT_ACKPACKET))
   return -1;
  if (recvPacket[1] == 0x00) {
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_1)+2, packet_1);
    writePacket(theAddress, FINGERPRINT_DATAPACKET, sizeof(packet_2)+2, packet_2);
    return recvPacket[1];
  } else {
    return recvPacket[1];
  }
}

This function is working, it puts the fingerprints to the buffer 1 and when I call the function to save with the ID it also works. When I print the fingerprints in the sensor, the structure is exactly the same as if they had been added directly from enrolling. However, when I serach the fingerprints the sensor always returns that the user does not exist.
I don't know what's the problem.

Don't cross post. Delete your other question on SO.

The sizeof() operator doesn't do what you think it does. It's not a function that is executed at runtime, it's an operator that is interpreted at compile time.
It takes a variable and returns the size (in bytes) of that variable. Since you are passing it a pointer it gives you the size of that pointer. That's 2 bytes on an 8-bit system like the Uno.
In C an array is not a single entity with a size. It's a pointer to a block of memory that has been reserved at the time the array is declared. All you get is that pointer, and it's up to your program to remember the size.
You will have to pass the size of the arrays your packet_1 and packet_2 pointers are pointing to, or always assume that those arrays are the same size at all times.


text:
Possibility to program the ATmega32u4 on the Arduino Yun using a configuration file
Is it possible to send a Configuration File viz. conf.json that can be sent to the Arduino Yun via Ethernet and a Python Program can parse the configuration and set for example Sampling Rate of a Sensor which is connected to the 32u4?
The problem for me is that Sampling Rate in the Arduino Sketch is actually a preprocessor directive and I understand that C++/Arduino Sketches need to be compiled once before the changes take place.
However, how can I change the preprocessor directive in the sketch using a configuration file?
e.g.
#define SAMPLE_RATE (100)

in a conf.json file somewhere there might be:
{"sample_rate": 1000}

Once the .json file is parsed using python is it possible to change
#define SAMPLE_RATE (100) // to #define SAMPLE_RATE (1000)

You can't. You'll have to change your macro into a variable and change that variable when suitable data is received through the serial port.
You may also have to trigger a reconfiguration of whatever software is doing the sampling, or reconfigure the hardware, depending on what it is you are sampling.

What if I had the Sketch on the Yun on an SD Card and use sed to check the parameters and compile the code again using command line?

That would just be plain nasty. Using a variable instead of a #define should be simple enough, depending on what you are doing in your code with that value.

I think you are right in this sense. I might as well use the Atheros microprocessor as a middleware to store the data and then do stuff on python and nodejs scripts than on the Microcontroller. Thanks for the insight


text:
How to control a DC Motor with absolute encoder using Arduino and Motor Driver?
I am a beginner in Arduino, I have only basic knowledge and a big appetite :)
I'm working on my cable-cam project. I've made all the mechanical parts by myself, bought all electricity parts through eBay, and everything works fine so far. With the basic RC controller I steer forward / back and I also have a speed potentiometer.
Now there is a question of security:
Since cable-cam runing on a rope fastened to two hubs/buildings/trees/piers,
up to 40 mph.
I would like to have the opportunity to program two points through which the cable-cam cannot overdrive, so that it would not go to the end of the rope and break itself.
THE concept: cable-cam is driven to point A and is marked. Then it is driven to point B and also marked. When the cable-cam reaches point B, it stops and can not go further, but it can go back to point A. And vice versa. Something like a "operation range control points" that can be programmed. Something like this: end points with Hall sensor
THE idea: on a non-powered wheel (for avoiding slippage and incorrect reading of data on the encoder), I'll set an absolute encoder to measure axis rotations and thus calculate the distance in both directions. The encoder would then be connected to the Arduino that would send the ESC signal to stop the engine when it reached that point, A or B. Stopping should be soft, not at the moment. The speed of the cable cam can be significant, so abrupt stoppage would also be a problem.
So...am I pre-ambitious? I need help with code for Arduino.
Parts:
RC: Turnigy 9X
ESC:Syren 50A and it has an Arduino library,
and the encoder:Koyo TRD NA1024NW

tie a string from A to B. the string passes through the carriage of the device. attach a "stopper" at each end of the travel. something like this https://www.google.co.in/search?q=drawstring+cord+lock&source=lnms&tbm=isch  .... then use a switch on each side of the carriage to detect the end points

Cannot do that,  I need more sturdy solution...

This is a quite high-level question, so I will answer in general terms,
skipping the fine details. You can ask here more specific questions once
you are implementing the stuff.
Yours is a 10-bit absolute encoder. It can tell you its shaft position
with a resolution of 1/1024 revolution. It's way overkill for your
application. I suggest you connect only the four most significant bits
(pins 9 – 12), which will give you a resolution of 1/16 revolution.
It's better to read the four bits simultaneously. This can be done using
direct port
manipulation. I
would connect pins 9 – 12 of the encoder to pins 4 – 7 of the Arduino
respectively. As the encoder outputs are open-collector, you have to
enable the pullups in setup():
PORTD |= 0xf0;  // enable pullups on pins 4..7

and you can read the encoder simply as
uint8_t ecoder_value = PIND & 0xf0;

Notice that this will give you a result that is left-aligned. This way
you can treat it as an 8-bit Gray code.
Next step is to decode the Gray code. I let you research how to do that,
as you can probably find examples, or even ready-made libraries for
that.
Next, you have to extend the value to a wider bit length in order to
know the absolute position of the cable-cam. The encoder only tells you
where you are within a revolution, but it doesn't tell you how many
revolutions you did. The extension is done by comparing the current
encoder position with the previous one, taking the difference (which can
be positive or negative), and adding it to the previously computed
absolute position. Something like this:
int32_t absolute_position;

void update_absolute_position(uint8_t encoder_position)
{
    uint8_t old_position = absolute_position;  // extract LSB
    int8_t delta = encoder_position - old_position;
    absolute_position += delta;
}

Beware of the types of the variables. The type of delta, for instance,
ensures that the result of the subtraction is wrapped the correct way to
yield a number between −128 and +127. Thus, the sign will tell you which
is the shortest path (clockwise or counterclockwise) from the previous
to the current position.
Note also that you have to call this function frequently enough: more
than once per half revolution. Otherwise it won't know which direction
the wheel turned. If your loop() runs fast enough (you don't use
delay(), right?), you just have to call this function once in
loop(). Otherwise you would have to setup a timer interrupt to ensure
the updates are frequent enough.
Lastly, you have to define the limits:
int32_t left_limit = INT32_MIN;
int32_t right_limit = INT32_MAX;

// To set the left limit to the current position:
if (user_pressed_the_relevant_button()) {
    left_limit = absolute_position;
}
// and likewise for the right limit.

and condition the maximum speed on the distance to the closets limit.
Assuming you store the speed as a signed number (the sign being the
direction), you would constrain it to always be between a negative
min_speed and a positive max_speed, which could be updated as
follows:
// Slow down if close to a position limit.
if (absolute_position - left_limit < BREAKING_DISTANCE) {
    min_speed = map(absolute_position,
        left_limit, left_limit + BREAKING_DISTANCE,
        0, -ABSOLUTE_MAX_SPEED);
} else {
    min_speed = -ABSOLUTE_MAX_SPEED;
}
if (right_limit - absolute_position < BREAKING_DISTANCE) {
    max_speed = map(absolute_position,
        right_limit - BREAKING_DISTANCE, right_limit,
        +ABSOLUTE_MAX_SPEED, 0);
} else {
    max_speed = +ABSOLUTE_MAX_SPEED;
}
speed_to_apply = constrain(requested_speed, min_speed, max_speed);

Note that this makes the speed limit a linear function of the position.
You may want to look into easing functions to have a smoother breaking.

Thx everyone for your effort to help me!!
I am aware that specific absolute encoder is overkill for my project, but I need it because of high rpm count. Cable-cam runs up to 40 mp/h and wheel is rotating up to 1500rpm. I have no problem to use it at lower resolutions.
Main point is to free drive cable-cam between two points, in any direction, at any speed. ONLY when cable-cam reach one of predefine points-it stops. Softly. You can manually drive it backwards, but you cannot go beyond that point.

Ufffff guys... This is soooo over me and my knowledge. I belive that I need to outsource somebody for this work...
In my head "little devil" told me: " you can do it, you just need two secure points, how hard it can be?"
Well...now I know :)))
So...if there is anyone willing to do complete code for me...I am sure that we will find some way to compesate that amount of work

@littlerock: You should probably try to find some help close to where you live. At some point you will have to debug and fine tune the firmware, which would require modifying the code and testing on the real hardware. If the person writing the code and the person doing the test are megameters apart, that won't be easy...

It is quite difficult to say any thing without the actual code, but if you are reading the position of the cam regularly you can implement a "if/else" condition. Some thing like this:
if(position==A)
reverse();
else
continue;

(this is very crude and undefined and there are many ways  to improve it)
Here position is assumed to be the position of the cam and A is the maximum that can be traversed to. A same condition can be applied in case of the other end as well. (also reverse() is a function that reverses the direction of motion. In addition to this, you can replace reverse() by some thing like stop() and after that check "position" is greater than A call the reverse function till the condition is met.
Hope this helped.


text:
Connecting two analog multiplexers (CD4051b)
Is it possible to connect two CD4051b analog multiplexers together so that I can receive 14 analog inputs through  them? Just by using one analog pin and three digital pins on the Arduino UNO.

CD4051b is an analogue multiplexer, not a shift register.  Your question seems to suggest you want lots of analogue inputs, not a shift register.  Have you read (or seen) the data sheet?

Oh okay. Yes I need analog inputs. What is the best option I have.

Thanks -- I've edited your question to reflect what you really want. Can you tell us more about what signal(s) you're trying to multiplex (switch) please?

Okay the components I need to connect are - 5 LDR sensors. 5 PIR sensors and 3 ambient heat sensors.

I have used all my digital input pins and only have the 6 analog in pins left.

Each CD4052B multiplexes 8 input to one output, and you need three digial pins to control it.  You have the six analogue input pins available and those pins can also serve as digital outputs, so you should be able to use  them to do what you need.
I would do as follows:
Assign three of your spare pins to be digital outputs.  Use these three to address both CD4052Bs together -- so both devices will receive the same addressing.
Connect the output of one CD4052B to the fourth analogue pin, and the output of the second CD4052B to the fifth analogue pin.  These will be your inputs.
On both CD4052Bs, tie the INHIBIT pin low, so they are permanently on.  (If you want to be able to switch them off, for some reason, you an use your sixth pin to control the INHIBIT line on both devices.)
Now when you want to read from sensor 1, you set 000 on the address lines (A, B and C) and read from the first input.  At the same time you'll have sensor 9 on the second input.
It would be well worth reading the data sheet


text:
Is this a good function for I2C receive?
I'm trying to fix my I2C code:
Is the following function correct because it has multiple returns. I don't know if that would work.
uint8_t I2C_rx(uint8_t ack_rx)
{
    uint8_t i;
    if (ack_rx)
    {
        TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA); // sending ACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
    else
    {
        TWCR = (1<<TWINT)|(1<<TWEN);           // sending NACK
        while (!(TWCR & (1<<TWINT)));
        return TWDR;
    }
}

You can have multiple returns. Some people disagree on style grounds, but it works as intended.

No problem with multiple returns but it could be reduced to:
uint8_t I2C_rx(bool ack_rx)
{
  uint8_t cr = (1<<TWINT) | (1<<TWEN);
  if (ack_rx) cr |= (1<<TWEA);
  TWCR = cr;
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

or
uint8_t I2C_rx(bool ack_rx)
{
  TWCR = (1<<TWINT) | (1<<TWEN) | (ack_rx<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}

Cheers!


text:
Disable auto-reset Mega 2560 on serial monitor open using 60 ohm resistor
I tried preventing my Arduino Mega 2560 from restarting every time I open the serial monitor. This link didn't work for me at all.
I tried connecting the RESET pin to 3.3v pin via a 60 ohm resistor and it worked for me. The question is: If I leave that resistor permanently connected, will this solution damage my board as time passes?

Personally I use a large capacitor between reset and ground. 22uF or greater should do it.

You should connect the resistor to 5V instead of 3.3V. There is no way you can damage the Arduino with this resistor, since the reset pin is pulled low by the USB-to-Serial chip through a (100nF) capacitor. So current can only flow for a tiny moment.

i already tried 5v with a 120ohm resistor but didn't work

A 22uF cap between reset and ground does work on my Mega 2560 - opening the serial monitor will not restart the program. However, the Mega is then not downloadable. Therefore, I grounded the cap thru a normally closed relay and connected its control to a digital output. I normally operate with the relay closed. When I want to download a new program I open the relay first. It works great :-)


text:
How do I import data from serial monitor to excel document without copying and pasting?
I need to be able to import incoming data from a motion sensor and then from the serial monitor (where the data is) import the data to an excel document or file.
Any suggestions would help,
Thanks.

The Arduino IDE's serial monitor is just one of many tools that can open a serial port and collect information from it.
The first step is to make sure the data you are writing to the Serial object in the Arduino is in a format suitable for importing into Excel. Separate multiple values on one line with a comma "," or tab "\t" character.
If you are running windows, you can often just use the built-in type command from a command prompt to write the serial port to a file:
type COM4 >> log.txt

(Assuming the Arduino is on COM4 and you want to write the data to a file called log.txt.)
If you're on a Mac, open the Terminal app and type:
screen -L /dev/tty.usbmodem1441335 9600

(Assuming your Arduino is on serial port named tty.usbmodem1441335 and your port speed is 9600 bps.) The session will be written to a file called screenlog.0.
Then you can open the text/log file in Excel. If you rename it to end in .csv, that may also help Excel recognize it as tabular data.

You could even connect directly to the serial port, from within excel, using VBA. http://www.dailyfreecode.com/Forum/accessing-serial-port-excel-vba-26041.aspx


text:
What is FaryLink? [Access Point]
When powering up my WeMos D1 ESP8266, I suddenly find this hotspot named "FaryLink". What is this? I programmed the ESP to work as a web server, thus connecting to an existing hotspot and not providing any beacons or acting as an access point.
Google could not provide any information to this behaviour.

What is the purpose of this AP and how can I use / disable it?

Did you use WiFi.setmode first?

look again ... it does not say FairyLink

wow, i guess i only see what i want to see. will edit question for future readers

Did you use setmode() to put it in station mode?
wifi.setmode()
Configures the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

Station mode, where the NodeMCU device joins an existing network.
Access point (AP) mode, where it creates its own network that others can join.
Station + AP mode, where it both creates its own network while at the same time being joined to another existing network.
WiFi off.

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.
NOTE: WiFi Mode configuration will be retained until changed even if device is turned off.
Syntax
wifi.setmode(mode)

Parameters
mode value should be one of

wifi.STATION for when the device is connected to a WiFi router. This is often done to give the device access to the Internet.
wifi.SOFTAP for when the device is acting only as an access point. This will allow you to see the device in the list of WiFi networks (unless you hide the SSID, of course). In this mode your computer can connect to the device, creating a local area network. Unless you change the value, the NodeMCU device will be given a local IP address of 192.168.4.1 and assign your computer the next available IP address, such as 192.168.4.2.
wifi.STATIONAP is the combination of wifi.STATION and wifi.SOFTAP. It allows you to create a local WiFi connection and connect to another WiFi router.
wifi.NULLMODE to switch off WiFi

Returns
current mode after setup

after adding "WiFi.mode(WIFI_STA);" in the servers constructor, the mysterious FairyLink was removed. THX


text:
I can't control my DC motors speed with analogWrite()
I have Arduino Uno and I attached it to 2 DC motors with L298N bridge.
I want to control the speed of the motors so they don't move at maximum speed.
I use analogWrite() but it does nothing,and the motors move at maximum speed
Here is my code:
//motor A
int enA = 9;
int in1 = 8;
int in2 = 7;

//motor B
int enB = 3;
int in3 = 5;
int in4 = 4;

void setup() {
  Serial.begin(9600);
  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void loop() {

  analogWrite(enA, 0);

  analogWrite(enB, 0);

  digitalWrite (in1, HIGH);
  digitalWrite (in3, HIGH);
  digitalWrite (in2, LOW);
  digitalWrite (in4, LOW);

  delay(50);
}

Do you know that analogWrite(enA, 0); stops it? Or what exactly is the problem?

With using analogWrite Do make sure you use the pwn pins of arduino to control the motors.

yes i know that analogWrite(enA,0) stops the motor and that is what i want but it dosen't work and the motors are alwayes at maximum speed

Please add a schematic of photo of your wiring setup. As you have described it thus far, your code should halt the motor, so perhaps the wiring is not correct.

@josecanuc i did my wire base on video on youtube with my same electronics and it runs perfect with his device

@MukharJain i am sure that i am using them and i tried all the pins ,however the problem still the same

If the youtube video project runs perfect and yours doesn't, this is why we are asking to see what you have done, because of the possibility that you made a mistake in re-creating this project.

I did find solutions for the problem. It turned out that the bridge does not work as it should be and the pins of en(A,B) is replaced with the in pins ..now I can control the speed but can't reverse the direction of the motors

This was really frustrating to figure out, so thanks for your answer here! I had a similar bad module, and looks like just connecting my pwm pin to IN1 was all that was needed for speed control in a single direction. I just disconnected the enable jumper/pin and in2 pin, and measured a good pwm output. Seems like the enable pin does nothing on my module!

analogWrite() can take values between 0 and 255 as its second parameter. Where 255 will give you the maximum motor speed and 0 will give you the lowest (motor will not run).
For example, below code will give you almost the half of max speed.
analogWrite(enA, 128);
analogWrite(enB, 128);

i know what it does but it does not work the way it should and the motors are allwayes at maximum speed even if i put it to (0) and i am sure of the pins

I'm looking at one of the L298N bridges on Amazon. What are those two jumpers on pins ENA and ENB? Try taking those off, because I wonder if they're pegging you at full "on".

@LegitimateWorkUser these are the speed control pins(voltage) if you take them off the motor will not run at all


text:
Not clear code procedure in Arduino wire library
The application code of sparkFun, has the following line which is difficult to understand.
It's requested 6, because it's requesting 6 bytes for HMC5883L module.
Wire.requestFrom(address, 6);
if(6<=Wire.available())

Where:
int TwoWire::available(void)
{
  return rxBufferLength - rxBufferIndex;
}

So, the available function should return return rxBufferLength - rxBufferIndex; where rxBufferIndex is modified in read function:
int TwoWire::read(void)
{
  int value = -1;

  // get each successive byte on each call
  if(rxBufferIndex < rxBufferLength){
    value = rxBuffer[rxBufferIndex];
    ++rxBufferIndex;
  }

  return value;
}

But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

What is the rxBufferLength value in your example?

6 according to HMC5883L 6 bytes data.

rxBufferLength is the number of bytes that have been received. rxBufferIndex is the byte you would next be handed with a read() function call.
So if you have received 6 bytes from the slave (which you will, since that is how many you requested) but not read any the available would be 6. Ergo, 6 <= 6. I.e., you asked for 6, it collected 6, and you are checking that it got at least 6 (it can never be >6 since you only asked for 6, so why they look for at least 6 I don't know).
rxBufferIndex is never decremented. It is incremented when you read a byte, up until rxBufferLength == rxBufferIndex at which point there is 0 bytes available.

But, my current question is why decrementing return rxBufferLength - rxBufferIndex; where  rxBufferIndex is initialized to 0 all the time, and there's no chance the returned value would be less than 6, because that would terminate the if statement?

The way that Wire.h works is that available() will always return the number of bytes you requested if the call to requestFrom() succeeded until you first read some of that data. If you request 6 and the call worked then you have 6. The if could just as well be written as:
if (Wire.available()) {...

since it will always be 6 immediately after a successful call. However, that makes assumptions about how the Wire API works and could be subject to change in the future or operate differently on different platforms.
So it checks that, right after the call to requestFrom() for 6 bytes it actually got at least 6 bytes. Without seeing what is inside the conditional if, all I can do is make assumptions, but I would assume that it is then reading those 6 bytes, and so it wouldn't care if there happened to be more for some reason. But it doesn't want there to be 5 or fewer bytes available when it is reading 6 of them.
An if statement doesn't "terminate" if its condition becomes false once it has been executed. It's not like a while that keeps running until it's false - it's a single decision made at a single point in time. If anything changes in the future that would have caused a difference decision to be made (e.g., you read() a byte, so available() would now return 5), the decision that has been made still stands.
An analogy for you:
You want to go out for a good healthy walk - but only if it's not raining.
if (!raining) {
    walk_to_shop();
    walk_to_cafe();
    drink_coffee();
    walk_to_shop();
    walk_home();
}

You go out for your walk to the shops, get a coffee, do some more shopping, and then walk home - but you only start doing that if it's not raining. If it starts raining while you're out you don't suddenly teleport back home.  You could make the decision, when you come out of the cafe and see it's raining, to cut your shopping trip short, but you have to actively make that decision. Just because raining becomes true doesn't affect the fact that you are outside and walking.

I edited the  question.

I think you're getting confused about what n if is.

What confused me is if(6<=Wire.available()) because available returns rxBufferLength - rxBufferIndex; so if rxBufferLength is 6 and  rxBufferIndex is 0, then available returns 6, which is true in this case. But, if rxBufferIndex is 1 or 2, then available returns 5 or 4, which is false. So, how's that if statement is working? Does if(6<=Wire.available()) returns the value one time, or it returns with all rxBufferIndex increments inside wire library?

@PerchEagle At the moment the if() executes Wire.available() will equal 6. That is the only time the if() executes, and it can only ever give 6, since nothing has been read at that point.

OK, I understand now, it runs only one time and the function every time returns 6. Thank you :) but I have another problem, the good news I succeeded accomplishing my I2C code, and that was amazing, but I have a new problem passing an array to I2C_tx function, I don't know why it's not working. I should ask about it in a new post.


text:
Project structure to build for PC and Arduino
Recently I have started developing for Arduino Uno. I have 10 years experience in software development (C#, Delphi), but not much with C/C++.
Compiling the Arduino sketches seems a little slow, and debugging isn't as convenient as it could be on a PC (compile, upload, watch the serial monitor, modify code, start over.... way too slow with lots of unnecessary steps)
So what I would like to achieve is to organize my code in a way to be able to compile my code either to Arduino, or to PC for debugging purposes (to a small console app). I know that there are libraries that cannot be used on a PC, but those can be abstracted away (hidden behind a facade or something like that). Unfortunately I could not find any tutorials, or articles how to do this. So I hope you can help me out.
BTW I'm using Visual Studio (with Visual Micro) on a Windows 10 computer.

How you plan to replicate things like buttons, led, sensors and relays?

With abstractions as I said. Of couse those stuff won't work on a PC but for example a led can be replaced with a Console.WriteLine. Sensors are providing data in a form of bytes/bytearrays, which can be faked with abstractions. With fakes the logic can be built/validated on PC much more faster than with a real board.

What you're looking for is an Arduino Simulator. I seem to recall people doing it Proteus, but don't quote me on that. It's something like that anyway.

This may help: http://www.instructables.com/id/How-to-Simulate-Arduino-in-Proteus/

I haven't done it yet, but you could do the following things to get a somewhat close approximation:

Make three different projects, one for the PC (only), e.g. Visual Studio, and one for Arduino (with the default Arduino IDE or e.g. Visual Micro). The last will be a generic library to be used for both the PC and Arduino.
Use the Arduino specific libraries only for the Arduino project.
Create facade/wrapper classes for each Arduino library.
Use a mock/stub for the Arduino libraries in the PC only project.
Put all non-hardware related code in separate classes, to be used by both projects.
Write unit tests for the PC only project.
The PC project will be tested by unit tests, and can be debugged on a PC
Only the specific Arduino libraries/interfaces have to be tested using the 'hard way', e.g. with Serial.

So the projects (including testing) will look like:

PC Project

References common code
Stubs for Arduino libraries, stubs can possibly be reused by PC Unit tests

PC Unit Tests

Unit tests
References common code

Arduino Project

Containing Arduino libraries
References common code

Common Code

All domain specific classes


text:
someVariable = { somethingThatLooksLikeAFunction }; possible?
Wasn't sure how to title this question...
I was curious whether the title example is possible somehow, and are there any good tricks to using it?
I have been using something similar quite a lot:
newBool = (someTest) ? true:false;
newInt  = (x + (y / z));
[...]

However, I was curious if it was possible to add far more conditions, almost like a function?
For some simple(*) examples:
someThing = {
    int _x = aFunction(_x);
    if(_x) {
        something = somethingElse;
        for(...){ ... }; // etc
    } else {
        /* otherStuff */
    }
};

Or
someThing = {
    for(_x=0;_x<y;_x++){
        z++;
    }
    someThing = (z>y) ? a:b;
};

I understand it's worth just separating it off into functions most of the time, although I'm trying to get away from a function/library-fest as much as possible...  It's getting annoying crawling through everything when I could just have the useful stuff right there, where I need it, instead of 1000 lines away, or in another library.  It also allows the text editor to fold the code out of sight, starting from one variable, instead of on each clause.
With the few tests I have tried, I've not been successful in achieving what I'm experimenting with, so, is this kind of thing possible in any way? and if so, what are the rules/possibilities/different ways you could implement this?
* Emphasis on simple! And a semi-pointless/completely useless "function" alert too!  I'm just curious about the "proof of concept" in the examples...

Something = {code} is just syntatic sugar for code; something=someotherthing

You can do it with a lambda function, though the syntax is somewhat cryptic:
int someThing = [](int y, int z, int a, int b){
    for (int _x = 0; _x < y; _x++) {
        z++;
    }
    return (z > y) ? a : b;
}(100, 0, 10, 20);

In that you are defining a lamda function [] with four parameters, y, z, a and b. Then calling that function with four numbers (100, 0, 10, 20) and assigning the return value to someThing.
It's the same as writing a normal function but there's a lot more brackets around.

That gave me inner smiles :D That's a really nice example! Thank you!  I assume (100, 0, 10, 20) could be (intOne, intTwo, boolOne, boolTwo), for example, too?

Yep. Just like calling any function.

I just don't understand what is the gain doing this. It's overkill using lambdas for something you can in-line for the same result with less code.

@LookAlterno No benefit at all. The compiler will probably optimize it away anyway. But.. why climb a mountain...? Cus it's there.

Then, some time latter, some poor soul have to mantain that code ...

@LookAlterno - I'd massively appreciate any advice or alternate ways if you have any? Reason I asked is that as my program is getting larger, I am ending up with many functions that are used only within a single other function; which is becoming increasingly cumbersome to keep track of.  With something similar to the above, I can just have the "simple but still important" function there and then where I need it, and the text editor folds away to a single variable, instead of on each for, if, etc that each variable pipeline is going through.  I find it far more readable for my uses, so far.

@Timeless. WIthout actual samples of your code is hard to add anything. I use lots of small functions (<20 loc), writing them as I needed. When the code grow too much and start to look complicated, it's time to refactor it until it become manageable again.


text:
How to get Velocity and Displacement from IMU sensor?
I have an imu mounted bot.I want to get the speed of the bot using imu i dont want to use the encoders. Imu gives acceleration how should i integrate that to get velocity and how much error would be there??

The error in this method would be massive.
Velocity is the integration of acceleration over time. However, you don't have acceleration over time - you only have acceleration at discrete points in time - the times that you actually sample the acceleration.
You would want the total acceleration between two points in time, which you just don't have.
Take the following timeline of acceleration points:
+3 +2 +5 +2 -3 -4 +3 -5 +3 +2 +6 -4 -2 +3 -4 -5 +6 -3 -1 -2 +7 -2
 ^           ^           ^           ^           ^           ^

The carets are the points where you are actually sampling the acceleration.
Assuming you start from 0m/s, and those are all changes in m/s, your calculated speed from your samples would be 3-3+3-2+6+7 = 14m/s.  However, the real velocity would be 7m/s.
In reality, there aren't discrete points of acceleration - just a single smooth waveform.
The faster you can sample the closer to reality you get, but there's always a chance that you would miss some critical brief change in velocity.
On top of that, you have noise. Quantisation noise, vibration, electrical noise, etc - all of which add a certain amount of uncertainty of their own.


text:
How to produce 6 PWM signals with 60 degrees phase shift?
How to produce 6 PWM signals with 60 degrees phase shift using Arduino Uno 6 PWM pins like in the image below?

What duty cycle? 50%?

You could also use a timer interrupt, that will bitbang PWM. Kind of similarly to how the servo library send "PWM" signals to multiple servos.

Using hardware it's not possible. Simply because you effectively only have three PWM timer units, each with two compare outputs.
That means you have three timebases, which are each compared with two values for two PWM signals each.
You would need a single master timebase with six independent offsettable counters with comparison for your needs.
It would be possible to (roughly) do it in software, though, depending on your needs. You get jitter from software generated PWM, due to interrupts getting in the way of your smooth execution. However you have complete control over how the waveform is generated. Instead of a 0-X duty cycle you could program it to have an X-Y duty cycle. And with all of them taken from the same counter value it's then all synchronised 100%.

Can I make the 3 timers begin counting at the same time?

Not precisely, no. There is no way of starting them in the same instance. You could do it close together though. It wouldn't give you different phases then though.

You can invert one of the two PWM outputs.

You'd have to setup the timers with appropriate TCNTx values before starting them at the same time.

You can start the three timers at the same time by using the “Timer/Counter Synchronization Mode”. See the description of the GTCCR (General Timer/Counter Control Register) in the datasheet.

I found the correct method for 6-phase PWM as the OP requested. And it can have any duty-cycle you want. My erroneous findings for 50% only duty we're because I used Fast-PWM mode. When I switched to Phase-PWM (mode-10-PWM in a 2560 ARduino), I got the correct waveforms, the same as the OP wanted.
Below is a link to a logic-analyzer snapshot showing the 6-phases from a 2560. The frequency is 500 Hz but that's easy to change. 4 Timers in all used to realize this outcome. 3 Timers used mode-10-PWM, 1 mode-14-PWM at the same frequency.
The full project is documented at Runtime Micro.

EDIT:
I can now do this using an Uno. But there are limitations to duty-cycle and some other concerns. Provides usable N-channel (2, 3, 4, 5, and 6) phase-shift PWM from a single Uno board.
EDIT:
A full 6-channel PSPWM solution using only an Uno is now published at Runtime Micro under Projects Menu. You'll find details, images, code and diagram. There are limitations such as no channel-to-channel overlap in pulse-width.
FWIW

Are you able to share your code so others can follow your method?

Use a timer to trigger an interrupt. Set the timer to 1/6 of the overall pwm cycle to get to 60degree phase. Each time the interrupt is triggered it turns on the next channel.
You could have a second timer and interrupt to turn them off working in the same manner.


text:
Code is not working (Matrix keypad)
I am new to Arduino. I am learning from Arduino Cookbook. I was using tinkercad.com for running my Arduino code. But it is not working.
The Serial monitor should show the key which I have pressed on the keypad.
I think there is some syntactical error in the code, I believe the connection is all right.
Any suggestion will be appreciated.
Please look into this:
const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
    pinMode(rpin[i],INPUT);
    digitalWrite(rpin[i],HIGH);
  }
  for(int j=0;j<4;j++)
  {
    pinMode(cpin[j],INPUT);
    digitalWrite(cpin[j],HIGH);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}

and the connection pic:

update 1:

Not working doesn't give us any information. What is not working? How is not working? Is it hardware or software? What is the right result in your opinion?

The serial monitor is blank.

The serial monitor should provide the key pressed on it.

I think so software problem.

In my opinion, it may be some syntactical error.

Did you put a resistor in serie with each pin?

To verify serial communication is working, add this line after your Serial.begin() statement: Serial.println("Program starting");. Let us know whether you see that line printed when you open the Serial Monitor.

No, instead i have used internal pull-up.

@per1234 it is working.

Please update the question with the full description of what you mean by "not working". Note that you already have 2/5 close votes on this question.

@per1234 is it okay? Or else should I provide more.

Add in the Serial test line to your code and note that part is printed so that people know your Serial communications is working correctly. You could add a comment to that line to remind yourself that it's only there for debugging and can be removed later to save memory. Your question should stand by itself without needing to read the information in the comment thread.

@per1234, Any solution?

Check pin modes. Should be INPUT_PULLUP and OUTPUT. Also consider debouncing.

@MikaelPatel, It is still not working.

"I think there is some syntactical error in the code" In that case the code wouldn't even compile.

Cited comment:

Check pin modes. Should be INPUT_PULLUP and OUTPUT. Also, consider
  debouncing. – Mikael Patel

Please, try:
const char keymap[4][4]={
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
 };
const int rpin[]={9,8,7,6};
const int cpin[]={5,4,3,2};
void setup()
{
  Serial.begin(9600);
  Serial.println("Program starting");//for debugging purpose and canbe removed later
  for(int i=0;i<4;i++)
  {
//Should be INPUT_PULLUP and OUTPUT
    pinMode(rpin[i],OUTPUT);
    pinMode(cpin[i],INPUT_PULLUP);
  }
}
void loop()
{
  char key=getkey();
  if(key!=0)
  {
   Serial.println(key);
   delay(200);              // Also, consider debouncing.
  }
}
char getkey()
{
  char key=0;
  for(int i=0;i<4;i++)
  {
    digitalWrite(rpin[i],LOW);
    for(int j=0;j<4;j++)
    {
      if (digitalRead(cpin[j])==LOW)
      key=keymap[i][j];
    }
    digitalWrite(rpin[i],HIGH);
  }
  return key;
}

I tested this code and it works. And the debouncing time can be lowered to something like 10.

@gre_gor , for what purpose do you reduce to 10?

So it's faster to respond.

@gre_gor , to manually control the buttons, a 0.2-second delay is acceptable. And 0.01-second delay may not be enough.


text:
Using signal strength feature of nRF24L01 module
This is a walkie-talkie project and this circuit really worked, voice can be transmitted from one nRF module to another nRF. Additionally, I want to observe how well the signal strength is, by lighting up an LED.

They talked about a test.RPD function here in order to do that. But it is said that we can't use this with nRF24L01, but can use only with nRF24L01P (I don't know what is the difference).

Test whether a signal (carrier or otherwise) greater than
  or equal to -64dBm is present on the channel. Valid only
  on nRF24L01P (+) hardware. On nRF24L01, use testCarrier().
  Useful to check for interference on the current channel and
  channel hopping strategies.
  @return true if signal => -64dBm, false if not
  */

Can't we use it in nRF24L01 really?
If I cannot use this how can I use the testCarrier function to light up an LED (as Bright, Low and Off) as mentioned in the quote?
If I can use this, what changes in the code should be done? (The member TmrhProjects talked about it a little)

He also hints to this code.
bool rpd = radio.testRPD();

while (radio.available()) {
  signalStrength = rpd + 1;
  radio.read, etc...
}

Should we write the above code in the RF24.h file or should we write it directly into the Arduino's main sketch?

To get the signal strength just send 100 packets with no retries and see how many times the packet arrives.
radio.begin();
radio.setRetries(0,0); // by default nrf tries 15 times. Change to no retries to measure strength

char buffer[32];
int counter = 0;

for(int i=0; i<100; i++)
{
   int status = radio.send(buffer,32); // send 32 bytes of data. It does not matter what it is
   if(status)
       counter++;

   delay(1); // try again in 1 millisecond
}

// if counter > 80 signal strength is great
{

}

// else if counter > 60 signal strength is good
{

}

// etc

radio.setRetries(5,15); change back to its default when done.

For this code to work the receiver must be listening for data. Just listen for data on the receiver there is no need to validate the data.


text:
Serial Monitor not properly interpreting data from my NodeMCU V3
I've just received several LoLin NodeMCUs from a 'cheap Chinese ebay vendor'.  They're working well except for the fact that I'm getting garbage in the Arduino IDE Serial monitor.
I am able to:

Load and run sketches
Use the NodeMCU as a webserver and
connect to it from a computer/smartphone/etc
Everything you else you would expect an ESP8266 to do EXCEPT

I am not able to get readable data to display in the Serial Monitor.
Some Details:
-My computer is running Linux Mint so I understand that drivers shouldn't be a problem
-The NodeMCU board has instructions printed on it to
           1) Install CH340G driver
           2) Use 9600 baud rate
           3) Connect to WiFi
-I have not tried issuing an AT command to slow the default baud rate down to 9600 (as suggested in answer to another question on this forum).  Since the NodeMCU standard rate is 115200 and it's only talking to my computer and not another Arduino, I didn't think that would be required.  {Could that be the answer to my problem?}
-I've tried all the standard baud rates between 9600 and 115200.  None produced readable outputs.
-I've connected stabilized external 5 and 3.3 V power sources to the board and added some caps for extra smoothing.
I'm running the simplest sketch I could think of to send data back the Arduino Serial Monitor:
int LEDState = LOW;
int pinNum = D7;  //LED on D7 will flash while loop is running

void setup()
{
  Serial.begin(15200);
  pinMode(pinNum, OUTPUT);
}

void loop()
{
  digitalWrite(pinNum, HIGH);
  Serial.println("T");  // send the Letter T to the serial output
  for (int c = 0; c < 10; c++)
  {
    Serial.println(c); // send the count 0 to 9 to the serial output
    delay (200);
    LEDState = blinkLED(pinNum, LEDState); // blink the LED to demonstrate that the loop is running
  }
}

int blinkLED(int pinNum, int State)
{
  if (State == LOW)
  {
    digitalWrite(pinNum, HIGH);
    State = HIGH;
  }
  else
  {
    digitalWrite(pinNum, LOW);
    State = LOW;
  }
  return State;
}

I've tried all the various line endings (CR/LF, CR, LF, nothing at all).  No success with any of them.

When you upload a sketch to you NodeMCU board the AT firmware is erased (the sketch you upload becomes the firmware) so AT commands don't apply. You should have the baud rate menu in the bottom right corner of the Serial Monitor set to 115200 since that is the speed you set with Serial.begin(115200).

That's not the simplest sketch to send serial data to Serial Monitor. Instead, try this:
void setup(){
    Serial.begin(9600);
}

void loop(){
    delay(500);
    Serial.println("Hello World");
}

Upload and open Serial Monitor at 9600 baudrate. Your AT firmware is already erased, never expect 'OK' response for 'AT' command. If Serial Monitor displays 'Hello World', then your board is okay. Then, you have to reflash AT firmware if needed.

I seem to have found a solution to my own problem.  I poached a code snippet from another post on this forum (which I don't seem to be able to find now or I would happily give credit for) and inserted it into my sketch.  Works like a charm.
The code snippet resets the baud rate to 9600 within the program itself.  I upload the sketch at 115200 baud, but then switch to 9600 baud to talk to the Serial Monitor.
I've been running this code on the NodeMCU for 14 hours now and it's still going strong.
My next steps will be to insert this code into the rest of the Example Sketches that use the Serial Monitor and see if they all work on the NodeMCU V3 now.
#include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX

int LEDState = LOW;
int pinNum = D7;  //LED on D7 will flash while loop is running

void setup() {
//   ***  Additional Code that fixed my problem  ****
  Serial.begin(9600);
  ESPserial.begin(115200);
  ESPserial.println("AT+IPR=9600");
  delay(1000);

  // Start the software serial for communication with the ESP8266
  ESPserial.begin(9600);

  Serial.println("Ready");
  ESPserial.println("AT+GMR");

// ***   End of additional code

  pinMode(pinNum,OUTPUT);

}

void loop() {
  digitalWrite(pinNum, HIGH);
  Serial.println("T");  // send the Letter T to the serial output
  for (int c = 0; c<10;c++)
  {
    Serial.println(c); // send the count 0 to 9 to the serial output
    delay (200);
    LEDState = blinkLED(pinNum, LEDState); // blink the LED to demonstrate that the loop is running

  }

}

int blinkLED(int pinNum, int State)
   {
      if (State == LOW)
        {
          digitalWrite(pinNum, HIGH);
          State = HIGH;
        }
        else
        {
          digitalWrite(pinNum,LOW);
          State = LOW;
        }
        return State;
   }


text:
My arrays are possibly causing the program to not enter loop?
I'm working on a project to make a digital clock with an 8x32 ws2812 LED grid, arduino uno, and a RTC module.
Everything works great separately, but when I integrate it all together the code never seems to reach the loop function. I have print statements in the setup and start of the loop, and the setup statement triggers but the first print in the loop does not. Nothing in the loop seems to occur. Commenting out line by line I've identified that the problem somehow is caused by my arrays of neopixel locations. When I comment out lines that refer to certain arrays, the code works, all print statements are called and every other functionality works fine. When I restore the lines that call the problematic arrays and remove some of the values, it will eventually start working when I remove so many values from the end. Weird.
Array examples:
int left_min_zero[] = {145,146,147,148,149,150,153,166,169,170,171,172,173,174,161,158};
int left_min_one[] = {158,157,156,155,154,153};
int left_min_two[] = {145,158,161,174,173,172,171,164,155,148,149,150,153,166,169};

The full code is here: https://github.com/SupaTreadz/Pixel-Clock/blob/master/PixelClock.ino
The offending lines are related to the following arrays:
"left_min_four", "left_min_five", and all of the "right_min_" arrays (possibly, I only checked the first three)
ALL of the other arrays work fine. WHAT THE HECK IS GOING ON HERE???
Just to reiterate, those arrays worked perfectly before adding the clock stuff. So right now all of the hour digits function perfectly, the first digit of minutes work except for 4 and 5, and none of the right minute digits work.
Any insight into this problem that is driving me crazy would be much appreciated.

Post a working example. Tell exactly what line change the sketch operation.

Have you checked the memory status (build, run-time, etc)?

Just 256 LEDs and 402 numbers in those int arrays = ~1.572kB of memory. An Uno has only 2kB of memory.

The code linked has the problematic lines commented out and works, those lines are 317, 326, 339, 348, 357, 366, 375, 384, 393, 402, 411, 420. And the code uploads to the board fine, says it only uses 31% of program space and 54% of dynamic memory. Should I try a larger board?

It looks like a memory problem, and using the String class probably does not help...

Commenting out the Strings does not solve the problem. I will try a larger board I guess, but I don't understand how it can be a memory problem when the IDE says it has so much memory remaining?


text:
Arduino Yun connection problems
I followed this guide and evertything works until I'm at chapter Configuring the onboard WiFi.
I can see the arduino as an AP.

And I can connect with it. However when entering the IP adress 192.168.240.1 or arduino.local it does not give me the login page.
When using the IP adress I get: the site is not accessable screen. Using arduino.local gives me a page that loads forever for a long time before giving me the exact same result.

I have looked on different forums for a solution. This one said that I should download bonjour and bonjour browser because they use the same port (port 5353). After installing the bonjour browser I should be seeing a connection called .arduino._tcp but I don't see that. In fact I often can't see any connection what so ever.

and sometimes I can see a few connections but none of those are the arduino.

I have tried to ping with the arduino on the adress 192.168.240.1 but all I got was a time out.
Pinging 192.168.240.1 with 32 bytes of data:
Request timed out.

Edit : I managed to get the bonjour browser to work all the time, by installing itunes. It also shows the arduino.

Have you confirmed that your computer has been given a correct IP address on the right subnet through DHCP?

Yes i have checked that. also i just tried to do it on another computer and it seems to work with that computer.

So this is a problem with your computer then, not the Yun. I suggest disabling all firewalls and antivirus products and trying again.

Please add a screenshot of WI-FI connection properties. You must be connected to the Arduino-Yun network and not WiFi-2.4-2348_EXT.

@AltAir i replaced the screenshot

@Majenko I disabled all firewalls and disabled my antivirus, still didn't manage to load the page

You have to find IP address of your Yùn on your local network.
What I do in this case:
- look on the Home router if you can see your Yùn and it's ip, or,
- there is a sketch in Arduino Ide / exemple / bridge / wifi status which can help you to get ip, or
-  open the Arduino Ide software, upload serialTerminal sketch and open serial monitor. It allows you to access the Linux part of the Yùn and type 'ifconfig' to get the IP from the Yùn.

Well as you can see on the last screenshot I made the ip is 192.168.240.1

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


text:
For loop not running
I've been trying to get a for loop to run 9 times using the below code but can't get the loop to run.
void output() {
  int r;
  r = 1;
  Serial.println("Output");
  digitalWrite(Latch, LOW);
  for (int r=1; r >= 9;  r = r + 1) {
    Serial.println("Test");
    digitalWrite(DataOutput, Q[r]);
    digitalWrite(ClockPin, HIGH);
    digitalWrite(ClockPin, LOW);
  }
  Serial.println("Done For");
  digitalWrite(Latch, HIGH);
  digitalWrite(Latch, LOW);
}

Change
for (int r=1; r >= 9;  r = r + 1) {

to
for (int r=1; r <= 9;  r = r + 1) {

The for loop will only run while the second part is true.

The middle expression r => 9 in the for loop is wrong. This will only loop whilst r is greater than 9 and you are starting from r = 1. Change it to r <= 9.


text:
Is my Arduino Micro bricked?
A few weeks ago I built my own Arduino Micro. Everything worked fine and it connects every time. I have built a second one, with the exact same processor schematic as the first one. It turns on, and I was able to bootload it with an Arduino Uno, just like the first one. But it will not connect to my computer.
When I plug it into my PC, the lights flash on but I get nothing. It does not show up in device manager anywhere, and its like I plugged nothing in, in the first place.
When I plug in my other Arduino Micro it works fine. But this one does not. I have tried switch PCB's (maybe the first one was bad) but nothing seems to work. I have even switched the ATMega32U4, but I still get the same issue.
When I connect my multimeter to the USB port and the corresponding D+ and D- pins on the processor, I get that there is resistance and there are no crossed connections.
I feel that at least the computer should say "Device not recognized," but I just get nothing. Is my Arduino bricked? Has anyone else had a similar problem?

I was able to bootload it ... are you really sure?

Yes I am really sure, the bootloader said done in Arduino and the Blink Sketch started running. Even if it wasn't bootloaded the ATMega32U4 should still show up in device manager.

have you tried another usb cable? ....... unplug all arduinos from the computer. remove the arduino micro driver by using the windows device manager, then plug in the bad arduino, to see if it may enumerate correctly. it is possible that windows will not talk to the second arduino because it is detecting something that does not match the first arduino (windows is pretty weird when it comes to USB devices)

Be sure to check out the answers on a very similar question: Have I bricked my Arduino Uno Problems with uploading to board


text:
Are lambdas a good way to improve readability in this instance?
Disclaimer: The following code hasn't been compiled, and probably won't work in any way.  This is just for opinions relating to this Arduino question as I'm still learning and experimenting with different coding techniques.
As I understand it (and please feel free to offer a (4.)), the following code could be written in numerous ways, including:

No lambdas, and each following lambda as a separate function of its own.
No lambdas, no external functions, and having it all flow within the same function.
Using lambdas in a similar way to the code provided below.
?

As my programs are getting sizeable, I'm currently finding it difficult to keep track using (1.) and/or (2.) when writing programs, especially if bugs show up. This has led me to question if there was a way to reduce a great many if and for (etc) into a single, text-editor-foldable "seed" (i.e. a single variable).
In my original question it was suggested that a possible way to do this could be option (3.) using lambdas.  However, it was also pointed out that it may be overkill/not practical, and without any examples of what I'm trying to achieve, it was difficult to make a more informed judgement. So with this in mind, I have thrown together an example showing how lambdas could help me achieve some readability to my code.
If this is an acceptable technique, or not, I would be extremely grateful for any advice.
Code, lambda example, unfolded:
// Structs data, fans;
void temperatures(int _temperaturePin) {

  data.cTemp = [](int _tPin) { // current temperature
    float _finalReading = 0.0f;
    for (int i = 0; i < temperatureResolution; i++) {
      float _currentReading = analogRead(_tPin);
      _finalReading += ( 10000 / ( ( 1023 / _currentReading ) - 1 ) );
    }
    _finalReading = (_finalReading / temperatureResolution);
    return (uint8_t)_finalReading;
  }(_temperaturePin);

  bool fanState = []( int rOne, int rTwo, int rThree ) { // fans on or off
    int _lowMin = data.tempTarget - ((data.tempTarget - data.tempMin) / 2);
    int _medMax = data.tempTarget + (( data.tempMax - data.tempTarget) / 2);
    bool _fanState = false;
    if (data.cTemp < data.minTemp) {
      digitalWrite(rOne, LOW);
      digitalWrite(rTwo, LOW);
      fans.off = !_fanState;
    } else {
      _fanState = true;
    }
    if ((data.cTemp > data.tempMin) && (data.cTemp > _lowMin)) {
      digitalWrite(rOne, LOW);
      digitalWrite(rTwo, HIGH);
      fans.low = _fanState;
    }
    if ((data.cTemp < data.tempTarget) && (data.cTemp < _medMax)) {
      digitalWrite(rOne, HIGH);
      digitalWrite(rThree, LOW);
      fans.medium = _fanState;
    }
    if (data.cTemp > data.tempMax) {
      digitalWrite(rOne, HIGH);
      digitalWrite(rThree, HIGH);
      fans.high = _fanState;
    }
    return _fanState;
  } (relayOne, relayTwo, relayThree);

  bool overloadProtection = [](bool _fState, int _lCount, int rCount) { // overload protection on or off
    bool _protect;
    int _pwmValue = 255;
    if (_fState) {
      _protect = ((_lCount > MAXLEDS) || ((_lCount > (MAXLEDS / 2) && (_rCount > MAXRELAYS) ))) ? true : false;
    }
    if (_protect) {
      for (int i = 0; i < _lCount; i++) {
        _pwmValue -= 10;
      }
    }
    for (int i = 0; i < _lCount; i++) {
      if (ledPins[i] == HIGH) {
        analogWrite(ledPins[i], _pwmValue);
      } else {
        digitalWrite(ledPins[i], LOW);
      }
    }
    return _protect;
  }(fanState, sizeof(ledPins), sizeof(relayPins);
}

Code, lambda example, folded:

I can see that methods vs lambdas don't appear to make a huge difference to overall word count in this case, however, I can happily fold away temperatures() and know that's the root of everything I need for anything temperature related (without having to break off into another library; as far as I am aware), instead of having potentially 3 more functions sitting there and cluttering up screen space.
This also makes working within temperatures() a less daunting task than having potentially 100's of for and if (etc) statements permanently in view.
I'm only a hobbyist programmer at the moment, learning in my own time with no formal programming education, so I am 100% completely open to any suggestions or advice, especially due to ignorance regarding this subject on my part.
Much appreciated!
P.S. codereview.stackexchange requires working code to post there otherwise I would have.

You can also use UECIDE instead of Arduino IDE. With UECIDE you don't need to open all source files in you project.

I currently use Atom as it allows split windows in both horizontal and vertical directions at the same time, and Notepad++ for single/double files. I only tend to use the normal IDE to compile and debug and write the *.ino.  UECIDE didn't work when I tried it (~2 years ago though maybe?), I'll definitely have another look, anything should beat the normal IDE! thanks!

I use UECIDE, but keep Arduino IDE mostly to do OTA upgrades to my NodeMCU projects.

Standard method using normal functions
Quickly tell me, what does the temperature() function do?
// Structs data, fans;
void temperatures(int _temperaturePin)
{
  data.cTemp = getTemperature(_temperaturePin);
  bool fanState = getFanState(relayOne, relayTwo, relayThree);
  bool overloadProtection = getOverloadProtecton(fanState, sizeof(ledPins), sizeof(relayPins);
}

Well, it get the temperature, fan status and overload protection status. No need to know about lambdas, or even know C/C++: if you know any programming language (PHP, Javascript), you will able to understand what this code do.
Of course, getTemperature and others are implemented as traditional functions elsewhere. It's not important or relevant to know how they work, just what they do/return. I can write it in another source file and forget about them, never to be seen again.
Lamba method
Same question (with your original code), what does the temperature() function do?
   // Structs data, fans;

    void temperatures(int _temperaturePin) {

      data.cTemp = [](int _tPin) { // current temperature
        float _finalReading = 0.0f;
        for (int i = 0; i < temperatureResolution; i++) {
          float _currentReading = analogRead(_tPin);
          _finalReading += ( 10000 / ( ( 1023 / _currentReading ) - 1 ) );
        }
        _finalReading = (_finalReading / temperatureResolution);
        return (uint8_t)_finalReading;
      }(_temperaturePin);
// More code ...

You have made one giant monolithic block of code, which is anatema by any standard. And code folding doesn't really solve that.
This not so easy to read. You have to scan searching for the each lambda end, taking mental notes about what is finally executing inside temperatures(). To much work, to much visual clutter, merging the what to do with the how to do it.
Think about testing. How do you test your lambdas? You can't do it easily. You need to extract the code from your application, to start with. And add all those external variables your are accessing from inside the lambda.
With traditional functions, no need to change your application to test your functions; just write a test program to exercise your code.
Think about code reuse. It's dificult with your code identify common code to refactor/reuse it.

Eventually it will be along the lines of, Computer computerOne; then computerOne.oledUpdate(temperatures(), timeAndDate(), etc() ).  All my previous iterations are becoming method/library nightmares, it would be nice to just have everything I need in less functions with less abstraction.  For myself personally, it's perfectly readable so far, and takes up much less screen space.  I will be using the "normal" way (how you have done it) within setup() and loop() mostly.

In addition to Computer, I also have Room which contains DomesticRooms, OfficeRooms, Car, and a load of other libraries, with Computer one of the sub libraries already.  My aim was to hopefully at least remove something from the amount of files and functions I am ending up with.  It's becoming extremely difficult having only 4 editing windows open at once on one screen.  I suppose my aim is to reduce the amount of files, and to reduce the amount of methods within each file; unless of course this is normal?

There is a reason, why the lambda concept was added to the C++ standard. This isn't it. This is called obfuscation.
void temperatures(int pin)
{
  // read the temperature with higher precision than single adc read:
  data.cTemp = 0.0f;
  for (int i = 0; i < temperatureResolution; i++) {
    data.cTemp += ( 10000 / ( ( 1023.0 / analogRead(pin) ) - 1 ) );
  }
  data.cTemp /= temperatureResolution;

Even this is a much better than misusing the lambda.
The main goal should be readability (= self docummented code), so anyone can quickly understand what is going on there.
That is also one of the reasons why the functions exists. The primary goal is you don't have to use the same snippets of code again and again (copy-paste). Try to fix the same bug on many places instead of one function.
In this code you should learn about concepts of finite state machines and ring buffers/floating averages, ...
Anyway, I've always hated parts of code in 10000 lines long file with only two methods or so. It's freaking hell to maintain that kind of code. Yes, having many tabs is also hard, but not harder than scrolling in mile long file. (I hate folding)

I was just trying to see if I could get around having to turn yet another group of methods into another library/lists of other methods.  The example above is what I "quickly" threw together as I've essentially turned 3 methods into one, I could in effect turn 100's of methods into one without having to make a library (but never would do that).  My real code is massive, and is becoming a huge struggle to keep track of easily - I was just after a way to remove long files, or loads of files that are more focused. - I'm struggling with finding that balance.

@Timeless I'm tending to use loads of files (almost like in Java - one file per class but I keep subclasses inside of class) to keep simple responsibility of classes / files.

Same as what I have been doing, so much fun :D Oh well, I'm glad Articy Draft exists, it's extremely helpful for pre-planning file structures sometimes