message:
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();
      }
    }

body:
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.


sender: user

sender: assistant

body:
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.


message:
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]:

1. Will the passing of several board cycles before the read completes affect the read?
1. Is there a method to lock the serial output buffer while reading
(such that the data does not change midread)?
1. 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.

body:
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.


message:
Help understanding Print::write()--it calls write()--where is write() defined? Help reading code

I'm writing a new serial library ([eRCaGuy_Peer2Peer][1]) 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][2], I see it inherits from the [Stream class][3], which inherits from the [Print class][4].

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:**

 1. What does this mean? I've never seen anything like this before: `virtual size_t write(uint8_t) = 0;` Why the `= 0`?
 2. 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));
    }`

 3. Where is the `write` command I've marked above defined? Is Print::write() calling itself recursively?
 4. Also, why does [SoftwareSerial.h][2] 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;

  [1]: https://github.com/ElectricRCAircraftGuy/eRCaGuy_Peer2Peer
  [2]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h
  [3]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Stream.h
  [4]: https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/Print.h

body:
`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.


body:
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.


message:
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:

 1. 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.
 2. 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:

 1. 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.
 2. 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?

body:
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.


body:
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.

[simple GPS library]: http://www.technoblogy.com/show?10WT


body:
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.


body:
You may be interested in my [NeoGPS](https://github.com/SlashDevin/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**.


message:
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 );

    }
    }

body:
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][1]
- 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.

  [1]: https://www.arduino.cc/en/Tutorial/Switch


body:
A few things will need to be done.

1. 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.

2. 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.


body:
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

    }


message:
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?

body:
<s>No, there isn't.</s> 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:

<!-- language: c++ -->

    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.


body:
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) {}


message:
Using SCL and SDA of ESP8266-01 with GY-30 BH1750FVI for lux measurement

I followed [this][1] 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;
    }

  [1]: http://blog.simtronyx.de/en/measurement-of-illuminance-with-a-bh1750fvi-breakout-board-gy-30-and-an-arduino-uno/

body: `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).


message:
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)).

body:
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.


message:
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

body:
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;


message:
Why using a ESP01 adapter?

I bought an ESP-01 adapter (initially I thought this was the WIFI module):

[ESP-01 adapter][1]

Than I bought the 'real'  ESP-01 (which is not arrived yet):

[ESP-01][2]

However, according to this link: [connect][3] (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)?

  [1]: https://www.aliexpress.com/item/ESP8266-Serial-WiFi-Wireless-ESP-01-Adapter-Module-3-3V-5V-Compatible-For-Arduino/32740663668.html?spm=2114.13010608.0.0.90dm9a
  [2]: https://www.aliexpress.com/item/Cr2032-battery-3v-cr2032-lithium-battery-button-cell-battery-electronic-2032-battery-electronic/1678385231.html?spm=2114.13010608.0.0.wrwcB5
  [3]: http://domoticx.com/esp8266-wifi-esp-01-module-aansluiten/

body:
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.


message:
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?

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


body:
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][1]

Use something like:

     pinMode(BUTTON, INPUT_PULLUP);

  [1]: https://www.arduino.cc/en/Tutorial/InputPullupSerial


message:
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][1], 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

  [1]: https://arduino.stackexchange.com/questions/38319/how-can-i-identify-debug-or-fix-a-faulty-imu/

body:
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.


message:
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.

body:
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.


body:
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


message:
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);
    }

body:
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.


body:
If you are using the [Adafruit MCP23017 library](https://github.com/adafruit/Adafruit-MCP23017-Arduino-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.


message:
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][1], 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.**

[![][2]][2]

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][3] 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.

  [1]: https://www.arduino.cc/en/reference/servo
  [2]: https://i.stack.imgur.com/W3Fpk.png
  [3]: https://www.youtube.com/watch?v=KUmNDbAEv_c

body: 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?


body:
You need to learn about [Inverse Kinematics](https://en.m.wikipedia.org/wiki/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.


message:
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);
    }

body:
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][1]?
**

  [1]: https://www.arduino.cc/en/Reference/SPI


body:
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.


body:
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](http://www.ti.com/lit/ds/symlink/ads8320.pdf)*

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


message:
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..

body:
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.


message:
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,
            "lu,],]\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!!

body:
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.


body:
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;


message:
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?

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


body:
Yes, but I am not sure it can work from the smaller Arduino models. Have a look at the [Phoenard project][1]. The platform, based on a 2560, flashes .hex files on demand, which are stored on the SD card.

It's an [open-source project][2], so it should be possible to go through the code and see how they do it.

  [1]: http://phoenard.com/
  [2]: https://github.com/Phoenard/Phoenard


message:
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?

body:
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.


message:
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.

body:
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


message:
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!

[![blip on disconnect][1]][1]

  [1]: https://i.stack.imgur.com/mMOw8.png

body:
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.
[![enter image description here][1]][1]

some boards have a jumper here instead that can be removed.

more info here

https://playground.arduino.cc/Main/DisablingAutoResetOnSerialConnection

  [1]: https://i.stack.imgur.com/t9Uoo.jpg


message:
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.

body: All you need to do is ignore any reading within the first <so many> 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 :)


message:
Which connection should I use (preferably wireless)?

For a (for now MIDI only) project I was planning to use multiple Arduinos and send messages around.

However, for the latency, I can have max 10ms (to prevent audible delay).

I hoped to use WIFI modules (ESP-01), however, according to a previous question in [Question][1], one remark that due to HTTP overhead the time/latency would be 15 ms. So that means WIFI is not possible.

My requirements:

- Latency of <= 3 ms (rationale: I need at least 5 ms for processing, and want to keep total latency < 10 ms)
- Preferably a wireless solution (rationale: I want to add later more Arduinos and want to prevent cabling)
- Preferably not using a hardware serial (low prio requirement) (rationale: the MIDI box which is a Mega, would preferably need 4 MIDI inputs, using a hardware serial would reduce one, software serial is unacceptable for MIDI).

Situation:

- Arduinos are very close together, probably within centimeters (upto like 50 centimeters)
- Messages are short (like 5-10 bytes max)
- Burst of messages can be possible, but not so likely

Background/message flow:

- Receiving MIDI input by Arduino 1
- Sending (filtered/changed) message to Arduino 2
- Arduino 2 process the manage, takes <= 5 ms
- Arduino 2 sends message back to Arduino 1
- Arduino 1 converts it to a MIDI message and sends back

This all needs to be done within <= 10 ms

**My thoughts so far:**

Wireless solutions:

- WIFI: HTTP seems to result in 15 ms delays, which is against my requirement.
- RF: probably overkill since my Arduinos will be very near to each other. Also I would need both a receiver and transmitter in both Arduino's.
- IR: Due to out-of-sight problems not very convenient.

Wired solutions:

- I2C: Might be possible, planning to use later also an I2C display possibly but should not be a problem
- SPI: On Arduino 2, I'm already using an SRAM with SPI which I do not want to stress more (also a time-critical resource). Also an SD card via SPI is used (but this is not a time critical resource).
- Wire: Not checked yet

**Question**
Is there any wireless (or wired) solution I can use (probably beyond the ones I analyzed)?

115200 baud is what I need for a Serial connection, probably a SPI/I2C (latter preferred) is also acceptable. Or I might have missed other communication possibilities.

  [1]: https://arduino.stackexchange.com/questions/38988/why-using-a-esp01-adapter

body:
I would either use the ESP8266 as a standalone device and directly program it to work with UDP datagrams or a permanently established TCP socket, or the nRF24L01+.

Of the two I would most likely use the nRF24L01+. It's good enough for 99% of wireless keyboards and mice, so plenty good enough for a few MIDI style messages.


message:
replacing #define with typedefs for bracket scope

I have a project in which basically i have to concatenate existing code.
Each code comes with its own #defines.
But defines are not touched by the compiler, but the preprocessor.

Each snippet of the program will exist in its own fucntion.

Is it possible to include the #defines of each program - now each function, inside this function (and visible only to this function's scope)?

The proper way to do it, would be to replace text reassignment from #define to typedef?

I understand typedef is originally for defining types. But can it be used here? Is there another alternative?

body:
    #define value 255

Can be replaced with

    const int value = 255;


body:
It is possible to use "namespace { ... }" to create local defines for a *.cpp file.
In the Arduino IDE all *.ino files are combined in a single *.cpp file, therefor the "namespace" is not very useful.

When you create new tabs in the Arduino IDE and name them *.cpp, then you have different *.cpp files. Then you can use the "namespace" to create defines that are only valid for that *.cpp file.

More info: [Hackaday: Using Modern C++ Techniques with Arduino][1]

  [1]: http://hackaday.com/2017/05/05/using-modern-c-techniques-with-arduino/


message:
Atmega2560 USART UDR r/w conflict possible?

I'm having a really weird issue with my project right now. I have an Atmega2560 using hardware serial, and the software on the other side is doing full duplex read/write at 500kbps. If I change it to be single duplex, everything works fine. But the second I try to run everything truly full duplex, I start to have some data transfer over from the transmit stream to receive stream on the device (characters that its trying to write, that it somehow ends up reading again).

I've simplified things as much as possible- disabling buffering on the arduino side, using mutexes on the client software side (to prevent overlapping read/write commands, despite the fact the underlying driver will do whatever it wants).

So, there's obviously a few potential problems here, but it has to boil down to:

a) Client software/drivers misbehaving

b) Hardware serial implementation misbehaving on the device.

I really want to rule out B, and from all my digging around, it really comes down to one question:

Is there *any* possible way that data written to the UDR register could somehow be read out again? I understand this register is actually 2 different registers, and just splits out reads and writes. But is there any possible way at all this data could be read again? Like, is it possible to even write to UDR and read that byte ever again? I'd really like to rule that out before I start unnecessarily tracing ISRs and all that garbage.

Here's what I've boiled the hardware serial code down to. Interrupt driven on read and direct write on write:

    void MarlinSerial::write(uint8_t c) {
      while (!TEST(M_UCSRxA, M_UDREx));

      M_UDRx = c;
    }

    ISR(M_USARTx_RX_vect) {
      const unsigned char c = M_UDRx;
      store_char(c);
    }

UPDATE: I'm an idiot. Found a buffer overrun way downstream in the device code. It just so happened that the temp response buffer for one routine butted up against the receive buffer, so it delightfully just over-ran into there. I'm happily chugging away now with 2 totally async command streams, total about 400kbps.

body:
> Is there any possible way that data written to the UDR register could somehow be read out again?

No, there is no possibility. [The datasheet](http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf) says:

>The USART Transmit Data Buffer Register and USART Receive Data Buffer Registers share the same I/O address
referred to as USART Data Register or UDRn. The Transmit Data Buffer Register (TXB) will be the destination for
data written to the UDRn Register location. Reading the UDRn Register location will return the contents of the
Receive Data Buffer Register (RXB).

Further on it says:

> The transmit buffer can only be written when the UDREn Flag in the UCSRnA Register is set. Data written to UDRn
when the UDREn Flag is not set, will be ignored by the USART Transmitter. When data is written to the transmit
buffer, and the Transmitter is enabled, the Transmitter will load the data into the Transmit Shift Register when the
Shift Register is empty. Then the data will be serially transmitted on the TxDn pin.

And for reception it says:

> The receive buffer consists of a two level FIFO. The FIFO will change its state whenever the receive buffer is
accessed. Due to this behavior of the receive buffer, do not use Read-Modify-Write instructions (SBI and CBI) on
this location. Be careful when using bit test instructions (SBIC and SBIS), since these also will change the state of
the FIFO.

So the only thing it is possible to read is data that has been received via the RX pin (and then once and once only). All written data (assuming there is room in the TX buffer) is sent out of the TX pin.

If you are getting TX data appearing in the RX buffer then somewhere there must be some kind of connection between the TX and RX pins - either in software at the remote end (the remote device echoing everything it receives, which is perfectly possible depending on what the remote device is), or though a fault in the cabling or circuit design.


message:
Powering multiple (separately enclosed) Arduinos by one adapter

I currently use one Arduino, but my plan is to use multiple Arduinos.

These Arduinos will be relatively close together (within one meter or less), and depending on the configuration I want 2 to 5 Arduinos, all in separate enclosures.

I don't expect a high power consumption from all of them, but I don't want to use batteries. So I would like to use a 9V or 12V adapter with 2A (cannot find higher amperage).

My questions:

- Can I just split the cable, and add extra plugs for the other Arduinos? (so like a parallel circuit of Arduinos)?
- Is it a problem if I only would connect 1 Arduino? (I don't think so)
- Is there a maximum Amperage I can divide this way? (I mean what if I would find a 5A adapter?)
- I see 9V or 12V adapters ... why would this matter, since the Arduino works on 5V anyway. I don't need to drive external motors, just like 5 small LEDs, some ICs (optocouplers, SRAM) and some basic connectors (like MIDI, later DMX, Audio etc), an RF or ESP01 module.

body:
> Can I just split the cable, and add extra plugs for the other Arduinos? (so like a parallel circuit of Arduinos)?

Yes.

> Is it a problem if I only would connect 1 Arduino? (I don't think so)

No.

> Is there a maximum Amperage I can divide this way? (I mean what if I would find a 5A adapter?)

You can draw, in total, whatever the power supply can provide. If 10 Arduinos need 500mA and you have a 5A power supply you can power 10 Arduinos from it.

If they draw just 50mA you could power 100 Arduinos from it. It's all just a matter of managing the wiring in a suitable manner (connecting hundreds of wires together gets tiresome).

> I see 9V or 12V adapters ... why would this matter, since the Arduino works on 5V anyway. I don't need to drive external motors, just like 5 small LEDs, some ICs (optocouplers, SRAM) and some basic connectors (like MIDI, later DMX, Audio etc), an RF or ESP01 module.

12V will cause more heat dissipation from the linear regulator in the Arduino than 9V will, since the 12V has to lose more of the voltage as heat.


message:
Sending information via USB/Serialport

Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

To put this in context, I'm doing some vision processing on my computer, with Visual Studio, and I want to send some motor output via USB for the Arduino to execute.

body:
You can do it in a number of ways, but essentially your PC is going to open a serial connection to the Arduino and send data to it which will be interpreted into state changes of the digital ports of the Arduino.  The content of the messages is up to you, as long as both ends know what it means.

Step 1 would be to learn how to drive the motors on the Arduino by writing a program that drives the correct ports.

Step 2 is to modify that program so that when you type 1180 in to the serial monitor the Arduino turns motor 1 180 degrees, etc.

Step 3 Start Visual Studio, press F1 and search MSDN for a Serial console program that you can 'borrow'.

Step 4 Check your new serial program can replace the serial monitor and you can still turn motor 1 to 180 degrees.

Step 5 Put a flowery GUI over you serial console and polish your turd. :)

It doesn't matter what the GUI does, its still just a serial client talking to the Arduino.  You could offer Bluetooth or Wi-Fi connections, but its essentially the same beast.


body:
I imagine Code Gorilla's given you the proper, specific answer you needed. I simply wanted to address your first (more general) ask,

> Am I able to send instruction from my computer, from another compiler, via the Arduino USB port?

... and mention some other ways I've done this before. As long the Arduino's listening to the serial port for some specific (or any) input coming in, you can use whatever you'd like to send a message to the COM port your Arduino's using.

You absolutely are *not* hemmed into using solely the Arduino IDE (or it's serial monitor) for serial communication.

For instance, I wrote a Python script that communicated with an Arduino R3 (Rx/Tx) via the COM port it was assigned via the `PySerial` library - before coming to Python, I'd been doing this through a MS Visual C# WPF that was connected to the COM port and communicating with the Arduino (Rx/Tx) (you might need to adjust baud rates here or there, if I recall). Just to give you some ideas.


message:
Battery Status notifier

I am new to Arduino, and I am aware that unlike Raspberry Pi you do not have a full blown OS with many custom applications running concurrently.
I plan to start an Arduino project with an Arduino NANO that will need to be portable, and include batteries. How may I get the battery status information without disrupting the rest of the functionality?

body:
Use analogRead to measure the voltage on the battery. You might have to use the internal 1.1V reference to get a good reading.

Don't write any blocking code and the processes won't interfere with each other. That means no long for or while loops waiting for something to complete and absolutely no delay.


message:
error using String class to convert a double to a string

i wanted to convert a double to a string i tested several examples online i allawys get the same error.

the code :

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

    }
    void loop()
    {
      double val =3.2222;
      String stringOne =  String(val, 3);
      Serial.print(stringOne);
    }
the errors :

    sketch_jun02c.ino: In function ‘void loop()’:
    sketch_jun02c.ino:10:36: error: call of overloaded ‘String(double&, int)’ is ambiguous
    sketch_jun02c.ino:10:36: note: candidates are:
    In file included from /usr/share/arduino/hardware/arduino/cores/arduino/Arduino.h:192:0,
                     from sketch_jun02c.ino:2:
    /usr/share/arduino/hardware/arduino/cores/arduino/WString.h:70:11: note: String::String(long unsigned int, unsigned char)
      explicit String(unsigned long, unsigned char base=10);
               ^
    /usr/share/arduino/hardware/arduino/cores/arduino/WString.h:69:11: note: String::String(long int, unsigned char)
      explicit String(long, unsigned char base=10);
               ^
    /usr/share/arduino/hardware/arduino/cores/arduino/WString.h:68:11: note: String::String(unsigned int, unsigned char)
      explicit String(unsigned int, unsigned char base=10);
               ^
    /usr/share/arduino/hardware/arduino/cores/arduino/WString.h:67:11: note: String::String(int, unsigned char)
      explicit String(int, unsigned char base=10);
               ^
    /usr/share/arduino/hardware/arduino/cores/arduino/WString.h:66:11: note: String::String(unsigned char, unsigned char)
      explicit String(unsigned char, unsigned char base=10);
               ^

body: I had installed arduino using apt-get and I didnt notice that I had an old version. I upgraded my arduino and it worked fine.


message:
WiFiClient::connected() not working

I use an ESP32 to open an access point and listen for TCP connections over a WiFiServer object.

When I get a client on the server I want to know when it has disconnected.

Currently I have a simple piece of code on both the client and the server side. I connect using a TcpClient in C#.

When I call `client.close()` on the client side, the `client.connected()` loop on the server just continues forever.

Here is the ESP code:
<!-- language-all: lang-cpp -->

    void setup()
    {
    WiFi.mode(WIFI_AP);

    WiFi.softAP("test");

    WiFi.softAPConfig(IPAddress(192, 168, 4, 1), IPAddress(192, 168, 4, 1), IPAddress(255, 255, 255, 0));

    Serial.println(WiFi.localIP());

    server.begin();
    }

    void loop()
    {
     while (!client)
     {
      client = server.available();

      delay(10);
     }

     while (client.connected())
     {
      Serial.println("ok");

      delay(1000);

      client.read();
     }
    }

C# code:

    static void Main(string[] args)
    {
         TcpClient client = new TcpClient("192.168.4.1", 222);

         client.Close();
    }

body:
This is a bug in a previous version of the library as mentioned on
https://github.com/bportaluri/WiFiEsp/issues/14

You can alternatively use WiFi.softAPgetStationNum() to get the count of stations connected to the AP interface.


body:
**My actual answer**

You can try to inquire `client.status()` as a workaround. When no one is connected it should return 0.

**Context**

What are you building on? I tried to reproduce your problem but everything works as expected, the serial stops printing "ok" when I disconnect.

Also, what libraries are you using exactly? I included `ESP8266WiFi.h` and `WiFiClient.h`.

I used platformio v3.4 on an ESP8266-01 module and a simple Android netcat app as client.


message:
Is it possible to use Serial window for debug statements while using the hardware serial port for GPS module?

I am using the hardware serial ports of Atmega 328 to connect to a GPS module . A GSM SIM900 module is connected via Software serial . Is it possible to print the debug statements in the Serial window while the GPS module is connected to the hardware serial ports? Both my module and the Serial window is set to 9600 bps baud rate .
Also I want to read the GSM responses from the Software serial and print the same in the Serial window for debugging. Is this possible?

body:
> Is it possible to print the debug statements in the Serial window while the GPS module is connected to the hardware serial ports?

Yes, that works.  If you connect the Arduino TX pin 1 to the GPS RX, then everything you print to Serial goes to *both* the Serial Monitor window and the GPS device.

This works, because:

*  It's ok if you see the GPS configuration commands (if any) on the Serial Monitor window.  Your debug prints will appear after them.
*  The GPS device ignores anything that doesn't start with a '$' character; it ignores all your debug prints.


body:
While I agree with slash-dev, I feel unless you're really struggling with pin real state, you don't really need to have both the GPS serial and UART on the same pins (unless I'm missing some point or convention, in which case please do correct me).

When I was using a GPS module (GTOP013) with an Atmega328p, I just used the SoftwareSerial library to configure some unused pins (12 and 13 I think? it's been a while) as a dedicated RX/TX lines to the GPS, whilst the atmega's RX/TX remained reserved for a USB connection. Any time I needed anything sent to or from the GPS, I had a function to handle that. Also allowed me to keep polling the lines for data from the GPS to be printed onto the Serial.Console as desired for debugging.


message:
Don't Print After decimal point in

In my code, I have  `float Hz = 0.00;` I want to display values to my user in RPM as

    Serial.print("Speed = ");
    Serial.print(round(Hz*60);
    Serial.println(" RPM);

The only hangup is that this displays as `Speed = XX.00 RPM` is there an easy way to get the Arduino to only print out `Speed = XX RPM`?

body:
From the documentation:

    Serial.print(round(Hz*60), 0);


message:
How do I load an image using fopen()?

I am trying to write a program that `fopen()`s an image so I can use it later.

I've wired my SD card adapter exactly the way shown here:
[![enter image description here][1]][1]

And I'm using the following code to `fopen()`:

    FILE *streamIn;
    streamIn = fopen("pic.bmp", "r");

When  I compile, I get the following error:

> In function main:
>
> ccA5H011.ltrans0.o:(.text.startup+0x29a): undefined reference to `fopen'

 - I have the most up-to-date Arduino software.
 - I am using the Arduino MEGA.
 - The image "pic.bmp" is 100x100 and is not in any folder of the SD card, it is located right in it instead (If I click on the SD Card in "My Files" when it is plugged into my computer, pic.bmp is there).

body:
Simple answer: use the SD library provided by the IDE.

Long answer: `fopen` etc are designed for use with an operating system. While it is possible to 'bend' them to work without a kernel or filesystem abstraction layer, it's not easy. The AVR compiler and libraries don't provide the facilities for doing it.

So you need to use the method that is specific to the Arduino, which is contained in a library supplied with the IDE called SD.h. It has examples with it to show you how to use it.

There are other alternatives, as well, such as the much better written FatFS that has been ported to many platforms, Arduino included.