message:
GPS Transmits False Data with SD card in; True data with SD card out

I've programmed my Arduino Ethernet to receive data from a Skytraq Venus GPS receiver and separate it using TinyGPS, then store it on an SD card. With the SD card inserted, everything else except the time is totally wrong. Once I remove the SD card and reset, the longitude and latitude are still wrong but everything else is correct. I've tried supplying more power, replacing the receiver, antenna, the arduino itself, even switched the serial ports I use but I can't seem to find a solution.

Here's a [link](https://github.com/mikalhart/TinyGPS) for the TinyGPS library and a [link](http://arduiniana.org/libraries/newsoftserial/) for the NewSoftSerial library. And for the schematics, I haven't drawn any yet but I'm using the Arduino Ethernet's SD port as my SD shield. My Skytraq GPS receiver's RX pin is connected to pin 2 on the arduino ethernet and the TX pin is connected to pin 3 on the ethernet. (Ethernet TX/RX has been set to pin 3 and 2 respectively.)

I'm using the Sparkfun Venus GPS with SMA connector from sparkfun.com. I would post the link but it says I need at least 10 reputation to post more than two links. Serial signals at 3.3V and GPS module is a 3.3V module. I use the same sketch with and without the SD Card. SD.begin is called just once and Serial.begin is also called once.

Here's my code:

    #include <SoftwareSerial.h> //NewSoftwareSerial Library
    #include <TinyGPS.h>        //TinyGPS Library
    #include <SPI.h>            //This Library is used by the SD library.
                                //Must be defined before SD library to prevent errors.
    #include <SD.h>             //SD Card Library

    //NB: To avoid SD Card Errors, use an SD Card whose size is at most 2GB
    //and use FAT16 format. Arduino has problems with FAT32 and cards>2GB.

    #define RXPIN 2
    #define TXPIN 3

    const int chipSelect = 4; //This selects the SD card port for read/write

    #define GPSBAUD 9600

    File logs; //Used to write to SD card later

    TinyGPS gps;

    //Initialize the Software Serial to recognize
    //our UART pins (Read(RX) and Write(TX))
    SoftwareSerial read_gps(RXPIN, TXPIN);

    void getdata(TinyGPS &gps);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);  //Start the serial port
      read_gps.begin(GPSBAUD);  //Start reading from the gps

      pinMode(chipSelect, OUTPUT); //Make pin 4 an output pin
      pinMode(10, OUTPUT);  //Pin 10 must always be set to output to avoid errors
      digitalWrite(10, HIGH); //Pin 10 must always be high to prevent errors.

      Serial.println("");
      Serial.println("Awaiting Lock");
      Serial.println("");

      //Initialize the SD Card
      SD.begin();
      Serial.println("Initializing SD Card. Please Wait.");
      if(!SD.begin(4)){//If card not available or card not recognized
        Serial.println("Failed.");
        return;
      }
      Serial.println("Card Initialized");

    }

    //the loop function is used to read the data from the gps,
    //check for valid data and then separate the data based on our specs.
    void loop() {
      // put your main code here, to run repeatedly:
      while(read_gps.available()){//as data is received from the gps
        int c = read_gps.read();
        if(gps.encode(c)){//check if new valid data available
          getgps(gps); //read the valid gps data and process
        }
      }

    }

    void getgps(TinyGPS &gps)
    {
      float latitude, longitude;

      gps.f_get_position(&latitude, &longitude); //Feature of tinygps.
                                                 //Gets the latitude and longitude

      Serial.print("Latitude: "); Serial.print(latitude);
      Serial.print("\nLongitude: "); Serial.print(longitude);

      int yr;
      byte mnth, dy, hr, minu, sec, hundredths;
      gps.crack_datetime(&yr, &mnth, &dy, &hr, &minu, &sec, &hundredths); //Gets the date and time and separates them
                                                                          //into individual components.

      Serial.print("\nDate: "); Serial.print(mnth, DEC); Serial.print("/");
      Serial.print(dy, DEC); Serial.print("/"); Serial.print(yr);
      Serial.print("   \nTime: "); Serial.print(hr, DEC); Serial.print(":");
      Serial.print(minu, DEC); Serial.print(":"); Serial.print(sec, DEC);
      Serial.print("."); Serial.println(hundredths, DEC);

      Serial.print("Altitude(metres): "); Serial.println(gps.f_altitude());

      Serial.print("Speed(kmph): "); Serial.println(gps.f_speed_kmph());
      Serial.println();

      logs = SD.open("datalogs.csv", FILE_WRITE);  //open the datalog file on the sd card. If it doesn't exist on the card, create it.

      if(logs){//Start writing data to SD Card
        Serial.print("Writing to datalogs...");
        logs.println("\nLatitude: "); logs.print(latitude);
        logs.print("\nLongitude: "); logs.print(longitude);
        logs.print("\nDate: "); logs.print(mnth, DEC); logs.print("/");
        logs.print(dy, DEC); logs.print("/"); logs.print(yr);
        logs.print("   \nTime: "); logs.print(hr, DEC); logs.print(":");
        logs.print(minu, DEC); logs.print(":"); logs.print(sec, DEC);
        logs.print("."); logs.println(hundredths, DEC);
        logs.print("Altitude(metres): "); logs.println(gps.f_altitude());

        logs.print("Speed(kmph): "); logs.println(gps.f_speed_kmph());
        logs.print("\n");
        logs.println();

        logs.close(); //close the file
        Serial.println("done.");
        Serial.println("\n");
      }
      else{
        Serial.println("Error opening file.");
      }

      unsigned long chars;
      unsigned short sentences, failed_checksum;
      gps.stats(&chars, &sentences, &failed_checksum);
    }

body:
You're trying to do too much (SD and Serial print operations) at the wrong time (GPS character receiving).

Most GPS devices will send several "sentences" per second, in a batch.  `TinyGPS.encode` returns `true` after *each* sentence, so your code will try to write multiple sentences per second to the SD card.  But it takes so long to open/write/close the SD card (and print to `Serial`) that the input buffer fills up and overflows.  [Here's](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Troubleshooting.md#quiet-time-interval) a detailed description of what is happening.

You must wait until the GPS "quiet time" begins.  Even then, you could have trouble, depending on how much data you need to save and print.

It may be possible to make it work with TinyGPS, but I eventually gave up in frustration and wrote the [NeoGPS](https://github.com/SlashDevin/NeoGPS) library to help address these problems.  It can be configured to save just the data you need (via the [configuration files](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Configurations.md)), and it can be used to detect when the quiet time begins (see NMEAorder.ino and NMEAfused.ino).  It [uses much less RAM](https://github.com/SlashDevin/NeoGPS/blob/master/doc/RAM.md) and [takes much less time](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Performance.md) to parse the GPS characters.  This will be important if you try to add the Ethernet libraries to the sketch.

If you still have trouble getting all the information written during the quiet time, you can use a companion library (e.g., [NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial)) to handle the GPS characters *during* the RX interrupt.

Regardless, I would suggest replacing `SoftwareSerial` with `NeoSWSerial`.  It, too, is much more efficient than the CPU-killer `SoftwareSerial`.  It won't fix the main problem, but it will pay off later.


sender: user

message:
Did I Brick my Controllino?

I recently obtained a Controllino Mini to be used in a small industrial project. While checking it out I also wanted to test the built-in RTC capabilities. In doing so I toyed around with the available commands from the supplied [library][1]. After uploading another sketch it seems I have bricked the Controllino, since I cannot upload anything else :
> avrdude: stk500_recv(): programmer is not responding avrdude:
> stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

and the reset LED is permanently lid. When looking at the [pinout][2] diagram of the Controllino Mini I saw that there was a small remark  near the top stating

> Not proper handling of the RTC/INT output can cause permanent
> controllino reset , so I guess I somehow reached that state.

Since I am pretty new to the whole Arduino / Microcontroller scene I don't really know where to go from here.

 - Is it a viable idea to try and burn a new bootloader ?

 - Is there a simpler way to reset the state of the device?

 - What did I even do wrong ?

Any help is greatly appreciated !

Christian

Below is the sketch that got me into this mess:

    #include <Controllino.h>

    unsigned char day, weekday, month, year, hour, minute, sec;
    #define analogInputPin A0
    void setup() {
      // put your setup code here, to run once:
    Serial.begin(9600);
    pinMode(analogInputPin, INPUT);
    Controllino_RTC_init(1);
    Serial.print("Initalized RTC: ");
    Controllino_SetTimeDate(1,6,4,2016,15,14,10);
    }

    void loop() {
     Controllino_ReadTimeDate(&day,&weekday,&month,&year,&hour,&minute,&sec);
      float voltage = 15*(analogRead(analogInputPin)/1023.0);
      Serial.print(hour);
      Serial.print(":");
      Serial.print(minute);
      Serial.print(":");
      Serial.print(sec);
      Serial.print(" : ");

      Serial.println(voltage);

    }

  [1]: https://github.com/Controllino/ControllinoLibrary
  [2]: http://controllino.cc/wp-content/uploads/2015/10/CONTROLLINO-MINI-PINOUT-02-10-15.jpg

sender: assistant

body:
It certainly looks like the INT pin of the RTC can kill the whole unit. Bit of a FUBAR on their part I would say.

> Is it a viable idea to try and burn a new bootloader ?

If the problem is that INT pin then you won't be able to replace the bootloader, and even if you did it wouldn't fix the problem.

> Is there a simpler way to reset the state of the device?

It looks like you will have to make a hardware modification - cut the connection between /INT and /RESET on the board - if you can identify which track that might be - or use a soldering iron to heat and lift the /INT pin of the RTC chip, which might be easier, depending on what the chip is (they are amazingly short on information).

> What did I even do wrong ?

Probably nothing serious - it's the design that is at fault. Anything that has the potential to completely cripple a system like that without even trying is just idiotic.


body:
I just received an answer from the official team which should work, I'll leave it here for further reference:

> 1. Open the device and disconnect (remove) connection board for approx. 30 seconds from the control board – RTC is disconnected from power (gold cap disconnected) and because of that there is reset of all RTC registers.
2.      Plug the connection board back in to the control board. Now we need to rewrite the SW inside the Controllino which caused wrong RTC setting.
3.      Open the Controllino example RTC sketch in Arduino IDE and prepare it to upload (function Controllino_RTC_init(0); shall reset all registers inside the RTC).
4.      Pres and hold reset button on the Controllino device.
5.      Connect the USB Cable (still hold the reset button, SW inside the Controllino doesn’t start)
6.      Click for upload the sketch in Aruduino IDE and wait for „uploading“ message on debug line, than immediately release the reset button and uploading shall be finished (=> hold the reset button during the compiling phase)
7.      If not successful, repeat the procedure


message:
Only return button state once in X amount of time?

I want to detect if a button has been pressed, but what I don't want is for it to keep returning the "pressed" state more than once within a second or two.

For example, with this code:

<!-- language: c -->

    void loop() {
      passButtonState = digitalRead(passButton);

      if (passButtonState == LOW) {
        Serial.println("PASSED!");
      }
    }

Would spit out something like this with a single quick press of the button:

    PASSED!
    PASSED!
    PASSED!
    PASSED!
    PASSED!
    PASSED!
    PASSED!
    PASSED!
    PASSED!

But what I want is for a single button press to just return `PASSED!` once for that single button press.

body:
To avoid this problem you can use a boolean variable as a flag that permit to enter inside the `if` only once.

    bool flag = true;

    void loop() {
      passButtonState = digitalRead(passButton);

      if (passButtonState == LOW && flag) {
        Serial.println("PASSED!");
        flag = false;
      }
    }


body:
If I understand the problem correctly, I think the answer might be a pretty common one. Your circuit may be suffering from "bounce" and the solution is called "debounce."

Check out this link for a possible solution:
[Software Debounce][1]

  [1]: http://playground.arduino.cc/Learning/SoftwareDebounce


body:
    void loop() {
      passButtonState = digitalRead(passButton);

      if (passButtonState == LOW) {
        Serial.println("PASSED!");
        while (passButtonState == LOW) delay(1);
      }
    }


message:
Shield:FAIL problem in ESP8266-01 with Arduino UNO

I have been working on a Security System project wherein I should get an email if the PIR sensor detects any human presence.
I have used an Arduino UNO, ESP8266-01 WiFi module and a PIR sensor.

Power supply:
Arduino is powered through the USB connection of desktop and ESP8266-01 is powered through the 3.3V pin of Arduino UNO and I have not faced any problem with that 3.3V connection of Arduino.

The connection between Arduino UNO and ESP8266-01 are as follows:

Arduino UNO-ESP8266-01

Rx - Rx

Tx - Tx

3.3V - CH_PD & VCC

GND - GND

GPIO0 and GPIO2 left open.

After successfully uploading the 'BareMinimum' code as found in 'File>Examples>Basics' of Arduino IDE, the ESP8266 is able to communicate correctly i.e. connecting to a wifi network or serving as an access point via

SERIAL MONITOR.The ESP8266-01 displays '0018000902-AI03' as the firware version when I type AT+GMR in the serial monitor of Arduino IDE v1.6.8
Then I created an account on https://temboo.com/ and used the 'SendEmail' choreo as found under 'Google>Gmail>SendEmail'.
I selected the 'Arduino' option in one tab and 'Arduino Wifi' option in another tab.I then entered the required details including the 'App specific password' and I was able to successfully run the choreo.

**Problem:**

I was able to successfully upload the code  to my Arduino UNO that was generated by Temboo.
But after uploading the code, when I'm opening my SERIAL MONITOR window from Arduino IDE a message "Shield:FAIL" is being displayed.
I'm not able to communicate with the ESP8266 any further.
But if I upload the BareMinimum code again, then ESP8266 works normally.

After connecting Rx-Tx and Tx-Rx of Arduino UNO-ESP8266-01, the serial monitor still displays 'Shield:FAIL'.

I'm a newbie and dont know much about the programming of Arduino though some basics of C are clear.Please if anyone can help me with this, I would be very grateful.

**The code is as below:**

    #include <SPI.h>
    #include <WiFi.h>
    #include <WiFiClient.h>
    #include <Temboo.h>
    #include "TembooAccount.h" // Contains Temboo account information

    WiFiClient client;

    // The number of times to trigger the action if the condition is met
    // We limit this so you won't use all of your Temboo calls while testing
    int maxCalls = 10;

    // The number of times this Choreo has been run so far in this sketch
    int calls = 0;

    int inputPin = A0;

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

      // For debugging, wait until the serial console is connected
      delay(4000);
      while(!Serial);

      int wifiStatus = WL_IDLE_STATUS;

      // Determine if the WiFi Shield is present
      Serial.print("\n\nShield:");
      if (WiFi.status() == WL_NO_SHIELD) {
        Serial.println("FAIL");

        // If there's no WiFi shield, stop here
        while(true);
      }

      Serial.println("OK");

      // Try to connect to the local WiFi network
      while(wifiStatus != WL_CONNECTED) {
        Serial.print("WiFi:");
        wifiStatus = WiFi.begin(WIFI_SSID, WPA_PASSWORD);

        if (wifiStatus == WL_CONNECTED) {
          Serial.println("OK");
        } else {
          Serial.println("FAIL");
        }
        delay(5000);
      }

      // Initialize pins
      pinMode(inputPin, INPUT);

      Serial.println("Setup complete.\n");
    }

    void loop() {
      int sensorValue = analogRead(inputPin);
      Serial.println("Sensor: " + String(sensorValue));

      if (sensorValue >= 2) {
        if (calls < maxCalls) {
          Serial.println("\nTriggered! Calling SendEmail Choreo...");
          runSendEmail(sensorValue);
          calls++;
        } else {
          Serial.println("\nTriggered! Skipping to save Temboo calls. Adjust      maxCalls as required.");
        }
      }
      delay(250);
    }

    void runSendEmail(int sensorValue) {
      TembooChoreo SendEmailChoreo(client);

      // Set Temboo account credentials
      SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
      SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
      SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

      // Set profile to use for execution
      SendEmailChoreo.setProfile("JigarFaria");
      // Identify the Choreo to run
      SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

      // Run the Choreo
      unsigned int returnCode = SendEmailChoreo.run();

      // Read and print the error message
      while (SendEmailChoreo.available()) {
        char c = SendEmailChoreo.read();
        Serial.print(c);
      }
    Serial.println();
      SendEmailChoreo.close();
    }

body:
 1. You seem to have the ESP connected via serial, but aren't sending it anything.
 2. The Rx of the ESP needs to be connected to the Tx of the Arduino (via a logic level shifter) and the Tx of the ESP needs to be connected to the Rx of the Arduino.
 3. Do you know with a proper email sending library you could use any email server, not some service that you may have to pay for?
 4. The ESP8366 is a much more capable device than the Arduino (IMO).  I suspect that you could directly connect your sensor to it, and program it (in Arduino C/C++) through the Arduino IDE and it would be much less hassle.
 5. I think the problem with your code is that you haven't initialised the Wifi object, the first time you call it is to ask the status.  However I don't think you need this code because its not talking to the ESP8266 and you should be sending the data via the serial connection.


body:
Both @CodeGorilla and @Majenko make valid points.

The shield esp will talk with the uno through Serial and your esp8266 has the AT firmware on it.
The BareMinimum reads input from serial and prints what the esp is sending .
the code you posted has code meant for the Uno and code meant for the shield esp.

 That wont work.

Your should use the arduino library for esp8266 (https://github.com/esp8266/Arduino,) make a suitable code for it , connect your sensor to the shield and forget the uno.


message:
Stop multiple presses in vex bumper (Unexpected bumper output)

According to [Official documentation of the Vex Bumper][1], it states that the bumpers will cause:

> the robot sometimes [counts] a press twice. This issue is also caused by the robot counting too fast and as the limit switch is released, a second press is registered by the robot.

The documentation suggests this code:

    task main() {
        while(true) {
       string presses = buttonPresses;
       if(presses != last) {
        writeDebugStreamLine(presses);
        }
       last = presses;

       if(SensorValue(bump) == 1) {
        wait1Msec(5);
     while(SensorValue(bump) == 1){}
        buttonPresses++;
       }
        }
    }

**However, if you are like me, this didn't work at all, multiple button presses were registered from holding down the button for a moment and releasing it.**

  [1]: http://www.education.rec.ri.cmu.edu/products/teaching_robotc_vex/sensing/operator_assist/docs/quick_tap.pdf

body:
Because this problem was so infuriating and strange, I managed to do a workaround which the program refused to take a sudden addition to button counts after taking a first one. This enabled me to use the button without multiple extra counts.

    string last;
    float buttonPresses = 0;
    float time = time1[T1];
    bool isFirstTime = true;

    task main()
    {
     ClearTimer(T1);
     clearDebugStream();
     while(SensorValue(go) != 1) {

      string presses = buttonPresses;
      if(presses != last) {
       writeDebugStreamLine(presses);
      }
      last = presses;

      if(SensorValue(bump) == 1 && buttonPresses < 6) {
       if(isFirstTime || time1[T1] - time > 50) {
        isFirstTime = false;
        wait1Msec(15);
        while(SensorValue(bump) == 1){time = time1[T1];}
        buttonPresses++;
       }
      }

     }
    }

If you want extra probability against multiple extra "presses" you can widen the interval of tolerance (in this case the 50 value) to something larger, but it makes it less accurate at registering quick taps.


body:
When you are testing buttons within a loop that runs repeatedly, there's no need for lengthy monolithic delays like `wait1Msec(15)`, and no need to store and test start times, like `time = time1[T1]` and `time1[T1] - time > 50`.

Instead, you can change your loop so it takes at least some small time (as via `wait1Msec(1)` in following code sample), and add a holdoff counter that inhibits sensor testing during probable bounce periods.

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

    string last;
    long bumpCount = 0;
    byte holdoff=0, isbump=0;

    task main() {
      while (SensorValue(go) != 1) {
        string presses = bumpCount;
        if(presses != last) {
          writeDebugStreamLine(presses);
        }
        last = presses;
        wait1Msec(1);
        if (holdoff) {  // Ignore bump sensor during holdoff
          --holdoff;
        } else {
          if (SensorValue(bump)) {
            if (isbump==0) {
           ++bumpCount; // Count a new closure
              holdoff = 40; // Start a holdoff period
            }
            isbump = 1;     // We detected bump is on
          } else {
            isbump = 0;     // We detected bump is off
          }
        }
      }
    }

The code shown above acts as follows:

• Initially, `bumpCount`, `holdoff`, and `isbump` are zero, to indicate we haven't counted any bumps, are not inhibiting bump sensing, and think the bump sensor is off.

• Under initial conditions and while the bump sensor is off, we will pass through the outer while loop, each time waiting a millisecond, then taking the `else` branch of `if (holdoff)` and the `else` branch of `if (SensorValue(bump))`, so will repeatedly set `isbump = 0`, thus maintaining initial conditions.

• When the bump sensor goes on, we take the first branch of `if (SensorValue(bump))`.  From initial conditions, `isbump==0` so we increment `bumpCount` and set `holdoff = 40`.  Lastly, set `isbump = 1` to reflect sensor state.

• During the next 40 milliseconds or so (that is, during the holdoff period) we repeatedly decrement `holdoff`, while ignoring the bump sensor, which may bounce a number of times or not, as it pleases, but we don't care.

• After the holdoff period, `SensorValue(bump)` may still be true.  But since `isbump==0` is false, we don't change `bumpCount`.

• If the bump sensor opens after the holdoff, `isbump` will go zero, restoring two of the initial conditions.  If it opens during the holdoff and stays open, the same thing happens at the end of the holdoff.


message:
Changing timing intervals with millis()

My goal is to run a vibrating motor for **specific** time intervals. I am using the `millis()` function to successfully turn the motor on and off, but only if the `intervalOn = intervalOff`. The problem comes when I try to change the intervals to turn the motor on for e.g. 120 ms, then turn off for 200 ms etc. My code seems to cause AVR restart and my motor sometimes stays running. First I thought this is caused by insufficient decouple capacitor (I have 100 uF one) but when running the `millis()` code with one no-changing interval, it all works flawlessly...
Is there any other way to change the intervals?

The `Vibrating()` function gets called from the `loop()` whenever `vibrEnabled = true`

<!-- language: c -->

    unsigned long interval = 0;
    unsigned long previousMillis = 0;
    int last = 120;
    int pause = 200;

    void Vibrating()
    {
    unsigned long currentMillis = millis();
 static byte cyclesPassed = 0;

    if((unsigned long)(currentMillis - previousMillis) >= interval)
 {
  PORTC ^= (1<<PC1);//toggle motor

  if(interval != last) //this part causes the problem
   interval = last; //
  else                 //
    interval = pause;//

  cyclesPassed++;
   if(cyclesPassed == 8)//motor is on 4x
  {
  cyclesPassed = 0;
  vibrEnabled = false;
  }

  previousMillis = millis();
  }
    }

body:
1. Maybe your vibrating motor is actually shaking something loose. A dodgy batter clip or something.

2. Maybe your vibrating motor is drawing too much current and power-cycling the board.

3. Maybe your vibrating motor is doing weird, bad things like generating back-EMF spikes that it's sending back into the arduino.

It's probably number 3. Generally speaking, you *never* power motors off an output pin. Run the output into a mosfet or something with a flyback diode across it. Google "circuit to power motor from digital out".


message:
Does an Arduino 101 come with bluetooth HID capabilities?

I would like to prototype an Ergodox-like keyboard. My take on this good design would be to affix each half of the keyboard to my chair's armrests, so that the arms are always in a natural relaxed position. In order to achieve this, bluetooth capabilities seem necessary in order to avoid cable mayhem each time I move the chair.

I am aware that the Arduino Leonardo has USB-HID capabilities, but will that translate to the additional USB module that would be required? I saw that Adafruit has an EZ-key bluetooth module that seems to fit the bill, but even so, it would require more cabling and complexity, for a project that is already very near my threshold (or above it).

What would be easy is if the Arduino 101 had HID capabilities. I would just need to solder the matrix of keys, and almost be done. Does it?

Thanks for your attention.

body:
The Arduino 101 has HID capabilities. I found example code for using the Arduino 101 as a keyboard, as well as some other discussions saying that the Arduino 101 has HID capabilities.

[Here is some example code on GitHub](https://github.com/mo10/Curie-bluetooth-HID-library/tree/master/src).


message:
Arduino-Bluetooth HC-05 Android app blueterm connection for chatting

I want to communicate between an arduino and an Android phone that has an Android app blue term. I connected HC-05 with Arduino using software serial and I connected the hc05 as a device with the android app. I am able to send data ( data as in message) from Android to Arduino but I am unable to send message from arduino to Android though I have given `.write()` command to Bluetooth connected.

Is it such that the Android app does not show the received message? Or there is some master-slave configuration issue? Do I need to configure HC-05 in master mode? It was configured in slave mode by default when I had connected it to Android app.

body:
Its totally Normal. You must be doing something wrong. It has happen to my Arduino Code a lot of times. try following:

 1. Try interchanging you Tx and Rx Pin Positions. (This happens all the time).
 2. Try connecting using default **Serial** and using Pin 1 and Pin 0 as Tx/Rx. (In this case remember to unplug the Tx/Rx Pins while running code.)
 3. Try using just basic **Serial.Write()** function in beginning.


message:
Why doesn't my 7 segment update every second like in the program?

I used sevseg.h library to write numbers to my 4 digit seven segment. The display should update every second with the current time since program started running. This is my code so far:

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

    #include <SevSeg.h>

    SevSeg sevseg;

    void setup() {
        byte numDigits = 4;
        byte digitPins[] = {5, 4, 3, 2};
        byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
        sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
        sevseg.setBrightness(50);
        sevseg.setNumber(0000, -1);
    }

    void loop() {
        unsigned long timer = millis();
        for (int i = 0; i < 500; i++) {
            sevseg.setNumber(timer/1000, -1);
            sevseg.refreshDisplay();
            delay(2);
        }
    }

Since the delay is 2, the for loop loops 500 times, resulting in 1000ms or 1 second. The current second is written to the display. For some reason, the display is updated every other 5 or 6 seconds. Why is this occurring? How can this be fixed so that my display turns into a stopwatch in a way?

body:
This is the code that fixed the issue:

      #include <SevSeg.h>
      SevSeg sevseg;

      void setup() {
        byte numDigits = 4;
        byte digitPins[] = {5, 4, 3, 2};
        byte segmentPins[] = {13, 12, 11, 10, 9, 8, 7, 6};
        sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
        sevseg.setBrightness(50);
        sevseg.setNumber(0000, -1);
      }

      void loop() {
        unsigned long timerGlobal = millis();
        sevseg.setNumber(timerGlobal/1000, -1);
        sevseg.refreshDisplay();
      }

In this, no delays are needed. `millis` is divided by 1000 and the integer second is drawn on the display. Proved to be much easier than I previously thought.


message:
Iterating an array of relays

Bear with me as I'm fairly adept at C# but I am having a problem understanding how to get an array iterated.

I am writing a program to test relay boards, it will eventually have an input mechanism to select the number of relays on the board. For now, i just need to get an array iterated to move on with the code.

The biggest relay board I've seen has 16 relays, so....

    #define Relay1  2  // Arduino Digital I/O pin numbers for UNO R3
    #define Relay2  3
    #define Relay3  4
    #define Relay4  5
    #define Relay5  7
    #define Relay6  8
    #define Relay7  9
    #define Relay8  10
    #define Relay9  11
    #define Relay10  12
    #define Relay11  13
    #define Relay12  A0
    #define Relay13  A1
    #define Relay14  A2
    #define Relay15  A3
    #define Relay16  A4

    int relays[]{ Relay1,Relay2,Relay3,Relay4,
        Relay5,Relay6,Relay7,Relay8 };
    int maxRelayCount = 8;
    char rx_byte = 0;

    void setup()   //Initializes all variables and settings
    {
      Serial.begin(9600);
     // create an input for the amount of relays on the board
    //hardcoded for now

    //Set pins to OFF & declare pins as OUTPUTS
     for(int i = 0; i < maxRelayCount; i++)
     {
       digitalWrite(relays[i], RELAY_OFF);
       pinMode(relays[i], OUTPUT);
       //How to convert i to a string in c++?
    //Serial.print("Relay " +[i] + " set HIGH and as OUTPUTS");
     }

     //Check that all relays are inactive at Reset
     delay(4000);

    }

So there are two issues. If I remove the loop and just hard code 8 times to set HIGH and OUTPUT it works fine, but the loop does not and won't upload to the Arduino, thus the reason I believe it is wrong. Secondary question is how to convert the counter i to a string to concatenate the message

body:
> the loop does not and won't upload to the Arduino

Most likely because `RELAY_OFF` has never been defined anywhere. Change that to HIGH (if that is what your relays need to turn off), or define it somewhere.

Also there is no `loop()` function - is that just you being economical with the paste?

> Secondary question is how to convert the counter i to a string to concatenate the message.

Simple: don't.  There's no need.

    Serial.print("Relay ");
    Serial.print(i);
    Serial.println(" set HIGH and as OUTPUT");


body:
As noted earlier, `RELAY_OFF` needs a defined value.

Note, rather than using clumsy list of `#define` statements to define a bunch of integer constants, you can use C's `enum` declaration to define them, as shown in the following sketch, which produces the output

    Relay 1 should be OFF
    Relay 2 should be OFF
    Relay 3 should be OFF
    Relay 4 should be OFF
    Relay 5 should be OFF
    Relay 6 should be OFF
    Relay 7 should be OFF
    Relay 8 should be OFF

when it is run.

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

    #include <Streaming.h>

    // Arduino Digital I/O pin numbers for UNO R3
    enum { Relay1=2, Relay2=3, Relay3=4, Relay4=5, Relay5=7, Relay6=8,
           Relay7=9,   Relay8=10,  Relay9=11,  Relay10=12,  Relay11=13,
           Relay12=A0, Relay13=A1, Relay14=A2, Relay15=A3,  Relay16=A4};

    int relays[] = {Relay1,Relay2,Relay3,Relay4,Relay5,Relay6,Relay7,Relay8};
    // Number of relays in the array
    enum { maxRelayCount = sizeof relays / sizeof relays[0] };
    enum { RELAY_OFF = HIGH }; // Set LOW or HIGH as appropriate
    char rx_byte = 0;

    void setup() {   // Initialize variables and settings
      Serial.begin(9600);
      //Set pins to OFF & declare pins as OUTPUTS
      for(int i = 0; i < maxRelayCount; ++i) {
        digitalWrite(relays[i], RELAY_OFF);
        pinMode(relays[i], OUTPUT);
        // Serial.print("Relay " +[i] + " set HIGH and as OUTPUTS");
        Serial << "Relay " << i+1 << " should be OFF" << endl;
      }

     // Check that all relays are inactive at Reset
     delay(4000);
    }

    void loop() {}

Note, the `Streaming.h` library adds some “syntactic sugar” to Arduino C. At compile time it converts C++-like << Serial stream operators to Serial.print statements, without increasing code size.  You can install it by unzipping [`Streaming5.zip`](http://arduiniana.org/Streaming/Streaming5.zip) from [arduiniana.org](http://arduiniana.org/libraries/streaming/) in your `sketchbook/libraries` directory[.](https://arduino.stackexchange.com/questions/18348/arduino-variable-data-type)


message:
Audio/Voice Recording Device

I'd like to build a little voice recorder for my grandmother. She told me "I get a lot of idea when I'm driving but then I forget them. I want a necklace where I can just press a button and it'll record my voice and I can press a button and it'll stop recording." She wants each recording to save as a separate file. I was thinking of concealing a mini Arduino board or Rasberry Pi or something in a necklace, with a removable micro sd card. Or something like that. I just don't know where to start, I don't have much experience with this. Does anyone have any tips on what kind of device I could use or where to start? I suggested that she just have Siri take notes for her on her iPhone but she wants something around her neck, and she wants me to make it.

body:
Try this amazing breakout board. Its all you need. [SparkFun Voice Recorder Breakout - ISD1932][1]

Moreover, If you thinking on letting that device talk back, try this: [VoiceShield][2]

Well, there is also an instructable for this, [HERE][3]. This Instructable will show you how audio input can be repeatedly added to a 512 byte buffer and then transferred to a SD card in real time. The audio file can be played back on a standard audio application or analysed byte by byte.

  [1]: https://www.sparkfun.com/products/retired/10653
  [2]: http://www.spikenzielabs.com/SpikenzieLabs/VoiceShield.html
  [3]: http://www.instructables.com/id/Arduino-Mega-Audio-File-logging/


message:
rf24 change order of data

I'm using two Arduinos with the rf24 modules.

I want to control a process with those, but for now I'm just checking the connection.

This is the code of the master:

 #include  <SPI.h>
 #include "nRF24L01.h"
 #include "RF24.h"
 unsigned char msg[4];
 unsigned char serial_msg[1];

 String mensaje = "ii";

 int CE = 9;
 int CSN = 10;

 RF24 radio(9,10);

 //const uint64_t pipe = 0xE8E8F0F0E1LL;
 const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

 bool done;
 int incomingByte = 0;

 String stringOne  = "";

 void setup(void){
  Serial.begin(9600);
  radio.begin();
  radio.setRetries(15,15);
  radio.openWritingPipe(pipes[1]);
 }

 void loop() {

  radio.stopListening();

  if (Serial.available() == 3) {

   while(Serial.available() > 0)
   {
    incomingByte= Serial.read();

    stringOne = String(stringOne + String((char)incomingByte));

   }
   Serial.println(mensaje);

   incomingByte = Serial.read();
   serial_msg[0] = incomingByte;

   radio.write(stringOne.c_str() ,2);

  }

  stringOne  = "";

  radio.startListening();    // Volvemos a la escucha para recibir mas paquetes
  delay(10); // necesario para activar el modo de esucha

  if (radio.available())
  done = false;
  {
   while (!done)
   {
    if (sizeof(msg)==4)
    {
     done = radio.read(msg,sizeof(msg) );
     Serial.print("Estado: ");
     Serial.println(msg[0]);
     Serial.print("Voltaje: ");
     Serial.print(msg[1]);
     Serial.print(msg[2]);
     Serial.println(msg[3]);
    }

   }

  }
  mensaje = "";
 }

What t does is read data for the serial monitor, convert it to a string and them send the string.

The code of the receiver is this:

 #include  <SPI.h>
 #include "nRF24L01.h"
 #include "RF24.h"

 int CE = 6;
 int CSN = 7;
 RF24 radio(CE,CSN);  /// ()
 const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };

 bool done = false;

 int voltaje = 141;
 String string_vol= "789";
 enum states {
  ESPERA,
  ENCENDIDO,
  PAUSA
 };
 enum states state = ESPERA;

 unsigned char msg[2];
 char incomingByte = '_';
 unsigned long previousMillis = 0;
 unsigned long currentMillis = 0;
 unsigned long interval = 1000;

 void setup() {

  Serial.begin(9600);
  radio.begin();
  radio.startListening();
  radio.openWritingPipe(pipes[1]);
  radio.openReadingPipe(1,pipes[0]);

 }

 void loop() {

  string_vol= "789";
  currentMillis = millis();
  if ((currentMillis-previousMillis)>interval)
  {
   previousMillis = currentMillis;
   msg[0] = char(state);
   radio.stopListening(); // Dejamos d escuchar para poder hablar
   string_vol = String(String((char)state)  + string_vol );
   radio.write(string_vol.c_str() ,4);
   radio.startListening();    // Volvemos a la escucha para recibir mas paquetes
   delay(10);
  }
  if (radio.available())
  done = false;
  {
   while (!done)
   {
    done = radio.read(msg,sizeof(msg));
   }
  }

  switch(state) {
  case ESPERA:

   if (msg[0] == 'i')
   {
    state =  ENCENDIDO;
   }

   break;
  case ENCENDIDO:

   currentMillis = millis();

   if (msg[0]=='r')

   {
    state =  ESPERA;
   }
   else if  (msg[0]=='d')
   {
    state =  PAUSA;
   }
   break;
  case PAUSA:
   if (msg[0]=='r')
   {
    state =  ESPERA;
   }
   else if  (msg[0]=='c')
   {
    state =  ENCENDIDO;
   }
   break;
  }
 }

This one acts as a state machine, and sends a string in this case:

    string_vol= "789";

plus the actual state of the Arduino:

    string_vol = String(String((char)state)  + string_vol );

When this Arduino is in state one:

In the other side I got:

Estado: 1
Voltaje: 555657

When is in state II I got:

Estado: 2
Voltaje: 555657

But if it's in state zero, which is the initial one, I got:

Estado: 55
Voltaje: 56570

It change the  position of the state for one of the chars of the string

EDIT.

The  issue is when sending the '0' of the first state, I changed enum to:

 enum states {
  foo, //  revisar, solo usada para comenzar en 1
  ESPERA,
  ENCENDIDO,
  PAUSA
 };

Now it works fine because the first state is '1', still don't now why it doesn't work if I use the '0'

body:
The problem you run into is that you are trying to insert the binary value of 0 into an Arduino `String`.   That may actually be possible, but the way you attempt to to do it utilizes some C-style mechanisms, specifically representing a string as a pointer to some characters terminated by a null byte - which is to say 0.

Your code:

    string_vol = String(String((char)state)  + string_vol );

Invokes this String constructor from WString.cpp

    String::String(char c)
    {
     init();
        char buf[2];
     buf[0] = c;
     buf[1] = 0;
     *this = buf;
    }

Which tries to turn the input `char` into a C-style string containing the input and then its own terminating null.  But in the case where state=0, that ends up being a buffer of two 0's.  A C-style string is terminated by the first 0, so when interpreted that way, the buffer is considered empty.  The last line of this constructor uses the buffer to invoke yet another constructor, that treats the input as a C-style null terminated string:

    String::String(const char *cstr)
    {
     init();
     if (cstr) copy(cstr, strlen(cstr));
    }

Since strlen() finds the input here in the state=0 case to be empty, it produces an empty String.  You then append some other data, and that is all that you see, with no state included in the packet.

----------

As this demonstrates, it is necessary to to be careful mixing binary and textual representations.

One thing you might do would be to add an offset to the state before transmitting, and subtract it out on the receiver.  If you have 9 or fewer states, adding the character code of '0' (ie, 0x30) would transmit them as potentially printable digits.  If you have more, you could add 'A' and transmit them as letters of the alphabet.  In the end it doesn't really matter what you add, as long as any value you intend to transport can be represented in all the intermediate data formats it passes through.

Of course the nRF24L01 parts will transmit binary data just fine; if you want to go ahead and move binary data through them you can, you just have to avoid using anything with C-style `char *` mechanics that is going to see `0` in the data as a terminator, not a character.


message:
DB:NO RESP Using inet.httpPOST on loop()

I'm using SIM900 module + arduino uno + gsmlib.org library.

I'd like to send a string to endpoint on my API , and it worked correctly for the first time when I using `inet.httpPOST` function in `setup()`, but... in `loop()`, when I call that function again, it doesn't work. On serial monitor I get:

    ATT: ERROR
    RIC:
    ERROR
    DB:STARTING NEW CONNECTION
    ATT: SHUT OK
    RIC:
    SHUT OK
    DB:SHUTTED OK
    ATT: OK
    RIC:
    OK
    DB:APN OK
    ATT: OK
    RIC:
    OK
    DB:CONNECTION OK
    ATT: ERROR
    RIC:
    xxx.xxx.xxx.xxx

    DB:ASSIGNED AN IP
    status=ATTACHED

    http://api.com.br/mystring

    ATT: OK
    RIC:
    OK
    DB:RECVD CMD
    ATT: CONNECT OK
    RIC:
    OK
    ATT: OK
    RIC:
    CONNECT OK
    DB:OK TCP
    ATT: >
    RIC:
    >
    DB:>
    ATT: SEND OK
    RIC:
    SEND OK

    DB:SENT

    http://api.com.br/mystring

    ATT: OK
    RIC:
    xxx.xxx.xxx.xxx
    ERROR
    ALREADY CONNECT
    DB:NOT CONN
    ATT: OK
    RIC:
    ERROR

    ALREADY CONNECT
    DB:NOT CONN
    ATT: OK
    RIC:
    ERROR

    ALREADY CONNECT
    DB:NOT CONN

How can I send data to my API continuously on loop() Could someone help me?

Following is my code (SOLVED):

    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>
    #include <inetGSM.h>

    InetGSM inet;
    TinyGPSPlus gps;
    SoftwareSerial serialGps(11, 10);

    /**
        setup
    */
    void setup() {
      // Serial connection.
      Serial.begin(19200);
      Serial.println(F("Starting App Arduino"));

      // Turn on GPRS
      powerUpGprs();

      // Start configuration of shield SIM900 with baudrate and  connect to internet.
      if (gsm.begin(9600)) {
        Serial.println(F("\nstatus=READY"));

      // Start configuration of shield GPS NEO-6M with baudrate.
      serialGps.begin(9600);

      // Mensure and show memory usage
      Serial.println(F("\nMemory usage"));
      Serial.print(freeRam());
    }

    /**
       loop
    */
     void loop() {
      serialGps.listen();
      while (serialGps.available() > 0)  {
        if (gps.encode(serialGps.read())) {
          // Get GPS position and send To API
          gsm.listen();
          // if sim900 started, connect to internet
          Serial.print(F("\r\n"));
          Serial.print(F(" CONNECT TO INTERNET \r\n"));

          // GPRS attach, put in order APN, username and password.
          if (inet.attachGPRS("zap.com.br", "zap", "zap"))
            Serial.println("status=ATTACHED");
          else Serial.println("status=ERROR");
          delay(1000);
          // Read IP address.
          gsm.SimpleWriteln("AT+CIFSR");

          Serial.print(F("\r\n\r\n"));
          Serial.print(F(" GET GEOLOCATION & SEND TO API \r\n"));
          // get geolocation
          String geo;
          geo.concat("lat=" + String(gps.location.lat(), 6));
          geo.concat("&lng=" + String(gps.location.lng(), 6));
          geo.concat("&spd=" + String(gps.speed.kmph()));
          geo.concat("&gps.uuid=1");
          // send2Api
          Serial.println(geo.c_str());
          Serial.print(F("\n"));
          gsm.SimpleWriteln("AT+CIFSR");
          inet.httpPOST("api.com.br", 80, "/geolocations", geo.c_str(), "", 100);
        }
      }
    }

    /**
       mensure memory usage
    */
    int freeRam() {
      extern int __heap_start, *__brkval;
      int v;
      return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
    }

    /**
       Power up
    */
    void powerUpGprs() {
      pinMode(9, OUTPUT);
      delay(100);
      digitalWrite(9, HIGH);
      Serial.println(F("\nPower Up SIM900!"));
    }

Thank You!!!

body:
[Like I told you before][1], you have 2 instances of `SoftwareSerial` active, but you're allowed to listen to only one at a time (implementation rules). So you have to alternate between calling `listen()` on each instance; any data arriving at any port while its not the active port will be discarded. `inet.httpPOST()` worked in `setup()` because you called the function before `begin()`ing `serialGps`. Calling `serialGps.begin()` immediately made `serialGps` the active port, severing communication with the modem.

 - Add this line to `SIM900.h` in the library, under the public methods:

        void listen();

 - Add this method to `SIM900.cpp`:

        void SIMCOM900::listen(){
           _cell.listen();
        }

 - Save the files and add `gsm.listen()` right before `gsm.SimpleWriteln("AT+CIFSR");` in `loop()`.

 - Re-initialize GPRS, like you did in setup() with attachGprs(), right after gsm.listen() in loop().

 - Make `serialGps.listen()` the last  statement in loop() immediately after the `inet.httpPOST()` call. Use braces to enclose the body of the while loop.

Hopefully this should solve your problem.

  [1]: https://arduino.stackexchange.com/questions/22149/gprs-sim900-and-gps-neo-6m-dont-work-together/


message:
User input for utility program

I am writing a utility program to test relay boards. I'd like to be able to accept a user input of the number of relays on the board. Is this doable via the serial monitor since when I'm testing boards I'm generally doing it at my desk with my testing Arduino attached to my laptop? I'd prefer not to go the LCD and keypad route.

Is there an accepted practice for doing this?

body:
Yes, it is perfectly do-able through the serial monitor.  However the serial monitor is very very basic and you will be able to create a much better user experience using a proper serial terminal emulator (such as TeraTerm, Putty, etc) and using ANSI control codes to lay the screen out as a proper text-based application.

A useful resource is on Wikipedia: https://en.wikipedia.org/wiki/ANSI_escape_code

I have a little library that I started a while back and never finished that performs two basic ANSI control sequences - clear screen and set cursor. You can look at it to see how to perform ANSI control codes: https://github.com/MajenkoLibraries/ANSI


message:
While loop not breaking

I'm trying to build a circuit that buzzes until a button is pressed, or it buzzes 5 times:

    void alarm()
    {
      int AlarmState = 0; //Just to get while loop going
      int count = 1;
      while(AlarmState==0)
      {
        int count = 1;
        AlarmState = digitalRead(alarmStop);
        digitalWrite(buzz,HIGH);
        AlarmState = digitalRead(alarmStop);
        delay(500);
        AlarmState = digitalRead(alarmStop);
        digitalWrite(buzz,LOW);
        AlarmState = digitalRead(alarmStop);
        delay(500);
        count++;
        if(count>=5){
        break;
        }
      }

I put a bunch of digitalRead's  so it has a better chance of catching the button press while the loop is going, there's a better way to do that I'm sure but it's not my main concern right now.

This is part of a larger project, but I hope I've posted only the necessary code. The function runs, but does not break after `count` equals 5. Why?

body:
Try This One its Simple:

    void alarm()
    {
      int count = 0;
      while ( digitalRead(alarmStop) && (count++ <5))
      {
        //A
        digitalWrite(buzz, HIGH);
        delay(500);
        digitalWrite(buzz, LOW);
        delay(500);
      }
    }

But, There is a logical problem with this Code. Lets say that your code is at point A (metioned in comment) and at same time button is pressed. Now This code above will, still buzz and then stop.

To avoid This try using interrupts. To use interrupts on Arduino I prefer [This Library][1]. [Download Here][2]. Extract this and inside you will find a folder Named **PinChangeInt**. Copy This whole folder to your **Documents\Arduino\libraries** folder. Now, restart Arduino IDE and copy paste this code:

    #include <PinChangeInt.h>

    int buzz = 3;

    bool alarmStatus = false;
    #define PIN3 4
    void pin3func() {
      digitalWrite(buzz, LOW);
      alarmStatus = true;
    }

    void setup() {
      pinMode(PIN3, INPUT); digitalWrite(PIN3, HIGH);
      PCintPort::attachInterrupt(PIN3, &pin3func, CHANGE);
    }

    int count = 0;
    void loop() {
      if (count < 5)
      {
        if (!alarmStatus)
        {
          digitalWrite(buzz, HIGH);
        }
        delay(500);
        digitalWrite(buzz, LOW);
        delay(500);
      }
    }

Because, of unavailability of hardware, I haven't tested this code. But, I hope It will work.

  [1]: http://playground.arduino.cc/Main/PinChangeInt
  [2]: https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/arduino-pinchangeint/pinchangeint-v2.19beta.zip


body:
The problem with your code is your using `delay()`. This is a function
that should most of the time be avoided for one simple reason: when the
Arduino is executing the `delay()` instruction, it does _nothing_ but
wait. This means, among other things, that it cannot be reactive to user
input. As outlined by ARK in his answer, interrupts could be used to
overcome this problem. But you actually do not need them: the standard
way to avoid delays is to use instead the `millis()` function to control
timings. This approach is well described in the [Blink without
delay](https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay) Arduino
tutorial.

Here is how you can apply this technique to your `alarm()` function: In
a nutshell, you can think of `delay()` to be roughly equivalent to this:

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

    void naiveDelay(uint32_t ms)
    {
        uint32_t start = millis();
        while (millis() - start < ms) {
            // do nothing
        }
    }

The problem here is the “do nothing” part. You do not want your program
to do nothing, you want it to monitor the “alarm stop” button. So the
simple solution to your problem is to replace `delay()` by the code
above, and then change it so that it monitors the button instead of
doing nothing. Then you get something like this:

    void alarm()
    {
        for (int count = 0; count < 5; count++) {

            // start the buzzer
            digitalWrite(buzz, HIGH);

            // first delay
            uint32_t start = millis();
            while (millis() - start < 500) {
                if (digitalRead(alarmStop) == HIGH) {
                    digitalWrite(buzz, LOW);  // stop the buzzer
                    return;
                }
            }

            // stop the buzzer
            digitalWrite(buzz, LOW);

            // second delay
            start = millis();
            while (millis() - start < 500) {
                if (digitalRead(alarmStop) == HIGH) {
                    return;  // buzzer already off
                }
            }
        }
    }


body:
I think the main problem with the code not breaking within the `while()` statement is what @ott pointed out above.

To expand on the exact problem, note that you have defined two different `count` variables in your code. Each has a different scope.

As soon as you enter the alarm function, you define an `int count` variable and initialize it. Then, when you enter the `while ()` statement, you define a second `int count` variable and initialize it. These are NOT the same variable. This second variable is the one being used and unfortunately, is reinitialized each time through the loop. It will always have a value of 1 so your test for it becoming greater than or equal to 5 will never test true. Thus no break.

If you comment out the second `int count` line, your loop should then work and break as expected. it should look like this:

      while(AlarmState==0)
      {
      //  int count = 1;
        AlarmState = digitalRead(alarmStop);

Others have pointed out other improvements that can be made to the code but the two variables of the same name with different scopes appear to be the specific cause of the `while()` not breaking.


body:
    void alarm()
    {
      int AlarmState = 0;
      int count = 1;
      while(AlarmState==0) //Your count == 2, then while starts over again and you redefine you count to 1, so thats becomes infinite loop
      {
        int count = 1; //Here you initialize "count" second time
        AlarmState = digitalRead(alarmStop);
        digitalWrite(buzz,HIGH);
        AlarmState = digitalRead(alarmStop);
        delay(500);
        AlarmState = digitalRead(alarmStop);
        digitalWrite(buzz,LOW);
        AlarmState = digitalRead(alarmStop);
        delay(500);
        count++; //Now you incrementing count value, 1+1 = 2, go back to "while" and read
        if(count>=5){
           break;
        }
      }


message:
Simulator for AD8232 Chip

How can I get AD8232 chip in Arduino simulator?
It is because I have my ciruit comprising AD8232 analogue chip but I dont get this chip? I want to make simulatoin of my ciruit.
If it is can not be found in Arduino please direct me in which circuit simulating software can I get it!

body:
I don't think there would be an actual simulator for this chip. Its hard. But there is a way around.

What you are doing eventually is **ECG** and the output given by this chip is just analog signal i.e. **a single float value**. So, lets say for now, all you are concerned with is obtaining those float **values** irrespective of source. And of course you need a lot of them.

What you can do is to use a **dataset**. As indicated by its name, a **dataset** contains a large number of (recorded) value of something.

So, you can use a **dataset for heart reate** to **simulate** this chip.

There are many related **datasets** available online for free. just [Google it][1]. and find one that suits you.

Hope it help. Thanks.

  [1]: https://www.google.com.pk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=dataset heart rate


message:
What are the consequences of different clock speeds on different boards?

I am a programming amateur, arduino noob, trying to decide which board will be better for my project. I need a small board. I am trying to decide between the Teensy 3.2 and the RFduino. I want to have blue-tooth capability for over air routine changes to a WS2812B LED strip, which makes the RFduino attractive because of its integrated BLE4.0 antenna. However, I want to be able to have enough speed for imperceptible LED modulation, which makes the 72MHz speed of the Teensy attractive.

What would be the objective difference between the 16MHz processor on the RFduino versus the 72MHz on the Teensy3.2? Is this something I should be concerned with?

body:
You would think on the face of it that a faster processor will give you "more speed" however that does not necessarily work in a linear way. The faster processors tend to have more sophisticated chips. And "more sophisticated" can be code for "it takes more clock cycles to achieve the same thing".

I have code that drives 300 NeoPixels in a seamless manner, on a 16 MHz Arduino Uno, however during the driving it is pretty processor-intensive (and interrupts have to be off). So certainly you can have some smooth effects at 16 MHz. However controlling them in real time, via Bluetooth, may be a different thing.

NeoPixels will "remember" the last thing that was sent to them, so (when interrupts are active) you could be accepting new instructions, and the pixels will just display what they were last sent. This may be acceptable for you.

The [Adafruit page](https://www.adafruit.com/products/1138) for RGB LED Strip mentions that their library is only for the AVR processors. So that may be a consideration for you.

Even with other display strips, you may find that, during reception of radio signals, the strips cannot alter their patterns at high speed. The 72 MHz you quoted is only 4.5 times as fast as 16 MHz. The NeoPixel timings are in the order of nanoseconds (350 ns for a zero-bit) so timing is tight. Having 4.5 x the clock speed isn't necessarily going to give you enough leeway to do radio communications.

---

> I just want to be able to select and change the program remotely via BLE, rather than send sequential commands over air. Does this change your answer at all?

Your design seems to me to consist of two components:

* Showing some pattern
* Receiving a new pattern (or code for a new pattern)

You can't be doing both at precisely the same time. (Maybe with two processors you might - one doing the radio, and one displaying the pixel pattern). I found I could refresh 1000 pixels in 63 ms, which is roughly 16 FPS. If you have less pixels it will be faster. I don't know exactly how long it takes to determine if a Bluetooth message has arrived, I assume not particularly long.

> Planning on 3M of 60LED/M WS2812B strip as of now

So, 180 pixels. At 63 µs per pixel that would be 11.3 ms to refresh the strip. You can see that this gives you quite a bit of time over in one second to receive new instructions.


body:
You have to set your requirements, or atleast elaborate what you want to achieve.

Best would be to program in a set amount of effects on the microcontroller and only send which effect you want to "start" with maybe even a color.

But you have to specify stuff, you should make a list like this:

    Length of messages
    (Max) baudrate of bluetooth device & microcontroller

    amount of bits in the total LED strip
    speed of sending bits into the LED strip

    Maximal time from sending to effect

**Sample calculation for NeoPixel (WS2182)**

If you can make a good approximation (or find actual values) you can determine which speed you are going to need. This might even be 1Mhz, try to avoid [premature optimization][1].

60 leds/m for 3M = 180 leds.
24bit data per LED.

180*24 = 4320 bits of data.

One bit takes around 1,3uS, so 4320*1,3 = 5616 uS
Which is 5,616 milliseconds to update the LED strip. (Processor Mhz won't help you here)

**Sample calculation for DotStar (APA102)**

180 leds, 32bit per LED = 5.760 bits total.
+64 bits (32bit start frame, 32bit end frame).
5824 total bits.

You can set the SPI clock divider to 2.
So if your board runs at 16Mhz, divided by 2, you get 8Mhz SPI output.

> 8 megahertz = 8 000 000 hertz

(EDIT)
> The fastest rate is "divide by 2" or one SPI clock pulse every 125 nS. - Nick Gammon (http://www.gammon.com.au/spi)

Neopixels take 0.85us + 0.4us = 1,25 us (1250ns).
So they would be 10x slower.

(never mind this calculation, it was from before using Nicks' facts)

    8.000.000  |  5824
     1 sec     |   x

(Your x value will be the time in seconds to update the DotStar strip with SPI@8Mhz)

**What was your point?**

After this you can check your baudrate + message length to see how long sending/receiving your message will take.

You can then reliably tell if you need 1, 8, 16 or 72Mhz.

I believe the DotStar led strips should be faster, but I haven't completely calculated it out. You could ask yourself if it's worth trying to omptimize that.

BUT, note that the DotStar/SPI led strip allows you to have "interrupts". Which means you can receive characters over the bluetooth while you're writing to the LED strip.

And, we're probably overthinking the situation. But it's better to overthink it using hard values :)

  [1]: http://c2.com/cgi/wiki?PrematureOptimization


body:
As was mentioned earlier about the DotStar LED strip/led

There is one thing missing in the calculation above. The End Frame shows as a 32 bit frame of all 1's. That is almost correct. The least obvious is that you need to add 1/2 of a bit for each led in the strip. This is due to the way that the clock is sent down the line. So the 180 led strip would require 90 bits in the End Frame. If you don't do this you will have some of the leds at the end that are not reacting correctly. I know this sounds strange, had me for a while (I use Raspberry Pi).

Also, I have seen where some have tested the SPI mode of sending the data down the line and managed to achieve about 16Mhz clock speeds. Great for POV display.

The DotStar don't require refreshment at all. Each LED has it's own PWM chip built in. They are more expensive than the Neopixel, so it depends on the application as to which is better for you. I loaded my string with colors and then disconnected the data lines (led strip on different power supply) and turned off my Pi. Yup, the DotStars stay as they are.

It has been said they are 'addressable' which is not truly accurate. When sending data, it is the first one, then the second and on. If you wanted, you can change only the first few. Odd hack. Just send the Start Frame (32 or more 0's) and start sending data to the first without affecting the rest of the strip. Note: you might have to account for the 1/2 bit clock loss. eg: 1 bit per 2 leds.

Here is a pretty good description of the DotStar functionality :
https://cpldcpu.com/2014/11/30/understanding-the-apa102-superled/

Here is a Youtube tutorial (2 short videos) that helped me quite a bit:
https://www.youtube.com/playlist?list=PLhXSL6B3uLd551fEQlQGd3LrhzvudKfJQ


message:
Arduino to Thingspeak using WiFly-RN171 (Firmware 4.0)

I am attempting to use an Arduino Uno+WiFly setup to send data to Thingspeak.
I have tried a few libraries by now. But nearly all of them don't have a working WebClient example (WebServer works fine).
I am using **Arduino 1.6.3 IDE** for Arduino UNO R3 + **Wifly-RN171 with Firmware 4.0**

The libraries I have tried (found through Google and forums):

 1. https://github.com/sparkfun/WiFly-Shield/tree/master/Libraries/Arduino

    A ThingSpeak example is given but the execution stops when WiFly.begin() is called.
I tried WebClient and WebClient(Faster) examples from the same library and they are both stuck at the same line: WiFly.begin().

I believe this could be compatibility issue (WiFly firmware version/Arduino) but am unsure how to fix it.

**Note:** There seems to be a few versions for the SparkFun WiFly library from my search results. I tried whatever I found but only listed the latest one since if it is indeed a compatibility issue a newer version should be more likely to work.

 2. https://github.com/Seeed-Studio/WiFi_Shield

   This one has a http example which I am attempting to use to send data to Thingspeak through http get/post. I am getting 'Bad Request' from their nginx server. Any help in the right direction will be much appreciated.

I hosted the sketch I tried here: codebender.cc/sketch:276925

p.s. I am not allowed to post >2 links due to reputation so the last one is plain text.

p.s.s Can someone with higher reputation help me add the new tags {thingspeak, wifly, rn171}

body:
I solved my problem by sending a GET request to a hosted PHP script which in turn updates Carriots by means of a Curl request.

**My PHP Script**

    <?php
    $humidity=$_GET['humidity'];
    $data = array("protocol"=>"v2", //Compose JSON stream
                  "at"=> "now",
                  "device"=>"DEVICE_NAME",
                  "data" => array ("humidity" => trim($humidity)),
                  "checksum" => "");
    $data_string = json_encode($data);

    $ch = curl_init('https://api.carriots.com/status'); //Compose the HTTP request
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json',
        'carriots.apikey: YOUR_API_KEY',
        'Content-Length: ' . strlen($data_string))
    );

    $result = curl_exec($ch); //Send the stream

**Note**:

 1. I switched to Carriots from ThingSpeak due to personal preference.
 2. This is by no means a standard way to send stream to Carriots.This
    involves additional effort which slows down transmission of data but
    I decided that this setup will be enough for a hobby project.
 3. A good understanding of how POST requests are built should allow me
    to skip the extra PHP script completely.


message:
How do we connect 2 FSR sensors to an Arduino Mega?

One can connect an FSR sensor (a [force-sensitive resistor](https://learn.adafruit.com/force-sensitive-resistor-fsr/overview)) to an Arduino via 5V, Gnd,  and A0 port (as below, according to [an adafruit.com page](https://learn.adafruit.com/force-sensitive-resistor-fsr/using-an-fsr)), but how will it work for two of them instead of one?

[![FSR circuit][1]][1]

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

body:
Attach the second FSR mostly the same as the first, but connect the second analog voltage to A1 instead of to A0.

You can use several copies of  the circuit (below left) with each circuit's analog voltage going to a different analog-converter input (A0, A1, A2, ...).
[![circuit + breadboard + avrisp pinout][1]][1]

To connect up multiple 5V and ground connections, you can:

•  use almost any popular shield
•  use breadboards like those illustrated above
•  cut and solder Dupont cables to add extra pins or sockets in or out (for example, cut two M-F Duponts in half, and connect both F halves to one M half)
•  connect to the extra 5V and Gnd pins on Uno or Mega boards.  (On a Mega, besides 5V and Gnd pins on programming headers, there are two 5V sockets next to 22 and 23, and two Gnds next to 52 and 53.)

The diagrams above right show the location of the 5V pins on the programming headers found on the Uno.  Most Arduino boards have at least one AVRISP header like that.

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


message:
How can we replace a 10k potentiometer with resistors?

I am using an LCD (16x2) with an Arduino Uno R3, in for that I need a 10 kΩ potentiometer, but I don't have it now. How can I replace that?

I have resistors of many kinds and a 1 kΩ potentiometer.

body:
Try using 9k~1k. (It worked for my 16*2 LCD)

Or place 9k in series with 1K and vary that.

Connect 10 of your 1K resistors in series. Connect one end to GND and other end to VCC. Now, you will have 10 different nodes (including VCC and GND) each having a different voltage. Connect your desired input pin to any of those nodes.


body: Just use your 1k pot in place of the 10k pot. The resistance doesn't matter that much (though you don't want to go loo low or you could draw too much current) since it is just being used as a voltage divider to set an offset point for the LCD.


body:
Derived from Ohm's Law:

 - R = R1 + R2 + ... + Rn (For resistors in Series)
 - (1/R) = (1/R1) + (1/R2) + ... + (1/Rn) (For resistors in Parallel)

----------
You can use any resistance from 1k to 10k with your LCD but the actual value depends on your choice and preferences. You may start with 5k and if you have one then its allright. But if you do not have a resistor of that value you can join resistors of lower values in **series** with your 1k POT to get resistance of 5k ~ 6k.

In such a way you may get a variable resistance (1k pot) with a suitably high value (other resistors in series). If you wish, you may add more resistors to get higher values like 8k ~ 9k and so on.


message:
Is cheap away arduino trustworthy

I have recently decided to buy an arduino over a raspberri pi and have been shopping for a good deal and learning about which model I need and where to buy.

I have come across a few very cheap arduino uno boards that are identical to every other board. These range from an unbelievable $4-$15. Are they officially branded and/or are they trustworthy?

Here is a link to a few links to some I've found:

http://m.ebay.com/itm/New-UNO-R3-ATmega328P-Development-Board-For-Arduino-Compatible-USB-Cable-DIY-/311418263595?nav=SEARCH

http://m.ebay.com/itm/NEW-UNO-R3-ATmega328P-CH340-Mini-USB-Board-for-Compatible-Arduino-WL-/161883302204?nav=SEARCH

body:
Caveat Emptor.

If it's not genuine you can never be sure quite what you are getting. You have to ask with some of then just how they can make them so cheap. Poor quality components is one way. Either counterfeit or reject components which may fail after a short time, or under certain conditions is a big risk.

There are different grades of board each with their own risks...

1. Genuine. High price, good reliability and quality. Good after sales support. Supports the Arduino cause.
2. Arduino clone. Genuine Arduino design made by a reputable third party. Almost as good as option 1 but doesn't support Arduino financially.
3. Arduino Based. A board created for a specific job that is based around genuine Arduino design. Support really only from the (often smaller) manufacturer. Quality varies.
4. Chinese clone. Low grade components made to original Arduino designs. Little or no support. Poor quality. Often with different USB interface that is unstable and low quality.
5. Counterfeit. Low quality components. Claims to be a genuine Arduino. Bad build quality.

Options 1-3 are ones I would consider buying. 4 and 5 I would stay well away from.


body:
How many Arduinos do you need? If you are just getting one to learn on, for heaven's sake pay the extra fifteen bucks and support the cause.

If you are manufacturing something and need a few dozen boards, buy 50 Chinese ones and chuck the ones that don't work.


body:
While, yes, caveat emptor, I have purchased a number of devices which are based on the Arduino open design. I have not yet had a problem.

Remember that, if you buy more expensive, prominently "Arduino" branded parts, from a third party, you also have no guarantee that they are quality controlled by Arduino. Even "genuine" electronics parts are usually manufactured in China, often in the same factories.

To answer your question, there are a number of ways the costs can be kept down:

Lack of unions, lack of labor laws, economies of scale, markup by the "official" companies, lack of development costs (remember, Arduino is open hardware, copying is allowed), cheap labor, tax, transport costs (there is some trickery in some countries, including Hong Kong, which makes shipping essentially free), shorter supply chain, cheaper components, smaller marketing budget.


message:
Arduino countdown timer preventing rest of program running

have a program that checks to see if an RFID tag has been read, if it has, it runs some code.

I also have a count down timer function (timer) that I'd like to run in the background. It displays the clock on the bottom of the LCD.

The problem I'm having is that when I put timer(); in the main loop, the rest of the program is delayed for the duration of the count down which means that no RFID cards are read.

The timer works, but nothing below timer(); is running. I assume this is because of the use of delay.

Does anyone know how I can prevent this? Thank you.

        #include <SPI.h>
    #include <MFRC522.h>
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    int readflag;
    int initstate = 1;

    int nextred = 4;
    int nextblue = 8;

    uint8_t readCard[4];

    int minutes = 1; //start min
    int seconds = 0; //start seconds

    MFRC522 mfrc522(10, 9);
    LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

    ///////////////////////////////////////// Setup ///////////////////////////////////
    void setup() {

        //Protocol Configuration
      Serial.begin(9600);
      SPI.begin();
      mfrc522.PCD_Init();
      mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);

      lcd.begin(20, 4);

    }

    ///////////////////////////////////////////////////////////////////////////////
      // Main loop
    ///////////////////////////////////////////////////////////////////////////////
    void loop () {

     do {
       readflag = checkread();
    if (initstate == 0) {
      timer(); //start timer - timer works but nothing below timer(); is running.
       lcd.setCursor(0,0);
       lcd.print("Red team next: ");
       lcd.print(nextred);
        lcd.setCursor(0,1);
        lcd.print("Blue team next: ");
        lcd.print(nextblue);

    }
      }
      while (!readflag);
      tone(8, 850, 15);
      recordid();
      updatenextteamnumbers();
    }

    ///////////////////////////////////////////////////////////////////////////////
      // Function to update team next numbers
    ///////////////////////////////////////////////////////////////////////////////
    void updatenextteamnumbers() {
    //If Blue Tag scanned show team info
      if (*((uint32_t *)readCard) == 0xACB7D573) {

        Serial.println("Blue Tag detected, showing team info");
        initstate=0;

       }

    //Red Team (sequence 4, 5, 2, 1, 9)
    else if (*((uint32_t *)readCard) == 0x29FDC9F5 && initstate == 0) {
        Serial.println("CARD 4 detected");
        nextred = 5;

          }

    else if (*((uint32_t *)readCard) == 0x3FCE7832 && initstate == 0) {

        Serial.println("CARD 5 detected");
        nextred = 2;

    }

    else if (*((uint32_t *)readCard) == 0x3FCCECE2 && initstate == 0) {

        Serial.println("CARD 2 detected");
        nextred = 1;

          }

      else if (*((uint32_t *)readCard) == 0x3F7AB752 && initstate == 0) {

        Serial.println("CARD 1 detected");
        nextred = 9;

        //activateredrelay

          }

      else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

        Serial.println("CARD 9 detected");
        redwins();

          }

    //Blue Team (sequence 8, 6, 3, 7, 10)

    else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {
        Serial.println("CARD 8 detected");
        nextblue = 6;

          }

    else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

        Serial.println("CARD 6 detected");
        nextblue = 3;

    }

    else if (*((uint32_t *)readCard) == 0x3F7ABA82 && initstate == 0) {

        Serial.println("CARD 3 detected");
        nextblue = 7;

          }

      else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

        Serial.println("CARD 7 detected");
        nextblue = 10;

        //activatebluerelay

          }

      else if (*((uint32_t *)readCard) == 0x00000000 && initstate == 0) {

        Serial.println("CARD 10 detected");
        bluewins();

          }

     }

    ///////////////////////////////////////////////////////////////////////////////
      // Stores the ID of the card that's been detected in readCard byte array
    ///////////////////////////////////////////////////////////////////////////////
    void recordid() {
        mfrc522.PICC_IsNewCardPresent();
        mfrc522.PICC_ReadCardSerial();

        for (int i = 0; i < mfrc522.uid.size; i++) {
            readCard[i] = mfrc522.uid.uidByte[i];
            Serial.print(mfrc522.uid.uidByte[i], HEX);
            }
    Serial.println("");
        mfrc522.PICC_HaltA();
      }

    /////////////////////////////////////////////
      // Returns 1 if a card has been detected
    /////////////////////////////////////////////
    int checkread() {
       if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return 0; }                                        //no card detected

        mfrc522.PICC_HaltA();
        return 1; }                                       //card detected

    /////////////////////////////////////////////
      // Runs if red team wins
    /////////////////////////////////////////////
    void redwins() {
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Red team wins!");
          lcd.display();
          Serial.println("Red team wins!");
          delay(36000);
    }

     /////////////////////////////////////////////
      // Runs if blue team wins
    /////////////////////////////////////////////
    void bluewins() {
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Blue team wins!");
          lcd.display();
          Serial.println("Blue team wins!");
          delay(36000);
    }

     /////////////////////////////////////////////
      // Count down timer
    /////////////////////////////////////////////
    void timer() {
    lcd.setCursor(0,3);
      lcd.print("Time left:");
     while (minutes > 0 || seconds >= 0) {
      lcd.setCursor(15, 3);
     (minutes < 10) ? lcd.print("0") : NULL;
     lcd.print(minutes);
     lcd.print(":");
     (seconds < 10) ? lcd.print("0") : NULL;
     lcd.print(seconds);
     lcd.display();
     decrement();
     delay(1000);
     }
    }

     /////////////////////////////////////////////
      // Decrement timer
    /////////////////////////////////////////////
    void decrement() {
          if (seconds > 0) {
              seconds -= 1;
          }
          else      {
             if (minutes > 0) {
               seconds = 59;
               minutes -= 1;
              }
              else  {
                timeup();
              }
           }
    }

     /////////////////////////////////////////////
      // Called when time expires
    /////////////////////////////////////////////
    void timeup() {
          lcd.clear();
          lcd.setCursor(0,0);
          lcd.print("Time up!");
          lcd.display();
    }

body:
Of course not - your timer() function is **blocking** meaning that it does not return, and so does not permit anything else to execute, until its timing is completely done.

You will need to re-design your program.  Some options include:

1) Capturing an initial timestamp from millis() and comparing to it on each iteration through loop() to decide when your time has approximately elapsed, and to update the display with an appropriate value if that point is not yet reached. This is probably the best choice for your application, but be aware that after about 50 days of uptime, the difference calculation can be briefly incorrect, unless you account for overflow.

2) Place a short delay in the main loop (maybe 100 ms), and count iterations of the main loop until you have reached your desired time.  Beware though that your effective time will become longer if other parts of the loop take time (especially variable amounts of it) to execute.

3) Set up an event timer in the background with interrupts.  This is a lot more complex and probably not advisable in your application.


message:
How do I use an AtTiny85 (or other AtTiny) with Arduino?

*Please mind that this is an "example" question.*

**How to make a "tiny arduino"?**

I've ordered a bunch of ATtiny85's off E-bay, they're like tiny Arduino's.

I've set up the [latest Arduino IDE][1] and would like to run the [blink example][2].

My process so far:

**Wiring**

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

**Code**

(The blink example)

    // the setup function runs once when you press reset or power the board
    void setup() {
      // initialize digital pin 13 as an output.
      pinMode(13, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
      delay(1000);              // wait for a second
      digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
      delay(1000);              // wait for a second
    }

  [1]: https://www.arduino.cc/en/Main/Software
  [2]: https://www.arduino.cc/en/Tutorial/Blink
  [3]: https://i.stack.imgur.com/X5RjA.png

body:
**1. The Tiny**

The ATtiny differs a little from the Arduino, don't expect it to be "fully compatible". It's a microcontroller which is just a part of an Arduino and not a full Arduino itself.

It's more of a device for "advanced users" and gives some more flexibility (at cost of usability). You can easily add this microcontroller on a breadboard, since putting a full Arduino on a breadboard makes little sense.

***1.1 USB?***

Since the ATtiny is a microcontroller (like the ATmega on an Arduino) and not a development board (as an Arduino), it does not have an USB connector.
The ATtiny series also does not have hardwareUART (Rx/Tx). The

You'll have to take care for a steady power-supply to your Microcontroller and the programming will be a little more tricky (details further below).
It is however possible to use `SoftwareSerial` and a customized bootloader. My ATtiny85 runs software serial with 115200 fine, though I have found a post which states that the internal oscillator [should be tuned][1] for a reliable connection.

***1.2 RAM/program memory***

The ATtiny has less RAM and program memory. This essentially means your program can't be as 'big' as on a normal Arduino. It also means that you can't use as much variables. A program for the tiny should be "small" or very efficient.

***1.3 "Speed"***

My ATtiny came with 1Mhz internal clock set, but if you change the fuse bits you can make it run at 8Mhz. An standard Arduino has a 16Mhz clock on the board. So your code would run 16x slower on default and 2x slower on "max". You could use an external clock for the ATtiny, but that eats up 2 pins.
The cool thing is, when you set it to 1Mhz it can run on about 2.7V (check datasheet first).

    Arduino                   16Mhz
    ATtiny (standard)         1Mhz
    ATtiny (set fuses)        8Mhz
    ATtiny (external crystal) up to 20Mhz

Higher Mhz is faster. Keep in mind that 1Mhz is roughly 1000000 instructions per second, which is still blazingly fast and good enough for most occasions, especially on such a tiny device.

**2. Programming the Tiny**

Most of the ATtiny's don't come with a customized (software serial) Arduino bootloader. This essentially means that you have to burn a custom bootloader by yourself or use another type of programmer. You should really watch [the video][2] from Ben Heck. He explains that Arduino boards have an USB converter on board and have custom code that is able to "bootload" your Arduino. But that ICSP/ISP programmers are used to upload programs without a bootloader/uart connection.

***2.1 The programmer***

You've got a load of options, check the "Programmer" item in the "tools" tab in your Arduino IDE. I'm using an USBasp which can be bought on [ebay for as little as 3€][3]. You should get one that has a selectable voltage (3.3V and 5V).

(If your ATtiny85 already has the bootloader, which is unlikely, you can use the software rx/tx pins for uploading)

***2.2 Preparation***

Check your microcontroller if it really is a ATtiny85 my E-bay reseller actually had one ATtiny45 included, which lead to an "error" when trying to upload.

The Arduino IDE does not know the "ATtiny board" so you can't select it easily. You'll have to let the IDE know that the ATtiny can also be programmed.

I found a very [nice tutorial][4] that describes how to do this.

> 1. Open the preferences dialog in the Arduino software. Find the
> “Additional Boards Manager URLs” field near the bottom of the dialog.
> 2. Paste the following URL into the field (use a comma to separate it from any URLs you’ve already added):
> https://raw.githubusercontent.com/damellis/attiny/ide-1.6.x-boards-manager/package_damellis_attiny_index.json
> 3. Click the OK button to save your updated preferences.
> 4. Open the boards manager in the “Tools > Board” menu.
> 5. Scroll to the bottom of the list; you should see an entry for “ATtiny”.
> 6. Click on the ATtiny entry. An install button should appear.
> 7. Click the install button. The word “installed” should now appear next to the title of the ATtiny entry.
> 8. Close the boards manager. You should now see an entry for ATtiny in the “Tools > Board” menu.

***2.3 Changing the internal clock***

Some [interesting post I found][5] told me that you can change the internal clock/oscillator to 8Mhz by selecting 8Mhz (internal) as the clock and pressing the "Burn bootloader" button. This won't flash a bootloader (since that makes little sense on a Tiny85) but does change the fuse-bits.

***2.4 Code***

You'll not get away with the standard blink tutorial. It uses digital pin 13 (the tiny only has 8 pins).

Mind that you might have to upload using Ctrl+Shift+U (or sketch->Upload with programmer).

I used the diagram below to check the pins (from highlowtech.org)
[![enter image description here][6]][6]
[![enter image description here][7]][7]

**3. Hardware**

Your "schematic" isn't complete, I don't see a way to program or power the microcontroller. And you might want to take some precautions.

I personally think a well-drawn schematic looks better as a "breadboard view".

[![enter image description here][8]][8]

The 10Kohm pull-up resistor on the reset pin is not 100% neccesary according to [the datasheet][9]. But the Uno has one in it's reference design (which I use as a reference).

There are two capacitors, one "big" capacitor as a reservoir. If one device suddenly pulls a lot of current, this capacitor will handle that. The smaller decoupling capacitor will damp the noise of other IC's or switching supplies. It may work withouth these, but your circuit will be more reliable with them.
Mind that the decoupling capacitor should be (physically) close to the IC.

You can power the board through the programming header, but mind that you'll need a smooth voltage between (most likely) 3.3V and 5V. If you want to power it with a bigger voltage (9V battery) then you'll need a voltage regulator.

  [1]: http://www.ernstc.dk/arduino/tinycom.html
  [2]: https://youtu.be/ncobWc61wL4
  [3]: http://www.ebay.nl/itm/USBASP-USBISP-3-3V-5V-AVR-Programmer-USB-ATMEGA8-/261021924011
  [4]: http://highlowtech.org/?p=1695
  [5]: http://forum.arduino.cc/index.php?topic=85033.0
  [6]: https://i.stack.imgur.com/kIjxX.png
  [7]: https://i.stack.imgur.com/GT4rK.png
  [8]: https://i.stack.imgur.com/4uKJR.png
  [9]: http://forum.arduino.cc/index.php?topic=20219.0


message:
What minimal resistance should be between an input and output pin not to burn Arduino?

So, I'd like to put a button between input and output pins to read when button is pressed. What minimal resistance should I add to the scheme not to burn Arduino when the button is pressed? Does this value depend on Arduino model?

body:
Looking towards the high end of recommended (vs absolute maximum) current and considering Ohm's law at a 5v difference if two outputs are trying to drive each other to opposite values, you would probably get away with as little as 250 ohms.  But in most cases that would needlessly waste power, and in the case of multiple instance you could start totaling towards the limit of power supply current for the chip overall.

Typical values for external pull up resistors are more in the range of 1K-10K though higher is not uncommon - the internal pullup which you can optionally activate by setting the output state of an *input* pin high has a value of several tens of kilo ohms.  Lower values will consume more power, higher values may be less reliable in a noisy situation.


body:
To read a button, normally you hook one end of the button to ground and one end to a pin in INPUT_PULLUP mode. Normally the pin reads 'high' because it is connected to +5v with a biggish resistor inside the arduino. When you press the button, it shorts out to ground and the input reads 'low'. The chip already has suitable resistors in it to handle this, and you don't need to worry about it. Just connect one end of your button the the pin, the other to the chassis, INPUT_PULLUP and away you go.

Output pins should have no less than 250Ω on them.

Beats me why you are thinking of connecting an output pin and an input pin together.


message:
Is that correct that input and output pins are not supposed to have current through them?

Are input and output pins not supposed to have current through them and only either apply voltage or "measure" it?

body:
An output pin (on an AVR 8-bit board like an Arduino Uno) can pass up to 40mA (*absolute maximum*). It is recommended not to exceed 25mA.  This is called *sinking current* when the output pin is set to LOW, and *sourcing current* when it is set to HIGH.

An input pin is what is known as *high impedance*. I.e., it looks, to the circuit connected to the pin, like an incredibly high value resistor connected between the input and ground. Because of that only very tiny currents will ever flow through it (unless you do something silly like plug it direct into the mains).


body:
First, you can not apply a voltage to or with an I/O pin connected to a circuit, and have no current flow as a result. There is a limit to the current a given pin on a given device can pass without damage and that is specified in the device's datasheet. How much current a given pin and circuit will pass or try to pass depends on the external circuit and the circuit internal to the device. Majenko's answer (except possibly for the specific limits, depending on the device) is correct.

You haven't specified what device. Is this a generic question or is it specific to the AVR micro-controllers used in most Arduino boards? If the latter, the limits in @Majenko's answer are also correct.


body:
What everyone else said.

It's difficult to measure voltage without taking at least a tiny trickle of current, and that's what input pins do.

Anything that is driven needs current to drive it (power = current * voltage). However, an arduino pin - as someone mentioned - should only ever be used to supply about 25mA. Drawing a heavier current than that can fry the chip.

V=IR, so, the resistance on an output pin should be no less than 200 ohms, hence the 330 ohm current-limiting resistor you put on an LED. Power is IV, so the maximum power you can safely get get is 125mW (oh, you can get more - but you may fry your chip). This translates directly into the maximum safe brightness of a LED, the strength*speed of a motor, the loudness of a buzzer powered by an output pin.

Another big thing when trying to drive coils (motors, solenoids, relays) is that when you switch off the power to a coil, it generates a spike of voltage going the other way. This spike also can fry the chip. This is why relay shields are a thing - they contain electronics to deal with this back-emf. If you want to drive a motor and don't want to buy a shield, look into darlington array chips. I used one to run a stepper - worked perfectly.

So.

* Inputs in theory need almost no current - but they do need that tiny trickle.
* Outputs must have current to do any work. The amount you can get off the board without frying it is limited.


message:
Signal pin of buzzer is connected with which Arduino uno pin

I bought a 3 pin buzzer. It has positive, negative and signal pin.

I don't understand how this signal pin should be connected with the Arduino.

[Here][1] is reported the description page of the buzzer.

  [1]: https://www.techshopbd.com/product-categories/modules-98775/1690/digital-buzzer-module-techshop-bangladesh

body:
As I have read in the page you have linked, I think you should program the Arduino to provide an impulse to the signal (`s`) pin.

Therefore, to answer your question you can use any digital pin of the Arduino. And I guess that as long as the impulse last as long as the buzzer will produce a sound.

Here an example of code:

    int buzzPin =  2;    //Connect Buzzer on Digital Pin3
    void setup()
    {
     pinMode(buzzPin, OUTPUT);
    }
     void loop()
    {
     digitalWrite(buzzPin, HIGH);
     delayMicroseconds(50);
     digitalWrite(buzzPin, LOW);
     delayMicroseconds(50);
    }


body:
Usually a buzzer only has two wires, positive and negative. The module you have bought though uses a transistor to drive the buzzer, which is a nice thing for very low power boards, which is not your case I believe.

Anyway, the module will take power from the positive and negative connections, allowing you to control it via the signal, from which very little power is drained.

How does a buzzer work? Actually to emit a sound via a buzzer you have to send a series of electrical pulses to the signal pin. The number of pulses per second (frequency, expressed in hertz, Hz) will determine the tone of the sound. higher the frequency, higher the pitch of the sound emitted.

Human ear is capable to detect frequencies between 20 and 20000Hz, but not everybody has such a broad perception, it decreases with age and not everybody is born with full range, so I advice to stay in the 2000-15000Hz range.

There is a nice library called [Tone][1] which helps you generate the correct signal for specific notes, allowing to even play some music via the buzzer (don't expect polyphony though!)

So, to play a note on your buzzer, assuming you have the buzzer signal pin tied to digital pin 6, you can just:

    void setup() { /* empty */ }

    void loop() {
        noTone(6);
        // play a note on pin 6 for 200 ms:
        tone(6, 440, 200);
        delay(200);
    }

Also have a look at [ToneMelody][2] if you wish to emit specific notes (each note has its own particular frequency)

  [1]: https://www.arduino.cc/en/Reference/Tone
  [2]: https://www.arduino.cc/en/Tutorial/ToneMelody


message:
Flickering LCD backlight with fingerprint scanner

I have the following problem: for some *** reason, my LCD is flashing when my fingerprint scanner turns on. Here is a video of the behavior: https://www.dropbox.com/s/mqk4u0vu8yvhiwz/IMG_3171.m4v?dl=0.

More details: I have a membrane keypad. When I start typing on it, the LCD turns on, and when I type the correct code, the fingerprint scanner turns on, and the LCD prompts the user to press a finger upon the scanner. However, then the LCD backlight starts flashing badly. Interestingly, if I just plug the wall adapter into the arduino and try the scenario, the LCD does not flash. However, if let's say 10-15 have passed since the adapter is plugged in, the LCD flickering becomes visible and irritating (again, when the fingerprint scanner is turned on). So, what could be the reason and how to fix it? Why if I just plug the adapter and execute the scenario, the LCD does not flash, and if I wait some time with the adapter plugged in, and then execute the scenario, the LCD flickers?

Just to add: My fingerprint scanner is GT511C1R (https://www.sparkfun.com/products/13007) and I am using the standard scheme for wiring it (560/1000 ohm for the RX). I am not using lcd.clear() command as I know it's heavy, and even if I don't write any text, the still LCD flickers.

Best regards,
Nike

body:
The backlights on these LCDs are just an LED array with a series resistor so the intensity will be directly proportional to the input voltage; flickering voltage = flickering backlight.

Check these things:

1.  Measure the output of the 5V regulator with an AC volt meter to see if the regulator is oscillating when the backlight flickers, i.e. AC voltage >> 0V.  If it is, then you probably need to increase the size of the output and possibly the input capacitors.

2.  Measure the Input-to-Output voltage differential of the regulator and multiply it by the output current.  If you dissipate more power than the thermal design allows this will heat the regulator making (1) more likely as well as driving the regulator into thermal shutdown.

If the regulator is linear, i.e. 7805 etc, you can solve both (1) and (2) by changing the regulator to a drop in switching type.  These will dissipate heat as a percentage of the output power instead of as a function of the input voltage and can be made self contained with regard to input/output capacitors which would be on-board instead of off-board.  A switcher can also do something a linear can't do:  Supply more current than the source.  A 12V 0.5A power supply into a 5V regulator can supply 5V at 0.5A with 3.5 watts of waste heat.  That same 12V supply into a decent switcher can deliver 1.14A at 5V with only 300mW of waste heat!

[This PDF][1] is an example circuit that runs about 95% efficient and fits on a 7805 footprint.

[This PDF][2] is the circuit of the 1516 switcher linked above configured to replace the NCP1117 linear regulator use on the Uno Rev3.

[This PDF][3] is a full thermal analysis of the Arduino Uno NCP1117 regulator running under the conditions stated in your question.  As you can see, you were right on the edge of what the NCP1117 could handle at 200mA (LCD plus scanner).  I have included a thermograph showing the same unit supplying 1.85A at 5V using a drop in switching regulator with no issues.

  [1]: http://ppl.ug/5iRK2MJOIPk/
  [2]: http://ppl.ug/tia-wJs1_Gg/
  [3]: http://ppl.ug/EvIVf5q4K3Y/


body:
A huge thanks for your detailed replies! They lead me into the very right direction. So here is what was it: As I mentioned, the situation gets worse as more time passes with the 12v jack plugged in. At the same time, the regulator was getting damn hot, I could not stick my fingers to it for more than half a second. So, I kind of did what you recommended - got a regulator and put down the voltage to 7V (with 5V the display did not want to show any text). With 7V the regulator is still getting warm, but even if I left it for 10 minutes running it's not getting hot any further further. The display - it's flickering very little and only if you look at it at a specific angle, but it's not flickering overall if you look straight at it. Interestingly, I also took a look at the schemes of the display and the fingerprint scanner and it sounds like it would not be possible for the arduino to feed these two. But, the whole project is running flawlessly (at least looks so). I just hope that math equations in regards to the mA would not cause harm to the fingerprint scanner or the arduino.

So, thanks again, for your kind and detailed replies, much appreciated.

All the best,
Nike