body:
My Arduino resets / bugs each time I put `myFile = SD.open` in `loop()`.

In `setup()` it works fine.

I have a 20*4 LCD and an RTC connected to I2C, an SD card reader connected to SPI, and a fingerprint sensor.

Here is my code:

    #include <Adafruit_Fingerprint.h>
    #include <SoftwareSerial.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    #include <SPI.h>
    #include <SD.h>
    #include <DS3231.h>;

    LiquidCrystal_I2C lcd(0x3f,20,4);
    DS3231  rtc(SDA, SCL);
    SoftwareSerial mySerial(2, 3);

    Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);
    Sd2Card card;
    SdVolume volume;
    SdFile root;

    int etat = 0;
    int getFingerprintIDez();
    const int chipSelect = 10;
    SDFile myFile;

    void setup() {
      lcd.init();
      lcd.backlight();
      rtc.begin();
      finger.begin(57600);
      SD.begin();

      // Reglage Heure
      //rtc.setDOW(TUESDAY); // Set Day-of-Week to SUNDAY
      //rtc.setTime(10, 57, 0); // Set the time to 12:00:00 (24hr format)
      //rtc.setDate(24, 11, 2016);   // Set the date to January 1st, 2014
      if (finger.verifyPassword()) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Capteur Initialise");
      } else {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Capteur Deconnecte");
      }
      delay(2000);
      if (SD.exists("data.csv")) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("data.csv OK.");
        delay (1000);
      } else {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Creating data.csv...");
        myFile = SD.open("data.csv", FILE_WRITE);
        myFile.close();
        delay (1000);
      }
    }

    void loop() {
      if (etat == 0) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Put Finger");
        getFingerprintIDez();
      }
      if  (etat == 1) {
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("ID #");
        lcd.setCursor(4,0);
        lcd.print(finger.fingerID);
    //  myFile = SD.open("data.csv", FILE_WRITE);
    //  myFile.print(rtc.getDateStr(1));
    //  myFile.print("\t");
    //  myFile.print(rtc.getTimeStr(1));
    //  myFile.print("\t");
    //  myFile.println(finger.fingerID);
    //  myFile.close();
        lcd.setCursor(0,2);
        lcd.print("Loged");
        etat = 0;
      }
      delay(1000);
    }

    int getFingerprintIDez() {
      uint8_t p = finger.getImage();
      if (p != FINGERPRINT_OK)  return -1;
      p = finger.image2Tz();
      if (p != FINGERPRINT_OK)  return -1;
      p = finger.fingerFastSearch();
      if (p != FINGERPRINT_OK)  return -1;
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Found ID #");
      lcd.setCursor(14,0);
      lcd.print(finger.fingerID);
      etat = 1;
      return finger.fingerID;
      delay(1000);
    }

Each time I uncomment lines using SD, the Arduino resets at the end of the loop.

What is the problem?

title: Arduino bug when "myFile = SD.open" is inside loop()

Answers: 1

body:
The solution to your problem is to extend your 2 states machine in a multiple states machine.

Declare the `enum eState` before `setup()`:

    typedef enum e_State {
     STATE_START = 0, // starting the loop (add some initialisation)
     STATE_READ_FINGER, // Step1: read the finger print
     STATE_DISP_FINGER, // Step2: display the finger print
     STATE_OPEN_LOGGER, // Step3: open the log file
     STATE_WRITE_LINE, // Step4: append a timestamp finger print
     STATE_CLOSE_LOGGER // Step5: close the log file
    } eState;

And update the `loop()` function with the state-machine:

    void loop()
    {
     static eState LoopState = STATE_START; // to store the current state

     eState NextState;  // for the next loop

     switch (LoopState) {
     case STATE_START:
      // add additional settings
      NextState = STATE_READ_FINGER;
      break;
     case STATE_READ_FINGER:
      etat = 0; // keep use your 'etat'
      // or return a boolean from your 'getFingerprintIDez()'
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Put Finger");
      getFingerprintIDez();
      if (etat == 1) {
       NextState = STATE_DISP_FINGER;
      }
      break;
     case STATE_DISP_FINGER:
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("ID #");
      lcd.setCursor(4,0);
      lcd.print(finger.fingerID);
      NextState = STATE_OPEN_LOGGER;
      break;
     case STATE_OPEN_LOGGER:
      myFile = SD.open("data.csv", FILE_WRITE);
      if (myFile) {
       // record only if file is opened
       NextState = STATE_WRITE_LINE;
      }
      else {
       lcd.setCursor(0,0);
       lcd.print("Can't open file");
      }
      break;
     case STATE_WRITE_LINE:
      myFile.print(rtc.getDateStr(1));
      myFile.print("\t");
      myFile.print(rtc.getTimeStr(1));
      myFile.print("\t");
      myFile.println(finger.fingerID);
      myFile.flush();
      NextState = STATE_CLOSE_LOGGER;
      break;
     case STATE_CLOSE_LOGGER:
      myFile.close();
      lcd.setCursor(0,2);
      lcd.print("Loged");
      NextState = STATE_READ_FINGER;
      etat = 0;
      break;
     default:
      NextState = STATE_START;
     }
     // next loop()
     LoopState = NextState;
     delay(200);
    }


body:
My sketch looks somehow like this:

    ClassA classA;

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

        classA = ClassA();
        Serial.println("Bar")

        ...
    }

    void loop() {
        classA.functionFoo();
    }

The constructor of `ClassA` however calls some internal methods that perform a `Serial.println()`.

My problem is, that the first (implicit) call of the constructor of `ClassA` comes in the first line of the sketch with

    ClassA classA;

This is before the Serial interface has been initialized (with `Serial.begin(9600)`). Therefore the Serial.monitor cannot interpret the first messages coming from the serial interface.

How can I either suppress any Serial.writes before the setup function or otherwise make sure that the Serial interface is initialized before the setup function?

title: Run 'Serial.begin(9600)' before loop()

Answers: 2

body:
In order to be sure that your `classA` object doesn't use the `Serial.println()` function before the baudrate is defined, it is necessary to add functions in your `class ClassA` and to inform from `setup()` your `classA` object.

The simplest way is to add:

 1. a boolean `bool bSerialReady`to keep the status of the Serial object,
 2. in all `ClassA` constructors, initialize that `bSerialReady = false;`,
 3. add a function `void SetSerialReady()` to switch the status `bSerialReady = true;`. The function should be called in the `setup()`function just after `Serial.begin(9600);`,
 4. and in all functions of `ClassA`, add a if-condition `if (bSerialReady)` before calling the `Serial.println()`.

Your `class ClassA` will become:

    class ClassA
    {
    private:
     bool bSerialReady;
    public:
     ClassA() {
      // ...
      // Initialize bSerialReady
      bSerialReady = false;
     };
     void SetSerialReady() {
      bSerialReady = true;
     };
    };

Your `setup()` function becomes:

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

And in functions of `ClassA`, it looks like:

    if (bSerialReady) {
     Serial.println("Bar");
    }

body:
You can make your current object a pointer so it isn't instantiated:

    ClassA *classA;

Then create an object with new:

    classA = new ClassA();

The constructor is then only called when the object is made.

Note that you will have to change your accessors to `->`:

    classA->myFunction();


body:
I am working on wifi based LED project which involves various ESP to be connected to router. Basically grouping of ESP has to be done. The android app sends HTTP command to IP address which is given by router to the ESPs, the IP are not static and expires after some time. Now my question is how can mobile app can get the IP of all the ESP connected to router?

Does using HTTP protocol complicates the process? Shall I switch to multicast UDP? or use UnPn Protocol for scanning (Sounds complicated though).

Please help!

title: Scan multiple ESP8266

Answers: 3

body:
The best protocol for these kind of applications is MQTT.

Read more [here][1]

  [1]: http://mqtt.org/

body: You can go with UDP Multicast.

body: Yes, Multicast is the only option.


body:
I have following setup (see also schematic in the end)

Arduino Nano is connected via I²C to the PCF8575C ([link][1]) IO Expander.
Both, SCL and SDA have 10kOhm pull-ups to 5V.
The Expander pins are connected to a MOSFET-driver that turns on/off 12V LED stripes.
The Expanders Bus address is set via Expanders A0-A2 pins to 0 (0x20).
The MOSFET driver pins have to be pulled to logic 1 (above 2.2V) in order to turn on the stripe.

Currently Arduino runs an blink example, that turns all Expander IO pins on/off every second (using Arduino Wire Library), but the **MOSFET-driver does not turn on/off any Stripe.**

I can manually turn on Stripes by connecting MOSFET-driver pins to Arduinos 5V (or 3.3V)

The power supply to the IO Expander is O.K.

By measuring the resistance between GND and IO pins of the Expander, I can see that it alternates every second (so I²C communication to the Expander works also)

**Curious thing:** While measuring this resistance (holding the multimeter test leads) to GND and to the IO pin of Expander, the MOSFET-driver turns the Stripes on and off! When I take the test leads away it stops working! **Magic?!**

**What am I missing?** Do the output pins of the PCF8575C need some extra pullup/pulldown resistors or something else?

Thank you in advance!

Schematics:
[![Schematics][2]][2]

  [1]: https://www.sparkfun.com/products/retired/8130
  [2]: https://i.stack.imgur.com/xrVRi.jpg

title: Does an I²C IO Expander needs additional resistors for outputs?

Answers: 2

body: Yes, according to the datasheet (which should always be your first port of call for any chip) the outputs are Open Drain. That means you require a pullup resistor, exactly as if the outputs were simple buttons.

body:
Think of the oped drain output (or open collector) as a pin that connects to ground when the device is on. If you connect the anode of an LED to plus and connect the kathode to the open drain pin, then you do not need a pull-up resistor (you may need a current limiting resistor though)

The test leads of the Ohmmeter produce a current to masure resistance, it also provides a current path to ground if the that's where you placed one of the leads. This would explain the **Magic**

More [here][1] about open collector outputs.

  [1]: https://en.wikipedia.org/wiki/Open_collector


body:
I'm trying to build Bluetooth RC car, but I can't run only one DC motor.. only both of them. Everything works fine, the bluetooth, the app but when i try to go forward/backward/left/right nothing happens, only when i run both of them. I'm running the Arduino Nano with usb cable. The bluetooth connection is stable, The DC motors are working. I don't know what I'm doing wrong. Thanks!

[![Schematic][1]][1]

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

    const int AIA = 2;
    const int AIB = 3;
    const int BIA = 4;
    const int BIB = 5;
    byte vSpeed = 255;
    int state;

    void setup() {
    pinMode(AIA, OUTPUT);
    pinMode(AIB, OUTPUT);
    pinMode(BIA, OUTPUT);
    pinMode(BIB, OUTPUT);

    // Initialize serial communication at 9600 bits per second:
        Serial.begin(9600);
    }

    void loop() {
      //Save income data to variable 'state'
        if(Serial.available() > 0){
          state = Serial.read();
        }

      /***********************Forward****************************/
      //If state is equal with letter 'F', car will go forward!
        if (state == 'F') {
          analogWrite(AIA, vSpeed);
          analogWrite(AIB, 0);
          analogWrite(BIA, 0);
          analogWrite(BIB, 0);
        }
      /**********************Forward Left************************/
      //If state is equal with letter 'G', car will go forward left
        else if (state == 'G') {
          analogWrite(AIA, vSpeed);
          analogWrite(AIB, 0);
          analogWrite(BIA, vSpeed);
          analogWrite(BIB, 0);
        }
      /**********************Forward Right************************/
      //If state is equal with letter 'I', car will go forward right
        else if (state == 'I') {
          analogWrite(AIA, vSpeed);
          analogWrite(AIB, 0);
          analogWrite(BIA, 0);
          analogWrite(BIB, vSpeed);
        }
      /***********************Backward****************************/
      //If state is equal with letter 'B', car will go backward
        else if (state == 'B') {
          analogWrite(AIA, 0);
          analogWrite(AIB, vSpeed);
        }
      /**********************Backward Left************************/
      //If state is equal with letter 'H', car will go backward left
        else if (state == 'H') {
          analogWrite(AIA, 0);
          analogWrite(AIB, vSpeed);
          analogWrite(BIA, vSpeed);
          analogWrite(BIB, 0);
        }
      /**********************Backward Right************************/
      //If state is equal with letter 'J', car will go backward right
        else if (state == 'J') {
          analogWrite(AIA, 0);
          analogWrite(AIB, vSpeed);
          analogWrite(BIA, 0);
          analogWrite(BIB, vSpeed);
        }
      /***************************Left*****************************/
      //If state is equal with letter 'L', wheels will turn left
        else if (state == 'L') {
          analogWrite(BIA, vSpeed);
          analogWrite(BIB, 0);
        }
      /***************************Right*****************************/
      //If state is equal with letter 'R', wheels will turn right
        else if (state == 'R') {
          analogWrite(BIA, 0);
          analogWrite(BIB, vSpeed);
        }
      /************************Stop*****************************/
      //If state is equal with letter 'S', stop the car
        else if (state == 'S'){
          analogWrite(AIA, 0);
          analogWrite(AIB, 0);
          analogWrite(BIA, 0);
          analogWrite(BIB, 0);
        }
    }

title: Can't run two separated DC Motors

Answers: 1

body:
Connect the Nano ground to the driver board ground.  Since they do not share a common ground, they can have odd behavior as their ground planes float.

You need only connect the grounds, the USB can still provide +5 to the Nano, and the +9 can still provide power to the driver.  The only energy that will flow through the black wire connecting the grounds is the energy that flows between pins 2,3,4,5 and the driver's AIA, AIB, BIA, BIB, for the logic signals, which I'd bet is in the sub-uA range.


body:
I have a code sample that uses serial3 (RX3 on a Mega) which I want to try and get working on a Uno.  It reads on RX3 and streams to USB.  What I had read, you use Serial for RX0, however Serial seems to be used for USB

     /*
    Arduino Neato XV-11 Laser Distance Scanner
    Motor control board v0.2 by Cheng-Lung Lee

    XV-11 LDS adapter reads LDS data from RX3 then relay to TX. Also extract the speed
    data from the data stream to do speed control on LDS motor. Everythin can power
    from USB no extra power required.

    Change log:
    V0.2 Add simple speed control code update PWM 3 times per rev.
    V0.1 Opend loop control version.

    This code is tested on Arduino Mega 1280
    I/O:
    Motor drive by low side driver IPS041L connect to PWM Pin4, Motor power from 5V
    Neato XV-11 LDS Vcc(red) : 5V
    Neato XV-11 LDS TX(Orange) : RX3

     */

    const int DesiredRPM=300;  // Setting Desired RPM Here.
    const int MotorPWMPin=4;
    int inByte = 0;         // incoming serial byte
    unsigned char Data_status=0;
    unsigned char Data_4deg_index=0;
    unsigned char Data_loop_index=0;
    unsigned char SpeedRPHhighbyte=0; //
    unsigned char SpeedRPHLowbyte=0;

    int SpeedRPH=0;
    const unsigned char PWM4dutyMax=255;
    const unsigned char PWM4dutyMin=100;
    unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

     void setup() {
        pinMode(MotorPWMPin, OUTPUT);
        Serial.begin(115200);  // USB serial
        Serial3.begin(115200);  // XV-11 LDS data

      // prints title with ending line break
      Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

      // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
        analogWrite(MotorPWMPin, PWM4duty );
    }

    void loop() {
        // if we get a valid byte from LDS, read it and send it to USB-serial
      if (Serial3.available() > 0) {
        // get incoming byte:
        inByte = Serial3.read();
        //Serial.print(inByte, BYTE);
        //Serial.write(inByte);
        Serial.print((char)inByte);
        decodeData(inByte);
      }

    }

    void decodeData(unsigned char inByte){
      switch (Data_status){
      case 0: // no header
      if (inByte==0xFA)
      {
        Data_status=1;
        Data_loop_index=1;
      }
        break;
      case 1: // Find 2nd FA
        if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_status=2;
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          Data_loop_index++;
        }
        break;
      case 2: // Read data out

         if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          readData(inByte);
          Data_loop_index++;
        }
        break;
      }

    }
    void readData(unsigned char inByte){
      switch (Data_loop_index){
        case 1: // 4 degree index
        Data_4deg_index=inByte-0xA0;
    //      Serial.print(Data_4deg_index, HEX);
    //      Serial.print(": ");
        break;
        case 2: // Speed in RPH low byte
        SpeedRPHLowbyte=inByte;
        break;
        case 3: // Speed in RPH high byte
        SpeedRPHhighbyte=inByte;
        SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

        SpeedControl ( DesiredRPM ) ; //
    //      Serial.print(SpeedRPHhighbyte, HEX);
    //      Serial.println(SpeedRPHLowbyte, HEX);
        break;
        default: // others do checksum
            break;
      }
    }

    // Very simple speed control
    void SpeedControl ( int RPMinput)
    {
     if (Data_4deg_index0==0) {  // I only do 3 updat I feel it is good enough for now
      if (SpeedRPH<RPMinput*60)
         if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
      if (SpeedRPH>RPMinput*60)
         if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
      }
      analogWrite(MotorPWMPin, PWM4duty ); // update value
    }

title: Serial question : Going from Mega to Uno

Answers: 1

body:
Arduino UNO only has one **hardware** UART, hence only one `Serial` available, which is linked to USB, but you could still use it for something else by connecting directly to D0 & D1.

However, if you need 2 separate, independent, UART then go for `SoftwareSerial` for the second one.

Now, if you need to connect 2 devices, one to exclusively get data from, the other exclusively to send data to, then you can use just one UART, i.e. `Serial` for both devices, as long as both links work at the **same speed** and **settings** (parity...)

Also you must ensure that USB won't receive anything otherwise you would get it and confuse it with input from the first device.

The non USB device providing input to the Uno should be connected to D0 (RX).


body:
I am going to create a project with a friend, but I have some technical questions.

The Arduino Nano has an EEPROM capable of storing the known WiFi connections. Basically what I want is say "Arduino, connect to this WiFi and remember it". When I then disconnect the Arduino completely, it should still save that information. Can the EEPROM store that without power?

I need an easy, but rather small, WiFi module to work with the Arduino Nano. I've looked at the ESP8266. I don't mind soldering the ESP8266 to the Arduino Nano *once*, but doing it more times (perhaps because I need more GPIO or something) is not a variable solution. If I get the ESP8266 ESP-12, I would only have to solder it to the Nano once. However:

 1. Is the ESP8266 ESP-12 compatible with the Arduino Nano?
 2. I like the ESP-05 because it's small and simple. Would that work?

Are there perhaps better ways of doing this whole thing? Should I go for something else than the Arduino Nano? I need to hook up:

 - WiFi
 - Microphone (smallest and easiest way)
 - LEDs

title: Arduino Nano + ESP8266 and saving to EEPROM

Answers: 2

body:
It sounds like you are quite new to all this stuff.  In summary I think you are taking the wrong approach and need to re-think things.

EEPROM is capable of storing data without any power.
Both the devices have EEPOROM, also you could look at external devices, which would be easier to replace if you wear them out (limited number of write cycles - see their data sheets for details but they are usually in the tens of thousands).

The difference between the ESP8266 range are the number of GPIO lines they offer up, to the 12E has more than the 5, etc.

You shouldn't be soldering this stuff more than once.  You should design it right in the first place (easier said than done!)  What you could do is mount the Nano on a board that took all the lines off to a single 30 odd pin connector the design a series of daughter boards for the ESP8266 which were compatible with the base board, so you could switch between the different ESPs.

Also, don't forget you will need logic level conversion between the 5V Arduino and the 3.3V ESP8266 unless you are planning on smoking electronics.

What do you think you are doing with the MIC connector?  Are you planning on processing sound on the Arduino?  You might want to research that before you design it.

Are you aware that the ESP8266 can be programmed via the Arduino and has a 80MHz processor and 256KB of RAM (compared to the Nano's 32Mhz & 32KB) so using the ESP as a slave to the Arduino is not necessarily the best idea.

If you are interested this is the approach I would take:
 1. Solder some male pins to the Nano so you can put it into a bread board.
 2. If you have a 12E, Buy a ESP8266 mounting board (£1 for 10 from you favourite Chinese web market) and solder pins to that.
 3. If you have a 5 then solder pins to that.
 4. Make all you other parts breadboard-able and try it all out.
 5. Once it works download Fritzing and draw it up.
 6. Make a Vero board version and play with it for real.

body:
The ESP8266 is a SoC (System On Chip) that includes a microcontroller. For most applications, you’ll need only the ESP without the Nano. ESP-12E boards are very handy for tinkering. You can program the ESP in different languages, even in Arduino C (https://github.com/esp8266/Arduino/).

Note that the ESP is only 3.3V tolerant, so it is not that easy to use it with a Nano that works at 5V. It is of course possible to use logic level shifters, but frankly, I would rather use the ESP alone.

You don’t have to worry about storing WiFi connection settings, they are usually hard-coded in the main program.

Connecting LED is described everywhere on the internet, so I don’t think that is a major problem. If you need a lot of LEDs, you can buy LED strips.

For the microphone I suggest that you search for I²C modules.


body:
  This should be a quick question.

I'm trying to figure out how I can restart `void loop()` if a certain condition is met. In this instance, if (s>10), I want the loop to restart. Any help will be appreciated.

     void loop() {

      if (getDistance(0) == true)                   //if the car passed the first sensor
      {
        while (getDistance(0) == true && getDistance(1) == false);
        unsigned long currentMillis = millis(); //time when the passed the first sensor

        while (getDistance(1) == true && getDistance(0) == true); //wating car to pass the second sensor

        unsigned long endMillis = millis(); //time at which the car passed the second sensor

        unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
        float timeSeconds = timeMillis / 1000.0; //because 1000ms = 1s

        float s = sensorDistance / timeSeconds; //speed = distance / time

        if(s>=7 && s<=10) // for red to turn on
        {
        Serial.print(s); // printing the speed magnitude
        Serial.print(" m/s");// printing the units of speed
        Serial.println(); // new line in printing

        char msg[2] = {'h','#'}; // sending some random message to indicate that speed is greater than 10
        digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
        vw_send((uint8_t *)msg, 2); // sending a message
        vw_wait_tx(); // Wait until the whole message is gone
        digitalWrite(led_pin, LOW); // again bringing the flash light to low

        }
        else if (s<7)
        {
        Serial.print(s); // printing the speed magnitude
        Serial.print(" m/s");// printing the units of speed
        Serial.println(); // new line in printing

        char msg[4] = {'h','e','l','#'}; // sending some random message to indicate that speed is greater than 10
        digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
        vw_send((uint8_t *)msg, 4); // sending a message
        vw_wait_tx(); // Wait until the whole message is gone
        digitalWrite(led_pin, LOW); // again bringing the flash light to low
        }

        delay(2000);
      }
    }

title: How to restart void loop if condition is met

Answers: 3

body:
To expand on what jfpoilpret said setup() and loop() are called by the code you can't see in every program.  `setup()` is called once and `loop()` is called in a `while(true)` loop until the program crashes or the universe ends.

To call you code while a condition is met you could either wrap it in a loop or an if, within the `loop()` function, so something like this:

    void loop ()
    {
        if (s > 10)
        {
            // Your stuff....
        }
    }

This will only call your code IF `s > 10`.  Something you need to watch for is ensuring that there is some code that can cause `s` to be greater than `10`.

You can also move `"// Your stuff..."` into a function of its own

    void MyCode ()
    {
        // Your stuff ...
    }

and then call this function from inside the if statement.  This makes you code easier to read and easier to fix.

If this answer wasn't what you meant then feel free to comment and I'll see if I can come up with a better answer.

body:
When programming with arduino IDE, you declare 2 functions, setup() and loop().

Before compilation, arduino IDE basically expands to :

    int main(void)
    {
        /* run the Arduino setup */
        setup();
        /* and the event loop */
        while (1) {
            loop();
        }
        /* never reached */
        return 0;
    }

So, from here you can see that setup() is called once at startup and then, loop() is called in an infinite loop.
Il you return from within your loop function, it will be called again.

body: I hate to bring this up, but I've now been programming for 58 years. One curious and often overlooked feature of the C & C++ languages is the GOTO keyword. It can be very useful. My second language was FORTRAN I. I know, now I'm relegated to the 9th circle of he|| where the miscreants are frozen into glaciers head down with their legs protruding?


body:
I´m using `LowPower.h` and `PinChangeInt.h` libraries to put my Arduino into the sleep mode every 8 seconds and then it wakes up, modifies a counter and it goes to sleep again, but also I need to wake it up when a button is pressed asynchronously.

I´ve reached to wake up the Arduino every 8 seconds using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` and, in other code, I´ve also reached to wake it up while it sleeps indefinitely with `LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF)` but I can´t combine that periodical awakening with the asynchronous awakening.

Here is my code:

    void setup(){

        Serial.begin(9600);

        //Pines declaration

        loopsToSend = setTimeToSend();  //

        //The three async buttons
        PCintPort::attachInterrupt(4, readOpinion,RISING);
        PCintPort::attachInterrupt(5, readOpinion,RISING);
        PCintPort::attachInterrupt(6, readOpinion,RISING);
    }

    void loop(){

        if(loops < loopsToSend ){

            byte opinionValue = readOpinion(); //This method must awake the Arduino ASYNC to give a value to the opinionValue var, write the result in the file and go to sleep

            if(opinionValue != 0){
                Serial.println("Button pressed!");

                //Writing result in a file
                opiniones++;
                delay(500);
            }
            //Go to sleep 8 seconds
            LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
            opinionValue = 0;
        }
        else {
            wdt_disable();

            if(opiniones > 0){
                //Send file using GSM module
            }
            else{
                loops = 0;
            }
        }
        loops++;
    }

Can anyone help me? Thanks

title: Waking up async the Arduino while it is sleeping periodically

Answers: 1

body:
My aim was to attach multiple interrupts to my Arduino but my problem was that I didn´t know if when the board changed to sleep mode using `LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF)` then it could be awake using another interrupt instead of the timer.

The `void loop()` method must sleep the board every 8 seconds if no button is pressed. Aside there is a method that is called when a button is pressed, that´s because in the `void setup ()` I´ve attached an interrupt using `PCintPort::attachInterrupt(PIN_NUMBER, METHOD_TO_CALL,MODE);`

----

OP (PinaGamer) posted this answer inside the question, hence the community wiki answer.


body:
### Question ###

As far as I know each I/O pin has to keep around 20mA, what are the consequences of going higher or lower? But if I am using all I/O pins is there a maximum current value I should keep in mind? For example, the sum of all currents in all pins should not be greater than 100mA.

title: What is the maximum current for each I/O pin?

Answers: 2

body:
The power limits per pin and per chip are listed for each model (based on the Atmel chip).  You can look up the Atmel chip number and see the power ratings.  For example, the chip may have a maximum of 40mA per pin, but a total of 200mA for everything on the chip. These numbers are just examples. The actual numbers depend on which Arduino and which chip you are talkng about.

Remember that microcontroller chips are NOT designed to SWITCH any significant amount of power. That is NOT the job of the microcontroller. Its job is to CONTROL external devices (transistors, thyristors,SSR, relays, etc.) which do the actual "heavy lifting" of switching larger amounts of power.

Your last question really does not make any sense. Can you clarify it?

VCC is the name of the main power bus and input to the microcontroller chip. It may or may not be 5V depending on which Arduino you are talking about. The older ones were 5V, but newer chips (including those used in Arduino) are tending more to 3.3V.

body:
This comes up as first result when Googling your question:

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

And can be confirmed by page 313 and 314 of the [datasheet][2]:

[![enter image description here][3]][3]

To know where each pin is connected to (on the Arduino Uno) you can look the official (messy) [schematic][4].

I provide an excerpt below that shows the **Vin** and **5V** pins at the headers, and the power barrel connection.

[![enter image description here][5]][5]

If you want to control a 12V motor or a 12V LED strip or other DC loads you can use the following (which is also easy to find using Google):

*Note that your 12V Gnd and Arduino Gnd have to be connected.

<!-- 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/urNHq.png)

<!-- End schematic -->

  [1]: https://i.stack.imgur.com/XL0p4.jpg
  [2]: http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf
  [3]: https://i.stack.imgur.com/zJZgj.png
  [4]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [5]: https://i.stack.imgur.com/kDojF.png


body:
Regarding my program, it is a program that does some calculations and then outputs a voltage based on the result using analogWrite function. However my problem is that I had done my programming based on a misconception that analogWrite function via PWM does output an analog voltage, where in fact it only "simulates" the analog voltage instead.

Here are the relevant parts of my code :

    int pwmOutput = 11;
    int pwm = 0;

    void compareNewOldVoltageYes(void)
    {
      if(pv_Vnew > pv_Vold && pwm != 255)
      {
        ++pwm;           //increasing value
      }
      else if(pwm != 0)
      {
        --pwm;           //decreasing
      }
    }

    void compareNewOldVoltageNo(void)
    {
      if(pv_Vnew > pv_Vold && pwm != 0)
      {
        --pwm;
      }
      else if(pwm != 255)
      {
        ++pwm;
      }
    }

    void loop()
    {
       reading();
       PowerCalculation();

       if(pv_NewP > pv_OldP)
       {
          compareNewOldVoltageYes();
       }
       else
       {
          compareNewOldVoltageNo();
       }

       analogWrite(pwmOutput, pwm);           //analogWrite

       float displayPWMvolt = pwm * 0.0196;

       Serial.print("Output Voltage: ");
       Serial.print(displayPWMvolt);
       Serial.println(" V");

       pv_OldP = pv_NewP;

       Serial.print("Previous Power: ");
       Serial.print(pv_OldP);
       Serial.println(" W");

    }

As for the circuitry, output pin 11 is being connected to a 1 ohm resistor and then to GND. (Where I measured the voltage) I am using Arduino Uno board.

**UPDATE**:

As said in the comments by @DatHa, pwm does not output voltage. **Is there a way to output voltage as said, without changing the board?**

title: How to output a true analog voltage at output pin

Answers: 6

body: As far as I know Arduinos have ADC (Analog to Digital Converters) but do not have any DAC (Digital to Analog Converters). So you can not output a set voltage from any pins based on a digital value.

body:
At 5V, a 1 ohm resistor will try to sink 1A and far exceed the 40mA specs.  Please use at least a 5/0.040=125 ohm resistor to protect your pin.  And if you put the a capacitor between your resistor and ground, the RC circuit of the capacitor will smooth out the PWM into an analog voltage.

Please try the suggested [@russell answer][1] with a 47K resistor and 1uF capacitor, you will get an analog voltage at the junction to use with your electronic load.

  [1]: https://arduino.stackexchange.com/a/10047/6628

body:
NO.. There is no way to get an analog voltage from the Arduino. The best that you can do is to use Arduino as a Buck Voltage converter in linear or boost mode using a voltage regulator, inductor and the mosfet transistor.  You will also might need to use a Mega or Dulorme which provide a PWM frequency other that the standard 50o Hz.

Best luck

body:
You basically have three options:

1. Switch to an Arduino Due which has a built-in DAC which outputs a real voltage.
2. Add an external DAC chip (such as the MCP4821/2) to create the voltage for you
3. Use a low-pass filter (R-C network) on a PWM pin.

Of the three options I usually use an MCP4822 since it gives the best results and doesn't cost as much as using a Due.

body:
There is no direct way.

In addition to @Majenko

Alternative way: you can use H bridge like L293d to provide continuous level. Many diy inverter circuits are useing this technique.

http://www.instructables.com/id/How-to-Make-an-Inverter-Using-ARDUINO/?ALLSTEPS

body:
I wondered if this would give a more stable output.

[![PWN presented to RC.  Cap charges, sample is made by another analog input.  When PWN pin goes low, slow discharge of cap.  Maybe a large resistor is needed in parallel with the cap for slow discharge?][1]][1]

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


body:
I want to emulate keyboard presses in an old C64 microcomputer using an Arduino.

The keyboard connection is a non-standard 20-pin port (i.e. the Arduino keyboard libraries won't be useful) which, as I understand, works as a simple matrix of switches.

Since my Arduino Mega has more than 20 general purpose I/O ports, I understand I can approach the problem by simply mapping these 20 keyboard pins to individual "digital" Arduino ports, and then programming around it, right?

Or is this too naive and I'm missing something here?

I'm new to Arduino, so any comments highly appreciated. Thank you!

title: Emulate non-standard keyboard from Arduino

Answers: 1

body:
Emulating a keyboard matrix is actually harder than you would at first think. It's not just a case of setting certain combinations of pins as HIGH or LOW - you need to actively monitor one side of the matrix as it sweeps across each row and control the other side depending on the buttons that are pressed or not pressed on the current row. And all that has to be done fast enough that the C64 doesn't see buttons constantly bouncing up and down.

Further, you really need all your outputs to be *open drain* so as not to interfere with each other or the rest of the system (depending on just how the C64 system works), and Arduinos can't do *open drain* natively - instead you have to emulate it by switching between INPUT and OUTPUT + LOW which adds extra latency.

If you only want access to a few of the buttons a better arrangement would be to add a small N-channel (logic level) MOSFET or an NPN BJT between the two sides of the matrix for whichever button(s) you want to control (check the schematics for which pins and which way round to connect it). Activating the transistor would then be the same as pushing the button down. It can even be in parallel to the existing button so as to not break the keyboard.


body:
I have been trying to exit from the `while(1)` loop by getting a value from the sensor and then run the code outside `while(1)`.But the problem is that it does not exit. How may I fix this problem?

See Code Below.......

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

    void loop() {
     int sensor;
     while(1)
     {
      sensor = digitalRead(2);
      if(sensor == 0)
      {
       Serial.println("inside while loop");
      }
      break;
     }
     Serial.println("Break......");
    }

title: How to use while(1) loop in arduino?

Answers: 3

body: In the Arduino paradigm, unlike ordinary C programming where there is only 1 entry point called "main()", there are 2 entry points called "setup()" and "loop()".  "setup()" is called only once after booting up.  But "loop()" is called over and over again right after "setup()" is called.  There is no need to create your own infinite loop (for example a "while(1)" statement) as in ordinary C programming.

body:
instead of while(1), one can use the variable name in while and change the value of the variable when you want to exit the loop. part of the code can be modified based on the following concept.
`bool condition= true;
while(condition){
if (sensor==0)
condition=false;`
This is my suggestion for the above problem.

body:
Used like this

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

    void loop() {
         bool cond = true;

    int sensor;
    while(cond)
    {
        sensor = digitalRead(2);
        if(sensor == 0)
        {
            Serial.println("inside while loop");
        }
        cond = false;
    }

      // like this you can used while inside the void loop()

    }


body:
I need to use a servo library in my class.
I read this question - https://arduino.stackexchange.com/questions/9296/use-object-of-other-class-within-class and it works fine for my LCD application, but now I need to use a 2D servo array in my class. I made one approach, it worked, but I think it is bad programming approach, what is right way to solve my problem?

1. My main file

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

        #include <SoftwareServo.h>
        SoftwareServo servo[5][5];
        Servolib Servoarray;

        void setup(){
          blah blah blah

2. My cpp file

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

        #include "Vending.h"
        #include "Arduino.h"
        #include <SoftwareServo.h>

        Servolib::TurnSevo(){
          for(int row=0;row<5;row++){
            for(int collum=0;collum<5;collum++){
              servo[row][collum].attach(Object[row][collum]);
              servo[row][collum].write(0);
            }
          }
        }

3. my .h file

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

        #ifndef Vending_h
        #define Vending_h
        #include "Arduino.h"
        #include <SoftwareServo.h>

        class Servolib:SoftwareServo{
        public:
          void TurnServo();

        private:
          SoftwareServo servo[5][5];
          int Object[5][5]={
            {42,21,20,19,18},
            {37,41,36,38,35},
            {31,33,30,34,39},
            {67,28,66,29,65},
            {56,63,55,64,54}
          };
        };
        #endif

So this code worked, but please give me better solution.

title: Using 2D servo array in my class

Answers: 1

body:
You can indeed use pointers, but passing multi-dimensional arrays is a bit of a pain in C(++).

There's a pretty good explanation [here][1].

  [1]: https://stackoverflow.com/questions/8767166/passing-a-2d-array-to-a-c-function


body:
I have got this quick sketch that post data to mysql db using php add.php module.

    #include <SFE_BMP180.h>
    #include <SPI.h>
    #include <Ethernet.h>
    #include<dht.h>
    dht DHT;

    // You will need to create an SFE_BMP180 object, here called "pressure":
    SFE_BMP180 bmp;

    #define DHT11_PIN 2

    double tempInC;
    int humidity;

    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(192, 168, 1, 177);
    char server[] = "192.168.1.3";

    EthernetClient client;
    byte php_server[] = {192 , 168 , 1 , 3};

    long previousMillis = 0;
    unsigned long currentMillis = 0;
    long interval = 250000; // READING INTERVAL

    String data;

    void setup() {
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      if (bmp.begin()) {
        Serial.println("BMP init Success");
      }

      // start the Ethernet connection:
      if (Ethernet.begin(mac) == 0) {
        Serial.println("Failed to configure Ethernet using DHCP");
        // try to congifure using IP address instead of DHCP:
        Ethernet.begin(mac, ip);
      }

      // give the Ethernet shield a second to initialize:
      delay(1000);
      Serial.println("connecting...");
      data = "";
    }

    void loop() {
      int chk = DHT.read11(DHT11_PIN);
      char status;
      status = bmp.startTemperature();
      if (status != 0) {
        delay(status);
        status = bmp.getTemperature(tempInC);
      }
      else Serial.println("error retrieving temperature measurement\n");

      humidity = DHT.humidity;
      data = "?temp1=" + String(tempInC) + "&hum1=" + String(humidity);

      if (client.connect(server, 80)) {
        Serial.print("connected. My IP is ");
        Serial.println(Ethernet.localIP());
        client.println("POST /arduino/add.php HTTP/1.1");
        client.println("Host: 192.168.1.3");
        client.println("Content-Type: application/x-www-form-urlencoded");
        client.print("Content-Length: ");
        client.println(data.length());
        client.println();
        client.print(data);
      }
      else {
        Serial.println("connection failed");
      }
      Serial.println(data);
      // if there are incoming bytes available
      // from the server, read them and print them:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }
      if (client.connected()) {
        client.stop(); // DISCONNECT FROM THE SERVER
      }
      delay(300000); // WAIT FOR A WHILE BEFORE SENDING AGAIN
    }

but its not updating the database, using the below **add.php** file from arduino **web-client.ino**

    <?php
            include("connect.php");

            $link=Connection();

            $temp1=$_POST["temp1"];
            $hum1=$_POST["hum1"];

            $query = "INSERT INTO `tempLog` (`temperature`, `humidity`)
                    VALUES ('".$temp1."','".$hum1."')";

            mysql_query($query,$link);
            mysql_close($link);

            header("Location: index.php");
    ?>

i checked in mysql prompt which is also the result displayed if I open the server url : 192.168.1.3/arduino/index.php

    mysql> select * from tempLog;
    +---------------------+-------------+----------+
    | timeStamp           | temperature | humidity |
    +---------------------+-------------+----------+
    | 2016-11-28 11:50:37 |           0 |        0 |
    | 2016-11-28 12:30:25 |           0 |        0 |
    +---------------------+-------------+----------+
    2 rows in set (0.00 sec)

I don't know how the first entry got created but second one I created by manually executing the url 192.168.1.3/arduino/add.php?temp1=26.64&hum1=18

the index page is showing he data from db as shown above in sql, that means connection is established and mysql and table is fetched from correct db. i.e. *arduinoSensorData*  in my case.

my serial monitor window got updated:

    BMP init Success
    connecting...
    connected. My IP is 192.168.1.131
    ?temp1=26.64&hum1=18
    connected. My IP is 192.168.1.131
    ?temp1=26.64&hum1=18
    connected. My IP is 192.168.1.131
    ?temp1=26.57&hum1=18

which means arduino is not able to put data to db using add.php

title: arduino web client uploading data to mysql database

Answers: 1

body:
I came to learn in my php code posted above, I am using `$_POST` variable when I should rather be using `$_GET`

In the PHP script, there are $_GET and $_POST variables that contain the data passed to the script, depending on the method used to to activate the script.

so using `$temp1=$_GET["temp1"];` and `$hum1=$_GET["hum1"];` fixes the problem.


body:
I have this code for a DC motor (using [this][1] library)
<!-- language-all: lang-cpp -->

    #include <Arduino.h>
    #include <Vnh2sp30.h>

    //              ENA A   B   PWM   CS    inv
    Vnh2sp30  mtrL( A0, 7,  8,  5,    A2,   0);

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

    void loop() {
      if (Serial.available() > 0)   {
        String first  = Serial.readStringUntil(',');
        Serial.read();
        String second = Serial.readStringUntil(',');
        Serial.read();
        String third = Serial.readStringUntil(',');
        Serial.read();
        String echo = Serial.readString();
        Serial.println(echo);
           if(first == "start"){
                    Serial.println("Starting DC motor");
                    int duration = atoi(second.c_str());
                    int power = atoi(third.c_str());
                    int starttime = millis();
                    int endtime = starttime;
                    while ((endtime - starttime) <= duration) // mS
                    {
                      endtime = millis();
                      mtrL.run(1023);
                    }
                    mtrL.stop();
                    Serial.println("DONE");
           }
       }
    }

Then I have this code to drive multiple stepper motors (using [this][2] library):

    #include "BasicStepperDriver.h"

    int incomingByte = 0;   // for incoming serial data
    String readString = "";

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

    void loop() {
        if (Serial.available() > 0) {
        String first  = Serial.readStringUntil(','); // start
        Serial.read();
        String second = Serial.readStringUntil(','); // motor number
        Serial.read();
        String third = Serial.readStringUntil(','); // motor steps
        Serial.read();
        String fourth = Serial.readStringUntil(','); // duration (millisec)
        Serial.read();
        String fifth = Serial.readStringUntil(','); // deg
                    if(first == "start") {
                      if(second == "ALL") {
                        Serial.println("Starting stepper motor ALL");
                        int steps = atoi(third.c_str());
                        int duration = atoi(fourth.c_str());
                        int deg = atoi(fifth.c_str());

                        BasicStepperDriver stepper1(steps, DIR, STEP, ENBL);
                        stepper1.enable();
                        stepper1.setMicrostep(MICROSTEPS);
                        stepper1.setRPM(MAX_RPM);

                        BasicStepperDriver stepper2(steps, DIR_2, STEP_2, ENBL_2);
                        stepper2.enable();
                        stepper2.setMicrostep(MICROSTEPS);
                        stepper2.setRPM(MAX_RPM);

                        BasicStepperDriver stepper3(steps, DIR_3, STEP_3, ENBL_3);
                        stepper3.enable();
                        stepper3.setMicrostep(MICROSTEPS);
                        stepper3.setRPM(MAX_RPM);

                        BasicStepperDriver stepper4(steps, DIR_4, STEP_4, ENBL_4);
                        stepper4.enable();
                        stepper4.setMicrostep(MICROSTEPS);
                        stepper4.setRPM(MAX_RPM);

                        int starttime = millis();
                        int endtime = starttime;
                        while ((endtime - starttime) <= duration) // mS
                        {
                          stepper1.rotate(deg);
                          stepper2.rotate(deg);
                          stepper3.rotate(deg);
                          stepper4.rotate(deg);
                          endtime = millis();
                        }
                        stepper1.disable();
                        stepper2.disable();
                        stepper3.disable();
                        stepper4.disable();
                        Serial.println("DONE");
                      }
                    }
            }
    }

My goal is to merge this two codes together and still be able to run both the DC motor and one (or all) the stepper motors all together simultaneously. The first code is running on Arduino UNO and the other code runs on Arduino MEGA board and has been tested to work. The goal is to migrate the code from Arduino UNO to the MEGA board. Driving the motor for a specific time will block Arduino from executing the Stepper motors and vice versa with the DC motor. What can be done with these codes to make sure it can run the DC motor and Stepper motors at the same time?

  [1]: https://github.com/OliviliK/Arduino-Robot/blob/master/libraries/Vnh2sp30/Vnh2sp30.h
  [2]: https://github.com/laurb9/StepperDriver/blob/master/src/BasicStepperDriver.h

title: Running multiple motors simultaneously

Answers: 1

body:
Use the AccelStepper library along with the Adafruit MotorShield library

https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software


body:
In the datasheet of the [SAM3X8E](http://www.atmel.com/devices/ATSAM3X8E.aspx) in Section 43.6.9 Page 1327 it clearly states that the SAM3X/A has a programmable offset for ADC input in Single-Ended mode and I believe that the Atmel ASF library also has a function dedicated to configuring analog offset for SAM's ADC (`adc_enable_channel_input_offset`). However the following lines of code did not work:

      adc_set_writeprotect(ADC,0);
      adc_enable_anch(ADC);
      adc_disable_channel_differential_input(ADC, ADC_CHANNEL_5);
      adc_set_channel_input_gain(ADC, ADC_CHANNEL_5, ADC_GAINVALUE_2);
      adc_enable_channel_input_offset(ADC, ADC_CHANNEL_5);
      adc_set_writeprotect(ADC,1);

Why??

title: Arduino Due SAM3X ADC programmable input offset not working

Answers: 0


body:
I'm trying to read in an analog signal (a heartbeat) to pin A0 on the Arduino Uno and then convert it to digital. I'm hoping to use the digital signal to make an LED light up every time the voltage of the heartbeat signal goes over 1 volt. This is the code I have right now, but something is wrong because it isn't lighting up the LED.

    unsigned int analog0;             // Raw data from A0 ranging from 0 to 1023
    unsigned long data_range = 2000;  // Length of time to record data for
    double volts;                     // The analog data from A0 converted to volts
    int ledPin = 13;
    unsigned long start_time;
    unsigned long data_time;

    void setup() {
      Serial.begin(9600);             // Initialize and set serial port baud rate
      pinMode(ledPin , OUTPUT);
    }

    void loop() {
      start_time = millis();
      while ((millis() - start_time) < data_range)
      {
        // Record current time of analog acquisition
        data_time = millis();

        // Record analog data on A0
        analog0 = analogRead(0);

        // Convert raw data into voltage
        volts = (analog0 / 1023.0) * 5;

        Serial.print(volts);
        Serial.println();

        // Slow the rate of data acquisition
        //delay(1);

        if (volts > 1.5){
          digitalWrite(ledPin, HIGH);
          //delay(50);
        }
        else{
          digitalWrite(ledPin, LOW);
        }
      }
    }

title: Arduino Uno Digital to Analog Converter

Answers: 2

body:
I think your voltage formula is wrong. Try this:

float volts = analog0 * (5.0 / 1023.0);

body:
Try commenting out the serial in your sketch. In my experience serial communication takes time, and I assume you have a short window where the voltage peaks at more than a volt. Or initialize the serial with a stupidly high baud rate.<br>
Edit: even better, you could try this for a faster response time:

    void setup(){
      digitalWrite(13,0);
      pinMode(13, OUTPUT);
    }

    void loop(){
      if(analogRead(A0)>204){ //at ~1V the ADC will read between 204 and 205
        digitalWrite(13,1);
        delay(100);
        digitalWrite(13,0);
      }
    }


body:
I'm trying to use the [Digispark][1] as a [Rubber Ducky][2] but the Digispark is only usable with the US laylout. German keyboard layout is QWERTZ. Some keys can be changed, like y and z, but if there are `[` or `]` this isn't possible. Trying to define a `[`-key in DigiKeyboard.h displays a `ü`.

Does someone know a solution?

  [1]: http://digistump.com/products/1
  [2]: https://hakshop.com/products/usb-rubber-ducky-deluxe

title: Digispark / DigiKeyboard change keyboard layout

Answers: 3

body:
You can edit the file scancode-ascii-table.h in your DigiKeyboard library.
It basically states which ASCII code corresponds to which keyboard scancode.

So if you try to print the ':' character but get a '>' instead, you know that in the above mentioned file at the ASCII position for ':' is the scancode for a '>'.

Using this, you can swap the scancodes around and basically create your own 'mapping'. For example, if you swap the values at ASCII 89, 90 and 121, 122 you for example solve the Y/Z switch.

However, I have not figured out how to correctly print a backslash. You might have to map that do a different ASCII character you don't need.

To add to this answer, there exists a workaround using mame82's duck2spark:
https://github.com/mame82/duck2spark

body:
Solution is here:
Python script to convert RubberDucky payloads to DigiSpark sketch with respect to choosen keyboard layout:

[duck2spark][1]

Btw: The keys '<' '|' and '>' are on NON-US-KEY-100 on German keyboard layout. The key has value 0x64 for USB HID and the right modifiers have to be set (f.e. ALT_GR for '|' ). You could send them using

    DigiKeyboard.sendKeyStroke(key,modifier);

For details see [USB HID usage tables][2]

  [1]: https://github.com/mame82/duck2spark
  [2]: http://www.freebsddiary.org/APC/usb_hid_usages.php

body:
here is a library version of Digistump with german keyboard support https://github.com/adnanonline/DigistumpArduinoDe
I adapted the keyboard library: digistump-avr/libraries/DigisparkKeyboard/DigiKeyboard.h to the german layout


body:
So I have a program that works great on the Mega, it uses serial 3 to read and streams out to the USB (I posted a previous question which someone answered)  I tried to use Serial (D0) to read and then write to serial, which did not work.  So now I am looking in to Software Serials

Is there a difference between a real serial and software serial as it does not seem to be working, It all runs a bit slower

    #include <SoftwareSerial.h>

    const int DesiredRPM=300;  // Setting Desired RPM Here.
    const int MotorPWMPin=4;
    int inByte = 0;         // incoming serial byte
    unsigned char Data_status=0;
    unsigned char Data_4deg_index=0;
    unsigned char Data_loop_index=0;
    unsigned char SpeedRPHhighbyte=0; //
    unsigned char SpeedRPHLowbyte=0;

    int SpeedRPH=0;
    const unsigned char PWM4dutyMax=255;
    const unsigned char PWM4dutyMin=100;
    unsigned char PWM4duty=PWM4dutyMin;  // have to set a default value make motor start spining

    SoftwareSerial mySerial(10, 11); // RX, TX

    void setup() {
        pinMode(MotorPWMPin, OUTPUT);
        Serial.begin(115200);  // USB serial
        Serial3.begin(115200);  // XV-11 LDS data

        // prints title with ending line break
        Serial.println("Arduino Neato XV-11 Motor control board v0.1 by Cheng-Lung Lee");

        // Pick your magic number and drive your motor , 178 is 178/255*5V=3.49V
        analogWrite(MotorPWMPin, PWM4duty );

        mySerial.begin(115200);
    }

    void loop() {
        // if we get a valid byte from LDS, read it and send it to USB-serial
      if (Serial3.available() > 0) {
        // get incoming byte:
        inByte = Serial3.read();
        //Serial.print(inByte, BYTE);
        //Serial.write(inByte);
        Serial.print((char)inByte);
        decodeData(inByte);
      }

      if (mySerial.available() > 0) {
        // get incoming byte:
        inByte = mySerial.read();
        //Serial.print(inByte, BYTE);
        //Serial.write(inByte);
        Serial.print((char)inByte);
        decodeData(inByte);
      }

    }

    void decodeData(unsigned char inByte){
      switch (Data_status){
      case 0: // no header
      if (inByte==0xFA)
      {
        Data_status=1;
        Data_loop_index=1;
      }
        break;
      case 1: // Find 2nd FA
        if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_status=2;
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          Data_loop_index++;
        }
        break;
      case 2: // Read data out

         if (Data_loop_index==22){
          if (inByte==0xFA)
          {
            Data_loop_index=1;
          }
          else // if not FA search again
          Data_status=0;
        }
        else{
          readData(inByte);
          Data_loop_index++;
        }
        break;
      }

    }
    void readData(unsigned char inByte){
      switch (Data_loop_index){
        case 1: // 4 degree index
        Data_4deg_index=inByte-0xA0;
    //      Serial.print(Data_4deg_index, HEX);
    //      Serial.print(": ");
        break;
        case 2: // Speed in RPH low byte
        SpeedRPHLowbyte=inByte;
        break;
        case 3: // Speed in RPH high byte
        SpeedRPHhighbyte=inByte;
        SpeedRPH=(SpeedRPHhighbyte<<8)|SpeedRPHLowbyte;

        SpeedControl ( DesiredRPM ) ; //
    //      Serial.print(SpeedRPHhighbyte, HEX);
    //      Serial.println(SpeedRPHLowbyte, HEX);
        break;
        default: // others do checksum
            break;
      }
    }

    // Very simple speed control
    void SpeedControl ( int RPMinput)
    {
     if (Data_4deg_index0==0) {  // I only do 3 updat I feel it is good enough for now
      if (SpeedRPH<RPMinput*60)
         if (PWM4duty<PWM4dutyMax) PWM4duty++; // limit the max PWM make sure it don't overflow and make LDS stop working
      if (SpeedRPH>RPMinput*60)
         if(PWM4duty>PWM4dutyMin) PWM4duty--;  //Have to limit the lowest pwm keep motor running
      }
      analogWrite(MotorPWMPin, PWM4duty ); // update value
    }

title: Serial 3 vs Software Serial

Answers: 1

body:
There are huge differences. The most important ones are:

* SoftwareSerial is half duplex (it can send or it can receive, it cannot do both at once)
* SoftwareSerial is blocking - while it is sending or receiving nothing else can happen

SoftwareSerial is very much a poor-man's serial port. It should only really be used for very low volume data (things like NEMA messages once a second or so) and only if you have absolutely no choice (and, let's face it, you always have a choice).


body:
I have a very simple setup which works fine with an *Uno*.

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

    #include <SevenSegmentTM1637.h>
    #include <SevenSegmentExtended.h>

    const byte PIN_CLK = 2;
    const byte PIN_DIO = 3;
    SevenSegmentExtended display(PIN_CLK, PIN_DIO);

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

      display.begin();
      display.print(F("TEST"));
    }

    void loop() {}

When I use the very same setup with a *Pro Mini* (XCSOURCE ATMEGA 328P, 5V 16Mhz), the display doesn't light up. I get monitor outputs and can blink the onboard LED, but no reaction from the *TM1637* display.

I get this output in the console:

    �E%MA1e� 10001111
    Acknowledged: 0
    ADDR :  11000000
    DATA0:  0
    write byte: 84
    ADDR :  11000000
    DATA0:  1111000
    write byte: 69
    ADDR :  11000000
    DATA0:  1111000
    write byte: 83
    ADDR :  11000000
    DATA0:  1111000
    write byte: 84
    ADDR :  11000000
    DATA0:  1111000

Does anyone have an idea how to debug or fix this?

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

title: Cannot move TM1637 from Uno to Pro Mini

Answers: 2

body:
Since you're using a Grove Display, I believe it will be using I2C.

For better debugging, try using the actual I2C pins on your Pro mini, which are A4 and A5.

> I2C: A4 (SDA) and A5 (SCL). Support I2C (TWI) communication using the
> Wire library.
> https://www.arduino.cc/en/Main/ArduinoBoardProMini

I2C may need pull-up resistors on your data lines.

(https://en.wikipedia.org/wiki/I²C)

It can also be nice to use "verified to be working" code, like example code from the manufacturer.

    /*
     * TM1637.cpp
     * A library for the 4 digit display
     */
    #include "TM1637.h"
    #define CLK 39 //pins definitions for TM1637 and can be changed to other ports
    #define DIO 38
    TM1637 tm1637(CLK,DIO);
    void setup()
    {
        tm1637.init();
        tm1637.set(BRIGHT_TYPICAL);//BRIGHT_TYPICAL = 2,BRIGHT_DARKEST = 0,BRIGHTEST = 7;
    }
    void loop()
    {
        int8_t NumTab[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};//0~9,A,b,C,d,E,F
        int8_t ListDisp[4];
        unsigned char i = 0;
        unsigned char count = 0;
        delay(150);
        while(1)
        {
            i = count;
            count ++;
            if(count == sizeof(NumTab)) count = 0;
            for(unsigned char BitSelect = 0;BitSelect < 4;BitSelect ++)
            {
                ListDisp[BitSelect] = NumTab[i];
                i ++;
                if(i == sizeof(NumTab)) i = 0;
            }
            tm1637.display(0,ListDisp[0]);
            tm1637.display(1,ListDisp[1]);
            tm1637.display(2,ListDisp[2]);
            tm1637.display(3,ListDisp[3]);
            delay(300);
        }
    }

You will need to adapt the pin numbers.

But after these steps it should work just fine.

Source: http://wiki.seeed.cc/Grove-4-Digit_Display/

body:
4.7k resistors on 2 and 3 pins does not help.

Works great if the tm1637 directly connected to 12 and 13 pins.


body:
Below is the link to three files I am using with a 32 bit ADC from TI, ADS1262, plus a link to it's datasheet. It works fine but I'm not getting any better voltage resolution than with a 16 bit ADC. I am using it for small voltage, from 0 to 0.070 volts. For example, for a known stable voltage of 0.01000 volts from a Fluke thermocouple calibrator I get 0.010000 to 0.010006. I get this same 0.000006 volt jitter if I short the ADS1262 input pins together. I suspect it may be a programmable gain amplifier issue. I can put 2.5 volts into it and not damage it. There is a line in the .ino file, #define PGA 1. On a guess, I changed this to #define PGA 32 but it had no effect on the results, it's like my attempted program change didn't take. I read in the ads1262 datasheet that the PGA Gain is in the MODE2 Register, address 05h. A gain of one is set with 000 and a gain of 32 is set with 101. But I do not know how to proceed. Perhaps somebody can help me out.

https://github.com/Protocentral/ProtoCentral_ads1262/tree/master/Libraries
http://www.ti.com/lit/ds/symlink/ads1262.pdf

title: How do I change PGA gain in this Arduino program?

Answers: 1

body:
The symbol `PGA` appears in `exapmle.ino` (sic) twice, once each in lines 28 and 30:

     #define PGA 1                     // Programmable Gain = 1
     ...
     #define VFSR VREF/PGA

It is not used elsewhere in the example or the library code.  The only effect of changing its value from 1 to 32 is to change the value of `VFSR`, and as`VFSR` appears only in line 30, that effect is nil.

Looking at the `ads1262.cpp` file from github, it appears that `ads1262::ads1262_Init()` initializes register `MODE2` to 0x6, via:

    ads1262_Reg_Write(MODE2, 0x06);

which per the ADS1262 spec sheet, page 93, table 44, enables the PGA and sets its gain to 1 and sets the sample rate to 60 SPS.

Apparently, if you wish to use some other gain setting, you should define `PGA` appropriately and put a corresponding setting into `MODE2`.  For example, if you want to set up a gain of 16 and sample rate of 400 SPS, in `setup()` you could say

    PC_ADS1262.ads1262_Reg_Write(MODE2, 4<<4 | 8); // 4=gain 16, 8=400 SPS

More generally, you could set up some constants for gain codes and SPS rates, and reference those constants when writing to `MODE2`.  For example, after

    enum { GainCode1, GainCode2, GainCode4, GainCode8, GainCode16, GainCode32 };
    enum { SPSCode2p5, SPSCode5, SPSCode10, SPSCode16p6, SPSCode20, SPSCode50,
           SPSCode60, SPSCode100, SPSCode400, SPSCode1200, SPSCode2400,
           SPSCode4800, SPSCode7200, SPSCode14400, SPSCode19200, SPSCode38400};

you would say

    PC_ADS1262.ads1262_Reg_Write(MODE2, GainCode32<<4 | SPSCode2400);

to set the gain at 32 and the sample rate at 2400 SPS.

(Note, `enum` is a C language element used to define integer constants.  In an `enum`, each symbol mentioned without an explicit value has a value one more than the previous symbol, or zero if there's no preceding symbol.  So `GainCode1` is 0, `GainCode2` is 1, `GainCode4` is 2, etc.)

Note, to get better ultimate resolution, you may need to combine multiple readings, or may need to set the ADS1262's filtering parameters.


body:
My fellow programmers,

I'm planning on creating a fan controller for my PC using an Arduino Duemilanove and a generic motor sheild. (Fan controllers are not exactly cheap here and i'd rather spend my money on an SSD than on a fan controller =)

On a normal scenario, I want my fans to spin slowly, just to keep some air flowing but not enough to make too much noise. Obviously, they should turn on at full speed (or so) during a demanding scenario, like playing a game.

My idea is to use a usb port to communicate with Windows, so that my arduino knows when a demanding application was started. Is there an easy way to do this or should I buy myself some cheap temperature sensors, place them on the more important parts and control my fans with these temperature readings?

I'd also like to have an option to turn of the communication between the arduino and whatever informs it about the computer usage, so that I can program it in order to test a different algorithm.

Thanks for any help!

title: Arduino based Fan controller for PC

Answers: 2

body:
Any Arduino with a USB interface can communicate with a PC via pseudo-serial ports (that is, serial-over-USB links).  If you have a PC program that somehow monitors what processes are running, your plan of telling the Arduino to speed up the fan when certain programs are running is practical to do.

On Linux systems, fan speed can be controlled by user programs like [fancontrol-gui](https://github.com/Maldela/fancontrol-gui) and [tpfanco](https://github.com/tpfanco/tpfancod/blob/master/src/tpfancod/control.py).  Probably similar programs are available on Windows and Mac systems.  Your Arduino could measure temperatures and send them to the host OS for fan speed control.  Or vice versa, your PC could use DBus or ACPI calls to measure its chip temperature and send it to the Arduino to control a fan.

Note, there's a thermometer built in to several ATmega devices.  Its resolution isn't great and due to chip thermal mass it might not respond quickly, but you might find it worthwhile to experiment with.  For example, see §24.8, Temperature Measurement, on page 247 of the document Atmel-8271J-AVR-ATmega-Datasheet_11/2015, which says to select the internal 1.1 V ADC voltage reference, read ADC channel 8, and scale the result per Table 24-2 to get °C.

body:
Yes you can. One of the options is using Visual Studio if you are Windows user (using built in [library][1] is enough to meet your 'option to turn off' needs). There so many examples of serial communication using either C# or C++ with Arduino, so you can do communication between Laptop - Arduino via serial cable or even built in bluetooth in laptop (with extra bluetooth module for Arduino).

The most simple setup is your laptop act as master and arduino as slave. Arduino does not need any information about what program is running, instead just waiting command from Laptop wether to turn off or turn down the fan

You can read  information from your PC (for Windows), such as [temperature][2] or [battery level][3]

  [1]: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport(v=vs.110).aspx
  [2]: https://stackoverflow.com/questions/1195112/how-to-get-cpu-temperature
  [3]: https://stackoverflow.com/questions/18865979/battery-level-c-sharp


body:
I'm a little new to Arduino, but not to programming or electronics in general.  I'm working on a library that will be more fleshed out later, but I'm having issues getting the basics working properly.

The following code produces the desired behavior if a servo is attached to pin 3:

    #include <Servo.h>

    Servo myServo;

    void setup() {
      myServo.attach(3);
    }

    void loop() {
      myServo.write(1);
      delay(1000);
      myServo.write(45);
      delay(1000);
      myServo.write(90);
      delay(1000);
      myServo.write(135);
      delay(1000);
      myServo.write(180);
      delay(1000);
    }

However, when I try to implement similar functionality in my own library the servo locks and just sort of grinds.  Here's the header file:

    #ifndef MotorControl_h
    #define MotorControl_h

    #include "Arduino.h"
    #include "Servo.h"

    class MotorControl
    {
      public:
        MotorControl(int north, int south, int west, int east);
        void setNorth(int value);
        void setSouth(int value);
        void setWest(int value);
        void setEast(int value);
        int getNorth();
        int getSouth();
        int getWest();
        int getEast();
      private:
        Servo _north;
        Servo _south;
        Servo _west;
        Servo _east;
        int _northVal;
        int _southVal;
        int _westVal;
        int _eastVal;
    };

    #endif

And here's the .cpp file:

    #include "Arduino.h"
    #include "MotorControl.h"
    #include "Servo.h"

    MotorControl::MotorControl(int north, int south, int west, int east)
    {
      _north.attach(north);
      _south.attach(south);
      _west.attach(west);
      _east.attach(east);
      _northVal = 0;
      _southVal = 0;
      _westVal = 0;
      _eastVal = 0;
    }

    void MotorControl::setNorth(int value)
    {
      _north.write(value);
      _northVal = value;
    }

    void MotorControl::setSouth(int value)
    {
      _south.write(value);
      _southVal = value;
    }

    void MotorControl::setWest(int value)
    {
      _west.write(value);
      _westVal = value;
    }

    void MotorControl::setEast(int value)
    {
      _east.write(value);
      _eastVal = value;
    }

    int MotorControl::getNorth()
    {
       return _northVal;
    }

    int MotorControl::getSouth()
    {
      return _southVal;
    }

    int MotorControl::getWest()
    {
      return _westVal;
    }

    int MotorControl::getEast()
    {
      return _eastVal;
    }

And finally, the code using the above library which should produce the same behavior as the code up top, but does not:

    #include <MotorControl.h>

    MotorControl mc(3, 5, 6, 9);

    void setup() {}

    void loop() {
      mc.setNorth(1);
      delay(1000);
      mc.setNorth(45);
      delay(1000);
      mc.setNorth(90);
      delay(1000);
      mc.setNorth(135);
      delay(1000);
      mc.setNorth(180);
      delay(1000);
    }

I'm not sure what else to add ... this is running on an Uno R3.

Edit:  This is interesting.  I've tried the code from this example:
https://arduino.stackexchange.com/questions/1216/how-do-i-initialize-a-servo-object-in-my-own-library
which works out just fine.  I'm still not sure that I see what I'm doing incorrectly here.  I see the differences between my code and the example, but not how they are causing problems.

If it's worth mentioning, I've also stored my library in the libraries folder.  Just throwing out any random detail I can think of.

title: Servo Driven Through Custom Library Not working Properly

Answers: 2

body:
In C++, when an object is declared as a member of another object, the **constructor method of the inner object must be called explicity** (see [constructors and member initializer lists][1]).

In your code, properties of _Servo_ type can be constructed within the header of the _MotorControl_ constructor:

    MotorControl::MotorControl(int north, int south, int west, int east)
        : _north(), _south(), _west(), _east()
    {
      _north.attach(north);
      _south.attach(south);
      _west.attach(west);
      _east.attach(east);
      _northVal = 0;
      _southVal = 0;
      _westVal = 0;
      _eastVal = 0;
    }

  [1]: http://en.cppreference.com/w/cpp/language/initializer_list

body: When you create your instance at global scope then you have no control over when exactly the constructor gets called.  If it gets called before init() runs then your attach lines won't work out.  You should have a begin method in your class that handles attaching the servos and call that method from setup.


body:
[![enter image description here][1]][1]
Here's an image of my circuit diagram. There are 8 9g servos connected to the arduino gpio pins. The servos have an external power supply of 3 volts (may vary depending on the voltage requirement of the 9g) and the arduino is powered through an adaptor. Is this a convenient way of doing it? Have I gone wrong somewhere? I am new to circuit designing so I am confused.

Thank you! :)

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

title: Can you tell me if this circuit will work?

Answers: 1

body:
These servo are driven off of a PWM signal. This means that you need to connect the control line to a pin that is capable of PWM.

For the Uno it is D3, D5, D6, D9, D10 & D11.

Unfortunately there are only 6 PWM capable pins and you need 8.

You could consider [bit banging][1] the PWM for the 7th & 8th motor.

Alternatively, if two of the motors are to be driven exactly the same, they could share the PWM control line between them.

If you need to control each motor separately (without bit banging) you may have to upgrade to a [Arduino Mega 2560][2]. The Mega has 15 PWM channels.

An Arduino example of controlling the servo motor can be found in the Libraries section of the Arduino website.
https://www.arduino.cc/en/Tutorial/Knob

  [1]: https://en.wikipedia.org/wiki/Bit_banging
  [2]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560


body:
I am trying to figure out how to break out of a loop if it is being called from a function.  I have a similar post, [here][1], that I've decided to do something with the Arduino onboard LED, to isolate it from the NeoPixels Library and it is giving me the same issue.  The answers I have received there have been helpful but something is still puzzling me.

Using serial from the Arduino to my PC, the below "Example 1" code, can break out of a local loop successfully (and immediately) when the Arduino received keyboard input with key "2".

    //Example 1
    int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
    char rx_byte = 0; // variable to hold serial input from console;
    int count = 0; // placeholder for incrementing during debugging of loops

    void setup() {

      Serial.begin(115200);

      pinMode (ledPIN, OUTPUT);

    }

    void loop() {

      if (Serial.available() > 0) {    // is a character available?
        rx_byte = Serial.read();       // get the character

        // check if a number was received
        if ((rx_byte >= '0') && (rx_byte <= '9')) {
          switch(rx_byte) {
            case '1':
              Serial.println("You've entered: 1");
              for (int i; i <=5000; i++) {
                rx_byte = Serial.read(); // must read character again
                if (rx_byte == '2') {
                  Serial.println("Quitting...");
                  digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
                  break;
                }
                else {
                  Serial.println(i);
                  digitalWrite(ledPIN, HIGH); // turn LED pin 13 on
                }
              }
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              break;

          }
        } // end: if (Serial.available() > 0)
      }
    }

From what I've been told, you shouldn't necessarily perform a "serial.read()" inside of a loop.  However, if I do not include that in the for loop, it does not allow for any further input.

Since "Example 1" works, I am now trying to accomplish the same principle, but, this time, when calling a function which contains its own independent loop of course.  I've spent countless hours trying to resolve this.

I was under the impression that I could use a while loop within "void loop()" and call in a function which also contains a loop, then be able to break it from the while loop.  When attempting this various ways, the for loop within the function seems to blink the LED 10+ times and totally ignores my keystroke "2" to break the loop and is now infinite.  I know I could just put the for loop up in "void loop()" and it would work to break out similar to Example 1, but I'm sure it can be broken from a function as well.  I will eventually have similar functions that will contain parameters.

How would I go about doing this the correct way?

Below is "Example 2" that I am trying to break from the function.  I'm assuming it's an issue with doing it from the while loop?

Again, any assistance is greatly appreciated.

    //Example 2
    int ledPIN = 13; // sets up onboard LED on Arduino located near PIN13
    char rx_byte = 0; // variable to hold serial input from console;
    int count = 0; // placeholder for incrementing during debugging of loops

    void setup() {

      Serial.begin(115200);

      pinMode (ledPIN, OUTPUT);

    }

    void loop() {

      if (Serial.available() > 0) {    // is a character available?

        rx_byte = Serial.read();       // get the character
        boolean forceTerminate = false;

        // check if a number was received
        if ((rx_byte >= '0') && (rx_byte <= '9')) {

          switch(rx_byte) {
            case '1':
              Serial.println("You've entered: 1");
              while(forceTerminate == false) {
                rx_byte = Serial.read(); // must read character again
                if (rx_byte == '2') {
                  Serial.println("Quitting...");
                  digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
                  forceTerminate = true;
                  break;
                }
                else {
                  //count = count+1;
                  //Serial.println(count);
                  blinkPIN13(); // FUNCTION: blinkPIN13
                }
              }
              digitalWrite(ledPIN, LOW);  // turn LED pin 13 off
              break;

          } // end: switch(rx_byte)

        }

      } // end: if (Serial.available() > 0)

    }

    /************************************************************************************
     * FUNCTION for blinking LED located on PIN 13 to the state of ON(1)/OFF(0)
     ************************************************************************************/
    void blinkPIN13() {

      for (int i; i <=10; i++) {
        digitalWrite(ledPIN, HIGH);
        delay(1000);
        digitalWrite(ledPIN,LOW);
        delay(1000);
      }

    }

  [1]: https://arduino.stackexchange.com/questions/31596/arduino-serial-response-is-slow-when-in-while-loop/31597#31597

title: How to break out of a loop if it is contained in a function

Answers: 1

body:
To tell a function-caller what to do when the function exits, have the function return a status value.  You can do this at multiple levels.  For example:

    byte doOtherStuff(int howLong) {
      digitalWrite(ledPIN, HIGH);
      delay(howLong);
      if (doneDoing()) return false;
      digitalWrite(ledPIN,LOW);
      delay(howLong);
      return !doneDoing();
    }

    void loop() {
      while(doMore) {
        doStuff();
        for (byte i=0; i<9 && doMore; ++i) {
          doMore = doOtherStuff(1234);
        }
        if (doMore) {
          doMoreOtherStuffInWhile();
        }
      }
    }


body:
*[SOLVED] By changing the offset for the incoming data into `int16_t` type there won't be any rounding errors and the values I'm getting are all back to zero in the sensor its base position*

This is my first project where I use Arduino.

Until today everything went good with the Arduino Pro Mini (3.3v).
But as of today I got a bit of a weird problem.
I am using a MPU gy-521 (doesn't really matter) and I'm working on calculating the actual movement.

The problem which occured is that I'm using a deadzone to negate the smallest numbers (I know, this isn't the right way to use data). The way I negate the numbers is with the following code

    // Check deadzone values
      if (ax+axo < adz && ax+axo > -adz) ax = -axo;
      if (ay+ayo < adz && ay+ayo > -adz) ay = -ayo;
      if (az+azo < adz && az+azo > -adz) az = -azo;

      if (gx+gxo < gdz && gx+gxo > -gdz) gx = -gxo;
      if (gy+gyo < gdz && gy+gyo > -gdz) gy = -gyo;
      if (gz+gzo < gdz && gz+gzo > -gdz) gz = -gzo;

ax is accelerometer data over the x-axis, axo is the offset, adz is the accelerometer deadzone.

gx is gyroscope data over the x-axis, gxo is the offset, gdz is the gyroscope deadzone.

All of the other letters are the same, for different axis.
After getting the values within the offset basically set to 0 with the offset I'm doing the following.

    // Calculate acceleration
      axa = (ax+axo) / aFactor * g;
      aya = (ay+ayo) / aFactor * g;
      aza = (az+azo) / aFactor * g;

      gxa = (gx+gxo) / gFactor;
      gya = (gy+gyo) / gFactor;
      gza = (gz+gzo) / gFactor;

The a- and gFactor are mentioned in the datasheet, but these values should all be 0 if the value of axis plus the offset is within the deadzone.
The problem is that I'm not just getting 0.00 values.
I'm also getting -0.00 and 0.01.

    0.00  0.00  -0.00  0.00  0.01  0.01

Could someone enlighten me about what's wrong in my situation or if this is just a Arduino issue.

*[EDIT]*

The data originally from the sensor is from type int16_t (ax, ay, az, gx, gy, gz) and the other variables are doubles.

The values which are off are always the same ones: Accelerometer Z, Gyroscope Y and Z.

title: It seems like the math of arduino is off

Answers: 1

body:
If your program is basically working but gives you rounding errors, it can be that you are facing some problems related to conversion from floating-point to binary or reverse. It is a very common problem in computer science. For example, the decimal number `0.1` has no exact binary  representation, it is infinite. For more information, you can read these pages:

http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/
https://www3.ntu.edu.sg/home/ehchua/programming/java/datarepresentation.html

In order to solve your problem, you can try to apply appropriate rounding to your results and if possible avoid mixing different data types and use `double` only if absolutely needed (which I guess is the case in your application).


body:
I want to use an Arduino Uno for a data-acquisition purpose.

Normally adhoc data acquisition boards can record each sample at a desired sampling rate. So that I can plot all the samples recorded. I want to do the same sort if thing with Arduino.

I want to record 30 minutes of analog voltage input at 4kHz sampling rate and record all the samples taken to a PC.

And at the end I want to be able to plot the data with all samples not the averages ect.

Is there an easy workaround for this?

title: Data acquisition/logging question

Answers: 2

body:
This question is actually two or three different questions.

To the first: is it possible to record 30 minutes of data with an arduino uno at 4KHz: no.  Assuming even that you are only taking 1 byte of data at a time, the uno only has 2K of RAM, so you'd be out of RAM in under a second.

To the second: can you instead send this data to a PC at the desired rate: possibly, depending on how much data you are taking.  If it's just a single analog channel, then you can most likely do it.  Anything more and I doubt it.  The problem is that you'll simulutaneously have to read the analog at the correct time AND send the data to the PC, presumably over the serial.  As long as you use Serial.write, NOT Serial.print, then your UART should be more than fast enough at high baud rates to handle a single channel with minimal overhead.  However, that would mean that you have to reconstruct the data on the PC, but that's the third question, to which I shall turn shortly.

If you need absolute real-time operation, then you need to use timer interrupts, which are not native to the Arduino libraries, if I recall correctly.  However, a quick google for "Arduino timer interrupt" leads me here: http://playground.arduino.cc/Code/Timer1, which is where you should start.

In terms of plotting the data: that's not an Arduino problem, that's a problem for whatever you choose to use to collect and analyze your data.  I suggest Excel, since it's relatively common, or Google Sheets, since it's free.  If you have access to Matlab, though, that's a much more powerful program.  Either way, that is off topic for this forum.

body:
Here is a program I wrote that follows an approach somewhat similar to
Michael Stachowsky's answer:

* The ADC is configured with the prescaler set to 128 (just like the
  Arduino core does), which gives a 104 µs conversion time,
  significantly shorter than the 250 µs sampling period you want.
  The first conversion takes longer, and it is discarded.

* It is also configured an auto-trigger mode, and the timer 1 overflow
  flag is selected as its trigger source.

* The timer 1 is configured to loop every 500 × 8 = 4000 CPU cycles
  (clocked at F\_CPU / 8, with TOP = 499), which
  provides the required 250 µs sampling period. It is set in a PWM
  mode even though the PWM outputs are not used, simply because in this
  mode the overflow flag is set every time the timer loops.

* An interrupt is triggered every time an ADC conversion is complete.
  The interrupt service routine clears the timer overflow flag (this is
  required because the ADC is triggered by the rising edges of this
  flag), saves the result in a global variable and sets a global flag.

* The main loop waits for that flag and sends the data through the
  serial port, in binary, LSB first:
    - the sample number modulo 64 (6 bits)
    - the sample value (10 bits).

* The serial port runs at 115.2 kb/s, it can then transmit the two bytes
  of data in about 174 µs, which is less than the sampling period.

* The sample numbers, and a 16-byte preamble can be used as a sanity
  check by the receiving end.

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

    #include <avr/interrupt.h>

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

        // Transmit preamble.
        for (int i = 0; i < 16; i++)
            Serial.write(0xff);

        // Start the ADC.
        ADMUX  = _BV(REFS0)   // reference = Vcc
               | 0;           // input = ADC0
        ADCSRA = _BV(ADEN)    // enable the ADC
               | _BV(ADSC)    // start first conversion
               | _BV(ADPS0)   // prescaler = 128,
               | _BV(ADPS1)   // ditto
               | _BV(ADPS2);  // ditto

        // Wait for the first conversion to complete.
        loop_until_bit_is_set(ADCSRA, ADIF);

        // Wait for the preamble to be fully transmitted.
        Serial.flush();

        // Stop timer 1.
        TCCR1A = 0;
        TCCR1B = 0;

        // Configure the ADC in auto-trigger mode.
        ADCSRA |= _BV(ADATE)   // enable auto-trigger
                | _BV(ADIF)    // clear interrupt flag
                | _BV(ADIE);   // enable interrupt
        ADCSRB  = _BV(ADTS1)   // trigger source = timer 1 overflow
                | _BV(ADTS2);  // ditto

        // Configure Timer 1.
        ICR1   = 500 - 1;     // period = 500 * 8 CPU cycles
        TCCR1A = _BV(WGM11);  // mode 14: fast PWM,
        TCCR1B = _BV(WGM12)   // ... TOP = ICR1,
               | _BV(WGM13)   // ... overflow flag set on TOP
               | _BV(CS11);   // clock at F_CPU / 8
    }

    volatile uint16_t reading = 0xffff;
    volatile bool reading_available;

    ISR(ADC_vect)
    {
        TIFR1 |= _BV(TOV1);    // clear timer overflow flag
        uint16_t x = reading;  // work on a copy of the reading
        x &= ~0x03ff;          // remove previous ADC value
        x |= ADC;              // add current ADC value
        x += 0x0400;           // increment sample number
        reading = x;
        reading_available = true;
    }

    void loop()
    {
        // Wait for a reading to be available.
        while (!reading_available) ;

        // Grab a copy.
        uint16_t x = reading;
        reading_available = false;

        // Transmit, LSB first.
        Serial.write(x >> 0);  // low byte
        Serial.write(x >> 8);  // high byte
    }

How you deal with the data on the receiving end (save to file, skip
preamble, check sample number consistency, extract sample values, plot
them...) is up to you. You can use whatever language and tools you want.
It is _not_ an Arduino-related question.

**Addendum**: More about the binary format used.

There is a preamble consisting of 16 `0xff` bytes. This can be useful
because it is not uncommon to get in one file a mix of data from two
different runs of the program. The buffering of the serial port on the
PC can lead to this happening. If you do not want that preamble, remove
the two lines right after the “Transmit preamble.” comment.

Then there is a continuous stream of 16-bit unsigned integers
(`uint16_t`), transmitted LSB first (i.e. little endian). The byte order
can be changed by swapping the two `Serial.write()` by the end of the
program.

Each of these integers contains an ADC reading in the lower 10 bits and
a sample number in the upper 6 bits. The sample number can be extracted
by right-shifting (`x >> 10` in C) and could be used as a sanity check
(the number should increment by 1, modulo 64, from one sample to the
next). The ADC reading can be extracted by masking out the sample number
(`x & 0x03ff`).

If you do not want the sample numbers, you can simplify the ISR to:

    ISR(ADC_vect)
    {
        TIFR1 |= _BV(TOV1);    // clear timer overflow flag
        reading = ADC;         // read the ADC result
        reading_available = true;
    }

and remove the (now useless) initialization of the `reading` variable.


body:
Hello is there an Arduino Simulator for Windows that can be detected by Arduino IDE through a Virtual COM Port?

I've seen simulator online but I can't seem to find a simulator that can be programmed using the Arduino IDE through a Virtual COM port.

Answers: 1

body:
One of the option is using Proteus simulator with [Arduino library][1]. You can build the program via Arduino IDE, then export the compiled binary (.hex file). Proteus also provided virtual terminal feature (not Virtual COM).

  [1]: http://www.electronicslovers.com/2015/03/how-to-add-arduino-library-in-to.html