text:
What programming practices should be adopted while coding sketches for Arduino?
What are some of the best programming practices that can be adopted while coding sketches for Arduino, so that it uses the least memory and performance should not suffer from memory outage, and still the code be robust?
From the link: https://www.arduino.cc/en/Products/Compare
I have learned that the Uno has 32 KB of Flash memory. The maximum available is in the MEGA with 256 KB. I think Uno and Mega are the most widely used by people.

First off, I'd consider NOT using Arduino library and directly use AVR C library, as Arduino adds a lot of code to simplify programming, but not necessary once you know AVR MCU. This is what I'm trying to achieve in https://github.com/jfpoilpret/fast-arduino-lib optimized library

Paul covered the most important points. This answer is intended to be a
complement to his.
First, you should keep in mind the general rules, which are more
important than the more specific ones. The general rule for saving RAM
is: be aware of what you are storing, and do not store anything you do
not really need. The general rule for saving flash is: be aware of what
you are doing, and do not do anything you do not really need.
Now, a few specific tips:
Use the const qualifier for declaring constants (e.g.
const int ledPin = 13;). The compiler will optimize-out the storage of
the constant and use immediate addressing instead.
Use PROGMEM for arrays of constants.
Whenever possible, use static memory (globals and static locals)
rather than heap allocation (malloc() and new). This will prevent
memory fragmentation and make the memory usage more predictable (only
the stack holds dynamic memory): you know at compile time, rather than
run time, whether you are low in RAM.
For the same reason, prefer C strings (char *) over String objects.
Use the C99 types int8_t and uint8_t whenever 8 bits are enough for
your integer variables.
Use the static qualifier for functions that will be used only in the
same source file, especially for functions that are called only from one
place. This gives the compiler more optimization opportunities.
If you need to optimize,
use avr-nm to know what is
consuming your precious RAM.

just out of curiosity @Edgar , is 'const int ledPin = 13' use the same memory size as const char ledPin = 13' ?

@dhimaspw: In my tests, yes, the size and the generated assembly are the same. In both cases, digitalWrite(ledPin, HIGH); compiles to ldi r22, 1 $ ldi r24, 13 $ call digitalWrite. Here, ldi means “load an immediate value into a register”, i.e. the value given as the second argument (1 for HIGH or 13 for ledPin) is part of the instruction itself.

Keep in mind that RAM is even less. 32KB is a fair lot of code, since C/C++ is highly efficient. "Don't save **** in RAM."
If you need to load images into a display, save the images on an SD card. And "stream" it to the display. You can read and transmit the bytes one by one, or 10 by 10 or something.
Also, if you need long strings, you can use the "flashStringHelper" to store the string in flash memory. For example: println(F(”Error message: Couldn't connect to server));. By using F() around the string, you save valuable bytes.
Not using Arduino code, but pure AVR-C/C++, can save you a little also. (Will also save the bootloader piece of memory, if you program directly with a programmer.)
If you use Arduino, know how it works. The Arduino serial library uses ~256 or 500 bytes (I believe) as a buffer. You can change this if you need it for other applications.
Keep in mind that your saving technique depends on what resources are low. If you need to do a lot simultaneously, it's better to write non-blocking code.
But also remember: Don't optimize unless it's actually needed! Or, actually set measurable and realistic requirements, optimizing something to be "as fast as possible" can take infinite amounts of time... Run a google search on "premature optimization" as the old folks in the field like to call it.

I agree with part premature optimisation is mother of all evils , I have read it before however the point of start looking into optimisation comes when you start seeing low memory warning while uploading to Arduino

@Ciastopiekarz That's complete nonsense, I am afraid. A mis-quote of a partial excerpt from a perfectly good quote. Good software design includes a certain level of optimization right from the start. What is "evil" is spending many man hours doing pointless micro-optimization of small bits of code. When that statement was first quoted "optimization" meant something completely different to what it does today, yet it is still erroneously spouted as a reason to not bother doing any optimization at all, and you end up with Windows applications.

Windows application

@Ciastopiekarz Have you ever noticed how things like Office run at about the same speed with a modern version on a 3GHz i7 as old versions ran on a 33MHz 486? They spread to fill the available space, but there hasn't been much change in functionality... Bloat is a blight. Interesting article: http://ubiquity.acm.org/article.cfm?id=1513451

@Ciastopiekarz If you share and explain your sketch (and the debug output, which states how many bytes have been used from what memory) we could try and point out where it could be optimized. Often, it's just the whole approach that is ineffective/inefficient.

Like using NeoPixels; to color them, you'll have to save the whole ledstrip in  RAM, using 3bytes per pixel. Which is a 3.000bytes for a 1000pixel strip. The library is heavily optimized, but it performs like sh*t and only causes issues on other platforms. But still they're heavily popular...

Using a ledstrip that can work with SPI, allows you to set the pixels one-by-one. So you can calculate what your next color will be inbetween setting the colors. Making nice rainbow effects with virtually endless amounts of pixels. And they're bound to work flawless on other architectures (Raspberry Pi, ESP8266) since they don't require strict timing. Using only one pin more to indicate the timing... they deserve more hype ;D
My point is; optimize where it makes sense. If something proves to be inefficient, you may check to replace it instead of spending hours of optimizing it.

Well,  my question is more in general, the reason is  while programming in python I am strictly trying to confine to PEP rules. And now just recently I have stepped in writing  Arduino sketch so I am wondering if there is something for Arduino programmers too

@Majenko I believe you maybe that's why they stopped IE and came with Edge , but its been I have used windows now

PEP rules don't really "optimize" code afaik. Arduino is based on C/C++, and there are an awfull lot of styleguides in C++. But you should pick one that matches your problem as well, the JSF C++ styleguide is very interesting, since it's aimed on military aviation and thus extremely strict. http://www.stroustrup.com/JSF-AV-rules.pdf but using it in an Arduino hobby project is a bit overkill ;) You can check through it, since it's rather interesting though.

Also, IMHO, now web developers also have to worry about Edge AND Internet Explorer, which isn't a very nice effect.
Majenko meant that, given better hardware, software is likely to get "worse" (optimized). Since the new Word versions run no faster on new PC's as the old versions did on old PC's.

@Paul  I will put a code review once I am done and share the link on this page


text:
How to convert Arduino GSR values to microsiemens?
In my project Arduino provides value range between 0-1024. I need to convert this serial value to a standard µSiemens value to measure emotional stress.
Can anybody point me to an answer that would give an appropriate equation for the conversion?

You understand that the ADC measures voltage, right?

A Siemens (aka a Mho) is a unit of conductance, the inverse of resistance.
You have a measure of the voltage (A/D value) between the pads so you can find voltage. You'll also need to know the current between the pads.
Convert your A/D reading into voltage and use that and the current to find resistance (using Ohm's law), and the reciprocal of the resistance is in Siemens. 1 Siemens == 1,000,000 uSiemens.
https://en.wikipedia.org/wiki/Siemens_(unit)

source: Stack Exchange

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

sort: votes


text:
Arduino Mega web server always returning JSON data even if JSON is not passed in URL
I am trying to return JSON data if JSON is found in the HTTP header, and if not I am trying to display a normal page. But instead it always displays the JSON text, even if I do not pass the JSON in the URL! Full code is here.
if (client) {
  // an http request ends with a blank line
  boolean currentLineIsBlank = true;
  boolean sentHeader = false;
  while (client.connected()) {
    if (client.available()) {
      // client data available to read
      char c = client.read(); // read 1 byte (character) from client
      // buffer first part of HTTP request in HTTP_req array (string)
      // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
      if (req_index < (REQ_BUF_SZ - 1)) {
        HTTP_req[req_index] = c; // save HTTP request character
        req_index++;
      }
      // last line of client request is blank and ends with \n
      // respond to client only after last line received
      if (c == '\n' && currentLineIsBlank) {
        if (!sentHeader) {
          // send a standard http response header
          client.println(F("HTTP/1.1 200 OK"));
        }
        // Ajax request - send JSON output
        if (util::StrContains(HTTP_req, "json")) {
          // Spit out JSON data
          client.println("Content-Type: application/json;charset=utf-8");
          client.println("Server: ArduinoMega");
          client.println("Connnection: close");
          client.println();
          client.print("{\"arduino\":[{\"location\":\"outdoor\",\"celsius\":\"");
          client.print(tempInC);
          client.print("\"}]}");
          client.println();
          break;
        } else {
          client.println(F("Content-Type: text/html"));
          client.println(F("Connection: close")); // the connection will be closed after completion of the response
          client.println(F("Refresh: 1000")); // refresh the page automatically every 60 sec
          client.println();
          sentHeader = true;
          client.println(F("<!DOCTYPE HTML>"));
          client.println(F("<title>"));
          client.println(F("Welcome to Arduino WebServer</title>"));
          util::printProgStr(client, htmlStyleMultiline );
          client.println(F(""));
          client.println(c);
          client.print(F("
 LIVE:
"));

Please help.

You should output the contents of HTTP_req to see where/if json is in it.

If I run URL in browser without json text in it then how from where json will come on HTTP_req

@Musa even if I do not pass json it returns json
HTTP_req GET /json HTTP/1.1 Host: 192.168.1.177:8090 U

I see a json in there, you just check the whole thing you should be only checking the url parameters

even if I do not pass json in the url parameters i still get json in HTTP_req

okay, so if you go to http://192.168.1.177:8090/ you still see json in HTTP_req?

Let us continue this discussion in chat.

So figured out the problem, the issue was  I was closing the connection instead when it was json fetched, I had to keep alive the connection.
so replaced client.println("Connnection: close"); with  client.println("Connection: keep-alive");
which fixed the problem.

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


text:
How to pass JsonObject from ArduinoJson to ESP8266WebServer object?
I am learning the ArduinoJson.h library and creating jsonOject:
JsonObject& prepareResponse(JsonBuffer& jsonBuffer) {
  JsonObject& root = jsonBuffer.createObject();
  JsonArray& tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray& humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray& dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray& EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);
  return root;
}

As per the example given here. However since I am using an ESP8266WebServer to create a server object from ESP8266WebServer.h, I cannot pass a JsonObject to server.send(.....).

no matching function for call to 'ESP8266WebServer::send(int, const
  char [10], ArduinoJson::JsonObject&)'

void outputJson() {
  StaticJsonBuffer<500> jsonBuffer;
  JsonObject& json = prepareResponse(jsonBuffer);
  writeResponse(client, json);
  server.send ( 200, "text/json", json );
}

void writeResponse(WiFiClient& clnt, JsonObject& json) {
  clnt.println("HTTP/1.1 200 OK");
  clnt.println("Content-Type: application/json");
  clnt.println("Access-Control-Allow-Origin: *");
  clnt.println("Connection: close");
  clnt.println();
  json.prettyPrintTo(clnt);
}

As far as I know, the only way is to serialize the JsonObject to a String:
String createJsonResponse() {
  StaticJsonBuffer<500> jsonBuffer;

  JsonObject &root = jsonBuffer.createObject();
  JsonArray &tempValues = root.createNestedArray("temperature");
  tempValues.add(t);
  JsonArray &humiValues = root.createNestedArray("humidity");
  humiValues.add(h);
  JsonArray &dewpValues = root.createNestedArray("dewpoint");
  dewpValues.add(pfDew);
  JsonArray &EsPvValues = root.createNestedArray("systemv");
  EsPvValues.add(pfVcc / 1000, 3);

  String json;
  root.prettyPrintTo(json);
  return json;
}

void outputJson() {
    server.send(200, "text/json", createJsonResponse());
}

By the way, I recommend that you use the ArduinoJson Assistant to compute the size of the JsonBuffer.

thanks I did tried the suggested already but forgot to get rid of the other stuff from outputJson. Thank you very much . greatly appreciated (y)


text:
Avoid global variables with classes
I want to avoid global variables when using my own classes in Arduino. Here is a example.
void setup(){
/* setup here */
  classA objectA;
}

void loop(){
  objectA.someMethod();
}

I know that my compiler will complain about it (out of scope, etc) but is it possible to do that or just forget it and use globally?
Thanks in advance!

Use globals. They're the recommended way. There are other ways, but global static declaration is the right way of doing it.

@Majenko even if my classes getting bigger? I don't have to worry about that?

Even if your classes getting bigger. By declaring it as a global with static declaration (MyClass foo;) you are reserving the RAM at compilation time. All other ways of doing it involve dynamic RAM allocation and that is bad on a microcontroller.

@majenko Are you familiar with any patterns to help organize larger, non-trivial programs?  Polluting the global space is frowned upon in most other problem domains.

A program small enough to fit in the Arduino Uno is probably too small for global name space pollution to be a very serious concern. By using objects, you are already in a sense organizing the name space. If you do worry about your global name space, you could put all your globals in their own name space, or inside a big “app” object.

If you want a variable to be available within more than one function it has to be global. There is no other possible way of doing it.
If you are only using the variable in the loop() function and nowhere else you can declare it static in loop(), which has the same effect of making it global, but it is only possible to see it within loop().
You can make a pointer global, then create a new object in setup() (using new...) and assign it to the pointer, but that has the potential of making a mess of your heap and should be avoided unless absolutely necessary. Also it's pointless, because you don't gain anything over having the object statically created in the global scope.

Seems enough for me. You convinced me! :)

I read to avoid new and delete when coding for arduino. It is not my priority. I am just curious if is possible to do what I asked.

You still end up with a global variable, just a different type of variable.

This answer isn't satisfying.  There has to be a way to balance programmer efficiency (e.g. organize logical bits of code in classes) with memory constraints.  Is there not a compiler that can optimize the end-product in the global namespace way you suggest, but also provide the developer-friendly code organization that @marquesm91 is asking for?

It is worth noting that the global constructors get called before the initializations done by the Arduino core and setup(). That's why many standard objects have a begin() method to do any initialization that needs to be deferred until the core is ready.

@AndrewAllbright: The C++ compilers have a namespace keyword.

You could completely ignore the global space and the setup() function and just treat loop() like main(). Stick a while(1) at the end of loop() to stop it looping, define all your variables as local to loop(), then pass them all as parameters to where they are going. What do you end up with? You end up with global now inside loop() and allocated on the stack instead of the BSS. Big deal. Just stick with global, it's easier.


text:
Is it possible to execute a code in runtime when gets updated over the air (OTA)?
I would like to build a lib like ArduinoOTA but with no downtime at runtime. To achieve that I am wondering if it is possible to create a simple setup and loop code to

Check for new releases
If we have a new one start download it
As download routine is not finished keep running the current release
When download has finished, swap current release to the new one.
Now the normal routine is running the new release.

I am pretty interested if it is possible to do by myself something like that.
I didn't find any paper or articles similar to this and I don't known if this is a challenge for Arduino scope or C/C++.
Maybe I am saying something bizarre but I have been thinking of save new release into flash memory, point to it and discard the old release from flash memory.

On an 8-bit Arduino? No. Or certainly not without a huge amount of work.

what are you trying to achieve? ... maybe it can be done without reflashing the program

@jsotola I am trying to deploy releases over the air without downtime in the middle of this process. That is, I want to download a new release from Internet and keep running the old one until the new has been downloaded.

that does not actually answer the question, it is a repeat of your question .... is it possible that an "update" could involve changing only some parameters that could be read from an online server

The "update" I am talking about is a new version of the current sketch previously uploaded to Arduino manually.

but the new sketch doesn't have everything on the same address. how will the instruction pointer be set to a good address. and what will initialize the new variables. reset is necessary

and about what MCU is it?

@Juraj Hmm make sense! Do you have any paper a could read for something like that? These questions is for my final paper and I am trying to do update OTA like we see in Web or Apps. It would be awesome if we have the same in IoT ecosystem.

The MCU will be an Arduino or ESP8266. I read both use Modified Harvard Architecture and can share instruction and data code. But you have a point when saying the MCU will don't know how to know the complete path for instruction pointer

Sorry. ESP8266 ESP-01

esp8266 has ArduinoOTA library supported by the  SDK. for SAMD Arduino has OTA anf I made this kind of OTA for ATmega  https://github.com/jandrassy/ArduinoOTA

On many Arduinos the processor is only a few dollar part.  You are asking for a feature that only starts appearing on platforms where the processor is over an order of magnitude higher in price.  Further, such inexpensive processors normally run a single program.  Running a sketch while managing a download & update would best be done by two programs existing in an operating system.  Again, likely requiring a processor an order of magnitude higher in price.
Instead, consider implementing your design using two different Arduinos.  Swapping one out for the other after updating.   Hot swapping may not be trivial.  This really depends on how your application interfaces with the world. But likely will be much easier than solving the problem of designing the supporting software to make sketch updates transparent to the Arduino user.

This is honestly the most simple and yet fun to implement. It is not be a perfect solution but definitely could attend me. Thank you so much for that!

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


text:
Uno Wifi Rev2 Programming via Uno R3 ArduinoISP
I'm attempting to program Atmega4809 (Uno Wifi Rev2) via the ICSP pins on the board by connecting in this manner:
The difference is that I have a Uno Wifi Rev2 on the right instead of a Uno R3. I've uploaded the ArduinoISP sketch onto the Uno R3 on the left. Here is the avrdude command that I am using:
$ avrdude -v -patmega4809 -cavrisp -P /dev/ttyACM1 -b19200 -U program.elf

...

avrdude: AVR device initialized and ready to accept instructions

Reading |                                                    | 0% 0.00savr_read(): error reading address 0x0000
    read operation not supported for memory "signature"
avrdude: error reading signature data for part "ATmega4809", rc=-2
avrdude: error reading signature data, rc=-2

Full log: https://pastebin.com/LUfhsYeD
I am wondering if I am missing some difference between the UnoR3 and Uno Wifi Rev2... there doesn't seem to be much documentation about external programming of the Uno Wifi Rev2's Atmega 4809.
If it helps, my usecase for trying to program my Uno Wifi Rev2 externally is a need to reprogram the 32u4 as a HID. Once I program the 32u4, I won't be able to program the 4809 via USB (afaik).
If anyone knows what I'm doing wrong or the proper way to program the Uno Wifi Rev2 externally, your help would be greatly appreciated.

those are not ICSP pins. there is only SPI. the USB chip (32u4) programs the ATmega over UDPI

The new generation of AVR chips created by Microchip no longer use the same ICSP protocol as the old ones. Instead they use a new protocol called updi.
You need to use a different sketch and wiring to turn your Arduino into a suitable programmer.  More information can be found here about how to do that.

Do the 6 pins labeled ICSP really use UDPI? Is the programming still over these pins? In the schematic, I see a UDPI pin that goes from the 4809 to the 32u4...

You will have to check the schematics and datasheet for the chip to know what pins to use.

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


text:
Firmware for Atmega32u4 on the Arduino Uno Wifi Rev2 (causing upload issues)
I reprogrammed the Atmega32u4 on my Arduino Uno Wifi Rev2 in order to use it as a human interface device, but I am now having difficulty programming the 4809 (through the 32u4 over UPDI) with the Arduino software. I have tried reprogramming the 32u4 with medbg_updi.hex from Atmel Studio and also Xplained Yourself Firmware from https://hackaday.io/project/162372-xplained-yourself.
I have had some success writing some smaller applications to the 4809 but when I try to program larger applications (which used to work before I fiddled with the 32u4), I now get verification error saying that there is a mismatch.
avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0200
         0x08 != 0x0c
avrdude: verification error; content mismatch
avrdude: jtag3_edbg_signoff(): unexpected response 0x03, 0x80

When cross referencing with other working Uno Wifi Rev2 boards, they have
ICE firmware version: 1.19 (rel. 57)

while I now apparently have
ICE firmware version: 1.13 (rel. 43)

I do not see any place to find the updated/original firmware which came with my arduino. My thought is that the firmware is not available for direct download because it may be licensed from Microchip (Atmel) and not distributed/proprietary...
Please assist me if possible in restoring the full functionality of my Arduino Uno Wifi Rev2. Any insights would be appreciated.

look on the Arduino IDE directory tree .... on my PC the firmware is at arduino-1.8.12\hardware\arduino\avr\firmwares

@jsotola, that is for Uno not for Uno WiFi Rev 2 with a 4809


text:
ESP8266 - Problem with LittleFS after reboot (solved in comments)
I'm trying to create an even log saved on flash.
I try to make it a class, called flashLOG as shown. Code behaves as expceted, reads, writes and  posts it size and entries.
The problem is that after reboot - it seems that the file "disappears".
Code is written based on the Arduino IDE example. First I thought it is a flash problem, but after flashing Arduino's example and tried to run my code on an other MCU - it seems there no physical problem with flash.
I tried to reduce most of my code only to write "events" in order to see what survives reboot - so please ignore commented out lines and some logic in reading text, in code attached.
The only thing came in mind-  perhaps it  has something to do with being in a class or inside a library.
Appreciate any help finding this bug
**EDIT 1: ** Update .h file and .ino fil
.h file
class flashLOG {
private:
    char *_logfilename = "/logfile.txt";
    const static int _logsize = 5;     // entries
    const static int _log_length = 20; // chars in each entry
    char _log_array[_logsize][_log_length];
public:
    flashLOG(char *filename = "/logfile.txt");
    void start();
    void read();
    void write(const char *message);
    void append(const char *message);
    void postlog(int x);
    int sizelog();
};

.cpp file:
flashLOG::flashLOG(char *filename)
{
    _logfilename = filename;
}
void flashLOG::start() {
    if (!LittleFS.begin())
    {
        Serial.println("LittleFS mount failed");
    }
    else {
        Serial.println("MOUNTED OK");
    }
}
void flashLOG::read() {
    int r = 0;
    int c = 0;

    File file = LittleFS.open(_logfilename, "r");
    if (!file)
    {
        Serial.println("Failed to open file for reading");
    }
    else {
        while (file.available())
        {
            char tt = file.read();
            //     if (tt != '\n')
            //     {
            //         _log_array[r][c] = tt;
            //         c++;
            //     }
            //     else
            //     {
            //         _log_array[r][c] = '\n';
            //         r++;
            //         c = 0;
            //         // Serial.println(_log_array[r-1]);
            //     }
            Serial.write(tt);
        }
    }
    file.close();
    //     return r;

}
void flashLOG::write(const char *message)
{
    char a[_log_length];
    //     sprintf(a, "%s\n", message);

    File file = LittleFS.open(_logfilename, "a");
    if (!file)
    {
        Serial.println("Failed to open file for appending");
    }
    else {
        if (file.print(message)) {
            Serial.println("Append OK");
        }
        else {
            Serial.println("Append fail");
        }
    }
    Serial.printf("file size: %d\n", file.size());
    delay(2000);
    file.close();
}
void flashLOG::append(const char *message)
{
    char a[_log_length];
    //     sprintf(a, "%s\n", message);

    File file = LittleFS.open(_logfilename, "a");
    if (!file)
    {
        Serial.println("Failed to open file for appending");
    }
    else {
        if (file.print(message)) {
            Serial.println("Append OK");
        }
        else {
            Serial.println("Append fail");
        }
    }
    Serial.printf("file size: %d\n", file.size());
    //     delay(2000);
    file.close();
}
void flashLOG::postlog(int x)
{
    int num_lines = 0;//read();
    int y = min(x, num_lines);
    for (int a = 0; a < y; a++)
    {
        if (y > 1)
        {
            char t[_log_length];
            sprintf(t, "[#%d] %s", a, _log_array[a]);
            Serial.println(t);
        }
        else
        {
            Serial.println(_log_array[a]);
        }
    }
}
int flashLOG::sizelog()
{
    File file = LittleFS.open(_logfilename, "r");
    int f=file.size();
    file.close();
    return f;
}

.ino file
#include <myIOT.h>
#include <Arduino.h>

flashLOG flog;
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("\nBEGIN!");
  flog.start();
//  flog.write("HITHERE");
  flog.read();
  flog.append("HITHERE2");
//  flog.read();

}

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

}

Without the class header, and preferably some skeleton code that demonstrates how you are using it, it's hard to tell exactly what is happening. For example, are you working from example code that formats the LittleFS file system every time setup() runs? In trying to reverse-engineer the code, I came up with this, and it is working correctly in that there is data after every restart, and it is valid. the cpp is what you gave above, with my own .h and .ino. If you give more info, I'll do a proper answer.  https://gist.github.com/pfeerick/7230ce3b93c35c8b8feb4e97979ac3f7

Will edit my question soon

@PeterFeerick - edited

Thanks for that. Other than a missing #include <LittleFS.h> it worked - i.e. it was appending. I would suggest that if it is not working for you at all, you've not formatted the LittleFS partition first - look at the sketch at the bottom of the gist linked above. There is also an underlying issue in the code, as after several appends, the code causes an exception, but to be expected if you can't get the initial bits to work!
BEGIN!
MOUNTED OK
HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2HITHERE2Append OK
file size: 104

I added this to the loop... do you get anything after the ESP has restarted with this?
void loop() {   delay(2000);   ESP.restart();   delay(100); }

@PeterFeerick -class is implemneted in another.h file - so you don't see that include you've mentioned ( but it is there ). about the format, I'll try again, but doesn't it when I erase all ( third option in Arduino IDE ), doesn't it also format as needed ? how come it shows file size and read properly but "loses" data only after reboot ??

@PeterFeerick - BTW why did you add another #include<LittleFS in .ino file? ( I know it is for format but after it is formatted once, do you still need it ? )

I can't tell you why it shows file size and read properly but "loses" data only after reboot - perhaps it's only buffered in memory, not saved? Have a look at the output here.
https://gist.github.com/pfeerick/33791f2ddbc70f30a89a590eab71d9a0
hm... begin() is supposed to format if a file system isn't detected... i just did an 'erase all' and re-loaded the sketch minus the format routine, and it got to the append after file size: 104 again and then continuous exceptions again. Very strange.
I added the include because I also format when flashLOG b0rks after several appends

Actually, I'm not sure now... because of how the Arduino IDE preprocessor works, it isn't needed in the sketch... as you can see from the second gist... I didn't add it at all, since it will be included via the flashLOG.h. In reality, since I used it in the sketch main, it should be there as well. For your project, it shouldn't need to be included in the main sketch - just in the class that uses it.

I'm UTC+10, so unfortunately it looks like your work is my late evening. Happy to try and work through this more, just need to find a time that works for both of us ;) Then we can also take it over to the chat thingy (only clicked on it before to see what it was about and because SE was being pushy).

@PeterFeerick - As I told, class was placed in another library ( encapsulate my entire IOT class ). Somehow - I had an instance of a file saving JSON, outside to all classes ( I dont know why I did it ), running FS.h - which caused some collision with LittleFS.h which probaby can't be ran together :).
Thank you very much!

Fantastic. Glad you got it working! It's those seemingly little gremlins that are the most annoying - hard to pin down!

@PeterFeerick - sooooooo annoying. I was so troubled about how without calling any class but the one I need, it failed while in a new library it didn't....URRRGGHH. cheers


text:
Cleaning up code? Removing repetition?
I am using Adafruit motor shield, I am running multiple DC motors for different amounts of time, but to start at the same time - I have researched that to do this I have to monitor the elapsed time of each motor in the loop instead of using the delay to avoid blocking if I want them to run at the same time.
Eventually, There will be around 10 DC motors running off this, however it seems very sloppy to me to have 10 repeat entries of very similar code.
Is there a way to create a class or something for the following code so I am not repeating it all as although it works it seems like the way I am currently doing it is bad practice(?) and could be done more eloquently! Forgive me if this is a strange question as I am new to arduino.
In this example there are only 2 motors, however when it gets to around 10, there will be a lot of code just for this bit!
Any suggestions are welcome.
Thanks in advance.
Example code:
#include <Wire.h>
#include <Adafruit_MotorShield.h>

boolean runMotor1 = false;
boolean Motor1Running = false;
unsigned long Motor1StartMillis;
unsigned long Motor1RunTime = 5000;

boolean runMotor2 = false;
boolean Motor2Running = false;
unsigned long Motor2StartMillis;
unsigned long Motor2RunTime = 10000;

//etc etc etc up to 10 Motors

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *MotorMotor1 = AFMS.getMotor(1);
Adafruit_DCMotor *MotorMotor2 = AFMS.getMotor(2);

void setup()
{
  Serial.begin(9600);
  AFMS.begin();
  runMotor1 = true;  // set condition to true for testing
  runMotor2 = true;
}
void loop()
{
/// Motor1 START
  if (runMotor1 == true) {
     Serial.println("Run Motor 1!");
     runMotor1 = false;
    MotorMotor1->setSpeed(255);
    MotorMotor1->run(FORWARD);
    Motor1StartMillis = millis();
    Motor1Running = true;
  }

  if( Motor1Running && (millis()-Motor1StartMillis > Motor1RunTime) )
  {
    Serial.println("Motor1 Time Elapsed!");
    MotorMotor1->setSpeed(0);
    MotorMotor1->run(RELEASE);
    runMotor1 = false;
    Motor1Running = false;
  }

  /// Motor 2
    if (runMotor2 == true) {
     Serial.println("Run Motor 2!");
     runMotor2 = false;
    MotorMotor2->setSpeed(255);
    MotorMotor2->run(FORWARD);
    Motor2StartMillis = millis();
    Motor2Running = true;
  }

  if( Motor2Running && (millis()-Motor2StartMillis > Motor2RunTime) )
  {
    Serial.println("Motor2 Time Elapsed!");
    MotorMotor2->setSpeed(0);
    MotorMotor2->run(RELEASE);
    runMotor2 = false;
    Motor2Running = false;
  }

}

Thanks for reading, and thank you for any input you may have.
Steve

It's not in the least bit bad practice: that's what classes are for! And it's exactly how the vast majority of all Arduino add-ons, your Adafruit motor shield included, are represented in software.

Yes, I meant, The way I am doing it is bad practice, and should I be using a class or something. Let me change it to clarify :)

Aha! If you can hold on for a few hours I can give you a fuller answer - you might benefit from extending the Adafruit class rather than reinventing the wheel.

You are perfectly right, a class would help simplify your code. Here is
a tentative class that should work for what you are doing:
class Motor
{
public:
    Motor(const char *_name, Adafruit_DCMotor *_motor,
          unsigned long _runTime)
    : name(_name), startNow(false), running(false),
      runTime(_runTime), motor(_motor) { }
    void start() { startNow = true; }
    void update();
private:
    const char *name;
    boolean startNow;
    boolean running;
    unsigned long startTime;
    unsigned long runTime;
    Adafruit_DCMotor *motor;
};

Most of this is almost copy-paste from your actual code, except for your
runMotorX variables that I renamed startNow, which seemed more
appropriate.
Beware that the name of the motor is copied as a pointer. Thus you
should better call the constructor with a literal string (like
"the name") as a first parameter. Otherwise it would be more
appropriate to allocate memory and copy the characters themselves, but I
like to avoid dynamic memory allocation on an Arduino if I can.
Now, all the code that you have in loop() for each motor would be the
Motor's update() method:
void Motor::update()
{
    if (startNow) {
        Serial.print("Run ");
        Serial.print(name);
        Serial.println('!');
        startNow = false;
        motor->setSpeed(255);
        motor->run(FORWARD);
        startTime = millis();
        running = true;
    }

    if (running && (millis()-startTime > runTime))
    {
        Serial.print(name);
        Serial.println(" Time Elapsed!");
        motor->setSpeed(0);
        motor->run(RELEASE);
        running = false;
    }
}

With this class, your code would now look like:
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor m1("Motor 1", AFMS.getMotor(1),  5000);
Motor m2("Motor 2", AFMS.getMotor(2), 10000);
//etc etc etc up to 10 Motors

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    m1.start();
    m2.start();
}

void loop()
{
    m1.update();
    m2.update();
}

Of course, when you get to 10 motors, this would still be annoying
repetition. You can simplify further by putting the motors in an array
and looping through it:
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor motors[] = {
    Motor("Motor 1", AFMS.getMotor(1),  5000),
    Motor("Motor 2", AFMS.getMotor(2), 10000)
    //etc etc etc up to 10 Motors
};
#define NUM_MOTORS (sizeof motors / sizeof motors[0])

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].start();
}

void loop()
{
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].update();
}

Excellent, thanks a lot, this is easy enough to understand and is exactly what I was looking for. Thanks for going the extra mile with the loop example too!


text:
Use of Resistor in PinWheel Exercise
I'm working on project 9 of the Arduino starter kit - the motorized pinwheel.
Here is the schematic:

(if img not showing: https://goo.gl/tqZmKD)
My question is, why is the 10k resistor needed after the switch? Why can't it just go straight to ground? The switch's output just connects to a digital pin, it doesn't care how much voltage there is, correct?
Thank you!
EDIT**: Additional help from the arduino forums:
The resistor is needed so when the switch is closed you don't short the supply
to ground.  Switch open the resistor pulls the signal to ground and no current
flows, when the switch is closed it forms a resistive divider with the 10k
(switch contacts might have 0.01 to 0.1 ohms resistance or so), thus pulling
the signal to Vcc, but with only 0.5mA flowing through the 10k resistor.
Replace the 10k with a wire and you'd simply overload the supply completely and
perhaps weld the switch contacts shut.
Arduino Forums

It's a pull-down resistor.
A pull-up or pull-down resistor is used the make sure that the input of a digital device is confined to strict logic levels, i.e +Vdd (positive, or HIGH) or GND (Ground, or LOW).
With the switch open and no resistor present, the Arduino pin is neither high nor low. It will probably read as low if you tried digitalRead(), but there's no guarantee. The probability of the pin being one or the other changes according to the layout of the PCB and other external factors; the pin is termed 'floating' because it could be at any voltage between Vdd and GND.
However, if you apply a pull-(somewhere) resistor you force the Arduino pin to one of either Vdd (up) or GND (down) until you press the switch, at which point the Arduino pin switches state.
If you removed the resistor and joined the switch directly to ground, what happens when the switch contacts close?
Think about it...
One side of the switch connected to Vdd.
The other side is connected to the Arduino and GND.
Close the switch, I dare you.
Vdd is now connected to GND

Apologies - I didn't understand that. The switch controls whether or not voltage will continue to the green wire and thus, the digital input (in this case, pin 2). If switch is closed, voltage will continue to pin 2 and it will read HIGH. If switch is open, no voltage will pass through and the pin will read LOW. Is this not correct? And thank you for your time!

@ZAR: There is no situation of "no voltage" here; there is either Vdd or there is GND.

Hmm, so how is there voltage if the switch is open and thus not completing the circuit? I thought there would only be current when the switch is pressed, closing the circuit... Clearly I am missing some fundamental knowledge ;)

@ZAR 'no voltage' and zero-volts ARE NOT THE SAME. No voltage is no connection to anything, Zero Volts is connection to ground.

...and a digital pin that is not connected to anything is called floating. Any floating digital input could be either high or low, and you can't guarantee which (unless you read it of course). Floating digital inputs are thus highly inadvised. The same doesn't apply for unused pins - they can be left unconnected.

Aha, I did not know this. So we want to have 'Zero Volts' in order for the pin to read LOW, correct? But why do we need the resistor? Can't we just connect this straight to GND and achieve the same thing?

NO !! Read my answer again, starting at "Think about it..." Then read it again, and again, until you understand the very last sentence. Although you are correct with "[...] we want to have 'Zero Volts' in order for the pin to read LOW [...]"

You've explained well that we need to have a connection to GND so that we can pull the input to either Vdd or GND (and not allow it to float). Got it. You've also explained that the switch will, when closed, connect the Vdd with GND. Got it. Here's what I have from you: a) We must connect to GND. b) the switch will connect the vdd to GND. You've asked my question "What if I removed the resistor" and then said think about it. Perhaps there will be too much voltage headed toward the arduino? We can connect to GND without the resistor.. The Vdd will still connect to GND, so what here is missing?


text:
Pointer problems using Adafruit MotorController
This may be a very simple problem but it has had me going round and round in circles, it is VERY similar to this [ Problem with wrapping Adafruit Motor Controller function calls in a class] question but try as I might I couldn't resolve the issue using this example. So I will include my code and hope that someone with more experience takes pity on me.
This code compiles with no errors but the motors don't start Like the linked question it all worked before it was separated into the individual files.
robot.ino:
#include "E:\chhs2017\LegoRobotics\SketchesThatNeedToWork\RobotBase\RobotBase.h"

RobotBase *base;

void setup(){
    base = new RobotBase();
}

void loop(){
    base->moveRobotForward(base->HALF_SPEED);
//  base->stopRobotAfter(1500);
}

RobotBase.h:
#ifndef ROBOTBASE_H
#define ROBOTBASE_H

#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

class RobotBase{

    public:
        const int MAX_SPEED = 255;
        const int THREE_QUARTER_SPEED = 190;
        const int HALF_SPEED = 127;
        const int QUARTER_SPEED = 90;
        const int MIN_SPEED = 30;

        RobotBase();

        void moveRobotForward(int inSpeed);
        void moveRobotBackward(int inSpeed);
        void moveRobotLeft(int inSpeed);
        void moveRobotRight(int inSpeed);
        void rotateRobotRight(int inSpeed);
        void rotateRobotLeft(int inSpeed);
        void stopRobotAfter(int time);

    protected:
        Adafruit_MotorShield AFMS;
        Adafruit_DCMotor *myMotorM1;
        Adafruit_DCMotor *myMotorM2;
        Adafruit_DCMotor *myMotorM3;
        Adafruit_DCMotor *myMotorM4;
};
#endif

RobotBase.ino:
/*************************************************************
* this is the robot base control class which is designed for a
* four wheel robot construction using an Adafruit_DCMotor controller
* and and arduino Uno
**************************************************************/

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#include "E:/chhs2017/LegoRobotics/SketchesThatNeedToWork/RobotBase/RobotBase.h"

RobotBase::RobotBase()  {
    AFMS = Adafruit_MotorShield();
    myMotorM1 = AFMS.getMotor(1);
    myMotorM2 = AFMS.getMotor(2);
    myMotorM3 = AFMS.getMotor(3);
    myMotorM4 = AFMS.getMotor(4);
}

void RobotBase::stopRobotAfter(int time){
    delay(time);
    myMotorM1->run(RELEASE);
    myMotorM2->run(RELEASE);
    myMotorM3->run(RELEASE);
    myMotorM4->run(RELEASE);
}

void RobotBase::moveRobotForward(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

void RobotBase::moveRobotBackward(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::moveRobotLeft(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::moveRobotRight(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

void RobotBase::rotateRobotRight(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(FORWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(FORWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(BACKWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(BACKWARD);
}

void RobotBase::rotateRobotLeft(int inSpeed){
    myMotorM1->setSpeed(inSpeed);
    myMotorM1->run(BACKWARD);
    myMotorM2->setSpeed(inSpeed);
    myMotorM2->run(BACKWARD);
    myMotorM3->setSpeed(inSpeed);
    myMotorM3->run(FORWARD);
    myMotorM4->setSpeed(inSpeed);
    myMotorM4->run(FORWARD);
}

Thanks in Advance!

You've not actually said what the problem is.  You've said "Its similar to this...", but it isn't because you have initialised the pointer.  Its strange that you have a RobotBase.ino rather than RobotBase.cpp, but if it compiles that must be OK.  You might want to check the values returned by AFMS.getMotor() to make sure they aren't NULL

Sorry if i didn't make it clear the problem is the motors don't spin, everything compiles without error but motors don't go. I also thought about the ino vs cpp but didn't have time to test it today

Silly question, are you supplying enough power?

12v dedicated to the motors which comes in via the power input of the motorshield

I was hoping you would say I'm running it of D3 :)

Nah these are 12v motors to move a 1.5-2kg robot around petty quickly! Four of them might be a little sluggish running off D3 :-P

Hey Guy's As I suspected it was actually an easy fix after leaving it alone for a couple of days came back with fresh eyes and saw the problem straight away. I had failed to start the MotorController board. So all that was needed was the begin function call base->AFMS.begin(); in the setup of robot.ino, all working fine now.
Thanks again for your help.

It may be the way you are initializing the motor shield object.
Try doing:
RobotBase::RobotBase() : AFMS() {
     myMotorM1 = AFMS.getMotor(1);
     myMotorM2 = AFMS.getMotor(2);
     myMotorM3 = AFMS.getMotor(3);
     myMotorM4 = AFMS.getMotor(4);
}

I can't test this solution yet as the hardware is at work but could you explain the reasoning behind the idea? Is addind the AFMS () after the call to the constructor extending AFMS? wouldn't i need to define that in the class definition in the .h file first?

AFMS is an instance of Adafruit_MotorShield and is defined in the header already. All this is doing is initializing it as part of the constructor of RobotBase.

AFMS = Adafruit_MotorShield(); takes an instance of Adafruit_MotorShield initialised by the default constructor and copies it to your variable AFMS.  :AFMS(){ Initialises your variable AFMS using the default constructor for Adafruit_MotorShield.  Its a subtle difference, but not copying things is always a good plan.       Do you need to change AFMS? No, because AFMS() is calling the class's default constructor.  You could do int aNumber(0); if you wanted, but you do int aNumber = 0; they are the same.

You could go a step further and do : AFMS(), myMotorM1(AFMS.getMotor(1)), myMotorM2(AFMS.getMotor(2)), myMotorM3(AFMS.getMotor(3)), myMotorM5(AFMS.getMotor(4)) {}  I think that will work, you might get issues with ordering, because of the dependencies on AFMS.

Both ideas were tested nothing to note occurred, so I am going to revert the code back to the previous layout. I understand your comment on efficiency and not making unnecessary copies of libraries, But as I am using this code with young (year 9; 14-15yr olds) students I need to consider readability as well as efficiency. To explain bringing Adafruit_MotorShield object to our code and use some of its features is easier if we actually bring the object to our code- I'll work on upping the efficiency later (when I get my head around it) :-D

Any other Ideas on where my stumbling block is?


text:
How to lower the power consumption of this ESP32 during delay(500)?
The following code works. It does the following:

wake up when pin GPIO0 is connected to GND  (the pulse duration is 400 milliseconds)
once every 10 wakings, I send the current index to a server with a HTTP request over WiFi
then go to deep sleep

Since GPIO0 is connected to GND during 400 milliseconds, it can reboot multiple times during these 400 milliseconds, which I don't want. So I added delay(500); at the end of the code.
Problem: this delay(500); is probably a waste of power, since the ESP32 is battery powered.
Question: by what could I replace this delay(500) to avoid that the ESP32 reboots multiple times while pin 0 is connected to GND during 400 milliseconds, with the least power consumption possible?
#include "WiFi.h"
#include "HTTPClient.h"
#include "esp_sleep.h"
byte WIFI_BSSID[] =         {0x01, 0x23, 0x45, 0x67, 0x89, 0x00};
String URL =                "http://example.com/submit?bootcount=";
RTC_DATA_ATTR int bootcount = 0;
HTTPClient http;
void setup() {
    bootcount++;
    pinMode(0, INPUT_PULLUP);
    esp_sleep_enable_ext0_wakeup(GPIO_NUM_0, 0);
    if (bootcount % 10 == 0) {
        WiFi.begin("MySSID", "password", 0, WIFI_BSSID);
        while (WiFi.status() != WL_CONNECTED) {
            delay(20);
        }
        URL += bootcount;
        http.begin(URL.c_str());
        http.GET();
        http.end();
    }
    delay(500);
    esp_deep_sleep_start();
}
void loop() {
}

it happens during 400 milliseconds ... what does this mean? ... does the pin interrupt happen every 400 ms?

@jsotola It's like a switch: usually pin 0 is not connected to GND. Then when a pulse happens, during 400 ms pin 0 is connected to GND, it's the pulse duration.

so, you want the ESP32 to wake only on the transition of GPIO0 ... perhaps a simple circuit could be used to modify the input pulse ... maybe the ULP processor could be used

@jsotola Yes, since the pulse lasts 400ms, if I don't add the delay(500), multiple "wake_up+increment_bootcount+deep_sleep" sequences can happen during one signe pulse. I want to wake up only on the transition. Do you think there is a purely software way (without additional hardware components), other than my delay(500) solution? And possibly that doesn't require to stay fully powered during the 500ms?

If the chip cannot be waked by the transition, you might consider to use a timer. Start it when the delay shall start, disable the pin interrupt, and go to sleep. Let the timer overflow/interrupt wake up the chip again, stop the timer, enable the pin interrupt, and go to sleep. Please be aware that a running timer might not allow a deep sleep.

Instead of driving the Pin 0 directly, add a small capacity (0.1uF) in serial between the driver and the Pin0, so that it generate a short pulse during the transition but not during the entire holding down period.

@hcheung Thanks I will try this. Also, isn't there a 100% code solution without hardware? It fully works with delay(500), the only problem is that it probably consumes 100 mA or 200 mA during these 500 milliseconds. Is there a deep_sleep_delay(500) or something similar that would consume max 1 mA ?

As I suggested, a timer needs no additional hardware, your microcontroller certainly has such timers. In that sense this is a "100% code" solution, just try it. -- Since you say that there is no "edge-triggered" wake-up but only a "level-triggered" wake-up, delay(500) is the only "100% code" solution, as it simply runs an empty loop. Anything else needs something more to measure the time or change the trigger.

@thebusybee oh ok thank I initially didn't understand! Would you have a short code example to demonstrate this part (timer), as an answer?

Sorry, no, I don't have an ESP32 here, not to mention a compiler. Please try this yourself, this is the way you will learn. SE/Arduino is not a code writing service. ;-)

I know ;) @thebusybee btw I already wrote the code (in my question). But by experience, often the devil is in the details, so sometimes some code can be useful for an answer :)


text:
Can an ultrasonic sensor differentiate b/w objects?
Can we potentially use an ultrasonic sensor to differentiate between objects based on the reflective capacity of the object?
For example to differentiate between metals and biodegradable wastes.

yes, but not in the way that you are implying .... it is not the sensor that does the differentiation, it is the computer program that does it

No. No, you can't. All they sense is the "time of flight".
The closest you would come would be to have a sensor which can detect physical properties of the target.  That could be colour, sound absorption, etc.  You'd need something that sends out a "broad spectrum" signal (white light, white noise, etc) and detects the reflected spectrum (colour sensor, wide-band microphone) and do spectral analysis of it.  The signal would also have to be fairly tightly focussed to exclude signals from the environment.
All-in-all not something for a little Arduino to consider without lots of extra expensive hardware.

I guess I could definitely use sound absorption.


text:
'D1' was not declared in this scope; did you mean 'y1'?
Even though i am mentioning everything in the beginning then too m getting out of scope error. Code Reference :- https://noisycarlos.com/project/how-to-turn-your-computer-on-and-off-remotely/
I dont know what wwrong here. I am using ESP8266 module. Please help.
#include <ESP8266WiFi.h>

    const char* ssid = <YOUR WIFI NAME>;
    const char* password = <YOUR WIFI PASSWORD>;
    const char ON = '+',
     OFF = '-',
     SLEEP = '/',
     AUTO = 'A';

    const int pinPowerLightOut = D1,
     pinPowerLightIn = D5,
     pinPowerButton = D6,
     pinResetButton = D7,

     buttonPressTime = 250;

    char currentStatus = OFF;
    char lightStatus = AUTO;

    unsigned long autoDisconnectTime = 0,
     powerButtonReleaseTime = 0;

    WiFiServer wifiServer(80);
    WiFiClient client;

    unsigned long lastOn = 0,
     lastOff = 0;

    void changeStatusTo(char newStatus)
    {
     if(newStatus != currentStatus)
     {
     Serial.print("Status changed to ");
     Serial.println(newStatus);

     }
     currentStatus = newStatus;
    }

    void recordLightStatusChange(bool lightIn)
    {
     if(lightIn)
     lastOn = millis();
     else
     lastOff = millis();

    if(lightStatus == AUTO);
     digitalWrite(pinPowerLightOut, lightIn);

    }
    void statusChange()
    {
     bool currentLightStatus = !digitalRead(pinPowerLightIn);

    if(lastOn != 0 && lastOff != 0)
     {
     if((millis() < lastOn + 4000) && (millis() < lastOff + 4000))
     {
     changeStatusTo(SLEEP);
     recordLightStatusChange(currentLightStatus);
     return;
     }
     }

    if(currentLightStatus)
     changeStatusTo(ON);
     else
     changeStatusTo(OFF);

     recordLightStatusChange(currentLightStatus);
    }

    void Print(String toPrint)
    {
     client.print(toPrint);
     Serial.print(toPrint);
    }
    void Println(String toPrint)
    {
     client.println(toPrint);
     Serial.println(toPrint);
    }

    void processCommand(String command)
    {
     Serial.print(F("Received command "));
     Serial.println(command);

    if(command.equalsIgnoreCase(F("status")))
     {
     Print("Status: ");
     if(currentStatus == ON)
     Println("On");
     else if(currentStatus == OFF)
     Println("Off");
     else if(currentStatus == SLEEP)
     Println("Sleeping");
     }
     else if(command.equalsIgnoreCase(F("on")))
     {
     if(currentStatus != ON)
     {
     Println("Power Button Pressed (powering on)");
     pressPowerButton(buttonPressTime);
     }
     else
     Println("Machine is already on (button not pressed)");

    }
     else if(command.equalsIgnoreCase(F("off")))
     {
     if(currentStatus == ON)
     {
     Println("Power Button Pressed (powering off)");
     pressPowerButton(buttonPressTime);
     }
     else
     Println("Machine is already off (button not pressed)");

    }
     else if(command.equalsIgnoreCase(F("reset")))
     {
     unsigned long releaseTime = millis() + 500;
     digitalWrite(pinResetButton, HIGH);
     while(millis() < releaseTime)
     {}
     digitalWrite(pinResetButton, LOW);

    Println("Reset Button Pressed");
     }
     else if(command.equalsIgnoreCase(F("force off")))
     {
     if(currentStatus != OFF)
     {
     Print("Holding Power Button for 10 seconds...");
     pressPowerButton(10000);
     }
     }
     else if(command.equalsIgnoreCase(F("pressPwr")))
     {
     digitalWrite(pinPowerButton, HIGH);
     Println("Power Button Pressed");
     }
     else if(command.equalsIgnoreCase(F("releasePwr")))
     {
     digitalWrite(pinPowerButton, LOW);
     Println("Power Button Released");
     }
     else if(command.equalsIgnoreCase(F("light on")))
     {
     setLightStatus(ON);
     }
     else if(command.equalsIgnoreCase(F("light off")))
     {
     setLightStatus(OFF);
     }
     else if(command.equalsIgnoreCase(F("light auto")))
     {
     setLightStatus(AUTO);
     }
    }

    void setLightStatus(char newStatus)
    {
     if(newStatus == ON)
     {
     digitalWrite(pinPowerLightOut, HIGH);
     Println("Light On");
     return;
     }

     if(newStatus == OFF)
     {
     digitalWrite(pinPowerLightOut, LOW);
     Println("Light Off");
     return;
     }

     if(newStatus == AUTO)
     {
     Println("Light Set to Auto");
     setLightStatus(currentStatus);
     }

    }

    void pressPowerButton(int duration)
    {
     powerButtonReleaseTime = millis() + (duration);
     digitalWrite(pinPowerButton, HIGH);
    }

    void runRoutineChecks()
    {
     checkIfPowerNeedsToRelease();

    if((millis() > lastOn + 4000) && (millis() > lastOff + 4000))
     statusChange();
    }

    void checkIfPowerNeedsToRelease()
    {
     if(powerButtonReleaseTime != 0)
     {
     if(millis() >= powerButtonReleaseTime)
     {
     digitalWrite(pinPowerButton, LOW);
     powerButtonReleaseTime = 0;
     Println("Power Button Released");
     }
     }
    }

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

    void setup() {
     Serial.begin(115200);
     pinMode(pinPowerLightIn, INPUT_PULLUP);
     pinMode(pinPowerLightOut, OUTPUT);
     pinMode(pinPowerButton, OUTPUT);
     pinMode(pinResetButton, OUTPUT);

     attachInterrupt(digitalPinToInterrupt(pinPowerLightIn), statusChange, CHANGE);

     WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED)
     {
     delay(1000);
     Serial.println("Connecting..");
     }

    Serial.print("Connected to WiFi. IP:");
     Serial.println(WiFi.localIP());

     wifiServer.begin();
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////////

    void loop()
    {

     runRoutineChecks();

     client = wifiServer.available();
     if (client)
     {
     while (client.connected())
     {
     String comm = "";
     while (client.available()>0)
     {
     char c = client.read();

    autoDisconnectTime = millis() + 60000;

     if(c == ';')
     {
     processCommand(comm);
     comm = "";
     }
     else
     {
     comm.concat(c);
     }
     }
     runRoutineChecks();
     if(autoDisconnectTime > 1000 && millis() > autoDisconnectTime)
     {
     Serial.println("Client timeout");
     client.stop();
     }
     }
     client.stop();
     Serial.println("Client disconnected");
     autoDisconnectTime = 0;
     }
    }

The ERROR :-
NODEMCU:2:30: error: 'D1' was not declared in this scope; did you mean 'y1'?
    2 | const int pinPowerLightOut = D1,
      |                              ^~
      |                              y1
C:\Users\wahid\Documents\Arduino\NODEMCU\NODEMCU.ino: In function 'void statusChange()':
NODEMCU:61:42: error: 'pinPowerLightIn' was not declared in this scope; did you mean 'pinPowerLightOut'?
   61 |   bool currentLightStatus = !digitalRead(pinPowerLightIn);
      |                                          ^~~~~~~
      |                                          pinPowerLightOut
C:\Users\wahid\Documents\Arduino\NODEMCU\NODEMCU.ino: In function 'void processCommand(String)':
NODEMCU:118:24: error: 'buttonPressTime' was not declared in this scope
  118 |       pressPowerButton(buttonPressTime);
      |                        ^~~~~~~
NODEMCU:130:24: error: 'buttonPressTime' was not declared in this scope
  130 |       pressPowerButton(buttonPressTime);
      |                        ^~~~~~~
NODEMCU:140:18: error: 'pinResetButton' was not declared in this scope
  140 |     digitalWrite(pinResetButton, HIGH);
      |                  ^~~~~~
NODEMCU:158:18: error: 'pinPowerButton' was not declared in this scope; did you mean 'pressPowerButton'?
  158 |     digitalWrite(pinPowerButton, HIGH);
      |                  ^~~~~~
      |                  pressPowerButton
NODEMCU:163:18: error: 'pinPowerButton' was not declared in this scope; did you mean 'pressPowerButton'?
  163 |     digitalWrite(pinPowerButton, LOW);
      |                  ^~~~~~
      |                  pressPowerButton
C:\Users\wahid\Documents\Arduino\NODEMCU\NODEMCU.ino: In function 'void pressPowerButton(int)':
NODEMCU:212:16: error: 'pinPowerButton' was not declared in this scope; did you mean 'pressPowerButton'?
  212 |   digitalWrite(pinPowerButton, HIGH);
      |                ^~~~~~
      |                pressPowerButton
C:\Users\wahid\Documents\Arduino\NODEMCU\NODEMCU.ino: In function 'void checkIfPowerNeedsToRelease()':
NODEMCU:232:20: error: 'pinPowerButton' was not declared in this scope; did you mean 'pressPowerButton'?
  232 |       digitalWrite(pinPowerButton, LOW);
      |                    ^~~~~~
      |                    pressPowerButton
C:\Users\wahid\Documents\Arduino\NODEMCU\NODEMCU.ino: In function 'void setup()':
NODEMCU:246:11: error: 'pinPowerLightIn' was not declared in this scope; did you mean 'pinPowerLightOut'?
  246 |   pinMode(pinPowerLightIn, INPUT_PULLUP);
      |           ^~~~~~~
      |           pinPowerLightOut
NODEMCU:248:11: error: 'pinPowerButton' was not declared in this scope; did you mean 'pressPowerButton'?
  248 |   pinMode(pinPowerButton, OUTPUT);
      |           ^~~~~~
      |           pressPowerButton
NODEMCU:249:11: error: 'pinResetButton' was not declared in this scope
  249 |   pinMode(pinResetButton, OUTPUT);
      |           ^~~~~~
exit status 1
'D1' was not declared in this scope; did you mean 'y1'?

@Juraj m using Nodemcu ESP8266 which contains D0 to D8 pins ?

Only for some esp8266 dev boards Dx pins are defined. The constants map esp module pin numbers to board's pin numbers (for example on most of them D1 is io 4).
If you have a dev board with Dx labels on the PCB, then select the right board in Tools menu.
For plain esp8266 module use pin numbers in code. If the author of the code had a Wemos D1 mini or a NodeMci dev board, use the Dx definitions in the header file to map the Dx pins to esp8266 pins.
Note that on esp8266 not all pins are general purpose IO. Some have limited usage, so use the same esp8266 pins as the author of the code.

I have used the  same pins as the author. Can u explain the mapping part i dnt understand.THANKS.

@Frankruss, if you have a NodeMcu, just select it in Tools menu. I wrote the answer before you revealed that you have a NodeMcu.

I have selected Generic ESP8266 module . should i select NodeMCU is yes then then which one?

@Frankruss, yes select NodeMcu. the version you have or any which works

U r gr8 sir i can compile the code but while uploading i still get this error :
esptool.py v3.0
Serial port COM8
the selected serial port _
does not exist or your board is not connected. @Juraj


text:
Spi based pin expander for Arduino
I don't have enough pins on my Esp32 board. I would like to use a pin expander. All the ones I could find online only use i2c. Are there ones available that use SPI?
I would like send pwm signals to the pin expander outputs. Is that possible?

Pin extenders for when you don't have enough pins on your board.

@Juraj what do you call this https://www.microchip.com/wwwproducts/en/MCP23S17

@Juraj I need to use the pins simultaneously. Multiplexers can only output through one pin at a time.

@NadimAhmed I do those chips in pairs on a breakout board: https://majenko.co.uk/expander32.php

@NadimAhmed The MCP23017 GPIO expander chips are digital only; ie., they can NOT do PWM.

@stevieb thanks for letting me know.

Here you go https://www.microchip.com/wwwproducts/en/MCP23S17. Found it. I am gonna leave this here in case anyone needs it.

I assume you will still have problems sending "pwm signals to these pin extender pins"


text:
What is causing this warning in Arduino IDE?
I'm using DS3231 module with rinkydink library and it is working just fine, however every time i want to compile the code Arduino IDE shows this warning:
C:\Program Files (x86)\Arduino\libraries\DS3231\DS3231.cpp:291:106:
warning: ISO C++ forbids converting a string constant to 'char*'
[-Wwrite-strings]

What is this warning and how to solve it?

You're passing a string constant to a function that expects a variable.

But often it's library writer's mistake and that parameter could (and should) be const because there is no write access to it.

why do you use this old library?

On the face of it your argument sounds fine.  But looking at the nuts and bolts of why a const is used makes it a bit more obvious why this is a warning.  When a compiler encounters a const, it might try putting that value into (read only) program memory.  After all, you promised not to change it.  But passing it as a formal value may be interpreted as you wanting to create a variable in the called to function.  So there can be confusion or a disconnect in what the compiler does and what you expect to happen.

Before giving up, try passing a pointer to the const.  Let me know if that works and I'll post it as an answer.

@st2000, for Uno compiler doesn't put const into progmem. the problem is inside a library OP uses, so they don't do anything to cause this warning

@st2000 i don't know how to do it, sorry i'm very new to this... post an answer and if it can solve the warning i'll make it the correct answer.

I have started building up a list of common errors and their explanations: https://majenko.co.uk/blog/common-arduino-errors-and-warnings

The warning was caused by this line:
char *monthShort[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

In C++, the content of a character string such as "Jan" cannot be
modified. Thus, if you assign the string to a pointer, the pointer
should be declared as const char *:
const char *monthShort[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
                            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};

The same applies to the other arrays of strings: daysLong, daysShort
and monthLong. As a consequence, the prototypes of the methods
getDOWStr() and getMonthStr() should be changed in order to return a
const char *.
BTW, are you sure this library is still maintained? This should have
been fixed a long time ago, and it seems the source was last modified in
2015. You may be better off using a more modern alternative. For
instance, in the Arduino library manager, you can find DS3231 and
Adafruit's RTClib.

i use this library because i'm very new to arduino and everyone every where suggested this and it's easy to use, i'll try the new libraries. thanks.

The DS3231 library from Rinky Dink is the best RTC library there is...I know, I tried them ALL.  This library allows one to print date and time strings with only 3 Arduino print statements:  Serial.print(rtc.getDateStr());
      Serial.print(" -- ");
      Serial.println(rtc.getTimeStr());
Other RTC libraries force user to make the strings up themselves, at a cost of about 12 lines of useless Serial.print commands.


text:
Trying to understand Classes
I have searched about class and int but I still don't understand.
I have seen this code online I want to understand it
class Motor {

  int enablePin;
  int directionPin1;
  int directionPin2;
  public:

  //Method to define the motor pins
  Motor(int ENPin,int dPin1,int dPin2){
    enablePin = ENPin;
    directionPin1 = dPin1;
    directionPin2 = dPin2;
};

here is an interactive web page that may help ... http://www.cplusplus.com/doc/tutorial/classes/

which part are you having problems with?

class Motor {

This says to start defining a class. A class is like a "container" that holds both data and functions (methods). After defining the class, it becomes like a new variable type that you can declare multiple instances of.
  int enablePin;
  int directionPin1;
  int directionPin2;

These define the 3 integer variables (int=integer; whole numbers like 2, 3, 1000, -5, etc.) that belong to the class and have the identifiers given (enablePin, etc.) Since not otherwise specified, these variables are private, meaning that only other functions in the class can access them. Other parts of the program are not allowed to access these variables.
public:

This means that the following definitions are accessible by parts of the program that exist outside the class.
Motor(int ENPin,int dPin1,int dPin2) {
  enablePin = ENPin;
  directionPin1 = dPin1;
  directionPin2 = dPin2;
}

This defines the only "member function" in this class and because it shares the same name as the class (Motor), it is called a "Constructor", and allows you to pass arguments to an object created from the class -- in this case, if you declare an object of class Motor by myMotor = Motor(1, 2, 3);, the constructor is called with parameters 1, 2, and 3. This constructor happens to just set the private variables to be the same as the arguments passed in.
But... All of this is basic C++, so a book or course on C++ programming would be better in-depth resource to understand this.
The code snippet also is incorrect because it has unbalanced curly-braces -- there is one to open the definition of the class and one to open the definition of the constructor, but only one closing brace.


text:
Arduino UNO button LED brightness vary
I am using an Arduino UNO and I am trying to vary the brightness by steps by 0.5 volts till it gets to a max of 5.0 V using buttonA and decrease the brightness of the LED by 0.5 volts with buttonB. The Problem I have is that when I push buttonA the LED steps it's voltage by 0.5V all the way to 5.0V and with buttonB its steps down to 0. I would like to have the LED step each time I press the button not all at once. Here is my code that I have so far can someone help me with telling the Arduino to Step each time a button is pressed. CODE IS DIFFERENT from another post I did
HERE is my code:
int ledPin = 9; // must be a PWM digital pin
int buttonApin = A2; //buttonA to analog 2
int buttonBpin = A1; // buttonB to analog 1
int maxBright = 255; // between 0 and 255
int ms = 1500;    // delay in milliseconds
int buttonPushCounterA = 0; //counter for the number of button presses
int buttonStateA = 0; // current state of the button
int lastButtonStateA = 0; // previous state of the button
int buttonPushCounterB = 0; //counter for the number of button presses
int buttonStateB = 0; // current state of the button
int lastButtonStateB = 0; // previous state of the button

void setup()
{
  pinMode(ledPin, OUTPUT);
  pinMode(buttonApin, INPUT_PULLUP);
  pinMode(buttonBpin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(buttonApin) == LOW) //if buttonA is pushed
   {
      buttonStateA = digitalRead(buttonApin);

     if (buttonStateA != lastButtonStateA)
     {
        if(buttonStateA == LOW)
     {
        buttonPushCounterA++;
     }
    }

// fade from min to max in increments of 25.5 points: basically (0.5 volts)
for (float n = 0; n <= maxBright; n +=25.5)
{
 // sets the value (range from 0 to 255):
 analogWrite(ledPin,n);
 delay(ms);
}
  }

  if (digitalRead(buttonBpin) == LOW) //if buttonB is pushed
  {
     buttonStateB = digitalRead(buttonBpin);

       if (buttonStateB != lastButtonStateB)
         {
            if(buttonStateB == LOW)
              {
                buttonPushCounterB--;
              }
         }

     // fade from max to min in increments of 25.5 points: basically (0.5 volts)
     for (float n = maxBright; n >= 0; n -= 25.5)
    {
     // sets the value (range from 0 to 255):
     analogWrite(ledPin, n);
     delay(ms);
    }
  }

  lastButtonStateA = buttonStateA;
  lastButtonStateB = buttonStateB;
 }

possible duplicate of Arduino UNO coding problem voltage varying

Yeah it was my other code I had changed and fixed some things

I don't see where in your code counter is changed; with this code, it will always be 0!

One problem in your original code is that you are only storing the current state of the buttons if they are pressed.  The next problem is that you are looping through all your brightness values when a button is pressed giving you your "fades all the way up in one go" problem.
This would be my replacement for your loop() code:
loop()
{
    int currentButtonStateA = digitalRead(buttonApin);
    if (currentButtonStateA != lastButtonStateA && currentButtonStateA == LOW)
    {
        currentBrightness += BRIGHTNESS_INCREMENT;  // BRIGHTNESS_INCREMENT is defined at the top of the file with #define BRIGHTNESS_INCREMENT 25
        if (currentBrightness > MAX_BRIGHTNESS)     // MAX_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 255
        {
            currentBrightness = MAX_BRIGHTNESS;
        }
    }
    lastButtonStateA = currentButtonStateA;

    int currentButtonStateB = digitalRead(buttonBpin);
    if (currentButtonStateB != lastButtonStateB && currentButtonStateB == LOW)
    {
        currentBrightness -= BRIGHTNESS_INCREMENT;
        if (currentBrightness < MIN_BRIGHTNESS)     // MIN_BRIGHTNESS is defined at the top of the file with #define MAX_BRIGHTNESS 0
        {
            currentBrightness = MIN_BRIGHTNESS;
        }
    }
    lastButtonStateB = currentButtonStateB;

    analogWrite(ledPin, currentBrightness);
}

Hopefully this is pretty self explanatory.  The current button A state is read and stored in a local variable.  If it is different to the previous state and it is low, the current brightness is incremented and capped at a maximum value.  Next the current button state is stored as the previous state ready for the next run through the loop.
Similar actions are performed for the B button, but with a decrement rather than an increment.  Finally the LED brightness is set regardless of whether any buttons have been pressed.
You do not need to store your current button states (buttonStateA) or your counts for the number of button presses (buttonPushCounterA - which you never referenced anyway) or your ms value so could get rid of those global variables.  You need a new global variable at the top of your file for currentBrightness (int currentBrightness = 0;).
You have used variables to store various non-changing numeric values, such as "maxBright = 255;" which is good practise, but is better (particularly with Arduino development) to use #define macros instead, such as "#define MAX_BRIGHTNESS 255".
The reason for this is that variables take up memory when the code is running - something that an Arduino Uno doesn't have a lot of, whereas a #define takes up no memory - the compiler uses it as a "search and replace" before compiling your code.

THANK YOU THANK YOU THANK YOU!! this made perfect sense and it works!! thank you!!

okay quick question.. i have wired it up and ran the program but sometimes when I push buttonA the voltage steps from 0 - 1V or from 1.0v-3.0V and not taking the half step intervals. is there anyway to fix that problem?

I think this is call bouncing.  As the button physically changes, the connection is made, broken, made and broken repeatedly causing several button clicks.  There are probably better ways to debounce, but a simple way would be to add a delay into your code.  Try delay(100) in the loop.  That would mean it only reads the buttons 10 times a second, which will probably be fast enough.  If it is not, reduce the delay a bit.

You forgot to check to see if the button was actually pushed or if it was just held down. See the State Change Detection example to understand how to perform edge detection.

Awesome! would I use the stateChange functions before or after the if Statement of "if (digitalRead(buttonApin) == LOW)" ?


text:
Spilt string and convert to float to compare
I'm transmitting: Temperature: 28.22C
and on the receiving end I'm receiving the whole tranmission as a string. I'm trying to spilt Temperature to leave it as a string and 28.22 as a float to compare, how do I do that ?
TX end hardware: (Arduino Uno board with Xbee S1)  to computer
RX end hardware: (Arduino Uno board with Xbee S2)  to computer

Is the "receiving end" an Arduino or a computer? If it's a computer, you should tell which language you use and probably ask your question on stackoverflow.

Hi, the receiving end is an Arduino Uno board which is hooked up to the computer. The transmitting end is also hooked up to an Arduino Uno board. Both communication goes through Xbee S1 card

Okk very simple approach :-
Suppose this is your string variable inStr = "Temperature: 28.22C"
String inStr = "Temperature: 28.22C";
int indexOfSpace = inStr.indexOf(' ');
//this stores the address of the space character in the string.
int indexOfC = inStr.indexOf('C');

String Temp = inStr.substring(indexOfScace+1,indexOfC);
//as the parameter for the function is supposed to be the starting point of the string to
 be extracted and one more than its ending point.

//Now to convert to float

float TempFlo = Temp.toFloat();

@user10566     if this answer worked please consider marking it as accepted so that the SE system does not bump it up as an unanswered question.

I suppose your communication is working... In order to retrieve a floating number from a string you might use toFloat() function. You can watch the reference page here to understand how does it work.


text:
I am running 1.6.5, but the folder says 1.6.3?
I just downloaded the latest version of the Arduino software (1.6.5). However, when I look into the Application Support folder under Library (I have a mac), I find that I have a folder named 1.6.3:
Library ▸ Arduino15 ▸ packages ▸ arduino ▸ hardware ▸ sam ▸ 1.6.3
Does this mean there is a hidden 1.6.5 folder that I am not seeing?
BTW, this issue surfaced, because I am trying to fiddle around with the ADC clock speed, but it seems that nothing is happening:
void setup() {
  #define ADC_FREQ_MAX = 1;
  Serial.begin(9600);
  Serial.println(ADC_FREQ_MAX);
}

void loop() {
}

gives me:
opamp.ino: In function 'void setup()':
opamp:2: error: expected primary-expression before '=' token
opamp.ino:4:18: note: in expansion of macro 'ADC_FREQ_MAX'
opamp:4: error: expected primary-expression before ')' token
opamp:4: error: expected ';' before ')' token
expected primary-expression before '=' token

It could simply be that the versions of code within that folder are at a level called 1.6.3.  Big applications are usually componentized which means that the release level of the app as a whole may be different from the release levels of its parts.  I could easily imagine that inside the 1.6.5 IDE there are parts that haven't changed since 1.6.3 and hence retain that version identity.

Ok, but I am changing the ADC frequency to like 1Hz, and I can't see any noticeable change, i.e. the analogRead() function still samples way faster than that - an apparent contradiction (I've even restarted the IDE)

Your define is incorrect, it should be #define ADC_FREQ_MAX 1 only, no =, no ;.

It's likely the different versions have been installed in different places - system wide vs. user-specific, etc.

I'm voting to close this question because there isn't a single, specific clearly answerable question here, and the question has been abandoned in this state long enough that it is unlikely to ever be improved.

1.6.5 is the version of the Arduino IDE.
1.6.3 is the version of the Arduino SAM Boards package that you have installed.

Does this mean there is a hidden 1.6.5 folder that I am not seeing?

Library/Arduino15 is where your preferences.txt file and Boards Manager index files are stored. Library/Arduino15/packages is where hardware packages installed via Tools > Board > Boards Manager are stored. The Arduino IDE will be located elsewhere on your hard drive. If you need to find it here is an easy way:

Tools > Examples > 01.Basics > BareMinimum
Sketch > Show Sketch Folder - this will open the Examples/01.Basics/BareMinimum subfolder of the Arduino IDE installation folder.

BTW, this issue surfaced...

That's off the topic of your question and already answered in a comment on your question so I will refrain from answering it.

The error you see is because of the equal sign in your #define.  That equal should not be there. So the line that uses it ends up being.
Serial.println(= 1);
Which is obviously wrong.


text:
Serial communication between Computer & Arduino via XBee
I configured two XBees using XCTU, connected them to the computer and sent Bytes back and forth. Works.

This is the current, non-working setup:

1 XBee, connected to the Computer using a SparkFun XBee Explorer USB.
1 XBee, connected to an Arduino Mega using SparkFun XBee Explorer Regulated

GND to GND
5V to 5V on the Arduino
DOUT to TX1 on the Arduino
DIN to RX1 on the Arduino

void setup() {
  Serial1.begin(9600);
  pinMode(13, OUTPUT);
  //After 3 seconds the XBee should send out a couple of "A"s coming from the serial port
  delay(3000);
  int i = 0;
  while (i < 10) {
    Serial1.print("A");
    delay(100);
    i++;
  }
}
void loop() {
  //If anything is sent to the XBee it should appear in the Arduino's serial buffer
  //making the LED on pin 13 turn on
  if (Serial1.available() > 0) {
    digitalWrite(13, HIGH);
  }
}

The DOUT LED on the Explorer Regulated flashes as supposed to but nothing is received on the computer where my Terminal application is listening.
Same when I send something from the Terminal, the LED on pin 13 of the Arduino does not indicate any bytes in the buffer, meaning that the XBee probably never received anything.
I already tried swapping TX & RX, resulting in the DIN LED blinking instead of DOUT. Transmission still not working.

Try swapping TX and RX.

Is the terminal configured for 9600 baud? Are both xbees configured to it too?

Anyway, DOUT is an output of XBee, so it should go to the input of Arduino, which is RX, rather than TX. First fix this. BTW, make sure you don't have any hard/soft flow control

@Dario Swapping TX and RX was the solution? Please share it with is for when we get the same problem :) Output of one device is likely to be input of the other and vice versa. It's not that RX connects to RX and TX to TX, they should be cross-connected.

@FuaZe I got it to work using a different board as well as connecting RX to RX and TX to TX, what seems a little odd but at least it works. I'll post a detailed answer in a few hours.


text:
Arduino nano (clone) with ethernet shield only works when I open up serial monitor

#include <EtherCard.h>

static byte mymac[] = { 0x7A,0x69,0x69,0x2D,0x30,0x31 };

byte Ethernet::buffer[500];
static uint32_t timer;

const char website[] PROGMEM = "x0201g2.cloudapp.net";

static void my_callback (byte status, word off, word len) {
  delay(1000);
}

void setup () {

  Serial.begin(57600);
  ether.begin(sizeof Ethernet::buffer, mymac, 10);

  ether.dhcpSetup();

  ether.dnsLookup(website);
}

void loop () {

  ether.packetLoop(ether.packetReceive());

  if (millis() > timer) {
    timer = millis() + 5000;
    ether.browseUrl(PSTR("/foo/"), "bar", website, my_callback);
  }
}

The way I tested this is I open up SSH terminal for x0201g2.cloudapp.net to monitor any incoming traffic.
The result is that it works fine, when I have the "serial monitor" (in Arduino IDE) open. I would see that there's a consistent stream of GET requests.
However, when I do not have the serial monitor open nothing ever happen.
Initially I had some Serial println to show response status and IP address, so I thought it might be related to the fact that the MCU's serial  controller is waiting for a handshake or some sort of ACK/NACK to happen...if that make sense.
However, that was not the case now because even after I have removed all serial print statements it is behaving in exactly the same way (except that my monitor will show up blank, but I still need to bring it up for it to work).

Maybe it's because it's some unknown cheap clone? You should try it with a genuine one.

Look at the ATmega reset pin.

@ChrisStratton could you give more hint? Are you saying it might be because of auto reset?

Update: Tried this with Genuine Arduino Nano. Still same behavior.

@ChrisStratton could it be something to do with voltage differences at RESET pin? Could you elaborate. Thanks in advance.


text:
WiFiManager autoconnect after timeout
I like to configure my ESP8266 with WiFiManager. After each power cycle, the config portal should open and wait for a new configuration. If there is no new configuration entered, WiFiManager should autoconnect with the last/old configuration.
For this I modified AutoConnectWithFSParametersAndCustomIP.ino slightly as you can see here:

#include <FS.h>                   //this needs to be first, or it all crashes and burns...

#include <ESP8266WiFi.h>          //https://github.com/esp8266/Arduino

//needed for library
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>          //https://github.com/tzapu/WiFiManager

#include <ArduinoJson.h>          //https://github.com/bblanchon/ArduinoJson

//define your default values here, if there are different values in config.json, they are overwritten.
//length should be max size + 1
char mqtt_server[40];
char mqtt_port[6] = "8080";
char blynk_token[33] = "YOUR_BLYNK_TOKEN";
//default custom static IP
char static_ip[16] = "10.0.1.56";
char static_gw[16] = "10.0.1.1";
char static_sn[16] = "255.255.255.0";

//flag for saving data
bool shouldSaveConfig = false;

//callback notifying us of the need to save config
void saveConfigCallback () {
  Serial.println("Should save config");
  shouldSaveConfig = true;
}

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

  //clean FS, for testing
  //SPIFFS.format();

  //read configuration from FS json
  Serial.println("mounting FS...");

  if (SPIFFS.begin()) {
    Serial.println("mounted file system");
    if (SPIFFS.exists("/config.json")) {
      //file exists, reading and loading
      Serial.println("reading config file");
      File configFile = SPIFFS.open("/config.json", "r");
      if (configFile) {
        Serial.println("opened config file");
        size_t size = configFile.size();
        // Allocate a buffer to store contents of the file.
        std::unique_ptr<char[]> buf(new char[size]);

        configFile.readBytes(buf.get(), size);
        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(buf.get());
        json.printTo(Serial);
        if (json.success()) {
          Serial.println("\nparsed json");

          strcpy(mqtt_server, json["mqtt_server"]);
          strcpy(mqtt_port, json["mqtt_port"]);
          strcpy(blynk_token, json["blynk_token"]);

          if(json["ip"]) {
            Serial.println("setting custom ip from config");
            //static_ip = json["ip"];
            strcpy(static_ip, json["ip"]);
            strcpy(static_gw, json["gateway"]);
            strcpy(static_sn, json["subnet"]);
            //strcat(static_ip, json["ip"]);
            //static_gw = json["gateway"];
            //static_sn = json["subnet"];
            Serial.println(static_ip);
/*            Serial.println("converting ip");
            IPAddress ip = ipFromCharArray(static_ip);
            Serial.println(ip);*/
          } else {
            Serial.println("no custom ip in config");
          }
        } else {
          Serial.println("failed to load json config");
        }
      }
    }
  } else {
    Serial.println("failed to mount FS");
  }
  //end read
  Serial.println(static_ip);
  Serial.println(blynk_token);
  Serial.println(mqtt_server);

  // The extra parameters to be configured (can be either global or just in the setup)
  // After connecting, parameter.getValue() will get you the configured value
  // id/name placeholder/prompt default length
  WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40);
  WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5);
  WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34);

  //WiFiManager
  //Local intialization. Once its business is done, there is no need to keep it around
  WiFiManager wifiManager;

  //set config save notify callback
  wifiManager.setSaveConfigCallback(saveConfigCallback);

  //set static ip
  IPAddress _ip,_gw,_sn;
  _ip.fromString(static_ip);
  _gw.fromString(static_gw);
  _sn.fromString(static_sn);

  wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn);

  //add all your parameters here
  wifiManager.addParameter(&custom_mqtt_server);
  wifiManager.addParameter(&custom_mqtt_port);
  wifiManager.addParameter(&custom_blynk_token);

  //reset settings - for testing
  //wifiManager.resetSettings();

  //set minimu quality of signal so it ignores AP's under that quality
  //defaults to 8%
  wifiManager.setMinimumSignalQuality();

  //sets timeout until configuration portal gets turned off
  //useful to make it all retry or go to sleep
  //in seconds
  wifiManager.setTimeout(120);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
  //here  "AutoConnectAP"
  //and goes into a blocking loop awaiting configuration
  if (!wifiManager.startConfigPortal("AutoConnectAP", "password")) {
    Serial.println("failed to connect and hit timeout");
    delay(3000);
    //reset and try again, or maybe put it to deep sleep
    ESP.reset();
    delay(5000);
  }

  //if you get here you have connected to the WiFi
  Serial.println("connected...yeey :)");

  //read updated parameters
  strcpy(mqtt_server, custom_mqtt_server.getValue());
  strcpy(mqtt_port, custom_mqtt_port.getValue());
  strcpy(blynk_token, custom_blynk_token.getValue());

  //save the custom parameters to FS
  if (shouldSaveConfig) {
    Serial.println("saving config");
    DynamicJsonBuffer jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();
    json["mqtt_server"] = mqtt_server;
    json["mqtt_port"] = mqtt_port;
    json["blynk_token"] = blynk_token;

    json["ip"] = WiFi.localIP().toString();
    json["gateway"] = WiFi.gatewayIP().toString();
    json["subnet"] = WiFi.subnetMask().toString();

    File configFile = SPIFFS.open("/config.json", "w");
    if (!configFile) {
      Serial.println("failed to open config file for writing");
    }

    json.prettyPrintTo(Serial);
    json.printTo(configFile);
    configFile.close();
    //end save
  }

  Serial.println("local ip");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.gatewayIP());
  Serial.println(WiFi.subnetMask());
}

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

}

My Problem is, that it does not connect after timeout. Only the config portal is closed.
What do I need to change, so that it automatically connects after timeout?


text:
Load website from SD card
I combined two different codes together, a captive portal and a SD card web server. I encountered a problem which the website in the SD card doesn't load when I connect to the AP (captive portal page). Here's the code..

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "./DNSServer.h"
#include <SPI.h>
#include <SD.h>

const byte        DNS_PORT = 53;          // Capture DNS requests on port 53
IPAddress         apIP(10, 10, 10, 1);    // Private network for server
DNSServer         dnsServer;              // Create the DNS object
ESP8266WebServer server(80);
String responseHTML = ""
                      "<title>Captive Portal Test</title>"
                      "
TEST
";

static bool hasSD = false;
File uploadFile;

void returnOK() {
  server.send(200, "text/plain", "");
}

void returnFail(String msg) {
  server.send(500, "text/plain", msg + "\r\n");
}

bool loadFromSdCard(String path) {
  String dataType = "text/plain";
  if (path.endsWith("/")) path += "index.htm";
  if (path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if (path.endsWith(".htm")) dataType = "text/html";
  else if (path.endsWith(".css")) dataType = "text/css";
  else if (path.endsWith(".js")) dataType = "application/javascript";
  else if (path.endsWith(".png")) dataType = "image/png";
  else if (path.endsWith(".gif")) dataType = "image/gif";
  else if (path.endsWith(".jpg")) dataType = "image/jpeg";
  else if (path.endsWith(".ico")) dataType = "image/x-icon";
  else if (path.endsWith(".xml")) dataType = "text/xml";
  else if (path.endsWith(".pdf")) dataType = "application/pdf";
  else if (path.endsWith(".zip")) dataType = "application/zip";

  File dataFile = SD.open(path.c_str());
  if (dataFile.isDirectory()) {
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }

  if (!dataFile)
    return false;

  if (server.hasArg("download")) dataType = "application/octet-stream";

  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
  }

  dataFile.close();
  return true;
}

void handleNotFound() {
  if (hasSD && loadFromSdCard(server.uri())) return;
  String message = "SDCARD Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void) {
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("TEST AP");
  dnsServer.start(DNS_PORT, "*", apIP);
  //PROBLEM HERE/
  server.onNotFound([]() {
  server.send(200, "text/html", responseHTML);
  });

  server.begin();

  if (SD.begin(SS)) {
    hasSD = true;
  }
}

void loop(void) {
  dnsServer.processNextRequest();
  server.handleClient();
}

This code replies the responseHTML as a Captive portal page which immediately pop-ups when I connect to the AP:
server.onNotFound([]() {
      server.send(200, "text/html", responseHTML);
      });

The void handleNotFound() handles the page/file request from the browser but if I use it on
server.onNotFound(handleNotFound);

The captive portal won't show but if I type the server address 10.10.10.1, the page will appear. What seems to be the problem?

Remove hasSD && from void handleNotFound() function.
It worked for me.