text:
Get image from Arduino Ethernet Shield sd card
I have a code that uploads the temperature and humidity from a dht22 to a website.
Now i want to add an image to the "add to homescreen" button in safari on ios.
Apple has a html code for this:
<link rel="apple-touch-icon" href="/custom_icon.png">

Now I want the "custom_icon.png" to be a link or some other method to a file "Icon.png" on the ethernet shield sd card.
I think I need something like this:
client.println("<link rel=\"apple-touch-icon\" href=\"/Icon.png\">");

But this doensn't work. It doesn't give an error, but its just the wrong way to acces that file.
I tried using the SD.h library but I am not able to use the library for my code. This is my code.
#include <dht.h>
#define dht_apin A0

#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>
#include <LiquidCrystal.h>

File root;
// initialize the library with the numbers of the interface pins

byte mac[] = {I HIDE THIS};   // physical mac address
byte ip[] = {I HIDE THIS};                        // ip in lan (that's what you need to use in your browser. ("I HIDE THIS")
byte gateway[] = {I HIDE THIS};                   // internet access via router
byte subnet[] = {I HIDE THIS};                  // subnet mask
EthernetServer server(10000);                          // server port
String readString;
dht DHT;
int Temp;

void setup() {
  // set up the LCD's number of columns and rows:
  Serial.begin(9600);
   while (!Serial) {
    ;
  }
  delay(100);
  Serial.println("DHT11 Humidity & temperature Sensor\n\n");

  Ethernet.begin(mac, ip, gateway, subnet);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());

    Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

 Serial.println("done!");

}

void loop() {

  EthernetClient client = server.available();    // Create a client connection
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();

        if (readString.length() < 100) {    //read char by char HTTP request
          readString += c;
         }

         if (c == '\n') {      //if  HTTP request has ended
          Temp = 0;
  switch (Temp){
  case 0:
           DHT.read22(dht_apin);
           Serial.print("Vochtigheid = ");
           Serial.print(DHT.humidity);
           Serial.print("%  ");
           Serial.print("Temperatuur = ");
           Serial.print(DHT.temperature);

           delay(500);

           File dataFile = SD.open("Icon.png");

           client.println("HTTP/1.1 200 OK"); //send new page
           client.println("Content-Type: text/html");
           client.println();
           client.println("");
           client.println("");
           client.println("<TITLE>Home Damian</TITLE>");
           client.println("<meta http-equiv=\"refresh\"content=\"1 \">");
           client.println("<meta name=\"apple-mobile-web-app-title\" content=\"Home\">");
           client.println("<link rel=\"apple-touch-icon\" href=\"/Icon.png"/>");
           client.println("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
           client.println("<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
           client.println("");
           client.println("");
           client.println("
");
           client.println("
Temperatuur =
");
           client.println(DHT.temperature,1);
           client.print("&#176C");
           client.println("

");
           client.println("
Vochtigheid =
");
           client.println(DHT.humidity,1);
           client.print("%");
           client.println("
");
           client.println("");
           client.println("");

           delay(1000);
           Serial.println("OK");
           Temp = 0;
           client.stop();

         }
       }
     }
   }
  }
}

void printDirectory(File dir, int numTabs) {
  while (true) {

    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i = 0; i < numTabs; i++) {
      Serial.print('\t');
    }
    Serial.print(entry.name());
    if (entry.isDirectory()) {
      Serial.println("/");
      printDirectory(entry, numTabs + 1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

Are Apple computers missing the function for copy pasting the code?

Try a simpler file name e.g. ICON.PNG. The SD library might not support extended names.

You have to write code that responds to the http request for the image and load the image (using the SD library) and pass it on to the web browser in the right format.

@gre_gor yeah sorry for the screenshot, i asked the question on my phone and had that screenshot.

@Majenko Do yo have code? I don't find my way

http://www.websiteoptimization.com/speed/tweak/inline-images/

Really nobody that just can give me the code

No, nobody can just give you the code. Write your code. We told you what you need to do. We do not hand out code willy nilly, especially not to people who post screenshots of a fraction of the code they have.

Here is a picture of my answer.

@Majenko okey, sorry your write. I'll post my code to but please help me. I really need it and I dont understand that part. Really sorry. But your image inswer tho? Haha thats really not needed ;)

@Majenko I added the code

The Arduino uses the 8.3 File Format. meaning that your filename must not be more than 8 characters and the file extension must not be more than 3 characters.
eg:
picture1.png
12345678.123
Hope that helps.
I have been toying with this for the last few days, and managed to find out that it uses the 8.3 format.
Also the index.html must also be in the 8.3 format.
so index.htm
Hope that helps.

You are reading the HTTP request into readString. You need to parse that request to see what is actually being requested.
If the URL being requested is "icon.png" then you need to open the file on the SD card and send the data back as a properly crafted HTTP response - something in the form:
HTTP/1.1 200 OK
Content-type: image/png
Content-length: <file size here>
Connection: close

<Raw PNG data>

The first line of the readString will contain the request:
GET HTTP/1.1 /icon.png

You needt to split that up and find what the request is. You could trap specific entries (/, /index.html, etc) and serve those as specifically crafted responses, and all other unmatched requests you could forward on to your SD card reading code. You should, though, extract the file extension and match it to a MIME time so you can set the Content-Type header correctly.

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


text:
Arduino Mega 2650 + Matlab/Simulink - Serial decimation
I am performing a control analysis on an Arduino board.
As such, I want to minimize the board cycle duration.
(Faster board = faster controller).
Introduction:
I use Mathworks Matlab/Simulink to program the board.
I created a model in Simulink,
and embedded this model into my Arduino Mega 2650.
The model includes an Arduino Serial Transmit block.
I am therefore able to use Matlab software on my PC to request
serial transmission from the Arduino board to Matlab.
The Arduino Mega 2650 has the following serial constraints:

Maximum output buffer: 64 [byte]
Maximum baud frequency: ~115,000 [bit/s]

Problem:
To perform my control analysis,
I want to minimize the board cycle duration, and
I want to read several signals simultaneously.
The time it takes to read all signals sent
(as dictated by the baud rate)
is the primary obstacle in reducing my board cycle duration.
Requested Information:
Is it possible to reduce the board cycle duration
without reducing the duration in which
the serial transmission must be completed.
For example,
what if I run my board at 0.001 [s],
but I can only send all of my signals in 0.010 [s],
what will happen during my reads?
If I read every 0.001 [s], obviously I will not receive all of the data,
as this is not feasible in the time that I am allotting.
My concern is regarding what will happen if I read every 0.010 [s]:

Will the passing of several board cycles before the read completes affect the read?
Is there a method to lock the serial output buffer while reading
(such that the data does not change midread)?
How long does it typically take to refill the serial output buffer with the next set of data?

Conclusion:
Ultimately, I would like to run the board as fast as possible,
since I believe that this could significantly improve my controller's performance,
despite not being able to read these additional cycles.

Decimation is not a problem, and is quite easy to do if you program the Arduino the “standard” way. The problem is you are programming with a tool that abstracts a lot of things away. You will then have to check whether this tool provides a “decimate” block.

@EdgarBonet Decimation in the standard sense is easy.  I could delay my read requests, such that they only occur every X board cycles. My concern is that if I start a read, and the read requires 10 board cycles to complete, then the variables which I am reading will change 10 times before I finish reading.  If this occurs, will these variables be rewritten to the serial queue before I finish reading.  If so, this could create racing conditions in which a read is occurring at the same time as a write.

@EdgarBonet You are correct that using a 3rd party tool obfuscates even more of the things going on under the hood.

@EdgarBonet - Adding a rate transition block before the serial transmit helped the decimation.  As stated in Michel's answer, the data otherwise was sent to the serial buffer no matter how long I waited to read it.

I don't think there will be a problem in this.
I do not understand exactly why you can only send signals every 0.010 s.
The board runs at 16 MHz, that's 16 million cycles per second, however, every 'instruction' normally takes many cycles (let along parsed C/Arduino language).
What you can do is to copy the read information into an array and use it later.
Keep in mind that the serial buffer is 64 bytes. If more is read, data will be overwritten. However, if you copy the buffer into your own (larger) buffer it might help. Also you can change the 64 bytes (it's somewhere in the Serial library).
The buffer works (afaik) with a sort of circular buffer, meaning it can store 64 bytes maximum 'unprocessed' bytes. So you don't have to wait until the buffer is full before processing (actually, this is not even the best method). You can process it as long as there are bytes available.
The pseudo code can be as follows:
lastSignalSent = millis(); // last time signals sent

void loop()
{
    while serial bytes available
    {
        process bytes
    }

    if (millis() - lastSignalSent > 10) // More than 10 ms ago
    {
        Send signals
         lastSignalSent = millis();
    }
}

This assumes the serial byte processing can be done faster than they arrive, but if not, you run into problems anyway, since the serial buffer (of only 64 bytes) will be full too fast.

Are these edits common? Mathworks provides no interface to make these edits by default with their standard library blocks, but I believe that it would be worth asking for if the changes were simple and unlocked faster  and/or larger communication.

This mentions increasing the serial rate to beyond 115,200 [Hz]. But it seems to require non-standard libraries, etcetera and references not a library specifically for faster transmission - rather, it mention a library intended for use with DMX (lighting) communication.

I thought the max speed for serial is 115.2KHz, but DMX is 250KHz; maybe it uses a specific way of using the UART (or not an UART at all). There are many other ways to communicate (like SPI, I2C).

About edits of common libraries, it's not common, but sometimes it is needed. It would be nicer if it was something that could be passed as argument. This edit is not inside Mathworks, it's in the Serial library (and unrelated to Mathworks). For Mathworks/matlab probably another forum is best to ask for details.

I tested some things.  I assumed that if I waited, that the old data was immediately overwritten by new data if I did not grab it.  Instead, the data just builds up in the buffer until I read it. @EdgarBonet was correct in that I'll need to decimate it before it hits the Serial Transmit block.

True ... so increasing the buffer only helps if there are just some occasions where you cannot handle it fast enough, if it is a chronical ' problem', decimating the data is needed. Circular buffers are very often used in resource critical systems.

source: Stack Exchange

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

sort: votes


text:
Help understanding Print::write()--it calls write()--where is write() defined? Help reading code
I'm writing a new serial library (eRCaGuy_Peer2Peer) to allow any 2 pins on an Arduino to be used for peer-to-peer type communication between Arduinos, withOUT interrupts or timers/counters.
Currently SPI, Serial, and I2C are pin-specific, and SoftwareSerial requires pin change interrupts. My implementation will solve these problems.
However, I first am trying to understand some things. As I study SoftwareSerial, I see it inherits from the Stream class, which inherits from the Print class.
I don't understand how Print's write is implemented. This is from Print.h:
virtual size_t write(uint8_t) = 0;
size_t write(const char *str) {
  if (str == NULL) return 0;
  return write((const uint8_t *)str, strlen(str));
}
virtual size_t write(const uint8_t *buffer, size_t size);
size_t write(const char *buffer, size_t size) {
  return write((const uint8_t *)buffer, size);
}

This is from Print.cpp:
/* default implementation: may be overridden */
size_t Print::write(const uint8_t *buffer, size_t size)
{
  size_t n = 0;
  while (size--) {
    if (write(*buffer++)) n++; //<--where is this write defined?
    else break;
  }
  return n;
}

My Questions:

What does this mean? I've never seen anything like this before: virtual size_t write(uint8_t) = 0; Why the = 0?
What does it mean/how does it work defining functions in .h files? I've never done this before: ex:
size_t write(const char *str) {
  if (str == NULL) return 0;
  return write((const uint8_t *)str, strlen(str));
}
Where is the write command I've marked above defined? Is Print::write() calling itself recursively?
Also, why does SoftwareSerial.h call using Print::write; (shown below) when it already re-implements the virtual write function just above that?

virtual size_t write(uint8_t byte);
    virtual int read();
    virtual int available();
    virtual void flush();
    operator bool() { return true; }
using Print::write;

I found the answer to my first question: the  = 0 means it is a "pure virtual function", which means derived classes MUST implement it: https://stackoverflow.com/questions/2652198/difference-between-a-virtual-function-and-a-pure-virtual-function

Will it work ? Do you have some explanation online to tell how you are going to make it ? When you are going to use micros or millis for synchronous data transfer, it might be limitied to 1 byter per 10 seconds. For example an Arduino with Ethernet shield that is retrieving a file from a SD card takes a while. When no timing will be used, you are going to need more pins for handshake signals.

Jot, follow my work live at my link above. I'm working on it as we speak. I have a clever plan. I believe I can make it happen. I don't expect it to be slow either. I'm expecting better than 115200 baud, and turning off interrupts for only a handful of microseconds at a time.

That might work. I like the idea and I like that the TX is always output and RX is always input. However, like the other software serial libraries, it has its own problems. The main problem is that the transmitter disables the interrupts for an unknown time, since the receiver might be very busy or it might execute interrupts while data is being transferred. I suppose it can be used as if it is full-duplex at a higher level using buffers just like the other serial libraries that inherit the Stream class. At a low level it is only half-duplex since RX is the acknowledge.

write is implemented in the class that inherits the Print class - such as HardwareSerial.
There are a number of write functions, and they are overloaded, which means that they are all distinct functions identified using their parameters as well as their name (write(uint8_t) and write(uint8_t *, size_t) are different functions).  The child class overrides the write(uint8_t) function that is pure virtual1 in the main Print class, but the other write functions with other parameter lists aren't overridden and are just "used".
The using Print::write tells it "the write functions to which I am referring are from the Print class."

Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived. In this case, nested-name-specifier must name a base class of the one being defined. If the name is the name of an overloaded member function of the base class, all base class member functions with that name are introduced. If the derived class already has a member with the same name, parameter list, and qualifications, the derived class member hides or overrides (doesn't conflict with) the member that is introduced from the base class.

I'm not entirely sure why they feel they need to use it, since the write functon(s) in Print are public and thus exposed already.

What does it mean/how does it work defining functions in .h files? I've never done this before

Exactly the same as if you had defined the function in a .cpp file, but with a few minor differences, the most important one of which is that the compiler finds it easier to inline the function (or if you're really lucky eradicate the function altogether). It's great for simple functions such as setters and getters that just set or return the value of a variable. In such cases inlining is desirable, and the compiler may even be able to replace the entire function with just direct access to the variable (if it's clever enough).
Another important thing to note with functions in .h files is that you can only really do it with class member functions or static functions. Otherwise you end up with compilation errors complaining about multiple definitions if you use the header file in more than one place.

1: A Pure Virtual function (such as virtual size_t write(uint8_t) = 0;) is one which has to be implemented in the child class. Failure to implement it results in a compilation error. The pure virtual function defines part of the interface but doesn't implement the software for it - that is down to the child class to implement.

I think there's more to it than that. SoftwareSerial inherits Stream which inherits Print, so what other write could it possibly be referring to? ie: I think there's more to the using keyword here than what you stated.

This seems to shed some light: http://forum.arduino.cc/index.php?topic=302730.0

There is more to it, yes, but I was on my phone, so couldn't go into detail. Two terms you need to learn all about: overloading and polymorphism.

In the Print class the virtual size_t write (uint8_t)=0 DEFINES and names a function that accepts a byte and returns a size.  ANY "virtual" function in a base class CAN be over-ridden in a derived class; however, the =0 declares that there is NO actual function in the base class -- the compiler sticks a null function pointer there.  This is why pure virtual functions MUST be over-ridden in the derived (child) class.
The using Print::write; in the .h header file of your derived class tells the compiler that YOUR size_t DerCl::write (uint8_t val) {} should fill in that null pointer in the base class...this is why your write function must be declared exactly like the one in the base class.  If it were not, then when the base class calls it, it would push too many values onto the stack, it would pop too many values off the stack, or it would mix up the parameters sent to the function, etc.
This "polymorphism" allows the base class (Print) to define an interface (for printing in this case) and simultaneously allows the derived class to determine where the resulting byte stream will be sent.  Serial sends it to the USART's serial port.  SoftSerial sends it to any two port pins (one Tx and one Rx).  But you also can create classes to use SPI, TWI(i.e. CAN), a HDMC file, an LCD display, etc.  And you can leverage the uniformity and the functionality of all of the Write(), print(), and println() functions that you're already familiar with by writing a single, simple size_t write(uint8_t) function for your derived class.

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


text:
GPS very short distance calculation
I'm currently working on a project involving making a "parent-child distance warning system" with my Flora board + Ultimate GPS Module (https://www.adafruit.com/product/1059).
I'm on the preliminary phase and just trying to retrieve the current GPS module position, comparing it with a pre-fixed position (expressed in GPS decimal coordinates, e.g. 40.779006, -74.289395), calculate the distance between these two points and, if the distance is more than a certain value, say 20 meters, print on serial monitor a warning message.
I was able to correctly retrieve the GPS module position (expressed in decimal coordinates, as above), but when I try to calculate the distance I'm not able to achieve a few-meter accurancy.
So, my questions are:

Is there a specific/best formula to calculate short distances (max 100 meters) on the earth surface with an accurancy of 2-3 meters?
I tried with Haversine formula with not so bad results, but because of the scarce Double precision (in ATMega processors is the same of the Float one, i.e. 32 bits), I'm able to obtain a precision of only 6-7 digits in total (as stated in https://www.arduino.cc/en/Reference/Float). These approximations lead to large errors in the final distance value.
How can I obtain a fast and precise position update during my path?
If I walk along a direction I'm no able to retrieve a fast enough position update in terms of lat/lon coordinates.

Hope to be as much clear as possible and to have explained my problem, thanks in advance to anyone will give me any feedback or any information and please be patience for my bad english.
Filippo
[UPDATE]
@EdgarBonet that's exactly what I was looking for!!! Huge thanks!
Does the simple GPS library you linked is good to me also if my Flora board mounts an AtMega32u4 processor instead of the ATtiny85 you mentioned?
Last question: do you know how faster can I retrieve a GPS fix? I mean, if I am in a certain position (say X) and I am able to correctly obtain my GPS coordinates, then I move 5 meters ahead (say X+5), when I arrive at X+5 position can I retrieve within few seconds the X+5 GPS coordinates?
Thank you so much again @EdgarBonet!!
I'm currently working on a project involving making a "parent-child distance warning system" with my Flora board + Ultimate GPS Module (https://www.adafruit.com/product/1059).
I'm on the preliminary phase and just trying to retrieve the current GPS module position, comparing it with a pre-fixed position (expressed in GPS decimal coordinates, e.g. 40.779006, -74.289395), calculate the distance between these two points and, if the distance is more than a certain value, say 20 meters, print on serial monitor a warning message.
I was able to correctly retrieve the GPS module position (expressed in decimal coordinates, as above), but when I try to calculate the distance I'm not able to achieve a few-meter accurancy.
So, my questions are:

Is there a specific/best formula to calculate short distances (max 100 meters) on the earth surface with an accurancy of 2-3 meters?
I tried with Haversine formula with not so bad results, but because of the scarce Double precision (in ATMega processors is the same of the Float one, i.e. 32 bits), I'm able to obtain a precision of only 6-7 digits in total (as stated in https://www.arduino.cc/en/Reference/Float). These approximations lead to large errors in the final distance value.
How can I obtain a fast and precise position update during my path?
If I walk along a direction I'm no able to retrieve a fast enough position update in terms of lat/lon coordinates.

Hope to be as much clear as possible and to have explained my problem, thanks in advance to anyone will give me any feedback or any information and please be patience for my bad english.
Filippo
[UPDATE]
@EdgarBonet that's exactly what I was looking for!!! Huge thanks!
Does the simple GPS library you linked is good to me also if my Flora board mounts an AtMega32u4 processor instead of the ATtiny85 you mentioned?
Last question: do you know how faster can I retrieve a GPS fix? I mean, if I am in a certain position (say X) and I am able to correctly obtain my GPS coordinates, then I move 5 meters ahead (say X+5), when I arrive at X+5 position can I retrieve within few seconds the X+5 GPS coordinates?
Thank you so much again @EdgarBonet!!
[UPDATE 2]
The DistanceBetween method recommended to me by @EdgarBonet returns to me always 0, even if I move my self a couple of tens of meters.
But, maybe I am wrong in passing the parameters. Do I have to pass the lat/lon parameters as decimal coordinates (e.g: 45.892829, 12.082583)? If I am wrong, in which format do I have to pass the lat/lon parameters to the DistanceBetween method?

It may be that you cannot get this kind of accuracy with the position fix outputs of everyday GPS units, but rather that you need DGPS (or yet fancier schemes) capable units that can exchange their raw data readings to factor out the part of the inherent system error that is essentially the same in the local region, leaving only the position difference.  This is really a differential GPS question, not an Arduino question - or at least, don't try to do it on an Arduino until you've verified elsewhere that computations on real sample data yield a useful result.

Why not use a short range radio signal, i.e. Bluetooth.  Pair the parent and child and then pulse a signal between them.  As soon as a number of pulses are missed raise the alarm at the parent end.  Its a bit more clumsy if you have 5 children, but...

You will have trouble getting the accuracy you want. An SBAS enabled GPS will give you a position error of around 1 m under ideal conditions (and assuming you have SBAS coverage). Under poor conditions (non-ideal antenna location, lots of buildings/trees around etc...) then expect 5 m of error. That's for each device so double it for position differences.

@Filippo not related to athe question itself, but.. Please avoid using multiple accounts (partcularly to add information about the question, like you did in the pending edit)..

@CodeGorilla That tells you they have wandered off but it doesn't tell you which direction they went. It will also be very environment specific, lots of people around will absorb the signals and so shorten the range. Not necessarily a bad thing for this application but it wouldn't be a controllable effect.

Do you have two user accounts? You appear to be suggesting edits from an  account that differs from the account that you originally posted your question from. If you contact the moderators, then they can merge the two accounts for you.

@FilippoDamuzzo Re Update 2. As indicated in the linked page These routines work in units of 1e-4 arc minutes. Thus one degree is represented as 600,000 units They do this so that all of the calculations are done as integers which is then a lot faster. So if you have lat and lon in degrees then multiply them by the constant DEGREE to get the correct results.

The Haversine formula is way overkill for your needs. At the scale you
are concerned about, the Earth is essentially flat, so the distance
between two points is given by the standard Cartesian formula:
d = √(Δx2 + Δy2)
where Δx and Δy are the distances along the west–east and south–north
axes respectively. These can be computed from the differences in
latitude and longitude as
Δx = R Δλ cos(φ)
Δy = R Δφ
where φ is the latitude, λ is the longitude (both in radians), and R is
the Earth radius. The term cos(φ) accounts for the fact that, far from
the equator, consecutive meridians are closer together than consecutive
parallels. When computing this cosine, it does not matter whether you
use the latitude of either point.
I suggest you take a look at this simple GPS library. It was
designed for doing exactly this kind of simple calculations on a small
AVR processor like the ATtiny85. It should work great on your Flora. The
function you want is DistanceBetween(). It uses the “locally flat
Earth” approximation above, which is only good for distances up to a few
hundred kilometers.
A couple of things worth noting about this library:

the library trades accuracy for efficiency: everything is fixed-point
and it uses low-order polynomial approximations for cos(x) and
√(x2 + y2)
angles are given in units of 10−4 arc minutes, as this is
what you usually get from an NMEA sentence
DistanceBetween() reports the distance as an integer number of
meters, but you can easily modify it to give it in units of
half-meters, quarter-meters, etc.: just replace the value 512 in the
last line (return ... / 512;) by a smaller power of two.

Personally I wouldn't trust the "locally flat earth" model for distances much over the 10-20 km region, certainly not hundreds of km. But it does depend a lot on what you consider to be good enough accuracy. But certainly good enough for the distances in this question.

But... Are you really sure that Earth is not flat?

@Andrew: The library is intended for low-accuracy applications. For example, it uses the approximation cos(π/2 ⋅ x) ≈ 0.962(1 – x²), which has a maximum error of about 0.038. It this accuracy level the “locally flat Earth” approximation is valid for quite large distances at mid-latitudes.

@EdgarBonet I'm probably just too used to working in an environment where an error of 1 cm is unacceptable high ;-)

I have successfully used an Arduino + hobby GPS to get an accuracy within a few meters with an update every second using normal floating point on Arduino. This should be possible.
A 32-bit float has 24 bits of precision, and one 2^24th of half the Earth's circumference is about 1.2 meters, so the theoretical cap is roughly that.
If I recall correctly, you would get better accuracy for short distances on a 32-bit float using normal 2D trig than haversine, but both should work.
Check to make sure you are reading your GPS correctly and go over the equations again. Is everything converted to radians correctly for the trig? Make sure your version of PI has enough digits. Are you correctly parsing the GPS output value as degrees+decimal minutes? It is not a simple decimal degree number (like Google Maps coordinates would be) if it came from an NMEA message. Are there any configuration startup commands you need to send your GPS unit?
I think the fastest updates you can expect is a new coordinate every second, but I haven't used your specific GPS.

Uhm.. in fact you do not have to take into account the radius of Earth, but the emi-circumference. This means that the maximum resolution for a float is about 1.2 meters...

@frarugi87 wow, yeah, thats a dumb mistake. Thanks.

The position difference calculation part of the question has been handled by Edgar. Which leaves the heading to the child part.
To work out which direction the parent is walking in don't use change in position. Use the heading and velocity outputs from the GPS. These will be far more accurate than calculating the velocity based on the change in position.
As for rate of update it depends a lot on the GPS being used, the one you linked to indicates that it supports 10 Hz updates so you should be able to get a position and heading update 10 times per second. The default will be 1 Hz so you'll need to send the correct configuration command. This will however significantly increase battery usage.
Those low end GPS systems typically have a fair amount of latency but the values you get in the serial stream shouldn't be more than 100 ms old, easily good enough for something as slow as a person walking.

You may be interested in my NeoGPS library.  It is smaller, faster, more reliable and more accurate than all other libraries.  It preserves the full accuracy of the GPS locations (10 significant digits), even during distance and bearing calculations.  NeoGPS uses the equirectangular simplification suggested by Edgar at small distances, and switches to Haversine at large distances.  As you have discovered, naive floating-point calculations (like those in all other libraries) lose that accuracy at small distances.
If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.

It is smaller, faster, more reliable and more accurate than all other libraries Not true. I have a library where the position is always 0,0. It's not very accurate but it's a lot smaller and far faster.

The library I linked to in my answer sits somewhere between @Andrew's library and NeoGPS, both in terms of speed and accuracy.

@Andrew, like the watch that is exactly correct once per day, your library would be optimal at exactly one place on Earth.  ;)

@EdgarBonet, I enjoyed reading about that project.  The parser is basically a custom scanf... cute!  I was curious how NeoGPS version would compare.  It would still fit in an ATtiny85, using about half the RAM of TinyNav (67 bytes vs. 119) but almost twice the program space (7746 bytes vs. 4084).  The NeoGPS Distance & Bearing routines require the floating-point library.


text:
Button and switch to turn on and off LED and changing after time
I have system connected to an Arduino Uno where I want to read whether the switch is open or closed.
Based on if the switch is open/closed, I want an LED light to turn on/off.  When the switch is open, the LED turns on and pushing the button turns it off and stays off for 24 hours then turns back on if the switch is still open and I can again turn off the light with one push of the button.  However, if the switch is closed within the 24 hours, the light doesn't turn on and pushing the button does not do anything.
I don't know how to change the state of the LED back on after the 24 hours.  Should I use a button counter, if statements, or while statements?  I'm really new to coding and took on a large project I'm not sure how to complete. This is obviously a very small portion of the project.  Any help is much appreciated.
This is as far as I've gotten.  When the switch is open the LED turns on, but when I push the button, the light just dims.  I also have to hold the button down to keep the light "off" and it turns right back on when I release the button.
if (digitalRead(switch) == LOW) {
digitalWrite(Light, HIGH );

if (digitalRead(Button) == LOW) {
    digitalWrite(Light, LOW);
}

else if (digitalRead(switch) == HIGH) {
  digitalWrite(Light, LOW );

}
}

Please edit your question (click "edit") and make clear whether you are describing what you want to happen or what does happen.  For example, you say  “However, if the switch is closed within the 24 hours, the light doesn't turn on and pushing the button does not do anything”; is that what your code does now, and it is erroneous or undesired behavior?  Try to write a clear specification of what should happen, couched in sentences that begin with phrases like “The system shall ...”

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem.  Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant.  Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem.

Do not name a constant switch.

You need to go back and learn to program. You are trying the climb the mountain by the hardest route possible. Start with small hills. Learn the basics, develop your skills. Enjoy each little step.

I have to make an answer, since I cannot use items/links easily in a comment.
Instead of creating the application for you, I suggest you do the following:

Read/try and experiment with the default Arduino examples for a switch (see Switch
In the above example also is shown how to debounce the signal, this is needed since you want to use it as a 'toggle'.
Use a timer for millis() and check for 24 hrs (which is 1,440,000) millis, so it should fit in a long.
Small thing: Always align brackets to make it easier for yourself and others.

A few things will need to be done.

You have to figure out to detect a button press. This needs to be transition based. Ie. Detect a button press when it was not pressed the previous time.

Once a button is pressed, you take a snap shot of the time. And then turn on the led.

Then you test current time at each pass and see if the desired time has passed.

This can be done by configuring one of the timers to record sufficiently long period.
If you have to use mill is(), you have to figure out how long it overflows and how to detect its overflow.
Both can be done, fairly easily.

Your problem is, that you do not keep the status and acts only on actual state of switch+button each pass of loop() (that is many thosand each second).
So you Light On is switch is turned, then Light off if button is pressed and next split of second you repaet it again - led looks dim, as your eye cannot see how fast is blinking.
You need to keep the status (OFF,ON,TEMP_OFF) and act upon that. Also if it is temporary off, you need know, when it happend, to undo it after 24 hours. (google for state automat arduino)
the code would be like this (not tested, I wrote it from head, so try to understand the principle and fix all small errors and play with the idea on your own)
// statuses - just some different values
#define ST_OFF 1
#define ST_ON 2
#define ST_TEMP_OFF 3

// pin assignment - change by tour projects need
#define pin_switch 2
#define pin_button 3
#define pin_led 13

unsigned long temp_time; // temporarry off from this time
byte status=ST_OFF; // start with dark

loop() {
  switch (status) {

    case ST_OFF:
      if ( digitalRead(pin_switch) == LOW ) {
          status = ST_ON;
          // light it on if switch turns/is LOW
          };
       break;

    case ST_ON:
      if ( digitalRead(pin_button) == LOW ) {
         status = ST_TEMP_OFF;
         temp_time=millis();
         // light it off temporary if button pressed, remeber when
         };
       if ( digitalRead(pin_switch) == HIGH ) {
          status = ST_OFF;
          // light it off permanently if switch released - override TEMP, if both happens
          };
       break;

    case ST_OFF:
       if ( millis()-temp_time > 24L*60L*60L ) {
          status = ST_ON;
          // light it on, if timeouted
          };
       if ( digitalRead(pin_switch) == HIGH ) {
          status = ST_OFF;
          // light it off permanently if switch released - overrides TEMP/ON
          };
       break;
    };

  digitalWrite(pin_led,(status == ST_ON) );
  // light the led if ST_ON, turn it off otherwise
  // we can keep old value or look for actual and write only if it differs, but it is the simplest way

}


text:
Is there an ICRn CTC mode interrupt vector?
I can use the CTC waveform generation mode to loop to OCRnA and trigger the corresponding TIMER1_COMPA_vect interrupt.
// CTC mode
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B &= ~(1 << WGM13);
TIMSK1 |= (1 << OCIE1A);
OCR1A = 250;

ISR(TIMER1_COMPA_vect) {}

But if I use CTC mode with ICRn as "TOP" is there a corresponding interrupt vector?
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B |= (1 << WGM13);
TIMSK1 |= (1 << ???);    // which interrupt to enable?
ICR1 = 250;

ISR(???) {}              // which interrupt vector?

I think it was TIMER1_CAPT_vect. Have to check when I get home.

It seems I used TIMSK1 |= _BV(ICIE1); ISR(TIMER1_CAPT_vect), but looking at the datasheet, that's not supposed to work. It works, but it's not specified behavior.

@Gerben That works for me too. Can you elaborate on "not specified behaviour"? The datasheet isn't very explicit as far as I can tell.

@Gerben: This behavior is actually specified. It would seem we had both misread the datasheet. :-/

You are right; I stand corrected. Apparently past me is smarter that present me :-)

No, there isn't. But you do have a simple alternative: use WGM 14
(fast PWM with TOP = ICR1). Then the TOV1 flag will be set after
the timer reaches TOP:
TIMSK1 |= (1 << TOIE1);  // enable Timer 1 overflow interrupt

ISR(TIMER1_OVF_vect) {}  // Timer 1 overflow vector

Note that this waveform generation mode behaves very much like the CTC
mode. If you do not set any of the COM1 bits in TCCR1A, then there will
be no PWM output.

Edit: My bad. As noted by Gerben and confirmed by you, the
TIMER1_CAPT_vect can be used, and it is specified in the datasheet,
although maybe not very prominently:
In section 17.9.2 “Clear Timer on Compare Match (CTC) Mode”:

An interrupt can be generated at each time the counter value reaches
  the TOP value by either using the OCFnA or ICFn Flag according to the
  register used to define the TOP value.

In section 17.11.40 “TIFR5 – Timer/Counter5 Interrupt Flag Register”, in
the description of bit 5 (Input Capture Flag):

When the Input Capture Register (ICRn) is set by the WGMn3:0 to be
  used as the TOP value, the ICFn Flag is set when the counter reaches
  the TOP value.

It does actually seem to work with CTC mode and ICRn as TOP, by using the TIMER1_CAPT_vect interrupt.
// CTC mode with ICRn as TOP
TCCR1A &= ~(1 << WGM10);
TCCR1A &= ~(1 << WGM11);
TCCR1B |= (1 << WGM12);
TCCR1B |= (1 << WGM13);

// enable interrupt
TIMSK1 |= (1 << ICIE1);

// TOP value
ICR1 = 100;

// interrupt at TOP
ISR(TIMER1_CAPT_vect) {}


text:
Using SCL and SDA of ESP8266-01 with GY-30 BH1750FVI for lux measurement
I followed this tutorial to get lux measurement from GY-30 BH1750 with Arduino.
It's working fine. But now I want to use it with ESP8266-01.
I read Pin 4 is SDA and 5 is SCL for it. But it's not working. Can someone tell me what do I need to change in the code? I'm a "bit" confused about the addressing.
Following is the code for Arduino:
#include <Wire.h>

int BH1750_address = 0x23; // i2c Addresse
byte buff[2];

void setup() {
  Wire.begin();
  BH1750_Init(BH1750_address);

  delay(200);
  Serial.begin(9600);
  Serial.println("Starte Beleuchtungsstaerkemessung - blog.simtronyx.de");
}

void loop(){
  float valf=0;
  if(BH1750_Read(BH1750_address)==2){
    valf=((buff[0]<<8)|buff[1])/1.2;

    if(valf<0)Serial.print("> 65535");
    else Serial.print((int)valf,DEC);

    Serial.println(" lx");
  }
  delay(1000);
}

void BH1750_Init(int address) {
  Wire.beginTransmission(address);
  Wire.write(0x10); // 1 [lux] aufloesung
  Wire.endTransmission();
}

byte BH1750_Read(int address) {
  byte i=0;
  Wire.beginTransmission(address);
  Wire.requestFrom(address, 2);
  while(Wire.available()){
    buff[i] = Wire.read();
    i++;
  }
  Wire.endTransmission();
  return i;
}

Wire is not setup for the ESP01 by default. There is no GPIO 4 or 5. you can specify the pins as arguments to the begin() method, ex: Wire.begin(sda, scl). Using GPIO of (0,2) is common. Since the ESP01 is picky about pin states during power-up, don't use external pullups (you don't need them anyway).


text:
how can I combine two 2 digit 7 segment display to a single arduino uno
One of the two digit 7segment display will read its values from a smoke sensor while the other will read its values from a temperature sensor. From what I have seen in textbooks recently;each segment display will make use of ten digital pins(7 segments, decimal point, display faces(correct me if I'm wrong Pls)).

You could connect the segments of the two displays to the same Arduino pins, so you only need two additional pins for the second display. You then multiplex over the four digits instead of the previous two.

You are correct about the 10 pins, shift register are probably the way to go for you. They are very cheap and pretty simple to use.
Try googling 74hc595. It basicly turns 3 pins into 8, and you can even Daisy chain the chips to get 16, 24, 32 and so on from the 3 pins on the arduino.
Good luck to you.

This is one way to do it, but you can do it without any extra hardware, as explained in the question/answer I linked to.

Well that's a brilliant solution! I suggest trying marks link before my solution.


text:
Errors creating instance MenuBackend and MenuItem attributes in a display class
I am doing a display class using 2*8 lcd on an arduino to display and navigate my menu using MenuBackend library but i can make instance of these variables. I tried using static variable it did not work either.
here is the codes
GPSMenu.h :
#ifndef GPSMENU_h
#define GPSMENU_h
#include "Arduino.h"
#include <MenuBackend.h>
#include <LiquidCrystal.h>

class GPSMenu
{
public:
GPSMenu(LiquidCrystal* lcd);

  void navigateMenus( byte read);

  private:
  void menuChangeEvent(MenuChangeEvent changed);
  void menuUseEvent(MenuUseEvent used);
  void menuSetup();
  LiquidCrystal *_lcd;

  MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);

  //beneath is the list of menu items needed to build the menu
  MenuItem Battery     = MenuItem(menu, "Battery ", 1);//----usable
  MenuItem Iteneraire  = MenuItem(menu, "Itener  ", 1);
  MenuItem Start       = MenuItem(menu, "Start   ", 2);//----usable
  MenuItem Stop        = MenuItem(menu, "Stop    ", 2);//----usable
  MenuItem FileOpn     = MenuItem(menu, "FileOpn ", 2);
  MenuItem NewFile     = MenuItem(menu, "NewFile ", 3);//----usable
  MenuItem OverWr      = MenuItem(menu, "OverWr  ", 3);//----usable
  MenuItem PtOpn       = MenuItem(menu, "PtOpn   ", 2);
  MenuItem Seconde_1   = MenuItem(menu, "Court   ", 3);//----usable
  MenuItem Secondes_15 = MenuItem(menu, "Moyen   ", 3);//----usable
  MenuItem Minute_1    = MenuItem(menu, "Long    ", 3);//----usable
  MenuItem GPSData     = MenuItem(menu, "GPSData ", 1);
  MenuItem Coord       = MenuItem(menu, "Coord   ", 2);//----usable
  MenuItem Time        = MenuItem(menu, "Time    ", 2);//----usable
  MenuItem Status      = MenuItem(menu, "Status  ", 2);//----usable
  MenuItem SpdAlti     = MenuItem(menu, "SpdAlti ", 2);//----usable
  MenuItem Filemnger   = MenuItem(menu, "Filemngr", 1);//----usable

};
#endif

GPSMenu.cpp:
#include "Arduino.h"
#include <MenuBackend.h>    //MenuBackend library - copyright by Alexander Brevig
#include <LiquidCrystal.h>  //this library is included in the Arduino IDE
#include "GPSMenu.h"  //this library is included in the Arduino IDE

GPSMenu::GPSMenu(LiquidCrystal* lcd){
 _lcd = lcd;
 _lcd->begin(8, 2);
 _lcd->clear();
  GPSMenu::menuSetup();

}

//this function builds the menu and connects the correct items together
void GPSMenu::menuSetup()
{
  //add the file menu to the menu root
  menu.getRoot().add(Battery);
  Battery.addRight(Iteneraire).addRight(GPSData ).addRight(Filemnger);
  Iteneraire.add(Start ).addRight(Stop).addRight(FileOpn).addRight(PtOpn);
  GPSData.add(Coord).addRight(Time).addRight(Status).addRight(SpdAlti);
  FileOpn.add(NewFile).addRight(OverWr);
  PtOpn.add(Seconde_1).addRight(Secondes_15).addRight(Minute_1);
}

//  This is where you define a behaviour for a menu item

void GPSMenu::menuUseEvent(MenuUseEvent used)
 {
   _lcd->setCursor(0, 0);
   _lcd->print(used.item.getName());
   _lcd->setCursor(0, 1);
   _lcd->print("Used    ");
}
/*
  Here we get a notification whenever the user changes the menu
  That is, when the menu is navigated
*/
void GPSMenu::menuChangeEvent(MenuChangeEvent changed)
{
  _lcd->setCursor(0, 0);
  _lcd->print(changed.from.getName());
  _lcd->setCursor(0, 1);
  _lcd->print(changed.to.getName());
}

void GPSMenu::navigateMenus( byte read) {
  MenuItem currentMenu=menu.getCurrent();

  switch (read){

  case 1:

    if(!(currentMenu.hasAfterChildren())){  //if the current menu has a child and has been pressed enter then menu navigate to item below
      menu.use();
    }
    else{  //otherwise, if menu has no child and has been pressed enter the current menu is used
      menu.moveDown();
    }
    break;

  case 2:
    menu.moveLeft();

    break;
  case 3:
    menu.moveRight();

    break;
  case 4:
    menu.moveUp();
    break;
  }
}

And the errors on my terminal :
In file included from GPSMenu.cpp:4:0:
GPSMenu.h:20:46: error: ‘void GPSMenu::menuUseEvent(MenuUseEvent)’ cannot appear in a constant-expression
       static MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);
                                              ^
GPSMenu.h:20:59: error: ‘void GPSMenu::menuChangeEvent(MenuChangeEvent)’ cannot appear in a constant-expression
       static MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);
                                                           ^
GPSMenu.h:20:74: error: invalid in-class initialization of static data member of non-integral type ‘MenuBackend’
       static MenuBackend menu =  MenuBackend(menuUseEvent,menuChangeEvent);
                                                                          ^
GPSMenu.h:20:74: error: initializer invalid for static member with constructor
GPSMenu.h:20:74: note: (an out of class initialization is required)
GPSMenu.h:23:46: error: ‘GPSMenu::menu’ cannot appear in a constant-expression
       static MenuItem Battery     = MenuItem(menu, "Battery ", 1);//----usable
                                              ^
GPSMenu.h:23:65: error: invalid in-class initialization of static data member of non-integral type ‘MenuItem’
       static MenuItem Battery     = MenuItem(menu, "Battery ", 1);//----usable
                                                                 ^
GPSMenu.h:23:65: error: initializer invalid for static member with constructor
GPSMenu.h:24:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Iteneraire  = MenuItem(menu, "Itener  ", 1);
                                                          ^
GPSMenu.h:25:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Start       = MenuItem(menu, "Start   ", 2);//----usable
                                                          ^
GPSMenu.h:26:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Stop        = MenuItem(menu, "Stop    ", 2);//----usable
                                                          ^
GPSMenu.h:27:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem FileOpn     = MenuItem(menu, "FileOpn ", 2);
                                                          ^
GPSMenu.h:28:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem NewFile     = MenuItem(menu, "NewFile ", 3);//----usable
                                                          ^
GPSMenu.h:29:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem OverWr      = MenuItem(menu, "OverWr  ", 3);//----usable
                                                          ^
GPSMenu.h:30:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem PtOpn       = MenuItem(menu, "PtOpn   ", 2);
                                                          ^
GPSMenu.h:31:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Seconde_1   = MenuItem(menu, "Court   ", 3);//----usable
                                                          ^
GPSMenu.h:32:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Secondes_15 = MenuItem(menu, "Moyen   ", 3);//----usable
                                                          ^
GPSMenu.h:33:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Minute_1    = MenuItem(menu, "Long    ", 3);//----usable
                                                          ^
GPSMenu.h:34:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem GPSData     = MenuItem(menu, "GPSData ", 1);
                                                          ^
GPSMenu.h:35:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Coord       = MenuItem(menu, "Coord   ", 2);//----usable
                                                          ^
GPSMenu.h:36:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Time        = MenuItem(menu, "Time    ", 2);//----usable
                                                          ^
GPSMenu.h:37:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Status      = MenuItem(menu, "Status  ", 2);//----usable
                                                          ^
GPSMenu.h:38:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem SpdAlti     = MenuItem(menu, "SpdAlti ", 2);//----usable
                                                          ^
GPSMenu.h:39:58: warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
       MenuItem Filemnger   = MenuItem(menu, "Filemngr", 1);//----usable

You can't set the value of a variable in the header file (class definition).
class foo
{
  int a = 1;  // This doesn't work
};

This works
class foo2
{
  static int b;
};
int foo2::b = 2;

why do we have to precise int in :int foo2::b = 2; since we have allready declared b as int.
I did what you said but i get
In file included from GPSMenu.cpp:4:0:
GPSMenu.h:59:70: error: invalid use of non-static member function
MenuBackend GPSMenu::menu =
MenuBackend(menuUseEvent,menuChangeEvent);

why do you have to declare int again in int foo2::b = 2; I don't know, but I d know it doesn't work if you don't.  That's because GPSMenu::menu is not a static member.

GPSMenu::menu is declated as static ...
in the class
public:
GPSMenu(LiquidCrystal* lcd);
void navigateMenus( byte read);
static  MenuBackend menu;
static  MenuItem Battery; ect.....

and outside it
MenuBackend GPSMenu::menu =  MenuBackend(menuUseEvent,menuChangeEvent);
MenuItem GPSMenu::Battery= MenuItem(menu, "Battery ", 1); ect...


text:
Why using a ESP01 adapter?
I bought an ESP-01 adapter (initially I thought this was the WIFI module):
ESP-01 adapter
Than I bought the 'real'  ESP-01 (which is not arrived yet):
ESP-01
However, according to this link: connect (sorry it's in Dutch), but the picture shows that the ESP-01 is directly connected to the 3.3V of the Arduino.
My question: why bother using the adapter card? Or does it give additional security/protection (and what)?

Using an ESP8266 with a traditional Arduino requires logic level translation of the UART signal. That is what this adaptor provides. It also provides a dedicated 5V -> 3.3V voltage regulator so you don't stress the Arduino's rather underpowered 3.3V regulator.
The two SOT-23 components are N-channel MOSFETs (probably BSS138P or similar), and the SOT-89 component is the voltage regulator.
Yes, you can provide all that yourself, to varying levels of complexity - this just makes things easier. And since you already have it you may as well make use of it.

Thank you very much ... I assume with logic level translation you mean also a 5V-3.3V translation (but for the data?) ... I will start using both than ... but eventually I will need more (thanks to your good idea to use multiple Arduinos).

Yes, the logic level translation converts the 5V TX from the Arduino into the 3.3V RX of the ESP8266, and the 3.3V TX of the ESP8266 into a 5V RX to the Arduino (the latter is not strictly needed, but helps to improve noise immunity).

Ah thanks .. and that probably explains also why sometimes I read RX needs to be connected to TX and vice versa instead of RX<->RX and TX<->TX

You connect RX->RX and TX->TX if you are using the Arduino as a UART interface (disabling the ATMeag328P by holding reset LOW or physically removing the chip). Otherwise you connect RX to TX and TX to RX (the Arduino pins in this latter case are usually chosen by you and used with SoftwareSerial since the UART pins are used by your USB connection).

Are software pins (meaning non RX and TX on Arduino) fast enough for WIFI speeds (like Mb/s), using software serial?

Mbps? No. But then neither is the ESP8266 - it usually runs no faster than 115200 baud. If you want high speed communication like that then you need a PC.

Ok ... I think 115kbps is enough, just wondering how much I lose if I use software serial ... but I will test it when I have the ESP-01 :-)

What is it you are hoping to do with it?

For two reasons actually: 1) make a PC application to send information to an Arduino ... this is not time critical (max 128 KB to be sent). 2) sending information between multiple Arduinos, close together (like 1 meter approximately), not much data, but time critical (sending information back and forth within preferably 1 ms, size like 5-25 bytes average).

How are you thinking of getting the Arduino to process the 128KB of data? No "normal" Arduino can store that much information for processing.

The 128 KB will be put into a 23LC1024 SRAM ... (I already tested it by copying it from an SD card). To prevent every Arduino to have its own 128KB I want to make one ' controller' Arduino with 128KB SRAM and the other Arduino's send/receive (processed) messages using that 128KB

Ok, that's fine then. As long as you have that covered. You'll have to "chunk up" your transfer, of course, into a number of smaller requests for the Arduino to process.

Yes the requests will be around 5-25 bytes .. for SysEx messages I might need more, but those will not be time critical (and need to be chunked up. My biggest worry is the speed for the small messages, but if that doesn't work I can use RS232 connector/cables (but WIFI is more convenient, although the distance is very small). RF is another option but I need a lot of extra items (receiver/transmitter), IR is impossible (line of sight).

you won't get 1ms times with wifi. i think my best half-legs are about 15ms. this is due to http overhead

@dandavis thanks for this info ... that means wifi is not possible (back for analysing a wired connection probably).

Unless you program the ESP8266 module(s) directly and get them to talk MIDI directly from their UART pins - then use UDP to transfer datagrams at much higher speed and lower latency.

Hmm, the adapter I got only has a single ceramic disc capacitor, none of the other stuff.  It also has eight pins instead of four, so it's barely anything at all. I guess you really have to be careful when ordering from Chinese sellers on eBay.

The anonymous downvoter strikes again.


text:
PCF8583 with Arduino delay of one second?
I'm trying to interface the RTC chip : PCF8583 with Arduino Uno. I'm using exactly the circuit shown below except instead of the variable capacitor near the crystal oscillator, I've used a 22pF ceramic capacitor.

For the programming side, I've used the Arduino PCF8583 library
The code I'm using is the following :
#include <Wire.h> // necessary, or the application won't build properly
#include <stdio.h>
#include <PCF8583.h>

/*
*  read/write serial interface to PCF8583 RTC via I2C interface
*
*  Arduino analog input 5 - I2C SCL (PCF8583 pin 6)
*  Arduino analog input 4 - I2C SDA (PCF8583 pin 5)
*
*  You can set the type by sending it YYMMddhhmmss;
*  the semicolon on the end tells it you're done...
*
*/

int correct_address = 0;
PCF8583 p (0xA0);
void setup(void){
 Serial.begin(9600);
 Serial.print("booting...");
 Serial.println(" done");
}

void loop(void){
 if(Serial.available() > 0){
   p.year= (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48)) + 2000;
   p.month = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.day = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.hour  = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.minute = (byte) ((Serial.read() - 48) *10 +  (Serial.read() - 48));
   p.second = (byte) ((Serial.read() - 48) * 10 + (Serial.read() - 48));
   // Use of (byte) type casting and ascii math to achieve result.

   if(Serial.read() == ';'){
     Serial.println("setting date");
     p.set_time();
   }
 }

 p.get_time();
 char time[50];
 sprintf(time, "%02d/%02d/%02d %02d:%02d:%02d",
  p.year, p.month, p.day, p.hour, p.minute, p.second);
 Serial.println(time);
 delay(3000);
}

When setting the time and date, everything went ok, but when getting date/time the result is always HALF the period of the elapsed time, for example if I set the time 10:30 and I check it after 30 MINUTES, I get 10:45 instead of 11:00.
I really don't know if this is a hardware or software issue. If anybody has any idea about this issue, that would be highly appreciable !
Thanks in advance !

I'm sorry, but that serial reading code is awful. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

It seems to me the 3 V battery serves no useful purpose.

Shouldn't VCC (PCF8583 pin 8) be connected? Together with the diodes and battery backup?

Check your schematic vs the datasheet and make sure that it makes sense.
Check to make sure that your input is right. You can print it back right away, or set the etc to a known good time and see if it keeps time.
Check the library to make sure that it is good.


text:
digitalRead influenced by touches
  const int BUTTON      = 8;

void setup() {
  Serial.begin(9600);
  pinMode(BUTTON, INPUT);
}

void loop() {

  Serial.println(digitalRead(BUTTON));

}

I have connected a cable to pin 8. It's not connected to anything else nor have I any other cables connected.
I am expecting constant zeros, but I keep getting ones and zeros all the time, e.g. when shortly touching the cable.
I didn't experience that before. Did I accidentally damage my Arduino?

Why are you expecting constant zeros? Do you have a pulldown on the pin? Unconnected inputs are undefined, unless something is driving the pin it'll float around at random. A person is a good 50/60 Hz antenna and so when you touch the wire you'll get random noise.

Google the phrase "Floating Input"

If you don't connect it to anything, it can be a result of a flipping 'input' ... try to use a pullup or pulldown resistor.
Or better:
PullUp
Use something like:
 pinMode(BUTTON, INPUT_PULLUP);

The pin is floating. Use pull up or pull down to help define its logic state.


text:
How can I2C be made to work through a level shifter?
I am attempting to use a bi-directional level shifter for an IMU to shift the SDA and SCL lines in an I2C implementation, however cannot get the level shifter working with the Arduino at all. It feels like the bi-directionality is confusing the master<>slave relationship and pulling the high and low levels to some average, preventing communications.
At idle, with no connection, the SDA and SCL lines on the Adruino are are 5 V, however when connected to two channels of the level shifter, the voltages drop to 2.5 V on the high side and 1.7 V on the low side of the shifter. The low side of the shifter is completely open so shouldn't be controlling the voltage at all, I've even tried a 10 kOhm and 1.5 kOhm pullup resistor between the low and high sides and their respective voltages, 3.3 and 5 V, but that hasn't worked either.
The level shifter works fine interfacing the MEGA to an SD card over the SPI pins, so I don't understand quite why the level shifting would stop working with the I2C.
The fault manifests as the Arduino hanging on a Wire.endTransmission(); call, which would seem to suggest the MEGA is failing to oscillate its SDA and SCL pins as it wishes. The problem occurs when either of the SDA or SCL pins are connected to the shifter high-side.
I also know that the Sparkfun datasheet for the IMU states that for I2C a level shifter is not necessary, but in debugging another problem, this is being attempted as a solution.
Level shifter: Adafruit 8-channel Bi-directional Logic Level Converter
IMU: Sparkfun LSM9DS1 breakout
Arduino: MEGA 2560 v3

For I2C you need a special kind of logic translator. This one isn't suitable.

This device can only translate push-pull CMOS logic outputs. If for open-drain signal translation, please refer to TI TXS010X products.

Personally I use the PCA9306DCUR since it is specifically designed for I2C operation.

I always use the I2C level shifters with mosfets. 30 cents at AliExpress (search for: i2c level). Adafruit: https://www.adafruit.com/product/757  Sparkfun: https://www.sparkfun.com/products/12009

@Jot they take up too much room for my liking. One of the variants of the PCA9306 is smaller than just one of those SOT23 MOSFETs. It's about the size of one pin and needs a microscope to work with it ;)


text:
How can I set a calculated value when my sketch is uploaded?
I have an Arduino based countdown timer that counts down the number of minutes remaining to an event and displays them on an LCD. Since the event's start time is fixed, I have to re-calculate my countdown duration and update a constant in the sketch every time I upload it.
Is it possible to calculate the duration on the PC and set the starting value for the timer automatically? Perhaps using some kind of pre-compile script? Or perhaps through some kind of debugging features?
I'm not interested in adding RTC or other hardware to this project b/c (1) I don't have it handy and (2) there's very limited physical space in the already assembled project.
I'm currently using the Arduino IDE but I would be open to solutions that use other IDEs, or external components.

Send it through serial?

Using a RTC would be better in this case, as it always keeps time, even when the Arduino isn't powered.

i would just use an ESP8266 to fetch the actual time from the web onboot. if you use epocs, you can just subtract the fetched value from the stored value to get "how much longer". this works across reboots and is immune to internal counter rollover.

I am avoiding changing the hardware at this point b/c (1) I don't have it handy and (2) there's very limited physical space in the already assembled project. However the ideas are valid; for another planned project I will be adding both Wi-Fi and an RTC for exactly this purpose.

@JensEhrich: if you have wifi+web, you don't need an RTC, just load time on each boot, takes 2 seconds...

@dandavis I won't have guaranteed access to wifi, so setting with NTP and keeping time with battery backed RTC would probably be the most robust for me. If I can find a way to set via standard radio signals (similar to some watches/clocks) I would try that too

@JensEhrich: speaking of that, GPS modules can provide time... ;)

Why not add the DS3231 RTC?  It makes it simplicity itself, and they are easy to wire and are cheap.

@SDsolar Thanks, but I'm not willing to modify the hardware at this point. I have updated my question to emphasize that.

The C compilers provide two macros that resolve to string literals:  __DATE__ gives the time the file was compiled, and __TIME__ gives the current time of day. They output e.g. "May 31 2017" and "21:19:49"
You'd have to parse these string to get the time and do the calculations to get the remaining time.

PC's date is not likely to be set for the future, can you elaborate on how this plan operates?

You know the date and time of the event. You know the current time, through the __DATE__ and __TIME__ constants. Subtract the latter from the former, and you get the number of minutes remaining. (provided the device doesn't lose power, and uses the now wrong value of __DATE__ and __TIME__

This is pretty much exactly what I was after. It will certainly solve the problem for this scenario; I'm aware of the clock reset issue, and have a battery backup on the timer already.

I'd suggest using a time library to parse the string and to do the date difference math.

IIRC TimeLib.h can work directly with these macros.

Store your time acquired the way Gerben is describing.
If you have a fixed future date, add that date with the compilation date (and calculate the number of seconds/hours).
Note however, this only works when you don't reset your Arduino, or might expect a power loss in the future. If this can happens, store the current time + event time in EEPROM.
Also, add some seconds in case accuracy is important between the compilation time and time for uploading/resetting the Arduino.
Also take into account that the normal way to get time is millis(), and this might cause overflows when used in calculations. So use a second counter to convert/check for overflows and convert to minutes/hours for example.e

Also, millis will start back from 0 after around 50 days. So you have to work around that if you want your countdown to be more that 50 days into the future.

The tip for adjusting the seconds between compile and run is a good one, but I don't need that kind of accuracy here. The target duration is within the limits of millis() but I'm still tracking full hours with a separate counter anyway. Thanks Michel.


text:
How to write a digitalWrite array for MCP23017 expander chip?
I'm using multiple expander chips for my project and I was wondering if there is a way to shorten the loop code by using array? So that I don't have a super long code.
void setup() {
  mcp.begin(0);
  mcp1.begin(1);
  mcp.pinMode(0, OUTPUT);
  mcp.pinMode(1, OUTPUT);
  mcp.pinMode(2, OUTPUT);
  mcp.pinMode(3, OUTPUT);
  mcp.pinMode(4, OUTPUT);
  mcp.pinMode(5, OUTPUT);
  mcp.pinMode(6, OUTPUT)
  mcp.pinMode(7, OUTPUT);
  mcp1.pinMode(0, OUTPUT);
  mcp1.pinMode(1, OUTPUT);
  mcp1.pinMode(2, OUTPUT);
  mcp1.pinMode(3, OUTPUT);
  mcp1.pinMode(4, OUTPUT);
  mcp1.pinMode(5, OUTPUT);
  mcp1.pinMode(6, OUTPUT);
  mcp1.pinMode(7, OUTPUT);
}

void loop() {
  mcp.digitalWrite(0, LOW);
  mcp.digitalWrite(1, LOW);
  mcp.digitalWrite(2, LOW);
  mcp.digitalWrite(3, LOW);
  mcp.digitalWrite(4, LOW);
  mcp.digitalWrite(5, LOW);
  mcp.digitalWrite(6, LOW);
  mcp.digitalWrite(7, LOW);
  mcp1.digitalWrite(0, LOW);
  mcp1.digitalWrite(1, LOW);
  mcp1.digitalWrite(2, LOW);
  mcp1.digitalWrite(3, LOW);
  mcp1.digitalWrite(4, LOW);
  mcp1.digitalWrite(5, LOW);
  mcp1.digitalWrite(6, LOW);
  mcp1.digitalWrite(7, LOW);
}

Which library are you using?

Use a variable ( iterator) and count from 0 to 8 (excluding):
void setup()
{
    mcp.begin(0);
    mcp1.begin(1);

    for (uint8 pin = 0; pin  < 8; pin ++)
    {
        mcp .pinMode(pin, OUTPUT);
        mcp1.pinMode(pin, OUTPUT);
    }
}

void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
        mcp1.digitalWrite(pin, LOW);
    }
}

If the order in which the digital pins are written to LOW matters than split them like in your example, (however, I do not think that is the case).
void loop()
{
    for (uint8 pin = 0; pin < 8; pin++)
    {
        mcp .digitalWrite(pin, LOW);
    }

    for (pin = 0; pin < 8; pin++)
    {
        mcp1.digitalWrite(pin, LOW);
    }
}

Note : for clarity I would call the mcp variables mcp1 and mcp2 instead of mcp resp mcp2, or an even more intuitive name if there is a clear function for both mcp's.
Using uint8 creates an unsigned byte instead of an int which saves also one byte of stack memory.

apt. I would also throw the routine in a function so I don't even have to repeat the looping code to apply it...

@dandavis ... it can be done, personally, I wouldn't do it because it barely reduces the number of lines and makes it less clear, but it's true it reduces copied code. Normally I start refactoring when it is 3 times used OR (2 times and on different locations).

If you are using the Adafruit MCP23017 library there is a shortcut you can use for setting all the GPIO pins in one go:
mcp.writeGPIOAB(val);

val is a 16-bit value which defines the IO level of all 16 pins at once.
There is a similar function for reading:
val = mcp.readGPIOAB();

You can also read just one bank of GPIO pins (why they didn't have a similar write function I have no idea):
valA = mcp.readGPIO(0);
valB = mcp.readGPIO(1);

Unfortunately there aren't any shortcut functions for setting the pin modes.


text:
Make a Robotic Arm move straight not curved
I am planning on a project that includes a robotic arm controlled by Arduino. A simplified program of this would be:

A robotic arm picks up an object
The robotic arm then moves the object in a straight line
The robotic arm releases the object

The problem with this is that every robotic arm that I have seen works with servos, which rotate precisely within 0 and 180 degrees. But, because the robotic arm moves with servos, it then moves in a curved path, rather than the desired straight path.
The two paths in this problem appear in this image. The one on the left is the desired, but the one on the right is the one that occurs when using any robotic arm.

Is there any way to make the robotic arm move in a straight path? Is there a specific robotic arm that moves in straight lines rather than curved lines?
Thanks for any help!
Here is the link to an example of a robotic arm picking up an object and moving in a curved path, and not a desired straight path.

can you not use stepper motors instead of servos? they can be moved in precise and non-fixed amounts

@dandavis Are there robotic arms or similar robots that can pick up objects run by stepper motors? And don't these motors also make the robot move in a circle, which doesn't solve the problem?

ahh, i see your question. look into CNC design. or maybe you could invent some sort of weird elbowed arm with carefully choreographed movements...

The formal term for this is "inverse kinematics"  - first you model how the arm responds to the angle of each motor, then you invert it to determine the sequence of angles that will produce the path you want.  If you have just a few motors you may be able to puzzle it out analytically without formal methods.

https://robotics.stackexchange.com/questions/tagged/inverse-kinematics

You need to learn about Inverse Kinematics.

In robotics, inverse kinematics makes use of the kinematics equations to determine the joint parameters that provide a desired position for each of the robot's end-effectors. Specification of the movement of a robot so that its end-effectors achieve the desired tasks is known as motion planning. Inverse kinematics transforms the motion plan into joint actuator trajectories for the robot.

By deciding how you want the end to move and calculating the joint positions for each point along that path you can get straight line movements, etc.

It requires doing some geometry.  Think about how you would do that with your arm.  You'd have to move more than one joint at a time.  So you have to define the line you want to follow, and back calculate from each point on the line what the angles of all the joints need to be in order to put the end there.  This will require a bit of trigonometry.  Is that something you've studied before?


text:
2.4Mhz clock for 3-wire SPI using Arduino Mega 2560
I am trying to develop an Arduino sketch for ADS8320 ADC IC, which is 3-wire SPI. I need a 2.4MHz serial clock for the SPI interface. I tried the code below, but I don't know how to generate clock pulses at 2.4MHz clock speed.
#define CLK 22
#define DBIT 24 // so
#define CS 26

#include <SoftwareSerial.h>

int v = 0;
float Ctemp, Ftemp;

void setup()   {
  Serial.begin(9600);
  pinMode(CLK, OUTPUT);
  pinMode(DBIT, INPUT);
  pinMode(CS, OUTPUT);
  digitalWrite(CS, HIGH);
  digitalWrite(CLK, LOW);
}

void loop()   {
  v = spiRead();
  if (v == -1)   {
    Serial.print("No sensor \n");
  } else   {
    Serial.println(Ftemp);
  }
  delay(100);
}

int spiRead() {
  int value = 0;
  digitalWrite(CS, LOW);
  delay(2);
  digitalWrite(CS, HIGH);
  delay(220);
  /* Bring CS pin low to allow us to read the data from
    the conversion process */
  digitalWrite(CS, LOW);
  /* 1st 5 clock cycles  */
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  /*
    Read bits 16-0 from ads8320 for the adc. Loop for each bit reading
    the value and storing the final value in 'adc'
  */
  for (int i = 16; i >= 0; i--) {
    digitalWrite(CLK, HIGH);
    value += digitalRead(DBIT) << i;
    digitalWrite(CLK, LOW);
  }
  // check bit D2 if HIGH no sensor
  if ((value & 0x04) == 0x04) return -1;
  // shift right three places
  return value >> 3;
}

'
i have added the code i tried with arduino spi library still i don't get any result
 // inslude the SPI library:
 #include <SPI.h>

 // set pin 10 as the slave select for the digital pot:
 const int slaveSelectPin = 10;

 void setup() {
 // set the slaveSelectPin as an output:
 pinMode(slaveSelectPin, OUTPUT);
 // initialize SPI:
 SPI.beginTransaction(SPISettings(2400000, MSBFIRST, SPI_MODE0))

 void loop() {
 while(1){
 spiread(slaveSelectPin);
 }
 }

 void spiread(int slaveSelectPin) {
 // take the SS pin low to select the chip:
 digitalWrite(slaveSelectPin, LOW);

 receivedVal = SPI.transfer(val);
// take the SS pin high to de-select the chip:
digitalWrite(slaveSelectPin, HIGH);
}

On an Arduino Mega and using the Arduino core the highest clock frequency by toggling a digital pin is approx. 70 kHz. The Arduino core is very slow. See GPIO library benchmark https://github.com/mikaelpatel/Arduino-GPIO/blob/master/examples/Benchmark/Benchmark.ino. It is possible to generate up to 4 Mhz clock but you need core or library that is optimized for performance. Also the SPI clock is scaled 8, 4, 2, ..., etc MHz. 2.4 Mhz would force you to select 2 Mhz.

The ADS8320 has to have a DCLOCK frequency of between 0.024MHz and 2.4MHz. Using primitive bit-banging with millisecond granularity delays is not going to get anywhere near even the lower end of that range (500Hz is all you could possibly get with a 1ms delay between each clock transition, also you're generating a pulse wave, not a square wave - nasty).
Even using smaller microsecond delays it's not going to give you good results.
Instead you should be using the hardware SPI port which generates a stable clock signal for defining the acquisition timing.
However you cannot get a 2.4MHz SPI clock on the Arduino. But, do you need a 2.4MHz SPI clock? That's the absolute top end of the sampling frequency. You can go much slower - all the way down to 0.024MHz (24kHz) and still be sampling.
On the Arduino SPI runs at a division of the system clock frequency. That is, 1/2, 1/4, 1/8, etc.  So with a 16MHz system clock you can run SPI at 1/8 that speed and get a 2MHz clock.
You will also need to do a certain amount of bit shifting and unpacking to get the 16 bit data from the 24-bit stream (more bits than you have now) since SPI can only work in 8 bit chunks.

Minimum 22 clock cycles required for 16-bit conversion. Shown are 24 clock cycles. If CS remains LOW at the end of conversion, a new datastream with LSB-first is shifted out again.
-- Datasheet: Figure 29. ADS8320 Basic Timing Diagrams

So you can just ignore what you get in the last two bits of a 24-bit stream.

It's hardly possible to generate a stable and exact frequency with your method.
Imagine you have an interrupt routine interrupting your spiRead() or any function called inside: Your clock will be extended by the ISR runtime.
Apart from this:

I'm not sure if your LOW phase is long enough (there's no delay between setting CLK from LOW to HIGH. If 2.4 MHz is the max frequency for the chip, it should be at least 208ns.
However:
If you are sure that the runtime of digitalWrite is always longer than 208ns, you could remove your delay() at all. The resulting frequency is the maximum possible you can achieve with your method.
The smallest delay() is 1ms, which leads to a maximum of something < 1 kHz (or even 0.5kHz for a 50:50 signal).
You should use delayMicroseconds() to get at least 500kHz.

But what I'm really wondering:
Why are you implementing bit banging instead of simply using the SPI library?

i did not find 3 wire spi example for sensor interfacing. how to use arduino spi library here. can you let me know basic functions for 3 wire spi? which sets 2MHz clock at least

@vassidefuk: For 3 wire SPI you could just leave MOSI unconnected. For the functions refer to the library documentation. What maybe is not so clear there: function "transfer" is byte oriented. As your sensor needs at least 22 bit for converting and sending one value, you would have to call "transfer" three times (24 bit; doesn't hurt) within CS = LOW

i have put another question can you have a look and tell whats is wrong with the code? [https://arduino.stackexchange.com/questions/39047/ads8320-with-arduino-mega-2560]

The Mega 2560 clock rate is 16 MHz. Your target SPI clock rate is 2.4 MHz. That leaves you with 16/2.4 = 6,67 clock cycles per SPI clock cycle, which means you have an available processing clearly insufficient for the task you intend. Your program will choke and will be unable to meet the hard time deadlines required. It will not work.
Instead, you should use another board with higher processing power, a slower SPI clock rate or a HW solution (instead of SW) for the SPI clock.


text:
Ring topology by using arduino and Bluetooth
I want to connect Bluetooth in a circular ring is it possible to contect 8 arduino with each other via Bluetooth hc05 or hc06  and share data into tha ring..

Its probably possible, but I don't think it would be a good idea.
Each Arduino is going to have to forward information it receives that is not for it.  This is a drain on processing power.  Add to that you are going to need to give the devices an identity, so they know what data is for them, and a inform them of the topology of the network so they know how to connect to the adjacent nodes.
Depending on what problem you are trying to solve you might want to look at direct radio coms implementing a mesh network, or the simplest of all solutions Wifi.  You could use an ESP8266 to form an access point and others to connect to it.  I believe there might be a limit to the number of connections an ESP8266 can have at any one time but this could be mitigated by dropping the connection after the message has been sent.

Every arduino needs two HC05 since it's only BT 3.0.
A BT 4.1 or 4.2 can pair multiple devices, only one BT hardware is needed.


text:
Overflow in bit calculation
I'm having a double buffer to write data from sensors to SD card. inBuf points to the buffer that are written into (from sensors). The other buffer write data to SD card.
char buffer[2][BUFLEN];
volatile int inBuf = 0;

inBuf = 1 - inBuf;

However, the update of inBuf does not work. Firstly inBuf is 0, and after that inBuf becomes 32!!! I tried different data types: boolean, uint8_t, int and the results are the same.
How could I fix this problem? Also, what datatype should I use for inBuf, as it's really just one bit?
I ended up using the following:
inBuf = inBuf? 0:1;

but seems really complicated and unnecessary.
EDITS:
Sorry for was not being clear previously. It turns out that I had an overflow in the code:
char buffer[2][BUFLEN];
volatile uint16_t bufferCounter;
volatile int inBuf = 0;
volatile bool outBufHasData = false;

Inside the interrupt handler:
if (bufferCounter < BUFLEN - SAMPLESIZEINCHAR + 1) {
  epoch = now();
  proximity = vcnl.readProximity();
  ambientLight = vcnl.readAmbient();

  // format to be fixed length as opposed to variable length
  // sacrifice overhead in written data with simpler and more robust code
  // since we know exactly how much to increment after each write
  int written = snprintf(&buffer[inBuf][bufferCounter], SAMPLESIZEINCHAR,
        "%10lu,%5d,%5d\n",
        epoch, proximity, ambientLight);

  if (written > 0) {
    bufferCounter += written;
  }
} else {
  // only switch buffer if out buffer is written to SD card
  if (!outBufHasData) {
    inBuf = inBuf? 0:1;
    bufferCounter = 0;
    outBufHasData = true;
  }
}

Then in the for loop, where the buffer is written to SD card when the buffer is full:
  if (outBufHasData) {
    myFile.print(buffer[1 - inBuf]);
    myFile.close();
    outBufHasData = false;
  }

Previously, I had bufferCounter < BUFLEN !! Thus I was writing over the memory of the buffer, and spill into bufferCounter and inBuf. That's why I got the value 32 of inBuf, which is the ASCII code of space. Mystery resolved!!

I see you have inbuf volatile. Is there an interrupt involved somewhere? Care to share your actual code instead of just 2 lines?

You obviously have a bug somewhere, but since it is not in the snippet you posted, we cannot help you. Could you post a Minimal, Complete, and Verifiable example showing the problem?

My guess is that, since inBuf immediately follows buffer in the definitions you are overflowing buffer and clobbering the contents of inBuf - but that's just a guess since we cannot see your code!

@Majenko That's a correct guess! My code has overflow and rewrote the number 1 to by space char, which is 32. If you want you could add an answer and I'll accept that!!

At least part of your edit, whilst clarifying what you are asking, also appears to contain an answer. It would be better to edit your question to clarify the original problem, and then post the solution and explanation as an answer, and then accept your own answer. I will vote to reopen the question, so that you can post your own answer. Your question (and answer) may prove to be useful for someone else.

Seeing  as your data typpe has the volatile keyword maybe the value of inBuf is being changed on another section of code like an interupt, other wise i see no reason for the variable to have a value of 32.
If you want to only use one bit you should just use the boolean data type with a true or false value.
In that bit of code i assume you are trying to invert the value of the bit, with the boolean you could always use the NOT operator:
inBuf != inBuf;

If you want a variable to be 'yes' and 'no' or perhaps '0' and '1', then you can use a boolean which is 'true' or 'false'. With a boolean you can use logic operators:
boolean dataReady = false;
dataReady = !dataReady;
if( dataReady) ...

A boolean on a 8-bit AVR chip (Arduino Uno,Leonardo,Nano,Mega) is 8 bit. You could also use a byte and make it 0 or 1.
A 8-bit variable is often used when a interrupt routine sets a flag. By making that flag only 8 bit and volatile, it can be used in the loop function as well without the need to disable the interrupts. Reading and writing a 8 bit variable can not be interrupted by an interrupt routine.
Using 8 bits when only 1 bit is needed is normal. You don't have to worry about that.
When you need hundreds of 1 bit variables, then it is possible to select each bit with macro's or a lot #define to select each bit. This is almost never used in normal code, but almost always used for the registers of a sensor.
And last but not least: a struct with bit fields packs the bits. That can be handy sometimes.

this answer does not answer the OPs question.

I was trying to see through the little information and tried answer the question that the OP probably should have been asking.

Thank you though, I'll be clear next time asking question!


text:
How to flash hex files from a micro SD card to an Arduino Nano using an SD card module?
I want to flash a hex file stored in a micro SD card into an Arduino [Uno/Nano]. So far I can read and write to the SD card using Arduino.
Without modifying the bootloader, is it possible to flash the Arduino using micro SD card module?

Do you have two user accounts? You appear to be suggesting edits from an account that differs from the account that you originally posted your question from. If you contact the moderators, then they can merge the two accounts for you.

I have rejected the edit as it changes the focus of the question. What you asked in your edit was a good question - I highly suggest that you ask it as another question (if it hasn't been asked already).

No. Only the bootloader is allowed to write to the program flash.

can you show us where this is explained?  The boot loader is just a program and so is the sketch.  I do not see why a sketch can not do what the OP asked.  That said, the knowledge to read the SDCard and modify the non-volatile program memory goes way beyond common Arduino programming knowledge.   One would have to be very familiar the the particular micro processor being used.  Even then it would be a challenge.  To put it another way, this task is easily on par with that of creating the Arduino boot loader in the first place.

@st2000 the bootloader has this extra privilege that a regular sketch hasn't.

Yes, but I am not sure it can work from the smaller Arduino models. Have a look at the Phoenard project. The platform, based on a 2560, flashes .hex files on demand, which are stored on the SD card.
It's an open-source project, so it should be possible to go through the code and see how they do it.


text:
Reading from software serial with an interrupt
I want to perform a serial read using software serial with Arduino. I am looping for my normal tasks, but whenever something is received on the software serial pins I want to perform a read operation and based on the character received, I want to run a function in the loop.
I think this is possible with interrupts only. But I can not see any documentation or help on how to perform this.
How to write an ISR for this task?

Please explain why you want to do such a thing. What is the difference of writing the incoming data in a buffer and processing that buffer in the loop. I think that if you write you sketch with 'millis' instead of 'delay' and use a hardware serial port with the standard Arduino functions, then all your problems are probably solved. Could this be a XY-problem ( http://xyproblem.info/ ) and your real question is how to reduce latency for incoming serial data in your sketch ?

you actually want more of an event callback than a strict interrupt routine

You can't do it directly with an interrupt. SoftwareSerial already uses an interrupt to do the actual reception - the received byte being placed in a circular buffer.
The only thing you could do would be to modify the source code for SoftwareSerial so that instead of storing the byte in the buffer it calls your custom code instead.

Ok, so you're NOT using SoftwareSerial, you're using (something which I have never heard of) "NeoSWSerial". That has the ability to attach an interrupt (by adding it to the reception interrupt ISR), and the README.md file with that library gives you an example of how to use it:
#include <NeoSWSerial.h>
NeoSWSerial ss( 4, 3 );

volatile uint32_t newlines = 0UL;

static void handleRxChar( uint8_t c )
{
  if (c == '\n')
    newlines++;
}

void setup()
{
  ss.attachInterrupt( handleRxChar );
  ss.begin( 9600 );
}

So just read the character in there, set a flag to say you have a new "mode" arrived, and in your loop react to that flag and run the right function for that mode.
If you want to terminate a mode early you will have to program your modes to also react to the "new mode" flag and terminate. The interrupt cannot do that for you.

can I do something with attachInterrupt?

No, you can't do anything with attachInterrupt.

I am using NeoSWSerial not the original Software Serial it has attachinerrupt function   https://github.com/SlashDevin/NeoSWSerial/blob/master/src/NeoSWSerial.cpp

Well that's a completely different story. It would have helped if you had stated that in your question. When you say you are using software serial it's immediately assumed (unless explicitly stated otherwise) that you are using the standard Arduino software serial. If you aren't you must state that at the beginning. Then we can tell you to go and read the manual where it shows you exactly how to do what you want to do.

Is some help possible with that library. Sorry, I thought NeoSWSerial is like an extension of the original one so I thought may be the library already has some support. Please help if possible

You mean the example, which I have copied and pasted for your convenience, is not enough? Do you want me to type it in for you as well?


text:
Powering an Arduino with more than 5 V
Last time, when I supplied 12 V from a power supply to the Arduino's 5V pin, it blew up. This time I'm going to use an adapter. Why does an adapter with a 12 V input not blow an Arduino up, as in the previous case?
Or, should I have supplied 12 V to Vin pin, instead of the 5 V pin?
Edit: Sorry for saying 12V input, it is written 12V output and I meant a power adapter that is plugged into wall.

What sort of adapter are you talking about? Do you mean a power adapter that you plug into the wall, to convert 240 V a.c. mains electricity to 5 V d.c.? Apparently you aren't referring to a power adapter, as you say that the adapter has a 12 volt input, so do you mean a DC-DC convertor? Or do you mean a regulator, that reduces voltage from 12 volts to 5 volts (which, effectively, does the same as a DC-DC convertor)? Please edit your question to clarify.

Congratulations on confirming their design.  That is exactly what it is supposed to do.  When you feed more than 5V into the 5V pin it is specifically designed to melt down and never work again.  I bend the pins inward to show they are n/w then give them to the kids to play with.
Sometimes I turn up a few pins like they are eyes or horns.  It makes a fun toy.  Meanwhile, you have now discovered why they provide the Vin pin, which goes through a regulator.  With that pin, 9-12 volts is just fine.

12 Volts is fine into the barrel connector.

First of all you should read the tech specs for Arduino Uno here:
https://www.arduino.cc/en/Main/ArduinoBoardUno
You will find this important information about power supply:
Operating Voltage   5V
Input Voltage (recommended) 7-12V
Input Voltage (limit)   6-20V

From documentation also:
Vin. The input voltage to the Arduino/Genuino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin.
5V pin.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.
So answering you question: yes you should have supplied 12v on Vin. Not on 5v.

Why does an adapter with 12V input not make the same blown up for arduino like in the previous case?

Because you are pluging 12v in the correct input, the 7-12v jack.
Another important link to read:
http://playground.arduino.cc/Learning/WhatAdapter


text:
Why do MEGA2560 digital pins go high on serial disconnect?
I'm trying to set up a system using an that delivers a specific number of digital pulses to a device using one of the digital pins. The number of pulses delivered is specified over a the Mega's USB serial connection using a Python script (or terminal for debugging).
When I close the serial connection to the Arduino, I get a short "blip" that looks like a digital high (see image below). This happens when I disconnect in PySerial using Serial.close() or when I simply close my Arduino IDE terminal window.
It does not occur when I press the reset button on the board
Any ideas on how to get rid of this?  Thanks!

You could try adding a pull-down resistor to the pin, and see if the problem persists. Does the Arduino reset itself, when you disconnect the serial connection?

Maybe it's a wiring thing. Try posting a schematic of your setup. Perhaps we need to see the circuitry inside the "device" you've connected the Mega to.

Its definitely a wiring thing; you may have shorted something or missed shorting all grounds in case you have more than one;

What digital pin? What is your code?

When you connect and disconnect from the Arduino, the usb host chip resets the entire device. If you do not want this you can cut the RESET trace on the board.

some boards have a jumper here instead that can be removed.
more info here
https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection


text:
Arduino HC-SR04 water experiment
I am working on an experiment with the HC-SR04 sound sensor, and i am using it to record the speed of sound. I successfully measured the speed of sound in air, but when measuring it in water, I encountered a small problem. The sound waves emitted by the sensor are both absorbed and reflected off the water. Obviously, the reflected sound waves are the first ones to reach the sensor, and therefore are the ones used for calculating the speed of sound. Is there a way to code the Arduino program in order to ignore the first set of waves and only record the set of waves that were absorbed by the water? I was thinking of increasing the delay time for the pulse, but I'm not sure that would work.
Thanks.

Are you submerging your HC-SR04?

I am not, I'm signaling from outside the water, and thats why the wave is reflected back. I believe if I submerged it, it would work, but I cant find a way of submerging it without breaking it.

All you need to do is ignore any reading within the first  milliseconds.  Off the top of my head there is a delay statement before reading from this sensor, just alter that.  You can work out how long it needs to be by working out how fast sound waves travel through the air and measuring the distance between the sensor and the source of the reflection.  I think you might know how to do that :)