message:
Can an accelerometer be used to detect heart sound?

I've recently come across accelerometer and how it can detect electrical mechanical response. I was wondering can it be used to detect heart sound? Lets say you attach the device close to your chest (where heat lies) and detect sounds and send it over bluetooth? [LPMS-B2 OEM][1]

  [1]: http://www.omniinstruments.co.uk/lpms-b2-oem.html?gclid=Cj0KCQjwyvXPBRD-ARIsAIeQeoHti08JPcuNGUKD9x-BlI_Uy1XLXcVWRV-4YPM_Q3BplXp0wrFHBJIaAvLyEALw_wcB

body:
An accelerometer detects motion (acceleration) of the physical device.

If you can convert the sound of the heart into physical vibration then the accelerometer can detect that vibration.

Converting the tiny amount of sound the heart produces into a large enough vibration for the accelerometer to detect would entail (realistically) using a microhone, amplifier, and speaker, with the accelerometer attached to the speaker cone.

So while theoretically yes, you can do it, practically why would you when you can just use the microphone and amplifier that you'd be using anyway. It's pointless.

So in reality: no, you can't.


sender: user

message:
Auto Fish Feeder

Good day, I am new to Arduino, but have made some nice projects work.
I have a n issue with a Auto fish feeder. I have used a servo that I modified to run 360. I am having a issue when the Nano board starts. It runs the time I have set between feeds, and then it stops. If I set it to feed every 10 sec, it starts up and run for 10sec and then the LED flashes and it stops. From there it works perfect. But if I lose power and it comes back, its going to feed for 10sec and that will kill the fish.

Here is my sketch I am using now, please can someone look at it and tell me where I am going wrong. I just want it not to run when it starts up, or just for the to that it feeds, not continues like now for 10sec, or 12 hours !!!

    //--Setting Vars

       //Fish Feeder Vars.
    int pinOutMotor = 3;
    int pinOutLed = 5;
    int pinInButton = 2;
    int MotorRunDuration = 1000;
    float AutoWaitDurationHours = 0.;
    //--Program Vars
    unsigned long currentMsSinceStart = 0;
    unsigned long msValueAtLastRun = 0;
    float HoursSinceLastRun = 0;
    int buttonValue = 0;

    void setup() {
      Serial.begin(9600);             //Turns on serial monitor.
      pinMode(pinOutMotor, OUTPUT);   //Is controlled by a 3906 npn transistor to switch the motor off and on.  When program started I need to add a line to turn off motor when program was started.
      pinMode(pinInButton, INPUT);    //Manual feed.
      pinMode(pinOutLed, OUTPUT);     //Shows motor is on when lite.
    }

    void loop() {
      //HoursSinceLastRun = AutoWaitDurationHours - 0.05; //this will make it run 3 minutes after turned on.

    //Fish Feeder
      //get miliseconds since program start and calc.
      currentMsSinceStart = millis();
      HoursSinceLastRun = (currentMsSinceStart - msValueAtLastRun) / 10000; //10000 millis= 10 seconds.  To change the time to vary feeding times set for 12hrs type in 43200000 or 6hrs tyoe in 21600000.
      //check for button press
      buttonValue = digitalRead(pinInButton);
      if(buttonValue == HIGH){  //had to change state because of button from LOW to HIGH.
        //run motor for button press.
        RunMotor();
        Serial.println("Feed Fish Manually");  //serial print funtion completed by button

      } else if(HoursSinceLastRun > AutoWaitDurationHours){
        RunMotor();
        msValueAtLastRun = currentMsSinceStart;
        Serial.println("Feed Fish Auto");      //serial print funtion completed by auto wait duration hours
      }
      //slow the loop down so it isn't running at full CPU Utilization for nothing.
      delay(50); //delay 1/20th of a second.
    }

    void RunMotor(){
        analogWrite(pinOutMotor, 0);   // turn on motor
        analogWrite(pinOutLed, 80);        // turn on green led to show motor is on.
        delay(MotorRunDuration);   // wait for motor run duration to expire
        analogWrite(pinOutMotor, 255);    // turn off motor
        analogWrite(pinOutLed, 0);        // turn off green led to show motor is off.
    }

sender: assistant

body:
If I correctly understand, your problem is really with the restart, that will always feed the fish.

You can use the EEPROM to save the last time you feed the fish. You also need a RTC to get the real time.

Every time you feed the fish, you also write in the EEPROM the current hour:minutes (from the RTC). When you restart, you read your last feed from the EEPROM and uses it to initialize `msValueAtLastRun`. You have to change your time recording to hh:mm instead of millis from start.

You code looks OK, only missing debouncing the button.

You can also use a NodeMCU, and get your time via NTP.


message:
Boil water inside a small container with an arduino

I am currently working with a sciene/electronic project where i need "steam". In order to create steam i need to boil water and i plan to boil it inside a very small container [around 5cmx5cmx5cm]. What i want to do is to control this with an arduino but I am very unsure on what step i currently need to make. Are there any "heating-up" modules out there? Or would I need to order a mini-mini kettle and connect that to my arduino?

I am very grateful for every advice i can get because as u can tell i am a bit confused as of right now!

body:
Try to find a boiler pot on electricity (I doubt you can heat water to boiling temperature with like 5V (unless you use many amperes).

Use a relais to switch it on with an Arduino.

Use a temperature sensor (0-150 degrees or so) to decide when to switch it off.

Warning: Get first some electrical knowledge before you start with >200 volts projects since it can be deadly. And boiling water can be devestating for skin and your Arduino.


message:
Getting wrong value from Serial.read()

I have an RGB LED, connected to my UNO R3 and would like to turn on the written color in the serial by following a table (1 for red, 2 for blue, 3 for green...) and I also want to make that if this LED is already turnt ON, I want it to turn OFF. The problem I have is that when I use Serial.read() it always returns a -1 value. Why is that?
I leave you the code here and in case you see something wrong please tell me. Thank you very much.

    #define RED 7
    #define GREEN 4
    #define BLUE 2
      String ledcolour[] = {"RED", "BLUE", "GREEN", "YELLOW", "PURPLE", "WHITE"}; //array to match the number typed to the LED colour
      char ledstatus[] = {0, 0, 0, 0, 0, 0}; //0 if the LED is OFF and 1 if it's ON
      String ledvaluefix[] = {"HIGH", "LOW"}; //if the ledstatus[] value is 0 it will write HIGH and if it's already ON it will write LOW
      char ledstatusfix[] = {1,0}; //to update in ledstatus[] if the LED is ON or OFF
      int led = Serial.read();
    void setup() {
      pinMode(RED,OUTPUT);
      pinMode(GREEN, OUTPUT);
      pinMode(BLUE,OUTPUT);
      Serial.begin(9600);
      Serial.println("Type the LED's colour you want to turn on following this table:");
      Serial.println("RED=1");
      Serial.println("BLUE=2");
      Serial.println("GREEN=3");
      Serial.println("YELLOW=4");
      Serial.println("PURPLE=5");
      Serial.println("WHITE=6");
    }

    void loop() {
      if (Serial.available()){
        Serial.println(led);
        loop();
       if (led <= 6 && led >=1){ //Checks if value is within 0-6
        if (led <=3){ //Classifies in primary or mixed colours (understand primary as just having to turn ON one single LED)
          if (ledstatus[led-1] == 0){//checks if the LED was OFF
            digitalWrite(led-1,HIGH);//turns the typed LED to HIGH
            char ledstatus[led-1] = {1};//updates the array to set the LED is now ON
            confirmer();//sends a serial confirmation message
          }else{//if it was already ON
            digitalWrite(led-1,LOW);//turns the typed LED to LOW
            char ledstatus[led-1] = {0};//updates the array to set the LED is now OFF
          }
        }else{//if it's not a primary colour
          Serial.println("YOU CHOSE " + ledcolour[led-1] + ", WHICH IS A MIXED COLOUR");
        }
        }else{//if the value is not valid (not between 0 and 6)
          Serial.println("SORRY, THE INTRODUCED VALUE IS NOT VALID");
          Serial.println("PLEASE, TRY AGAIN");
        }
      }
    }
     int confirmer(){
        Serial.println("YOU CHOSE THE " + ledcolour[led-1] + " LED");//sends the serial message confirming it's been turned ON
       }

body:
This

     int led = Serial.read();

is execute before `setup()` and `loop()`, just one time. All initializations outside any function are execute before the start of the program. You have not execute `Serial.begin` yet.

You probably want to read inside the `loop` ...

**Edit:**

Second problem: you are calling `loop` recursively

    void loop()
    {
     if(Serial.available()) {
      Serial.println(led);
      loop();

When a byte in available in the serial port, you will call `loop`. As you never read the serial port, `Serial.available` will still return > 0, and you will enter in a never ending recursion.


message:
Change Arduino Clock Speed

I want to run an arduino board at a slower - but more accurate - clock speed. What (if anything) needs to be changed in the arduino code/libraries in order to achieve this? Normally the boards I use run at 16MHz, but I wish to derive a 10MHz clock from a GPS timing module and run the ATMEL processor off the 10MHz timing clock.

body:
You have to change `F_CPU` only - You can add new board into the boards.txt with correct clock speed.
EDIT: Aparently millis counter will be drifting much more then expected due to "rounding" errors.

The bootloader on the other side needs to be recompiled with correct `F_CPU` and  reflashed, if you want it working at the same baud rate (plus it's possible to change fuses to use external clock source instead of crystal). Otherwise you have to try reduced speed (also configured in board config).

You can use [MCUdude/MiniCore][1] as inspiration. It supports many clock speeds (but 10MHz doesn't)

  [1]: https://github.com/MCUdude/MiniCore


message:
Using Li-Poly battery to run UNO + Adafruit data logger

I want to power Arduino UNO+Adafruit data logger (https://www.adafruit.com/product/1141) with a 3.7V 2000mAh Li-Poly battery. I am providing an excitation voltage of 3V, through one of the digital pins and a potential divider arrangement, to a sensor which is providing output signal in analog (voltage) form. I am using ADC to read that voltage. My question is, since the battery voltage is going to drop during its operation, would the voltage output from the digital pin, and thus the potential divider, also drop? Could this voltage drop also affect the reference for the ADC?

body:
You can't run the Arduino UNO directly from 3.7V.

You can use a boost regulator to step up to 5V and feed that into the 5V pin - in which case your question becomes null and void, since you are running at 5V, not 3.7V.

Or you can perform some hardware and/or fuse modifications and run the board directly from 3.7V into the 5V pin:

* You will have to change the surface mount resonator to an 8MHz one instead of the normal 16MHz, or
* Switch the clock to use the internal RC oscillator by reprogramming the fuses.

Either way you will then have to also modify the board configuration in the IDE to run at the new clock speed.

So given all that the simplest thing to do is to invest in a 5V boost regulator. Personally I'd suggest the [LiPower Shield from Sparkfun](https://www.sparkfun.com/products/13158). It also has a "fuel gauge" chip to monitor the batter charge.

Either that or scrap the Uno and invest in a development board that is designed to run from a Li-Poly / Li-Ion / LiFePO4 battery.


message:
ESP8266 Websocket issue

I realize it might be dumb question, but I've been at it for a few hours and I'm going nowhere. I am trying to figure out the standard Websocket library, however I have an issue casting the uint8_t to a String, so I can work with it easily, how do I do that and is it even possible? What I want to do is, get the payload from the main function as shown in the standard library and give it as a parameter to a function I have. This is the part I need, this is part of the switch statements in the standard library.

    void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {

       switch(type) {
         case WStype_DISCONNECTED:
         Serial.printf("[%u] Disconnected!\n", num);
       break;
       case WStype_CONNECTED:
        {
          IPAddress ip = webSocket.remoteIP(num);
          Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);

          // send message to client
          webSocket.sendTXT(num, "Connected");
        }
       break;
       case WStype_TEXT:
          Serial.printf("[%u] get Text: %s\n", num, payload);
          move(payload);

body: you can't cast it. payload is an array of received bytes and length is the size of received data in that array. if the bytes are characters and you would know that there is one more position allocated in that array, you could put a 0 to payload[length] and by cast to char* it would become a zero terminated string. but you can't know if there is that one byte allocated, so you must copy the payload to your buffer of chars and set a zero at the end.


message:
Set clockspeed of Arduino Pro Micro a. k. a. AtMega32u4

Is it possible to change clock speed when running sketch?

Low-power lib drops the current consumption from 20mA to 9.5mA at 8MHz, it is still too much. Is there a way how to set clockspeed (for example) to 1MHz, go to sleep, after interrupt wake up, set clockspeed back to the 8Mhz (for 3v3), do some stuff and then go sleep again?

Thanks

body:
Absolutely. The built-in prescaler can dynamically change the clock speed for most of the systems on the chip (USB still needs to run at full speed in order to operate properly).

    #include <avr/power.h>

     ...
    clock_prescale_set(clock_div_32);
    sleep();
    clock_prescale_set(clock_div_1);
     ...

See the datasheet and AVR Libc documentation for more details.


message:
Arduino Mega 2560 not recognized/overloaded

I pulled my Arduino set out of storage yesterday and was very upset to find that it is not working for some reason.  Before I explain the problem, let me explain the situation.

Hardware (all DFRobot):

Arduino Mega 2560

Arduino Mega 2560 4x-platform breakout board

GPIO Expansion Shield V1.0

I/O Expansion Shield V7.1

8 Channel 5V Relay Board

4 LED/Resistor set up

1 digital speaker

1 digital humidity/temperature tester

7 analog chemical air chemical testers

The whole project:
[![enter image description here][1]][1]

LED Portion:
[![enter image description here][2]][2]

Relay Portion:
[![enter image description here][3]][3]

Sensor Portion:
[![enter image description here][4]][4]

Pin Connections:
[![enter image description here][5]][5]

In this 4th photo, the two analog pin sets in use right in front are the ones I remove in order to gain control again.  if those are plugged in then it doesnt work.  It has nothing to do with those pins specifically, If I remove any two it works again, those ones are just easiest to remove to get it to work:
[![enter image description here][6]][6]

Explanation of project:

This is basically a test station, where I can hook up what ever I want and see how it works and then move onto another peripheral piece of hardware and make them interact.  I went with the 4x-platform breakout board as to maximize I/O space.  Once a project is done, I Velcro band them together as to not get them confused and move on.

Explanation of problem:

When I plugged the Arduino into my PC the first time, the lights came on the Arduino and then after about 15 seconds it powered down and the lights went off.  My PC did recognize it while it was powered up and the port option under tools in the Arduino IDE was available and I could select the port.  After the power down and problems I realized something must be up.

I considered the fact that maybe the Velcro was constricting the wires and causing them to short circuit through the rubber insulation, but couldn't find any info on that online.

After this I decided to cut the PC out of the equation and try just plugging it into the wall, 1st, via USB to 5V1A wall charger, it stayed on for a few seconds and then turned off, 2nd with a 5V2A wall charger, same scenario, 3rd via the barrel jack with the same wall chargers, with no success.

I undid all of the wire bundles to rule out a short circuit, which it did.  I then found out after much trial an error that if I removed any 2 of any analog or digital wires, the lights would stay on and it would work.

Now, with two cables removed so it did not lose power, I plugged it into my PC and am now able to program it again and see it in the port in the IDE, but as soon as I plug in another 2 analog or digital peripheral devices it will lose all power and stop working.

I also tried plugging my DFRobot Beetle micro-controller in with the same USB cable and it worked perfectly.  I also tried resetting the micro-controller, to no avail.

Conclusions so far:

A short between rubber insulation at 5v is extremely unlikely

one would think that if a mega board was designed to have so many I/O pins you could actually connect to all of them with out any problem.

Since this happened on both the PC and wall charger scenarios, and the problem seems to be associated when disconnecting any 2 sensors, the problem is most likely at the micro-controller level.

Questions:

are all the peripheral devices draining the board so much that the USB port on the PC or wall chargers cant handle it?

How do I provide enough power to the board if this is the problem?

Or is this simply faulty board?

If it is a faulty board, what causes this and how do you avoid it?

Just to clarify, looming the wires together into bundles is OK right?

Finally, any help would be really appreciated, this is the first time this has happened and it sucks.

  [1]: https://i.stack.imgur.com/uQXQD.png
  [2]: https://i.stack.imgur.com/ST2Bi.png
  [3]: https://i.stack.imgur.com/gPIrM.png
  [4]: https://i.stack.imgur.com/HtJxz.png
  [5]: https://i.stack.imgur.com/I1nu2.png
  [6]: https://i.stack.imgur.com/UNftq.png

body:
First off, that is one heck of a rig.  I'm impressed to the point of "I gotta get me one of those."

Bundling your wires shouldn't have the kind of impact you are seeing, unless there are bare wires touching.  You might get induction interference, but not a total shut down.

From what I can see here, it looks like there's so much stuff connected to the Arduino that it's probably starving it for power.  You should look into using power rails for Gnd and +5v.

You will also need to check if you are supplying it with enough amps, too.  Your computer's USB port only supplies 0.5A, unless it happens to be USB3, then it's 0.9A.  Even your 5V1A PSU might not be enough.  Consider finding a 2-5 amp wall wart to do some more testing with.  There are usually spec sheets with components, so you'll need to add all the power draw for all the components, including the Arduino, and make sure you have more than enough to meet that calculated power draw.  Exceeding it by at least 10-20% is usually considered good practice, even for a test rig.

Consider powering your rig's new power rails with the extra PSU even when the Arduino is plugged into your computer.  As long as you make sure you aren't trying to take power from the computer and the PSU at the same time with the same component, you should be fine.  (Don't cross the streams.)

There could be a short or feedback loop somewhere in your sensors that's causing the extra drain.  There are so many wires here that it'd be easy to hook up something backwards.  Along with the number of wires, the bundling doesn't let SE-us help you track that down.

You might want to look at the direction your pins are facing.  It was an odd situation for me, but having two of the metal clips facing each other was enough for a short.  In your "Relay Portion:" pic, they are all facing the same way, which is good.  See if there are places where that's not the case and fix it.  Like I said, it was an odd situation, but it's a phantom problem you can avoid.


message:
Arrays, and for loops... faster to use together, or not to use?

I'm a 4th year EE undergrad, so I'm more of a hardware guy than software. But concerning best programming techniques, is it "better" (more efficient/and/or equally effective) to use for loops when trying to change several items in an array by the same mathematical operation?

--OR--

Is it best to list each item out and have each operation performed by the rate at which the primary "void loop" cycles?

I'm using a Teensy 3.2 board and trying to get a DSP reverb effect working. I have an array of 8 delay tap lines, each with a different time multiplier. I'm trying to determine if it will take more time to process a for loop for each delay-tap line, versus multiplying each element in my array without the additional loop. I need to minimize processing time at all costs to avoid additional system lag.

Sample code:

      //Set delay times
      for(int i = 0; i < 8; i++)
      {
        delay1.delay(i, pot1*pauses[i]);
      }

versus

      delay1.delay(0, pot1*pauses[0]);
      delay1.delay(1, pot1*pauses[1]);
      delay1.delay(2, pot1*pauses[2]);
      .
      .
      .

**EDIT**
Added sample code.

body:
Have a look at the compiler output.

**The Loop option**

The first alternative produce a preface (setting things) and the loop itself.

*Preface*

    40201803: 21c9       s32i.n a12, a1, 8
    40201805: 3109       s32i.n a0, a1, 12
    40201807: 00a0c2         movi a12, 0
*loop*

    4020180a: 202cc0         or a2, a12, a12
    4020180d: 01ccc2         addi a12, a12, 1
    40201810: ff8585         call0 4020106c <delay>
    40201813: f38c66         bnei a12, 8, 4020180a <_Z6XYtestv+0xa>

**The unfolded option**

While the unfolded version is:

    40201823: 020c       movi.n a2, 0
    40201825: 3109       s32i.n a0, a1, 12
    40201827: ff8445         call0 4020106c <delay>
    4020182a: 120c       movi.n a2, 1
    4020182c: ff83c5         call0 4020106c <delay>
    4020182f: 220c       movi.n a2, 2
    40201831: ff8385         call0 4020106c <delay>
    40201834: 320c       movi.n a2, 3
    40201836: ff8345         call0 4020106c <delay>
    40201839: 420c       movi.n a2, 4
    4020183b: ff8305         call0 4020106c <delay>
    4020183e: 520c       movi.n a2, 5
    40201840: ff8285         call0 4020106c <delay>
    40201843: 620c       movi.n a2, 6
    40201845: ff8245         call0 4020106c <delay>
    40201848: 720c       movi.n a2, 7
    4020184a: ff8205         call0 4020106c <delay>

So, the loop execute 4 instructions per each array element, while the unfolded version had only 2 instructions per array element.

But you are trading speed for space and and risking an error while coding the same repetitive thing.

However, GCC (the 'Arduino' compiler) can unfold the loop by itself, so you still can write a loop but execute a sequence. Look at [Tell gcc to specifically unroll a loop][1]

**Real numbers**

I run a sketch (Arduino UNO) to time loop vs unfolded. The times for 1,000 execution of each method are:

    loop:     6524us
    unfolded: 3808us

Quit a difference!

Sketch

    int pause[8] = {1, 2, 3, 4, 5, 6, 7, 8};
    typedef int (*fn)(void);

    void setup() {
      Serial.begin(9600);
      while(!Serial);
      Serial.println();

      Serial.print("Timing loop: ");
      Serial.print(time(met1));
      Serial.println(" us");

      Serial.print("Timing unfolded: ");
      Serial.print(time(met2));
      Serial.println(" us");
    }

    void loop() {

    }

    int time(fn f) {
      unsigned long start = micros();
      int x = 0;
      for (int i = 0; i < 1000; i++) {
        x = f();
      }
      unsigned long dif = micros() - start;
      return dif;
    }

    int met1() {
      int sum = 0;
      for (int i=0; i < 8; i++) {
        sum += pause[i];
      }
      return sum;
    }

    int met2() {
      int sum = 0;
      sum += pause[0];
      sum += pause[1];
      sum += pause[2];
      sum += pause[3];
      sum += pause[4];
      sum += pause[5];
      sum += pause[6];
      sum += pause[7];
      return sum;
    }

  [1]: https://stackoverflow.com/questions/4071690/tell-gcc-to-specifically-unroll-a-loop


body:
>  is it "better" (more efficient/and/or equally effective)

depends on your definition of "better", or "efficient", ...

for example unrolling a loop is typically more efficient speed-wise, but less so space-wise. or vice versa.

on top of that, you have other potential definitions for "efficiency", like readability, etc.


message:
How do I combine a variable and characters into a string with Arduino?

I am building some sensors with Arduinos, which each have a unique integer address from 1-9 (This address is an int variable stored in a struct 'Matrix', the variable name is Matrix.Address). The sensors will all be connected to a PLC via SoftwareSerial (BitBanging) through an RS232 converter. Since all of the Sensors will be connected to the same RX & TX ports on the PLC, I need a way to address each sensor through a unique string.

My plan is the following:

*If the PLC wants a reading from sensor #1, it will send the string: "1,read<CR>"
All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

*What I am trying to do is come up with a line of code similar to the following:

        if (plcCommand == (Matrix.Address + ",read<CR>")) {
      mySerial.print(GenerateEquation());

Basically, I need to insert that 'Matrix.Address' variable into a string which will be compared to the incoming string.

It seems like a very simple thing to do, but I am having trouble coming up with a solution.

Any help would be appreciated!

body:
You're thinking backwards. Instead of building up one string and comparing it to another, you should instead be splitting down the string you are being sent and dealing with the different parts of it separately.

Say you are being sent the string `32,read\r`. Instead of making another string `32,read\r` and comparing it to what you have received you should instead be splitting the incoming string up.

That way you then have a string containing `32` which can be converted to an integer, and a string containing `read`. It now becomes very simple to do your comparisons without messing with building strings in RAM wasting precious memory.


body:
> it will send the string: "1,read"

Fairly simple:

1) the dumbest would be to use serial print to print the number, and then ",read".

2) a close 2nd (in terms of dumbness) is to use s/printf(): simple but costly on a mcu.

3) a smarter approach is to convert the number to a string - you can use standard c routines if your compiler supports them, or hand-roll your own.

4) if the number of sensors are limited, a look-up table or a switch/case statement would work well.


body:
> If the PLC wants a reading from sensor #1, it will send the string: "1,read" All of the sensors should receive this string, but I only want the sensor with address '1' to respond.

Is your question about sending the "1,read".  If you're using a serial line like you say then there is no difference between sending that as a single string in one print command or sending first the number and then the text part using two print commands back to back. The exact same thing will end up going out over the wire either way.  So just use two separate print commands.


message:
Using typedef to declare a buffer type which then to pass by reference as function argument

I'm new to Arduino, but I'm a C/C++ veteran (not to mention some other languages).

Now I was under the impression that the code I'm typing into the Arduino IDE was a C or C++ dialect. However, just now I ended up puzzled because the compiler wouldn't swallow either of the following:

    #define RFID_SIZE 5
    #define CSUM_SIZE 1
    typedef unsigned char rfidbuf_t[RFID_SIZE+CSUM_SIZE];

or my first attempt:

    #define RFID_SIZE 5
    #define CSUM_SIZE 1
    typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

Now I figure that a `#define` ought to be cheaper than a constant, so that's why I went for defines. The fact that `#include` is supported suggested to me there'd be a `cpp` in the Arduino development environment as well.

What struck me as odd was the fact that I get to see the error only on the next code line (not on the line with the `typedef`):

    rfid_serial.ino:6:18: error: ‘rfidbuf_t’ was not declared in this scope
    rfid_serial.ino:6:29: error: ‘code’ was not declared in this scope
    rfid_serial.ino: In function ‘bool ReadRFIDTag(byte (&)[6])’:
    rfid_serial.ino:15:33: error: ‘bool ReadRFIDTag(byte (&)[6])’ redeclared as different kind of symbol
    rfid_serial.ino:6:6: note: previous declaration ‘bool ReadRFIDTag’
    rfid_serial.ino: In function ‘void loop()’:
    rfid_serial.ino:96:21: error: ‘ReadRFIDTag’ cannot be used as a function

The code I came up with was an attempt at optimizing the way [this works][1]. In particular I noticed that `String` (a class, it seems?!) Increases the size of my code quite a lot. So I thought a reference to the buffer would be a sensible choice here.

Here's the complete code:

    #include <SoftwareSerial.h>
    #define RFID_SIZE 5 // the code size (digits) of the RFID tag.
    #define CSUM_SIZE 1  // the csum size (digits) of the RFID tag.
    typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

    SoftwareSerial RFID(2, 3); // RX and TX

    void setup()
    {
      RFID.begin(9600); // start serial to RFID reader
      Serial.begin(115200); // start serial to PC
    }

    /* From: https://efxa.org/2013/05/23/simple-function-implementation-for-parsing-rfid-tags-in-arduino/ and adjusted. */
    bool ReadRFIDTag(rfidbuf_t& code)
    {
      byte value = 0;       // temporary data received from RFID reader.
      byte checksum = 0;    // checksum data of RFID tag received.
      byte bytesRead = 0;   // number of received data from RFID reader.
      byte tempByte = 0;    // temporary value used for checksum calculation.

      bool handled = false; // flag indicating if an RFID tag was handled.

      // if there are any data coming from the RFID reader.
      if (RFID.available () > 0)
      {
        // check for the STX header (0x02 ASCII value).
        if (0x02 == (value = RFID.read ()))
        {
          // read the RFID digits & the checksum digits.
          while (bytesRead < (RFID_SIZE + CSUM_SIZE))
          {
            // if there are any data coming from the RFID reader.
            if (RFID.available () > 0)
            {
              // get a byte from the RFID reader.
              value = RFID.read ();

              // check for ETX | STX | CR | LF.
              if ((0x0D == value) || (0x0A == value) || (0x03 == value) || (0x02 == value))
              {
                // stop reading - there is an error.
                break;
              }

              // convert hex tag ID.
              if ((value >= '0') && (value <= '9'))
              {
                value = value - '0';
              }
              else if ((value >= 'A') && (value <= 'F'))
              {
                value = 10 + value - 'A';
              }

              // every two hex-digits, add byte to code.
              if (bytesRead & 1 == 1)
              {
                // make some space for this hex-digit by shifting
                // the previous hex-digit with 4 bits to the left.
                code[bytesRead >> 1] = (value | (tempByte << 4));

                if (bytesRead >> 1 != 5)
                {
                  // if this is checksum byte, calculate the checksum (XOR).
                  checksum ^= code[bytesRead >> 1];
                }
              }
              else
                tempByte = value;

              // ready to read next digit.
              bytesRead++;
            }
          }

          // handle the RFID digits & the checksum digits.
          if (bytesRead == (RFID_SIZE + CSUM_SIZE))
          {
            // check if the RFID code is correct.
            if (code[5] == checksum)
            {
              // set that the tag was handled.
              handled = true;
            }
          }
        }
      }

      return handled;
    }

    void loop()
    {
      rfidbuf_t buf = {0};
      if(ReadRFIDTag(buf))
      {
        Serial.println(buf[0]); // TODO
      }
    }

Is it impossible to use `typedef` the same I'm used to from C and C++? Because what I am attempting isn't all too unusual in C or C++ code, but of course references only exist in C++.

Does it mean I should rather into working with `avr-gcc` directly? I was under the impression that the Arduino IDE is basically built atop `avr-gcc` and `avrdude` (and possibly other backend programs).

  [1]: https://efxa.org/2013/05/23/simple-function-implementation-for-parsing-rfid-tags-in-arduino/

body:
The Arduino IDE (un)helpfully copies function declarations towards the top, but fails to handle custom types properly. The solution is to hide the declarations in an unnamed namespace.

     ...
    typedef byte rfidbuf_t[RFID_SIZE+CSUM_SIZE];

    namespace {
      bool ReadRFIDTag(rfidbuf_t& code);
    }
     ...


body:
Your version of the IDE (1.0.5) is incredibly ancient (just because it's in APT doesn't mean it's up to date - only that at some point within the last 20 years someone submitted it).

That version suffers from the problems that Ignacio describes in his answer. More modern versions (we're up to version 1.8.5 now...!) use a different build system which is far more intelligent about how it lays out its function prototypes.

Go to the Arduino website and download the latest version and you won't have these kind of problems and have to work around them with strange things like unnamed namespaces.


message:
Trying to determine the phase difference between two square signals

I have been looking for the phase difference between two square signals and this is the code:

<!-- language: lang-cpp -->

    #include <avr/io.h>
    #include <avr/interrupt.h>

    void setup() {
      //Serial.begin(9600);
      pinMode(2, INPUT);    //set pins 2 and 3 as inputs and 11 as output
      pinMode(3, INPUT);
      pinMode(9, OUTPUT);
      pinMode(10, OUTPUT);

      cli();           // disable all interrupts
      TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);  //set up timer2 to generate a PWM
      TCCR2B = _BV(CS20);    //set prescalar value to 1
      //TCCR1A = 0;
      //TCCR1B = _BV(CS20);
      //TCCR1B |= (1 << CS12); //256 values
      TCNT2  = 0;
      sei();             //enable all interrupts

      attachInterrupt(digitalPinToInterrupt(2), t1_ISR, RISING);     //enable interrupt service routines on pins 2 and 3
      attachInterrupt(digitalPinToInterrupt(3), t2_ISR, RISING);

      //Serial.print(OCR2A);
      //Serial.print(OCR1A);

    }

    volatile uint8_t t1, t2;

    void loop() {
      if (t2 == t1)
      {
        OCR2A = 0;
        OCR2B = 0;
      }
      //compare time that one signal goes high to time the other signal goes high
      else if (t2 > t1)
      {
        OCR2A = (t2 - t1); //output PWM based on phase difference on pin 11
        OCR2B = 0;
      }
      else if (t2 < t1)
      {
        OCR2B = (t1 - t2);  //output PWM on pin 11
        OCR2A = 0;
      }
    }
    }

    void t1_ISR() {         //interrupt if signal on pin 2 goes high and store counter
      t1 = TCNT2;           //value to variable t1
    }

    void t2_ISR() {         //interrupt if signal on pin 3 goes high and store counter
      t2 = TCNT2;           //value to variable t2
    }

I want to operate the input pulses at 40 kHz, how can I do this and read the difference of phase? I am using the Arduino Mega2560

body:
There are a few things very wrong here.

First problem: you are clocking Timer 2 with the prescaler set to 1.
This means the timer will roll over every 256 CPU cycles. Your
input signal, on the other hand, has a period of 25 µs, which is
400 CPU cycles (I am assuming a 16 MHz Arduino). Unless you
know beforehand that the phase difference is within some window less
than 16 µs wide, your readings will be ambiguous.

You have to make sure the rollover period of your timer is larger than
the period of the input signal. This means either using a larger
prescaler (8 should do), which will decrease your phase resolution,
or using a 16-bit timer instead of an 8-bit timer.

Second problem: you are using a _signed_ integer type for the timer
readings. This makes little sense. Worse: you are computing differences
like `t2-t1`, which can overflow. Signed integer overflow is [undefined
behavior](https://en.wikipedia.org/wiki/Undefined_behavior) in C++, and
invoking it is _always a bug_.

You should declare `t1` and `t2` as unsigned, i.e. either
`volatile uint8_t`, or `volatile uint16_t` (if using a 16-bit timer).
Then you don't get overflows: you get instead a well-defined rollover
behavior.

Third problem: you are doing comparisons like `if (t2 > t1)`. This,
again, makes no sense, if only because the timer is repeatedly
rolling-over to zero. You should instead just compute `t2-t1` and work
your way from that.


body:
> how can I do this and read the difference of phase?

a few simple ways:

1) poll the input signals: For example, once a pin has gone high, wait for the other pin to go high as well.

2) xor the input signals: wait for the XOR of both inputs to go high, wait for it to go low. essentially the 1st approach;

3) use interrupts: once the first signal goes high, start a timer; once the 2nd signal to go high, stop the timer.

4) use input capture: ...

...


message:
Why char 0x80 == 0xFFFFFF80?

As far as I know a char is an 8 bit variable

[![char 0x80 == 0xFFFFFF80][1]][1]

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

    void loop() {
      char x = 0x80;
      if(x != 0x80){
        Serial.println(x, HEX);
      }

      delay(1000);
    }

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

body:
Sign extension. Try this:

    void loop() {
      char x = 0x80;
      if(x != (char) 0x80){
        Serial.println(x, HEX);
      }

Before any operation involving different types, the lower ones must be promoted to higher ones.

The constant 0x80 is an integer value, so `x` must be promoted to `int` before the test. The first bit of an `int` value is the sign bit. Sign bit is extended (copied to the left side bits). So `x` become 0xFFFFF80 and then you compare it against 0x0000080.

Every time you put a *char* where an *int* is excepted the same thing happen.

See? Programming is hard, programming in C is harder, programming in C++ is the hardest.

C is full of traps.


body:
char is signed so `0x80` is really `-0x80` (`==-128`). When promoted to a higher width the sign gets copied into the new bits `0xffffff80` (still `==-128`).

if you put unsigned in front of char you won't get that issue (though may encounter others).

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

    void loop() {
      unsigned char x = 0x80;
      if(x != 0x80){
        Serial.println(x, HEX);
      }

      delay(1000);
    }


body:
To illustrate the reasons better let's look at the actual content of the data.

`0x80` is `0b10000000` in binary. A `char` is a *signed* variable, which means that the most significant bit is the sign bit, with *two's complement* representation

So in 8-bit signed representation the value `0b10000000` is a sign bit and zero value - which is -128 in decimal notation, which is "-128 + the 7 least significant bits", or -128 + 0 in this case.

When you print a signed value on the Arduino as HEX there is no 8-bit specific function for it. Neither is there a 16 bit function. However there is a 32-bit signed function, which is the closest match available. So the compiler performs *type promotion* to 32-bit signed, then represent it as hexadecimal.

Now -128 in signed 32-bit is calculated in the same way - take the value of the most significant bit, negate it, and add the value of all the other bits to it.  With 32-bits the value of the most significant bit, in decimal, is 2147483648, so negate that into -2147483648. Now we need to make that into -128, so we need the difference between the two to add to it. That's 2147483520.

So you get the MSB + 2147483520, which in hexadecimal, is 0xFFFFFF80.

Of course, the compiler doesn't go through that whole routine - instead it uses something called *sign extension*. This method basically means copying the sign bit from the original smaller (char) type into every bit to the left of it in the larger type:

                               10000000 8 bit signed
                      11111111 10000000 16 bit signed
    11111111 11111111 11111111 10000000 32 bit signed

All those are -128 in two's complement, just stored in different size variables. So when you come to print it, that is just what you get - the two's complement representation of -128 in the variable size that has been accepted by the print function.

You might find [this site](http://www.binaryconvert.com/) useful for experimentation and furthering your understanding of variable data storage.


message:
Analog input draws current when Arduino is turned off

I am using a Arduino Pro Micro from SparkFun (similar to Arduino Leonardo, cpu: Atmega 32u4). It has a analog input: A0, which I use to keep track of the battery voltage in my battery powered project (via analogRead).

I found out that the red LED on the board lights up, even if there is no supply voltage on the usual inputs (micro-USB or Vcc). If I use a multimeter to measure the current between the battery and A0, I see that the analog input is drawing about **30mA** if the Arduino is not powered.

Is this the normal behaviour? Can I fix this via hardware?

body:
That's probably due to the clamping diodes. To protect the chip against ESD, there are diodes between the pins and Vcc and ground. This is to make sure that when charge builds up on a pin, it can flow to Vcc (when it's higher than the supply voltage) or to ground (when it's lower than ground level).

If you supply a voltage to a pin without a voltage on Vcc, current will flow through the pin to the supply line, powering the circuit.

You could probably solve this by adding a relatively large resistor in series with the pin.


body:
Yes, it is normal behaviour, and it's called *back-powering*.

The current is flowing into the input pin and then flowing up through the ESD protection diode inside the chip to VCC.  It's bad, because the ESD protection diode can't take much current and is easy to damage.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/VnqVi.png)

<!-- End schematic -->

You can prevent it from happening by adding some isolation into the input:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/u0ZJM.png)

<!-- End schematic -->

MOSFET M1 will be ON when VCC has power, but off when it doesn't. The 100kΩ resistor pulls the gate to ground when VCC is off so it doesn't float. The diode is the body diode of the MOSFET added for clarity. You don't need to add a diode there.


body:
This is normal, if you *abuse* the chip in this fashion.

But you must take into consideration that it is strictly prohibited to apply a voltage to any I/O pin when the chip itself is unpowered.

This is because the protection diodes are not rated to supply power to the chip, and relying on them to do so may cause damage.

The literal statement of this rule is in the data sheet as

>Voltage on any Pin except RESET with respect to Ground . . . . . . . . . .-0.5V to VCC+0.5V

If VCC is 0v, then the maximum voltage you may apply to any I/O is half a volt which is approximately (or just below) the point where a protection diode would begin to meaningfully divert current from the I/O to trying to lift the Vcc net of the chip, and likely the entire board.


message:
I fried my arduino. Can I upload code wirelessly?

So, I'm a complete arduino newbie. I left a live wire close to my arduino and part of it burnt (underneath the USB output). The LED that indicates power still turns on when I plug it into my computer, and a simple LED circuit on my breadboard, when hooked up to the arduino, still works. The only thing that's wrong is that my computer doesn't recognize the Arduino serial port any more, so I can't upload any code onto it.

I also own a bluetooth HC-05 module. Is there any way I could upload code onto my Arduino wirelessly, using that? Or am I better off just buying a new one?

body:
You did not say which Arduino you are using.

Most Arduinos abstract the complexities of the USB interface, format and protocol by using a 2nd processor on the Arduino board.  If damaged, you will essentially have to replace this function.  It is unlikely that a Bluetooth radio will act similar enough to do this.

If the main processor and supporting circuitry is not damaged, it would be easier to program the Arduino from another Arduino such as described [here][1].

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


body:
If the main MCU is still functioning fine then yes, sure you can.

The only caveat is that you may have to manually reset the Arduino at the right moment in order to enter the bootloader for programming.

* Connect the bluetooth module to TX/RX/GND (TX->RX, RX->TX)
* Configure the bluetooth module to work at the bootloader baud rate (115200 baud) - you may need to wire it to your PC to manage this part.
* Connect a virtual COM port to it and program through that.
* Press RESET just as it's about to run AVRDUDE in the IDE.


body:
It sounds like you have fried the Atmega16U2  which is programmed as a USB-to-serial converter, as seen in the picture below.

[![Arduino Uno][1]][1]

You can still program the Atmega328P microcontroller using the ICSP and an appropriate Atmel programmer such as the Atmel Ice or the AVRISPmkII. Alternatively you can use another Arduino Uno as a [In-System Programmer][2].

I cannot say about using a bluetooth HC-05 module,however I imagine it would be a fair bit of effort and hence would be easier to buy a new one. Keep the current one though because you can use the new one as an in-system programmer as per the link above.

  [1]: https://i.stack.imgur.com/W0qfY.jpg
  [2]: https://www.arduino.cc/en/Tutorial/ArduinoISP


message:
Does 12v 5A power supply is okay to operate motor shield external power

[![My motor][1]][1]I am new to arduino.
[![Motor Shield DK Electronics v1.0][2]][2]
Recently purchased motor shield V1.0 which have two l293 and can run 4 DC motors simultaneously.
But here the problem comes: when I purchased the shield I was not aware that it can only supply 2A peak current.
However, my DC motor rating is 12v 5A. So I purchased a 12v 5A power supply.
But now I am not sure to operate shield with external power of 12v 5A.

Does it works or will it burn?

  [1]: https://i.stack.imgur.com/4IzeN.jpg
  [2]: https://i.stack.imgur.com/rl6DQ.jpg

body:
The shield will "burn". You need a shield that can provide minimum 5A *per channel* to run a 5A motor.

However, your motors *aren't 5A*. They have a stall current of 300mA, which is well within the capabilities of the motor shield, and the 5A power supply you have would barely even notice they were there.


message:
3-speed DC fan control with Uno

I have built this MOSFET circuit, which is supposed to run 2 DC fans using an Arduino Uno.

[![enter image description here][1]][1]

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

I am trying to get the two DC fans running with four settings: OFF, LOW, MED and HIGH. I have been having issues with the MED option, because when its option is selected by the rotary switch (5 V pulse detected by the analog pin A2) the speed of the fan is not the constant 75% duty cycle (191) as defined on line 75 in the code below:

<!-- language: lang-js -->

    int motorPin1 = 3;
    int motorPin2 = 9;
    int DCfanSpeed = 0;
    int voltageZero = 0;
    int voltageOne = 1;
    int voltageTwo = 2;
    int voltageThree = 3;

    void setup() {
      pinMode(motorPin1, OUTPUT);
      pinMode(motorPin2, OUTPUT);
      digitalWrite(voltageZero, INPUT_PULLUP);
      digitalWrite(voltageOne, INPUT_PULLUP);
      digitalWrite(voltageTwo, INPUT_PULLUP);
      digitalWrite(voltageThree, INPUT_PULLUP);
      Serial.begin(9600);
    }

    void loop() {
      int voltageReadingZero = analogRead(voltageZero); // OFF SWITCH
      int voltsZero = voltageReadingZero / 204.6;
      if (voltsZero == 5) {
        delay(300);
        if (voltsZero == 5) DCfanSpeed = 0;
        // else DCfanSpeed = DCfanSpeed;
        while (voltsZero == 5) {
          analogWrite(motorPin1, DCfanSpeed);
          analogWrite(motorPin2, DCfanSpeed);
          voltageReadingZero = analogRead(voltageZero);
          voltsZero = voltageReadingZero / 204.6;
        }
      }
      int voltageReadingOne = analogRead(voltageOne); // LOW SWITCH
      int voltsOne = voltageReadingOne / 204.6;
      if (voltsOne == 5) {
        delay(300);
        if (voltsOne == 5) DCfanSpeed = 128;
        //else DCfanSpeed = DCfanSpeed;
        while (voltsOne == 5) {
          analogWrite(motorPin1, DCfanSpeed);
          analogWrite(motorPin2, DCfanSpeed);
          voltageReadingOne = analogRead(voltageOne);
          voltsOne = voltageReadingOne / 204.6;
        }
      }
      int voltageReadingTwo = analogRead(voltageTwo); //  MED SWITCH
      int voltsTwo = voltageReadingTwo / 204.6;
      if (voltsTwo == 5) {
        delay(300);
        if (voltsTwo == 5) DCfanSpeed = 191;
        //else DCfanSpeed = DCfanSpeed;
        while (voltsTwo == 5) {
          analogWrite(motorPin1, DCfanSpeed);
          analogWrite(motorPin2, DCfanSpeed);
          voltageReadingTwo = analogRead(voltageTwo);
          voltsTwo = voltageReadingTwo / 204.6;
        }
      }
      int voltageReadingThree = analogRead(voltageThree);  //  HIGH SWITCH
      int voltsThree = voltageReadingThree / 204.6;
      if (voltsThree == 5) {
        delay(300);
        if (voltsThree == 5) DCfanSpeed = 255;
        //else DCfanSpeed = DCfanSpeed;
        while (voltsThree == 5) {
          analogWrite(motorPin1, DCfanSpeed);
          analogWrite(motorPin2, DCfanSpeed);
          voltageReadingThree = analogRead(voltageThree);
          voltsThree = voltageReadingThree / 204.6;
        }
      }
    }

Excuse the poor formatting but the basic rundown of the medium option is such that the voltage across the analog pin 2 is measured and converted into volts and if it is 5 Volts (rotary turned to the medium position) then it enters a while loop where the voltage is monitored such that if there is any change then there must be a speed setting change. This is the only option for which I get this pulsating speed on the fans instead of smooth and continuos operation.

Any ideas about how I could improve this? I have taken away one fan to see if one was faulty but this didn't work.

body:
Solved simply by condensing code and getting rid of unnecessary variable declarations.

Corrected program:

        int motorPin1 = 3;
        int motorPin2 = 9;
        int DCfanSpeed = 0;

        void setup()
        {
          pinMode(motorPin1, OUTPUT);
          pinMode(motorPin2, OUTPUT);
          digitalWrite(A0, INPUT_PULLUP);
          digitalWrite(A1, INPUT_PULLUP);
          digitalWrite(A2, INPUT_PULLUP);
          digitalWrite(A3, INPUT_PULLUP);
          Serial.begin(9600);
        }

        void loop()
         {

           int voltsZero = analogRead(A0)/204.6; // OFF SWITCH
           if(voltsZero == 5)
            {
              delay(300);
              if(voltsZero == 5) DCfanSpeed = 0;

               while(voltsZero == 5)
                {
                  analogWrite(motorPin1, DCfanSpeed);
                  analogWrite(motorPin2, DCfanSpeed);
                  voltsZero = analogRead(A0)/204.6;

                }
             }

          int voltsOne = analogRead(A1)/204.6;    // LOW SWITCH
          if(voltsOne == 5)
            {
              delay(300);
              if(voltsOne == 5) DCfanSpeed = 128;
              while(voltsOne == 5)
               {
                 analogWrite(motorPin1, DCfanSpeed);
                 analogWrite(motorPin2, DCfanSpeed);
                 voltsOne = analogRead(A1)/204.6;
               }
            }

           int voltsTwo = analogRead(A2)/204.6;  //  MED SWITCH
           if(voltsTwo == 5)
            {
              delay(300);
              if(voltsTwo == 5) DCfanSpeed = 191;
              while(voltsTwo == 5)
               {
                 analogWrite(motorPin1, DCfanSpeed);
                 analogWrite(motorPin2, DCfanSpeed);
                 voltsTwo = analogRead(A2)/204.6;

               }
            }

          int voltsThree = analogRead(A3)/204.6;  //  HIGH SWITCH
          if(voltsThree == 5)
            {
              delay(300);
              if(voltsThree == 5) DCfanSpeed = 255;
              while(voltsThree == 5)
               {
                 analogWrite(motorPin1, DCfanSpeed);
                 analogWrite(motorPin2, DCfanSpeed);
                 voltsThree = analogRead(A3)/204.6;
               }
             }

        }


message:
ATtiny85 MIDI IN with less than 3V -can it be done?

I've been trying to add a MIDI INput to an ATtiny-based synthesizer, powered by a CR2032 battery (3v) and running softwareSerial.

Currently I'm using an H11L1 optocoupler, which works fine at 5v, but I am missing notes at 3V; I'm not sure whether the problem is the optocoupler, or that the ATtiny can't establish proper communication on that voltage; any pointers will be much appreciated :)

body:
The H11L1's minimum supply voltage is 3 V.
There are low-power optocouplers like the TLP2361, but event those do not go below 2.7 V. (And those limits are actually designed for 3.3 V ± 10 % or 3.0 V ± 10 %.)

To get a high-speed optocoupler for lower voltages, you have to build it yourself from discrete parts, e.g.:
![MIDI input with PC817](https://i.stack.imgur.com/4Awtc.png)

(R1 is sized for the PC817-A's minimum CTR of 50 %; higher CTRs should use a lower value for R1. Q1 can be any random small-signal transistor. Adjust R2 for about 1 mA, depending on VCC.)


message:
RESET and RESUME case in Arduino mega 2560 code (PUSHBUTTON AS INTERRUPT)

[![enter image description here][1]][1]
I am working on Arduino Mega 2560 which is controlling four steppers with BT6560 Driver, six pushbuttons and four limitswitches.

I want to code Arduino such that when I press RESET button (not talking about RESET button on Arduino), Arduino should run the code again from beginning.

And when I press RESUME button, Arduino should run the code from the moment I pressed the RESET button (like any song is resumed).

How can I be able to do this?

Below is a code I am working on:

    int dirH_T1 = 3;
    int steppin_T1 = 4;
    int dirpin_F1 = 5;
    int dirH_F1 = 6;
    int steppin_F1 = 7;
    int dirpin_T2 = 8;
    int dirH_T2 = 9;
    int steppin_T2 =10;
    int dirpin_F2 = 11;
    int dirH_F2 = 12;
    int steppin_F2 =13;
    int PB17ACW=23;
    int PB17ACCW=22;
    int PB17BCW=25;
    int PB17BCCW=24;
    int S01 = 34; // SENSOR INPUTS
    int S02 = 35;
    int S03 = 36;
    int S04 = 37;

    void setup()
    {
     pinMode(dirpin_T1, OUTPUT);
     pinMode(dirH_T1, OUTPUT);
     pinMode(steppin_T1, OUTPUT);
     pinMode(dirpin_F1, OUTPUT);
     pinMode(dirH_F1 , OUTPUT);
     pinMode(steppin_F1, OUTPUT);

     pinMode(dirpin_T2, OUTPUT);
     pinMode(dirH_T2, OUTPUT);
     pinMode(steppin_T2, OUTPUT);
     pinMode(dirpin_F2, OUTPUT);
     pinMode(dirH_F2 , OUTPUT);
     pinMode(steppin_F2, OUTPUT);

     pinMode(PB17ACW,INPUT_PULLUP);
     pinMode(PB17ACCW,INPUT_PULLUP);
     pinMode(PB17BCW,INPUT_PULLUP);
     pinMode(PB17BCCW,INPUT_PULLUP);

     pinMode(S01,INPUT);
     pinMode(S02,INPUT);
     pinMode(S03,INPUT);
     pinMode(S04,INPUT);

    }
    void loop()
    {
     if(digitalRead(PB17ACW)==LOW &&  digitalRead(PB17ACCW)==LOW) {
    // STOP MOTOR WHEN NO KEY PRESSED
     }

    // FOR FILAMENT 1 FORWARD FEEDER
     if(digitalRead(PB17ACW)==HIGH &&  digitalRead(PB17ACCW)==LOW) {
      digitalWrite(dirpin_T1, LOW);      // Set the direction.
      digitalWrite(dirH_T1, LOW);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to
       when to step.
       delayMicroseconds(50);
      }

      digitalWrite(dirpin_F1, LOW);      // Set the direction.
      digitalWrite(dirH_F1, LOW);
      delay(1000);

      do {
       digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the

       digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);

      } while(digitalRead(S01)==LOW);

      delay(1000);

      digitalWrite(dirpin_T1, LOW);      // Set the direction.
      digitalWrite(dirH_T1, HIGH);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to
       when to step.
       delayMicroseconds(50);

      }
     }

    // FOR FILAMENT 1 BACKWARD FEEDER
     if(digitalRead(PB17ACW)==LOW &&  digitalRead(PB17ACCW)==HIGH) {
      digitalWrite(dirpin_T1, LOW);      // Set the direction.
      digitalWrite(dirH_T1, LOW);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);

      }

      digitalWrite(dirpin_F1, LOW);      // Set the direction.
      digitalWrite(dirH_F1, HIGH);
      delay(1000);

      do {
       digitalWrite(steppin_F1, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_F1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);
      } while(digitalRead(S02)==LOW);

      delay(1000);
      digitalWrite(dirpin_T1, LOW);      // Set the direction.
      digitalWrite(dirH_T1, HIGH);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T1, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T1, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);
      }
     }

     // FOR FILAMENT 2 FORWARD FEEDER
     if(digitalRead(PB17BCW)==HIGH &&  digitalRead(PB17BCCW)==LOW) {
      digitalWrite(dirpin_T2, LOW);      // Set the direction.
      digitalWrite(dirH_T2, LOW);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);
      }

      digitalWrite(dirpin_F2, LOW);      // Set the direction.
      digitalWrite(dirH_F2, LOW);
      delay(1000);

      do {
       digitalWrite(steppin_F2, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_F2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);
      } while(digitalRead(S03)==LOW);

      delay(1000);

      digitalWrite(dirpin_T2, LOW);      // Set the direction.
      digitalWrite(dirH_T2, HIGH);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);

      }
     }

    // FOR FILAMENT 2 BACKWARD FEEDER
     if(digitalRead(PB17BCW)==LOW &&  digitalRead(PB17BCCW)==HIGH) {
      digitalWrite(dirpin_T2, LOW);      // Set the direction.
      digitalWrite(dirH_T2, LOW);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);
      }

      digitalWrite(dirpin_F2, LOW);      // Set the direction.
      digitalWrite(dirH_F2, HIGH);
      delay(1000);

      do {
       digitalWrite(steppin_F2, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_F2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);

      } while(digitalRead(S04)==LOW);

      delay(1000);

      digitalWrite(dirpin_T2, LOW);      // Set the direction.
      digitalWrite(dirH_T2, HIGH);
      delay(1000);

      for(int i = 0; i<32767; i++) {      // Iterate for 4000 microsteps.(32767)
       digitalWrite(steppin_T2, LOW);  // This LOW to HIGH change is what creates the
       digitalWrite(steppin_T2, HIGH); // "Rising Edge" so the easydriver knows to when to step.
       delayMicroseconds(50);
      }
     }
    }

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

body:
Doing the "hibernate" thing in a general fashion you need to:

 1. Capture the relevant status of the whole system (Arduino + modules). That include registers, the stack and all variables in your program.
 2. Write it to some storage medium (EEPROM, SD, whatever).
 3. Upon **resume**, restore registers, stack, variable and reinicialize all modules (sensors, relays, ...)

Arduino can't do that.

Your only alternative is to use, as @Majenko says, a *finite state machine* and take care yourself to restore execution to the point where button was pressed.


message:
Will 5V to input pin damage the Arduino board?

I am fairly new to Arduino. When I am experimenting with circuits, do i need to worry about shorting out a pin if I accidentally connect the +5V pin on Arduino to an input pin on Arduino without a resistor? I just want to make sure I avoid destroying the board when learning how to create circuits.

body:
Apply 5V directly, without any resistor:

[![Arduino power][1]][1]

**5 V socket**

  it is directly connected to the regulator’s output, thus the 5 V to power external loads to Arduino can be drawn from it. In the case voltages are not applied to the USB Port or to the JACK socket, the 5 V socket can be even used to power Arduino directly, if having an external stabilized 5 V source. One has to consider that, in general, regulators do not like voltages being applied to their output, but in this particular case this situation turns out to happen even when powering Arduino from the USB port, therefore we may assume that the designers judged this problem as harmless. Even in this case there is no form of protection, since both the diode and the PTC fuse are found above this socket and thus they do not have any active function. As in the case of the Vin socket, the voltage negative pole can be found on the board’s GND sockets.

NOTE: regardless of the input used, Arduino has a 3.3 V output socket to power loads operating at this voltage; in fact a second regulator, right for the purpose of generating 3.3 V, is directly connected to the 5 V. This socket cannot be used as input.

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


body:
No, no short. Arduino (Atmega) pins default to inputs. Pins configured this way are said to be in a high-impedance state. Input pins make extremely small demands on the circuit that they are sampling, equivalent to a series resistor of 100 megohm in front of the pin.

*Answer provided by Look Alterno and converted from a comment.*


message:
Serial uart communication issues

I know this isnt specific but could you suggest some causes for the following issue:

Mega2560 sends values to Raspi 3 and Raspi 3 receives prints them accordingly (arduino also prints out the values it sends). However, at every occasional instances, garbage data is printed on Raspi terminal while the right data is still printed on the serial monitor for Arduino for a baudrate of 115200 for both.

Any helpful suggestions would be appreciated

body:
This answer will also be not so specific, but you can try:

- Check all wiring (use a multimeter/analyzer)
- Reduce the data rate
- Find out if there is a pattern whenever garbage is created (depending on values?)
- Check (if possible) for errors (overrun/parity)
- Play with the parity setting/stop bits to see if it makes a difference


body:
I often have this issue with my data-loggers.  They use Nano or Uno to send readings to the Pi3 Python programs.   My Arduinos send data every 60 seconds.  Then the Pi adds a date and time stamp and appends it to the day's data file

Invariably, in my case, it happens that I might get some garbage as I start the program, and then it runs fine after that.  I solved the garbage part by flushing the input buffer.  Then I also make sure my data is of the expected length, which depends on how many variables it is sending.

Once I applied a little Python Fu the issue has ceased to be a problem.

Here is a generic representation of my solution:

    import serial
    ser = serial.Serial("/dev/ttyUSB0",9600)
    ser.flushinput()
    while True :
        linein = ser(readlin)
        if len(linein<10) : continue
        if len(linein>50) : continue
        PROCESS THE INPUT


message:
Arduino relay power supply question

Hello everyone i got 2 ssr's from here

[![enter image description here][1]][1]

([link][2])

Sorry about the long link. My question is what power supply should i use. I was thinking a 12v 2amp. On a side note do i look at the input or the output when choosing a power supply

Thank you

  [1]: https://i.stack.imgur.com/QY5L3.png
  [2]: https://www.amazon.com/dp/B071CL4VN6/ref=asc_df_B071CL4VN65253936/?tag=hyprod-20&creative=395033&creativeASIN=B071CL4VN6&linkCode=df0&hvadid=216538221087&hvpos=1o1&hvnetw=g&hvrand=5668615048753802770&hvpone=&hvptwo=&hvqmt=&hvdev=m&hvdvcmdl=&hvlocint=&hvlocphy=9022821&hvtargid=pla-359481199162

body: In the product description it says "DC 12V 8-Channel Relay interface board, and each one needs 15-20mA Driver Current." So 8 times 0.020A is 0.160A per board. I think your 2 amp power supply should work just fine.


message:
Porting code from Arduino IDE to other IDEs - expected code size reduction

Could I realistically be expecting some 25% - 50% code size reduction if I abandoned Arduino IDE's framework and moved to something more rudimentary such as AVR Studio ? I am using the EEPROM, Timer1 and Wire libraries whereas my own code is about 700 lines of code.

body:
If you like the Arduino IDE, you also can do the following:

- Do not use the library functions, but use registers directly.
  The compiler is smart enough that it does not link functions you do not use with your executable/binary.
- Optimize your code by
  - Checking if you can simplify algorithms
  - Remove unnecessary statements
  - Remove global variables (maybe move them to locals if you can)
  - Reduce or remove text strings.
  - For globals (but also to reduce SRAM) minimize memory sizes of variables, e.g. use uint8_t instead of integers, especially when using arrays of them.
- If you use library functions, optimize them:
  - Simplify library functions if you use them (by 'paying' less portability for example)
  - By removing functionality that you do not need

Other tips (not necessarily answering your answer but things to keep in mind);

- Use another Arduino which has more memory (Mega/Due)
- Switch to another type of microControllers with more memory/flash


body:
> Could I realistically be expecting some 25% - 50% code size reduction ...

code size has nothing to do with the ide, but compiler, compilers used, and libraries / routines used.

in general (which means that there are lots of exceptions) you will see a size increase when porting to an non-arduino environment.

with that said, many of the arduino functionalities are not that well implemented so you can save code size if you roll your own functionally equivalent code.


body:
You don't need to abandon the Arduino IDE.

Let me quote from [my forum post about sketch sizes](http://www.gammon.com.au/forum/?id=12173).

---

# Introduction

Every now and again this subject pops up on the Arduino forum. Why does it take 1000 bytes to blink an LED? Why, oh why? It is obviously very bloated, eh?

---

# Example: blink

Let's check that claim first.

The "blink" sketch, as shipped with the IDE (and stripped of comments) is:

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

    int led = 13;
    void setup()
    {
      pinMode(led, OUTPUT);
    }

    void loop()
    {
      digitalWrite(led, HIGH);
      delay(1000);
      digitalWrite(led, LOW);
      delay(1000);
    }

Compiled:

    Binary sketch size: 1,084 bytes (of a 32,256 byte maximum)

OK, over 1000 bytes to "blink an LED".

Well first, as someone on the Arduino forum humorously pointed out, it doesn't take 2000 bytes to blink **two** LEDs!

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

    int led1 = 13;
    int led2 = 12;
    void setup()
    {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
    }

    void loop()
    {
      digitalWrite(led1, HIGH);
      delay(1000);
      digitalWrite(led1, LOW);
      delay(1000);

      digitalWrite(led2, HIGH);
      delay(1000);
      digitalWrite(led2, LOW);
      delay(1000);
    }

That takes:

    Binary sketch size: 1,140 bytes (of a 32,256 byte maximum)

So the overhead for the second LED is only:

    1140 - 1084 = 56

So you could argue that it only takes **56 bytes** to blink an LED (providing you are already blinking another one).

---

# It does more than blink

The first relevant rejoinder here is that the example sketch does more than blink an LED. Rather importantly, it also waits for a second between turning the LED on and off (the "delay" function call).

If we remove that, the sketch is somewhat smaller:

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

    int led = 13;
    void setup()
    {
      pinMode(led, OUTPUT);
    }

    void loop()
    {
      digitalWrite(led, HIGH);
      digitalWrite(led, LOW);
    }

Code size:

    Binary sketch size: 882 bytes (of a 32,256 byte maximum)

So we saved 202 bytes by not doing a delay. This isn't totally unreasonable, as doing delays requires the library to configure a timer, and have code to check that timer.

---

# The pins numbers are variables

The code in the Blink example uses (wrongly in my opinion) a **variable** to hold the pin number (13) when a **constant** would do. And if you use a constant there is a library called
[digitalWriteFast](https://github.com/NicksonYap/digitalWriteFast) that generates more efficient code.

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

    #include <digitalWriteFast.h>

    const int led = 13;
    void setup()
    {
      pinModeFast(led, OUTPUT);
    }

    void loop()
    {
      digitalWriteFast(led, HIGH);
      digitalWriteFast(led, LOW);
    }

Code size:

    Binary sketch size: 470 bytes (of a 32,256 byte maximum)

Now we are down to 470 bytes to "blink an LED".

---

# We can use port manipulation

If all we want to do is blink the LED, we can omit using setup and loop, and go straight into using the processor registers. For example:

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

    int main ()
      {
      DDRB = bit (5);
      while (true)
        PINB = bit (5);
      }

That blinks pin 13, believe it or not*. And now it only takes 178 bytes:

    Binary sketch size: 178 bytes (of a 32,256 byte maximum)

\* very rapidly indeed

---

# Interrupt vectors

Well, you may be thinking "Pfft! Still 178 bytes. Why not 10 bytes?"

The answer to that lies in the way the hardware works. The Atmega328P has 26 interrupt vectors, at the start of program memory. Each one is 4 bytes (it jumps to a handler for each interrupt). So 26 * 4 = 104 bytes.

Thus there is an unavoidable overhead of 104 bytes in any piece of code. (Unless you know in advance you aren't going to use all those interrupt vectors, but this is rather specialized).

You can see these vectors if you add handlers for them:

    EMPTY_INTERRUPT (INT0_vect)
    EMPTY_INTERRUPT (INT1_vect)
    EMPTY_INTERRUPT (PCINT0_vect)
    EMPTY_INTERRUPT (PCINT1_vect)
    EMPTY_INTERRUPT (PCINT2_vect)
    EMPTY_INTERRUPT (WDT_vect)
    EMPTY_INTERRUPT (TIMER2_COMPA_vect)
    EMPTY_INTERRUPT (TIMER2_COMPB_vect)
    EMPTY_INTERRUPT (TIMER2_OVF_vect)
    EMPTY_INTERRUPT (TIMER1_CAPT_vect)
    EMPTY_INTERRUPT (TIMER1_COMPA_vect)
    EMPTY_INTERRUPT (TIMER1_COMPB_vect)
    EMPTY_INTERRUPT (TIMER1_OVF_vect)
    EMPTY_INTERRUPT (TIMER0_COMPA_vect)
    EMPTY_INTERRUPT (TIMER0_COMPB_vect)
    EMPTY_INTERRUPT (TIMER0_OVF_vect)
    EMPTY_INTERRUPT (SPI_STC_vect)
    EMPTY_INTERRUPT (USART_RX_vect)
    EMPTY_INTERRUPT (USART_UDRE_vect)
    EMPTY_INTERRUPT (USART_TX_vect)
    EMPTY_INTERRUPT (ADC_vect)
    EMPTY_INTERRUPT (EE_READY_vect)
    EMPTY_INTERRUPT (ANALOG_COMP_vect)
    EMPTY_INTERRUPT (TWI_vect)
    EMPTY_INTERRUPT (SPM_READY_vect)

Now the start of the object code is:

    00000000 <__vectors>:
       0: 0c 94 34 00  jmp 0x68 ; 0x68 <__ctors_end>
       4: 0c 94 51 00  jmp 0xa2 ; 0xa2 <__vector_1>
       8: 0c 94 52 00  jmp 0xa4 ; 0xa4 <__vector_2>
       c: 0c 94 53 00  jmp 0xa6 ; 0xa6 <__vector_3>
      10: 0c 94 54 00  jmp 0xa8 ; 0xa8 <__vector_4>
      14: 0c 94 55 00  jmp 0xaa ; 0xaa <__vector_5>
      18: 0c 94 56 00  jmp 0xac ; 0xac <__vector_6>
      1c: 0c 94 57 00  jmp 0xae ; 0xae <__vector_7>
      20: 0c 94 58 00  jmp 0xb0 ; 0xb0 <__vector_8>
      24: 0c 94 59 00  jmp 0xb2 ; 0xb2 <__vector_9>
      28: 0c 94 5a 00  jmp 0xb4 ; 0xb4 <__vector_10>
      2c: 0c 94 5b 00  jmp 0xb6 ; 0xb6 <__vector_11>
      30: 0c 94 5c 00  jmp 0xb8 ; 0xb8 <__vector_12>
      34: 0c 94 5d 00  jmp 0xba ; 0xba <__vector_13>
      38: 0c 94 5e 00  jmp 0xbc ; 0xbc <__vector_14>
      3c: 0c 94 5f 00  jmp 0xbe ; 0xbe <__vector_15>
      40: 0c 94 60 00  jmp 0xc0 ; 0xc0 <__vector_16>
      44: 0c 94 61 00  jmp 0xc2 ; 0xc2 <__vector_17>
      48: 0c 94 62 00  jmp 0xc4 ; 0xc4 <__vector_18>
      4c: 0c 94 63 00  jmp 0xc6 ; 0xc6 <__vector_19>
      50: 0c 94 64 00  jmp 0xc8 ; 0xc8 <__vector_20>
      54: 0c 94 65 00  jmp 0xca ; 0xca <__vector_21>
      58: 0c 94 66 00  jmp 0xcc ; 0xcc <__vector_22>
      5c: 0c 94 67 00  jmp 0xce ; 0xce <__vector_23>
      60: 0c 94 68 00  jmp 0xd0 ; 0xd0 <__vector_24>
      64: 0c 94 69 00  jmp 0xd2 ; 0xd2 <__vector_25>

The "real" code has to start at 0x68 (decimal 104) which is where the reset vector takes us (the first vector).

So now, our code is really 178 - 104 bytes of useful code. That's 74 bytes to blink an LED.

However even some (most) of that is overhead, generated by the C compiler to initialize global variables, call class constructors, etc. Let's test that by blinking **two** LEDs.

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

    int main ()
      {
      DDRB = bit (5);  // pin 13
      DDRB |= bit (4);  // pin 12

      while (true)
        {
        PINB = bit (5); // pin 13
        PINB = bit (4); // pin 12
        }
      }

Code size:

    Binary sketch size: 186 bytes (of a 32,256 byte maximum)

Eight bytes difference. So really, you can **blink an LED in 8 bytes**. That is the bottom line. And you can do it in the Arduino IDE.

---

# The libraries are designed to make things easy

The fact is that the default behaviour of the Arduino libraries is to simplify things for beginners. Thus they do some things which take up a bit of memory;

* You can pass **variables** to pinMode and digitalWrite. Not just constants. Thus, at runtime, code has to convert the variable value to an actual processor port.
* You get an automatic set-up of Timer 0, so you can use millis(), micros(), and delay() function calls.
* You get Timer 1 and Timer 2 set-up, so you can do PWM output easily.

So you are trading off program space, to an extent, for ease of use. But if you want to code around it, as I did above, you can trim that program space right down.

---

Tests on an Arduino Uno board type, IDE 1.0.5.


body:
I have managed some 33% downsizing, hurrah!

Adding to the current answers: the biggest reduction came by ridding the floating points. I have come across [the answer here][1] and put `avr-objdump` to good use. That's how I have had the shock of my life (no hardware FPU built into these $1 MCUs :-o) and also that is how you can see other offenders sneaking into your binary image.

HTH

  [1]: https://arduino.stackexchange.com/questions/11680/overview-of-compiled-code-size/11684#11684


message:
How can configuration values be stored on an ESP8266?

I have a project that uses [an MQTT service][1], and I'm wondering how to best store the configuration settings (server, user, password, port) for the service as right now they are just hard-coded into some constants.

I saw that [EEPROM][2] can be used for this but I'm not sure it is the best way. I went to look at the code for [WifiManager][3] to see how it accomplishes this task for the SSID and password since it works so well and it removed its EEPROM dependency back in 2015: https://github.com/tzapu/WiFiManager/commit/659df9cb277c5f93946d9d8795e39a5ae5863ab1

I can't figure out how those settings are persisted.

If EEPROM *is* the best way for storing something like this, I'd like to write my values without overwriting/corrupting existing values, is that possible? How can I set the initial values of the EEPROM to the constants that I need?

**Edit:** well after digging into the [esp8266/Arduino repository][4] I found that the [`WiFi.SSID()`][5] and [`WiFi.psk()`][6] settings come from `wifi_station_get_config` and stored with `wifi_station_set_config` although I haven't found how *those* work so I think EEPROM might be the way to go here, I just need a bit of guidance and clarification on the right way to use it.

  [1]: https://www.cloudmqtt.com/
  [2]: https://www.arduino.cc/en/Reference/EEPROM
  [3]: https://github.com/tzapu/WiFiManager
  [4]: https://github.com/esp8266/Arduino/
  [5]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.cpp#L480
  [6]: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WiFi/src/ESP8266WiFiSTA.cpp#L490

body:
Thanks to [Jaromanda X][1] and [Juraj][2] for the [SPIFFS][3] recommendation. I was able to use [this block of SPIFFS code][4] as an example and safely store settings in my project outside of the compiled source.

To upload files to my ESP8266, I followed the [installation][5] and [usage][6] instructions for the [ESP8266 filesystem plugin][7] for the [standard Arduino IDE][8].

First, I created a `.gitignore` file and added this so that none of the actual values would get added to the repository:

<!-- language: lang-bash -->

    # MQTT config info
    data/config.json

Then I created a `data` folder and added a `config.json` file that had all the configuration properties that I need to reference:

<!-- language: lang-js -->

    {
      "cloudmqtt_server": "***.cloudmqtt.com",
      "cloudmqtt_user": "********",
      "cloudmqtt_pass": "************",
      "cloudmqtt_port": 10000
    }

Following the [example above][4], I added `#include <FS.h>` at line #1 (as well as `#include <ArduinoJson.h>` for parsing the JSON) and have this block to instantiate the variables with dummy values that will be replaced by the actual values from the JSON file:

<!-- language: lang-cpp -->

    // MQTT pub/sub for the servo functions
    #define CLOUDMQTT_CONFIG  "/config.json"
    // these values are loaded from a config.json file in the data directory
    char cloudmqtt_server[18] = "***.cloudmqtt.com";
    int  cloudmqtt_port       = 0;
    char cloudmqtt_user[9]    = "********";
    char cloudmqtt_pass[13]   = "************";

Then in the setup I have this block to load the values from the config:

<!-- language: lang-cpp -->

    if (SPIFFS.begin()) {
      Serial.println("mounted file system");

      // parse json config file
      File jsonFile = GetFile(CLOUDMQTT_CONFIG);
      if (jsonFile) {
        // Allocate a buffer to store contents of the file.
        size_t size = jsonFile.size();
        std::unique_ptr<char[]> jsonBuf(new char[size]);
        jsonFile.readBytes(jsonBuf.get(), size);

        DynamicJsonBuffer jsonBuffer;
        JsonObject& json = jsonBuffer.parseObject(jsonBuf.get());
        if (json.success()) {
          strcpy(cloudmqtt_server, json["cloudmqtt_server"]);
          cloudmqtt_port = json["cloudmqtt_port"];
          strcpy(cloudmqtt_user, json["cloudmqtt_user"]);
          strcpy(cloudmqtt_pass, json["cloudmqtt_pass"]);
        } else {
          Serial.println("failed to load json config");
        }
        jsonFile.close();
      }
    }

I'm not sure if there's a better way, but this way works for me:
https://github.com/dieseltravis/esp8266-projects/tree/master/servo-demo

  [1]: https://arduino.stackexchange.com/users/21371/jaromanda-x
  [2]: https://arduino.stackexchange.com/users/37622/juraj
  [3]: https://esp8266.github.io/Arduino/versions/2.3.0/doc/filesystem.html#file-system-object-spiffs
  [4]: https://github.com/tzapu/WiFiManager/blob/039702327e6c3aef2a7ccc766bcf8bbab20bdae2/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino#L38-L68
  [5]: https://github.com/esp8266/arduino-esp8266fs-plugin#installation
  [6]: https://github.com/esp8266/arduino-esp8266fs-plugin#usage
  [7]: https://github.com/esp8266/arduino-esp8266fs-plugin
  [8]: https://www.arduino.cc/en/Main/Software#download


message:
Arduino: Camera streaming

I want to make Arduino to stream video by camera thru bluetooth to android.

   1. Is Arduino powerfull enough to stream it without lag(Sorry if the question is stupid)

   2. Are there any good cameras, I have been searching before, but only found        one 0.3 mp camera, so are there other cameras with better quality?

   3. What is better, to use Arduino or Rasberry Pi for that job?

body:
1.  Not even close
2.  In light of 1 it doesn't matter
3.  Get a Pi if you want to do video


body:
Assuming a 0.3 MP camera, that means 300,000 pixels. The Arduino (Uno) has a few KB of SRAM, so you need much more. External SRAM might be an option, but even 300.000 pixels need a lot (like multiple 23LC1024 SRAMs).

Also the Arduino is 16 MHz. This means 16.000.000 cycli/s. That means for every pixel processing only 53 cycli are available. And using those external SRAMs will probably need much more.

A Raspberry is much more suitable for this task.


message:
Arduino Due's clock frequency

I want to change the clock frequency of the Arduino Due. The default value of the main clock, according to the SAM micro-controller, is 4 Mhz. But I found in some forums that it is 84 Mhz. But I need to work with it at 16 Mhz. Hence, I need to access to the low-level clocks of the Due and **change its operating clock frequency**.

1. How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?

2. Is it possible to write code for the Arduino Due via Atmel Studio 7? When I tried compiling code in AS7, Chip.h was not found. How to avoid this? Is it possible with "micro" IDE in AS7? Can I access registers of the Due via AS7 and change its clocking?

3. I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

body:
> How can I find the low-level registers of the Due in the Arduino IDE? Any header files for the Due to change its clocking?

Read the datasheet / programming manuals for the chip. The Arduino Due is arranged to run at 84MHz.

> I cannot find the "sam" library in the Arduino IDE. Only avr is present. How can I find this sam library?

Install it. The IDE is (fairly) modular these days.

But I have to ask... why do you want to run at 16MHz?


message:
Trying to connect a 1.3" IIC OLED display to an Arduino M0 board (not Uno)

I'm trying to connect an OLED display to the Arduino M0. I got the code example (ssd1306_128x64_i2c) from the Adafruit SSD1306 library I downloaded.

[Video showing at 8:14 how it should look][1]

However, when I upload the code to the board most of the display just lights up with no motion. It's only in the bottom that you can see the program is running, showing part of the different shapes.

After I uploaded it the first time I didn't change anything but now the compiler gives an error message saying that one display setting must be specified in SSD1306.h

I've tried setting the display size in the library header file which looks like this:

    Displays
    -----------------------------------------------------------------------
    The driver is used in multiple displays (128x64, 128x32, etc.).
    Select the appropriate display below to create an appropriately
    sized framebuffer, etc.

        SSD1306_128_64  128x64 pixel display
        SSD1306_128_32  128x32 pixel display
        SSD1306_96_16

    #define SSD1306_128_64
    //#define SSD1306_128_32
    //#define SSD1306_96_16

But the same error message appears in the compiler.

Does anybody know how I can fix this?

Thank you.

  [1]: https://www.youtube.com/watch?v=VEZGn0zYHiE

body:
That header part should look like this (notice the comment starts and ends):

        /*=========================================================================
        SSD1306 Displays
        -----------------------------------------------------------------------
        The driver is used in multiple displays (128x64, 128x32, etc.).
        Select the appropriate display below to create an appropriately
        sized framebuffer, etc.
        SSD1306_128_64  128x64 pixel display
        SSD1306_128_32  128x32 pixel display
        SSD1306_96_16
        -----------------------------------------------------------------------*/
    #define SSD1306_128_64
    //   #define SSD1306_128_32
    //   #define SSD1306_96_16
    /*=========================================================================*/

If it compiles but doesn't work try to replace the I2C address of Adafruits 128x64 module (0x3D) by the address often used in Chinese modules (0x3C):

    display.begin(SSD1306_SWITCHCAPVCC, 0x3D);

to

    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

If that doesn't work, use an I2C scanner to find the address of the connected module.


message:
Where is random defined with no arguments?

I can't seem to find `void random()` (with no arguments) defined in the library and yet my sketches seem to compile just fine when calling `random()` with no arguments.

I've found [random with 1 argument](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WMath.cpp#L35) and [random with 2 arguments](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WMath.cpp#L43) but no cases of random with no arguments.

Is `random()` defined in the library with no arguments?

If so, where is it defined?

If it isn't, what could explain how my code compiles despite me not providing any arguments?

body: It's defined in the libc, in `stdlib.h`.


message:
Const data optimisation for Arduino

I'm taking a course on Arduino Uno programming and on today's talk I heard that the const data is optimized by Arduino, so that it occupies less space than the actual data type (namely, a const int occupies less than an int).

If instead of int I use const uint8_t, const uint16_t etc. is the optimization still applied, or does using the 8 and 16 bit ints represent bad practice?

body:
Const memory will still store ts value both in Flash and in SRAM. For arrays PROGMEM can be used and for strings F() to remove the copy to SRAM.

Normal (non const) memory will be stored in SRAM. And if it is initialized with a value, that value is stored in Flash.

However, uint8_t will always occupy 1 byte, and uint16_t always two bytes.

You can read more about the different types of memory and F [here][1].

You can read more about program [here][2].

Update:

Test with const:

    const uint8_t  Amount1 = 4;
    const uint8_t  Amount2 = 4;
    const uint8_t  Amount3 = 4;
    const uint8_t  Amount4 = 4;
    const uint8_t  Amount5 = 4;
    const uint8_t  Amount6 = 4;
    const uint8_t  Amount7 = 4;

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

    void loop() {
      // put your main code here, to run repeatedly:
      Serial.print(Amount1);
      Serial.print(Amount2);
      Serial.print(Amount3);
      Serial.print(Amount4);
      Serial.print(Amount5);
      Serial.print(Amount6);
      Serial.print(Amount7);
    }

Result: 1758 bytes of program storage space, 184 bytes of dynamic memory.

Same without word 'const:

Result: 1758 bytes of program storage space, 184 bytes of dynamic memory.
No difference

using #define Amount1..7 4

Result: 1702 bytes of program storage space, 184 bytes of dynamic memory.

Conclusion: to save Flash space, use #define instead of (const) uint8_t.
However, also see Jot's experiment, it seems that code optimalization is smarter than my conclusion.

  [1]: http://playground.arduino.cc/Learning/Memory
  [2]: https://www.arduino.cc/reference/en/language/variables/utilities/progmem/


body:
This question is not really about the Arduino. It is about GNU C/C++ compiler optimizations.

By adding the keyword `const` the compiler can do a lot of optimization. One is that the value does not need to be stored in SRAM. The value can end up as part of an instruction, become part of an expression that is evaluated at compile-time, etc.

In the [Arduino-GPIO][1] library `static const` member data is used to allow the compiler to optimize to a single instruction `digitalRead()` with almost X100 performance improvement (on Arduino Mega).

Check GCC and AVR optimizations for further details.

1. http://www.nongnu.org/avr-libc/user-manual/using_tools.html
2. https://gcc.gnu.org/wiki/avr-gcc
3. http://www.linuxjournal.com/article/7269

Cheers!

  [1]: https://github.com/mikaelpatel/Arduino-GPIO/blob/master/src/Hardware/AVR/GPIO.h


message:
Problem with simple coding for PLDuino: trying to turn relay on and off

I am writing the following, simple code to try to turn a relay in the PLDuino on and off, and it is giving me warnings and not compiling/uploading. Any help would be greatly appreciated. Here is my code:

    #include <PLDuino.h>
    using namespace PLDuino;

    void setup()
    {
      // A necessary call.
      // It sets pin modes according to their function.
      PLDuino::init();
    }

    void loop()
    {
      // Simple switch RELAY3 on and off with 2 second timeout.
      digitalWrite(PLDuino::RELAY3, HIGH);
      delay(2000);
      digitalWrite(PLDuino::RELAY3, LOW);
      delay(2000);
    }

I have installed the proper libraries. Here are the warnings I am getting:

    WARNING: Category 'Graphics' in library PLDTouch is not valid. Setting to 'Uncategorized'
    WARNING: Category 'General' in library PLDuino-Library is not valid. Setting to 'Uncategorized'
    WARNING: Category 'Graphics' in library PLDuinoGUI is not valid. Setting to 'Uncategorized'
    Sketch uses 1702 bytes (0%) of program storage space. Maximum is 253952 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
    avrdude: ser_open(): can't open device "\\.\COM4": The system cannot find the file specified.

    avrdude: ser_drain(): read error: The handle is invalid.

    avrdude: ser_send(): write error: sorry no info avail
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: ser_recv(): read error: The handle is invalid.

    avrdude: ser_recv(): read error: The handle is invalid.

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: ser_send(): write error: sorry no info avail
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: ser_recv(): read error: The handle is invalid.

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: ser_send(): write error: sorry no info avail
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: ser_recv(): read error: The handle is invalid.

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: ser_send(): write error: sorry no info avail
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: ser_recv(): read error: The handle is invalid.

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: ser_send(): write error: sorry no info avail
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: ser_recv(): read error: The handle is invalid.

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: ser_send(): write error: sorry no info avail
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: ser_recv(): read error: The handle is invalid.

    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer

body:
For the library warning, you'll need to add / edit library.properties to those folders to specify a valid category.

This is an example library.properties to give you a feel for the structure (I found this particular one [here][1]).

    name=TMRpcm_PLDuino
    version=1.0
    author=TMRh20
    maintainer=digitalloggers
    sentence=PCM/WAV Audio playback (USE_TIMER2 enabled)
    paragraph=Play WAV audio files from SD card using AVR (UNO,Nano,etc) based devices.
    category=Communication
    url=https://github.com/digitalloggers/TMRpcm_PLDuino
    architectures=avr

However, these are just warnings, and don't seem to be the cause of your problem.

<hr>

Your actual problem in this case seems to be that it's trying to upload the sketch via COM4 and it can't find the PLDuino on that port.

  [1]: https://github.com/digitalloggers/PLDuino


message:
can arduino on output mode sink current?

I have a arduino set below:

    pinMode(1,OUTPUT);
    digitalWrite(1,LOW);

Now, I am expecting 1.2mA current flow through the pin that is set as output. Is that accepted? If so, what it the max current a pin can sink?

The current comes from a pul up resistor on the line

note: I can't protect it with a diode.

body:
Ok, I just found it.

from the arduno docs:

Atmega pins set aa output can source (provide positive current) or sink (provide negative current) up to 40 mA (milliamps) of current to other devices/circuits.


body:
> can arduino on output mode sink current?

yes.

> from the arduno docs:

the datasheet for the particular device is the best place for that answer.


body:
Yes it can. [This blog post of mine will help to explain it](https://hackingmajenkoblog.wordpress.com/2017/03/20/what-exactly-is-a-gpio-pin/).

In short:

> It’s all so simple now, isn’t it? The output pin is just like a switch that either connects it to 5V or to ground.


message:
How to use arduino IDE to compile .s files

Hi I'm new to arduino and im using it to learn assembly for my computer hardware 101 class, I read online that I can make the IDE accept .s files and compile them to the board but I dont know how to do this (something about editing the source code and recompiling the IDE?).

Could I get a step by step walk through? Assuming it's relatively simple, or just a link to some relevant documentation that's not a literal reference manual :-).

**EDIT**
As terrible as it is,I'm working from a macbook pro

body:
The IDE should be able to accept `.S` files (not `.s` - the difference is very important: `.S` will be preprocessed, `.s` won't).

Just create a new sketch, and create a new tab called `whatever.S` (obviously rename the `whatever` to whatever you want to call it.

Then in the main sketch `.ino` file put something like:

    extern "C" void myAssemblyMain();

    void setup() {
        myAssemblyMain();
    }
    void loop() {
    }

That will then call the function `myAssemblyMain:` in your assembly file and not much else.

(Note: I haven't tested this since I don't use the Arduino IDE).