body:
I am trying to communicate between HM-10 module (without any breadboard or soldering) and experience problem with reading data from serial.

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

    #define TO_HEX(i) (i <= 9 ? '0' + i : 'A' - 10 + i)

    void afterSetup() {
      Serial3.write("AT+NAME?");
      delay(500);
    }

    void setup() {
      // initialize both serial ports:
      Serial.begin(9600);

      /*Serial3.begin(115200);  // The Bluetooth Mate defaults to 115200bps
      delay(100);  // Short delay, wait for the Mate to send back CMD
      Serial3.println("U,9600,N");  // Temporarily Change the baudrate to 9600, no parity
      // 115200 can be too fast at times for NewSoftSerial to relay the data reliably*/
      Serial3.begin(9600);  // Start bluetooth serial at 9600

      Serial.write("\n\n\n==== START ====\n");

      afterSetup();
    }

    unsigned char mode = 2;

    void wr(HardwareSerial*, int);

    void wr(HardwareSerial *target, int bt, unsigned char mode) {
        //target->write(TO_HEX(((bt & 0xF000) >> 12 )));
        //target->write(TO_HEX(((bt & 0x0F00) >> 8 )));
        if(mode > 0) {
          target->write("\t\t\t\t");
        }
        target->write(TO_HEX(((bt & 0x00F0) >> 4 )));
        target->write(TO_HEX((bt & 0x000F)));
        target->write(" (");
        target->write(bt);
        target->write(")\n");
        return;
    }

    void loop() {

      // read from port 1, send to port 0:
      if (Serial3.available()) {
        int inByte = Serial3.read();

        if(mode != 1) {
          mode = 1;
        }

        wr(&Serial, inByte, 1);
      }

      // read from port 0, send to port 1:
      if (Serial.available()) {
        int inByte = Serial.read();
        Serial3.print((char)inByte);

        if(mode != 0) {
          mode = 0;
        }

        wr(&Serial, inByte, 0);
      }
    }

Wiring is simple:

    HM-10    | due
    -------------------
    RX       | TX3
    TX       | RX3
    VCC      | 3V3
    GND      | GND

Basically, I am able to get data from serial, but it **corrupted**.

Here is an example:

- Command: AT+NAME?
- Expected: HMSoft
- Response:

                28 (()
    25 (%)
    2A (*)
    35 (5)
    15 ()
    FE (�)

And another, simpler:

- Command:  AT
- Expected: OK
- Response: F5

What am I doing wrong?

title: HM-10 and Arduino Due

Answers: 0


body:
here is a very simple circuit, with a LED between pin 2 and ground, and a loose wire in pin 8.

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

Here is the sketch that was intended for use with a small 4-contact switch like these in every arduino starter kit :

    int yellowCIn = 8;
    int yellowCOut = 2;

    void setup() {
      pinMode(yellowCIn, INPUT);
      pinMode(yellowCOut, OUTPUT);
    }

    void loop() {
      if (digitalRead(yellowCIn) == HIGH) {
      digitalWrite(yellowCOut, HIGH);
      }
      else {
        digitalWrite(yellowCOut, LOW);
      }
    }

However, simply moving my hand near the loose white wire is enough to light the LED, moving it away to put it off. As I am writing this, with the arduino connected by usb, rather than on the blue battery visible in the picture, I notice moving my hands away from the keyboard lights the led, moving them close to the keyboard powers it off...

So back to my title : are my hands magic, my electronics competency crap (well, it is, for sure) enough that I never heard of such a tremendous static electricity effect (and never fried one of the many computers I built from parts), or does this board have dire problems?

Thanks for your attention :)

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

title: Proximity sensor without proximity sensor; is my hand magic, my competency crap, or my arduino fried?

Answers: 2

body:
Try configuring your input pin as INPUT_PULLUP instead. This connects an internal pullup resistor to stop the input value from drifting around.

I would only use the "INPUT" mode on its own if I have that pin wired to something on the board and the levels won't be erratic.

Your hands are magic - they pick up interference from various sources and the high impedance input of the chip pick this up...

(There's a bit more on the modes here: [Arduino DigitalPins page][1])

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

body:
Nothing's broken; you have discovered  the nature of a floating pin.  Unfortunately, that means that strange things happen...

A very small charge from your hand is triggering the logic because the state of the pin (high or low) is not set.  To fix this, you need to add a [pull-up or pull-down resistor][1] (or activate the internal [input-pullup resistor][2]).

You can read about how to accomplish this [here][3].

  [1]: http://playground.arduino.cc/CommonTopics/PullUpDownResistor
  [2]: https://www.arduino.cc/en/Reference/PinMode
  [3]: https://learn.sparkfun.com/tutorials/pull-up-resistors


body:
I have a GSM shield connected with my Intel Galileo board.

I intend to connect the board with serial communication at a baud rate of 115200 instead of the GSM library. I want to print the results of "at" commands in my serial window, how should I do it?

title: Print the response from GSM shield

Answers: 1

body:
I have only worked with the SIMCOM series of GSM modules like the SIM900 and the SIM808. Here is a sample of the kind of code you should be looking at using.
It will send one "AT" to the GSM module and then it will spit out the result in the serial monitor.

    void setup()
    {
      Serial.begin(115200);
      int bytesSent = Serial.write(“AT\r\n”); //send "AT" and send the end of line characters to signify end of the command
     }

     void loop()
    {
       if (Serial.available() > 0) {
                // read the incoming byte:
                incomingByte = Serial.read();
        }
    }


body:
I have just programmed a new micro, loaded the basic blink code in it. After that neither my laptop, nor my desktop sees it anyway with the following usb error:

    Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:01 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
    [Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:02 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:02 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
    [Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
    [Fri Apr  1 14:32:03 2016] usb 1-2: reset full-speed USB device number 8 using ohci_hcd
    [Fri Apr  1 14:32:03 2016] usb 1-2: device not accepting address 8, error -62
    [Fri Apr  1 14:32:03 2016] usb 1-2: USB disconnect, device number 8
    [Fri Apr  1 14:32:03 2016] usb 1-2: new full-speed USB device number 9 using ohci_hcd
    [Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62
    [Fri Apr  1 14:32:04 2016] usb 1-2: device descriptor read/64, error -62

If I push the reset button on it it comes back a bit then disappears again:

    22620.495256] usb 1-2: New USB device found, idVendor=2341, idProduct=0037
    [22620.495263] usb 1-2: New USB device strings: Mfr=2, Product=1, SerialNumber=0
    [22620.495268] usb 1-2: Product: Arduino Micro
    [22620.495272] usb 1-2: Manufacturer: Arduino LLC
    [22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
    [22627.966141] usb 1-2: USB disconnect, device number 32
    [22628.432089] usb 1-2: new full-speed USB device number 33 using ohci_hcd
    [22628.572111] usb 1-2: device descriptor read/64, error -62

Anybody experienced this? I have tried to reconnect it multiple times to both computers, even tried a new cable doesn't help.

title: Arduino micro lost connection after first programming

Answers: 2

body:
The USB part of the Atmega32U4 needs quite a bit of software to operate correctly, which is either not included in the basic blinky example or you got a binary for a different Arduino model.

The syslog looks like there is a bootloader present after Reset for a couple of seconds..

    [22620.497393] cdc_acm 1-2:1.0: ttyACM0: USB ACM device
         ^
    [22627.966141] usb 1-2: USB disconnect, device number 32
         ^
.. which shuts down and starts blinky. This is documented on the [ArduinoBoardMicro] page.

Re-flashing the chip is a bit tricky in this state, as you must press the reset button at the "right" time just before the software wants to access the chip.

[ArduinoBoardMicro]: https://www.arduino.cc/en/Main/ArduinoBoardMicro

body:
> If I push the reset button on it it comes back a bit then disappears again:

That's exactly how it works. The Micro enumerates as a Serial interface for a couple of seconds after reset, enough time for you to upload a new sketch. If you don't upload in time, and unless your code specifies a serial port, the serial interface goes away. Blink doesn't use a serial port.

You need to quickly press and release Reset at the exact moment that the IDE says it is uploading, and the board should then detect the new sketch.


body:
I am trying to use map command which is used to power servo 180 degrees as the potentiometer moves...

 in fact what i want to do is just when i adjust my potentiometer to zero; stop the dc motor then after turn the pot to 512 analog value turn the motor to the left (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);)and then stop when it reach 512 then when adjust the pot back to zero turn the dc motor to the right (digitalWrite(I1, HIGH); digitalWrite(I2, LOW);) but the think is what i am trying to do is exactly what we can do with the servo motor in the knob http://www.arduino.cc/en/Tutorial/Knob

I'm using a normal DC motor and l293D IC but I want to control the DC as knob method like the 200 degrees.

**Code**

    #define E1 11    // Enable Pin for motor
    #define I1 10    // Control pin a for motor
    #define I2 9     // Control pin b for motor
    const int analogPin = A0;
    int analogValue ;

    void setup() {
      pinMode(E1, OUTPUT);
      pinMode(I1, OUTPUT);
      pinMode(I2, OUTPUT);

    }

    void loop() {

      int analogValue = analogRead(analogPin);

      if(analogValue > 0 && analogValue < 512)  {

      analogWrite(E1, 255);
      digitalWrite(I1, HIGH);
      digitalWrite(I2, LOW);
        delay(100);
    } else
      analogWrite(E1, 255);
      digitalWrite(I1, LOW);
      digitalWrite(I2, HIGH);
     }

title: Using map for DC motor instead of servo

Answers: 1

body:
It looks like you want to use the "analogValue" to control the direction and speed of your DC motor.  If this is correct consider using this:

          //This method assumes: The center position of the pot is the motor's 0 speed point,
          //(because this is an ideal speed to actually reverse the motor's direction).
          //A PWM control range of 0-255, and the ADC input range of 0-1023.

          //First create a relative speed value from "analogValue",
          //with the pot mid point at 0 speed, and pot high/low points being full speed.

          int motorSpeed = 0;
          if (analogValue < 512 )
          {
           motorSpeed = map(analogValue, 0, 511, 255, 0);
          }  //Note that mapped range is reversed to give 0 speed at mid point.
          else
          {
           motorSpeed = map(analogValue, 512, 1023, 0, 255);
          }

          //then replace each analogWrite(E1, 255) with:
          analogWrite(E1, speedValue);

          //you should also change "  if (analogValue > 2 && analogValue < 500) {  " to:
          if (analogValue < 512) {


body:
My [Adafruit 5V Trinket][1] works fine when powered via USB connected to my computer (and the power going in to the Trinket is 5V), but if I use a 9V wall adapter with a microUSB adapter, it just powers on but doesn't seem to actually run the program on the Trinket.

Am I _over_ powering the Trinket and sending too much voltage to everything? If that's the case, is there some way to decrease the voltage?

  [1]: https://learn.adafruit.com/introducing-trinket?view=all

title: Trinket works with USB but not with wall adapter

Answers: 1

body:
Yes, you are probably over-powering the trinket. The trinket expects 5V on the USB connector. However, it has an voltage regulator on board that can take up to 16V.

The BAT pin is connected to the voltage regulator and can take anywhere from 5.5V to 16V.


body:
This is the outline of my project:

 1. interpret environment data (sensor, motor, etc..).
 2. Modify this data into a more usable form,
 3. send it back to the same motor for further operation from modified data.

As an example (this is not the project, but just an example to make sure I am being clear).

A motor moves a conveyor belt with various size flasks on it, some large other small. Depending on the reading of the position of the motor (from encoder) another process (filling the flasks) will take place.  If the first motor encoder data indicated the flask was small then the amount of liquid poured will be small. If large, the amount of liquid dispensed will be large.

More generally, read the location of an item based on motor encoder feedback.  Modify this data. Send this modified data back to a different motor so that it does something specifically as a function of the first motor encoder data.

I am able to send the original encoder feedback to a file, manually massage it and paste it into an Arduino script, compile and have everything work great. I just want to remove the manual steps (cut & paste) and data massaging (I'm looking to an Arduino program to do that).

To further complicate things, I want this process to be part of a distributable package that does not require further compiling. Reading from a sim card is fine.  Also, I am not too price sensitive as the Arduino is a small portion of the total cost of the final product.

I hope someone can give me some insight or pathway to a solution.
All the very best, John.

title: Reading sensor data, massaging it and performing operation based on transformed data

Answers: 1

body:
Here's a back-of-envelope sketch, off the top of my head:

Conveyor belt driven by stepper motor, controlled by the Arduino.  Each step is a known distance.

Bottles are either of exactly two heights, at random.  Two [beam break sensors][1], one to determine where a bottle starts and one to determine whether it's tall or short.

Some sort of valve to control the water flow - I presume you have some idea how this can be controlled.  I don't, but washing machines have electrically-controlled valves so something broadly along those lines.  Controllable on/off by the Arduino.

Software on the Arduino steps the motor until it sees the start of a bottle (first beam broken).  Then uses second beam to determine whether the bottle is large or small.

Arduino switches on the water valve (outlet positioned exactly right to be above the bottle) for either 2s or 4s accoriding to bottle size, then off again.   (Water pressure and flow rate regulated independently, perhaps fed from a header tank).

Arduino steps motor more until it sees another bottle.

----------

No string concatenation in there, nor sorting of lists or need for a Raspberry Pi.  It's not clear to me why you'd need those things for the application described.

I'm not aware that you can program the Arduino in Python unfortunately.  Someone may know better.  C isn't hard though - get an Arduino and some LEDs or whatever, go through some tutorials, you'll get the hang of it.

  [1]: https://learn.adafruit.com/ir-breakbeam-sensors/overview


body:
I own a UDOO Quad board which features two CPUs (SAM3X8E like Arduino Due and a ARM Cortex-A9) connected with an internal OTG USB.

I am trying literally for months to use the USB Host Shield Library (https://github.com/felis/USB_Host_Shield_2.0/) in order to make the Due act as a USB host to the other CPU (which runs Android). The Due runs well a piece of code collecting some data every X milliseconds within a built-in timer's ISR.

What I want to achieve is to send this data collected by the ISR to the other CPU via the USB connection of the two; but there seems to be an issue with the Usb.Task() call. This Usb.Task() needs to be executed from within the Loop() but it seems to need much more time than the timer's frequency. So eventually it is never executed.

Please note that all of the above work when the interrupt is not involved; Usb.Task() works perfectly from the Loop() (data to/from the other CPU can be both sent and received).

Bits from the code:
<!-- language-all: lang-cpp -->

    void readPlantStatus() {
      if (analogRead(E2_STATUS)*(3.3/1023.0) > 2.0) e2_reached = true;
      else e2_reached = false;
      if (analogRead(F2_STATUS)*(3.3/1023.0) > 2.0) f2_reached = true;
      else f2_reached = false;
      if (analogRead(T2_STATUS)*(3.3/1023.0) > 2.0) t2_reached = true;
      else t2_reached = false;
      if (analogRead(E3_STATUS)*(3.3/1023.0) > 2.0) e3_reached = true;
      else e3_reached = false;
      if (analogRead(F3_STATUS)*(3.3/1023.0) > 2.0) f3_reached = true;
      else f3_reached = false;
    }

    void TC3_Handler() {
      TC_GetStatus(TC1, 0);
      readPlantStatus();
      writeToController();
      readFromController();
      controlPlant();
    }

    void loop()
    {
      Usb.Task();
    }

Any help would be greatly appreciated!

title: Due as USB Host timing issues

Answers: 0


body:
I have [this 8x8 LED RGB matrix][1]. How do I get it connected to an Arduino Uno?

It came with no other wires/modules/connectors and has a veritable crap-ton of pins to connect.

[![enter image description here][2]][2]

  [1]: http://www.amazon.com/Geeetech-LED-Matrix-8x8-Display/dp/B007ZK4I10
  [2]: https://i.stack.imgur.com/a0aRi.jpg

title: How do I connect an 8x8 LED RGB matrix to an Uno?

Answers: 2

body:
Because you have, unfortunately, decided to buy a product without a datasheet (and the product description can't even decide if it's common anode or common cathode!), you'll have to find a product which is similar that _has_ a datasheet, and determine by experimentation if the pinout matches.

For instance, [this Sparkfun LED matrix](https://www.sparkfun.com/products/retired/683) looks similar. Take a look at the datasheet for an internal schematic and manually verify the pinout.

Once you know the pinout, you can begin to figure out how to drive it. There are many ways to drive large numbers of LEDs, one of the simplest of which is a bunch of shift registers.

Getting yourself a couple of 595 SRs and playing with the matrix (hint: try and get a single colour working first, then add the others) would be a good place to start.

Alternatively, the display description says that it is compatible with "Arduino RGB LED Matrix Driver Shield". That may or may not be true, but looking at a schematic of that board would give you insight into how to drive the matrix. I believe that board uses a DM163 8x3 CC LED driver chip, which seems to be perfectly suited to drive the matrix, but buying and wiring that chip up may be non-trivial.

body: The idea is to use a shift register PMIC (power management ic), such as the MAX6971; you'll need a pair of them; each has 16 bits of output; if you want to really shave off a dollar, get four TPIC6C596.


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

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

Answers: 1

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.


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

title: Did I Brick my Controllino?

Answers: 2

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


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

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

Answers: 4

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:
You can add a delay.

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

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

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


body:
Can anyone explain to me why my output ip is: 15.16.17.18?

I configured my addresses as follows:

    Arduino :
    gateway 192.168.1.1
    ipaddress 192.168.1.8
    subnet 255.255.255.0

    My local network:
    gateway 192.168.1.1

    ipaddress 192.168.1.3

    subnet 255.255.255.0

Then when I print it, it shows
15.16.17.18

Arduino code:

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

    // network configuration. dns server, gateway and subnet are optional.

    // the media access control (ethernet hardware) address for the shield:
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

    // the dns server ip
    IPAddress dnServer(192, 168, 1, 1);
    // the router's gateway address:
    IPAddress gateway(192, 168, 1, 1);
    // the subnet:
    IPAddress subnet(255, 255, 255, 0);

    //the IP address is dependent on your network
    IPAddress ip(192, 168, 1, 8);

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

      // initialize the ethernet device
      Ethernet.begin(mac, ip, dnServer, gateway, subnet);
      //print out the IP address
      Serial.print("IP = ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
    }

My output is:

IP = 15.16.17.18

Please help, thank you.

title: Problem related to Arduino ip address

Answers: 0


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

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

Answers: 2

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.


body:
Considering the GSR is the inverse of the Resistance, if I know the resistance and how much it increases for every celsius degree, the game would be done.
Here's how my code looks like at the moment:

    const int GSR=A0;
    int threshold=0;
    int sensorValue;
    const long interval = 1000;
    unsigned long T = millis();

    void setup(){
      long sum=0;
      Serial.begin(115200);
      delay(1000);

      for(int i=0;i<500;i++)
      {
      sensorValue=analogRead(GSR);
      sum += sensorValue;
      delay(5);
      }
      threshold = sum/500;
       Serial.print("threshold =");
       Serial.println(threshold);
      }

    void loop(){

      if( millis() - T >= 250)  {
       int temp;
      sensorValue=analogRead(GSR);
      Serial.println(sensorValue);
      temp = threshold - sensorValue;
      T = millis();

      }
      }

The page of the sensor:
http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

title: How can I read also the temperature with this GSR sensor?

Answers: 0


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

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

Answers: 2

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.


body:
I'm following the tutorial in [WebClientRepeating][1] and it says that "The content of the page is viewable through your Arduino's serial window." However the output in my Serial window is just saying "Connecting..." repeatedly.

[![enter image description here][2]][2]

Here is my code:

        /*
      Repeating Web client

     This sketch connects to a a web server and makes a request
     using a Wiznet Ethernet shield. You can use the Arduino Ethernet shield, or
     the Adafruit Ethernet shield, either one will work, as long as it's got
     a Wiznet Ethernet module on board.

     This example uses DNS, by assigning the Ethernet client with a MAC address,
     IP address, and DNS address.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13

     created 19 Apr 2012
     by Tom Igoe
     modified 21 Jan 2014
     by Federico Vanzati

     http://www.arduino.cc/en/Tutorial/WebClientRepeating
     This code is in the public domain.

     */

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

    // assign a MAC address for the ethernet controller.
    // fill in your address here:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    // fill in an available IP address on your network here,
    // for manual configuration:
    IPAddress ip(10, 1, 1, 4);

    // fill in your Domain Name Server address here:
    IPAddress myDns(10, 1, 1, 1);

    // initialize the library instance:
    EthernetClient client;

    char server[] = "www.arduino.cc";
    //IPAddress server(64,131,82,241);

    unsigned long lastConnectionTime = 0;             // last time you connected to the server, in milliseconds
    const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds
    // the "L" is needed to use long type numbers

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

      // give the ethernet module time to boot up:
      delay(1000);
      // start the Ethernet connection using a fixed IP address and DNS server:
      Ethernet.begin(mac, ip, myDns);
      // print the Ethernet board/shield's IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // if there's incoming data from the net connection.
      // send it out the serial port.  This is for debugging
      // purposes only:
      if (client.available()) {
        char c = client.read();
        Serial.print(c);
      }

      // if ten seconds have passed since your last connection,
      // then connect again and send data:
      if (millis() - lastConnectionTime > postingInterval) {
        httpRequest();
      }

    }

    // this method makes a HTTP connection to the server:
    void httpRequest() {
      // close any connection before send a new request.
      // This will free the socket on the WiFi shield
      client.stop();

      // if there's a successful connection:
      if (client.connect(server, 80)) {
        Serial.println("connecting...");
        // send the HTTP GET request:
        client.println("GET /latest.txt HTTP/1.1");
        client.println("Host: www.arduino.cc");
        client.println("User-Agent: arduino-ethernet");
        client.println("Connection: close");
        client.println();

        // note the time that the connection was made:
        lastConnectionTime = millis();
      } else {
        // if you couldn't make a connection:
        Serial.println("connection failed");
      }
    }

Here are my Mac's network settings.

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

It's my understanding that I can assign an IP address to my Ethernet shield by just changing the last number of my computers IP address. Hence I changed 10.1.1.5 to 10.1.1.4.

Can anyone see any obvious errors? This is not really my area of expertise :)

  [1]: https://www.arduino.cc/en/Tutorial/WebClientRepeating
  [2]: https://i.stack.imgur.com/1c93O.png
  [3]: https://i.stack.imgur.com/7i2ry.png
  [4]: https://i.stack.imgur.com/5Iy7G.png

title: WebClientRepeating not printing response to Serial

Answers: 0


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

title: Changing timing intervals with millis()

Answers: 2

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

body:
The problems were caused by the vibrating motor. It's shaking caused the rotating part touched the surface and the motor stopped for a while.
Thank you for you help.


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

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

Answers: 1

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


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

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

Answers: 1

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.


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

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

Answers: 2

body:
On [SevSeg.h Arduino Page][1], It says:

> Your program must run the refreshDisplay() function repeatedly to
> display the number.

I think that's the Problem. You are calling it just once and then your **the number** is changed.

Plus, you are saying it must get updated after One Second, but I think in your code, its being updated ever other **2 milisecond** (WOW).

What I suggest is that you add a **delay()** for one second and then call **sevseg.refreshDisplay();** several times in a **for** loop. You also need to change the way you measure no. of seconds elapsed.

i.e. try Something like this:

    #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);
    }
    unsigned long timerGlobal = millis();
    void loop() {
      delay(1000);
      sevseg.setNumber( (timerGlobal - millis())/1000, -1)
      for (int i = 0; i < 50; i++) {
        sevseg.refreshDisplay();
      }
    }

  [1]: http://playground.arduino.cc/Main/SevenSegmentLibrary

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.


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

title: Iterating an array of relays

Answers: 2

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)


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

title: Audio/Voice Recording Device

Answers: 1

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/


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

title: rf24 change order of data

Answers: 1

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.


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

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

Answers: 2

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/

body:
I had similar problem. I have added gsm.begin() method at the end of the loop, and it has solved my problem!!

Seems like you can't send multiple http requests with single gsm session.
Relevant parts of setup() and loop() methods are shown below:

    void setup()
    {

    Serial.begin(9600);
    Serial.println("GSM Shield testing.");

    if (gsm.begin(2400)){
      Serial.println("\nstatus=READY");
      started=true;
    }
    else Serial.println("\nstatus=IDLE");

    }

    void loop()

    {
       if(started){
          if(inet.attachGPRS("internet.wind","",""))
            Serial.println("status=ATTACHED");
          else
            Serial.println("status=ERROR");

          if(inet.httpPOST(server,port, path,parameters,msg, 50)){
              Serial.println("Data sent to server succesfully!");
          }
          else{
            Serial.println("Failed to send data to the server");
          }
     }

     if (gsm.begin(2400)){
      Serial.println("\nstatus=READY");
      started=true;
    }
    else Serial.println("\nstatus=IDLE");

    };


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

title: User input for utility program

Answers: 1

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


body:
When this 3 wire LCD code is compiled the following message results:
NewLiquidCrystal-master\I2CIO.cpp:35:26: fatal error: ../Wire/Wire.h: No such file or directory

 #include <../Wire/Wire.h>                         ^

compilation terminated.

exit status 1
Error compiling for board Arduino Nano.

Thanks for your help.
<!-- language-all: lang-cpp -->

     // Original LiquidCrystal library that can be inherited from to support other
     // connectivity:
     // https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

     #include <LiquidCrystal_SR_LCD3.h>

     // Standard HD44780 20x4 LCD display driven via 3 output pins to a 4094 8-bit
     // shift register like 74HC4094 pebblev2's MC14094

      // This demo was written for the PebbleV2 to test LiquidCrystal_SR_LCD3, but it
     // should work with other LiquidCrystal Displays that are 20x4.
     // http://www.freetronics.com/pages/pebble-v2
     // https://github.com/lukeweston/pebble20

     // Data are the input bits
     // Clock tells the SR that the data pin holds the next valid bit
     // Strobe gets data input to be made visible on the parallel output pins.

     const int PIN_LCD_STROBE         =  2;  // Out: LCD IC4094 shift-register strobe
     const int PIN_LCD_DATA           =  3;  // Out: LCD IC4094 shift-register data
     const int PIN_LCD_CLOCK          =  4;  // Out: LCD IC4094 shift-register clock
     const int PIN_LCD_BACKLIGHT      =  5;  // Out: LCD backlight (PWM)

     // srdata / srclock / strobe
     LiquidCrystal_SR_LCD3 lcd(PIN_LCD_DATA, PIN_LCD_CLOCK, PIN_LCD_STROBE);

     // Creat a set of new characters
     byte heart[8] = {
       0b00000, 0b01010, 0b11111, 0b11111, 0b11111, 0b01110, 0b00100, 0b00000
     };

     byte smiley[8] = {
       0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b10001, 0b01110, 0b00000
     };

     byte frownie[8] = {
       0b00000, 0b00000, 0b01010, 0b00000, 0b00000, 0b00000, 0b01110, 0b10001
     };

    byte armsDown[8] = {
       0b00100, 0b01010, 0b00100, 0b00100, 0b01110, 0b10101, 0b00100, 0b01010
     };

     byte armsUp[8] = {
       0b00100, 0b01010, 0b00100, 0b10101, 0b01110, 0b00100, 0b00100, 0b01010
     };

     void setup(){
         pinMode(PIN_LCD_BACKLIGHT, OUTPUT);
         analogWrite(PIN_LCD_BACKLIGHT, 80);

         lcd.begin(20, 4);               // initialize the lcd

         // load characters to the LCD
         lcd.createChar(0, smiley);
         lcd.createChar(1, frownie);
         lcd.createChar(2, armsDown);
         lcd.createChar(3, armsUp);
         lcd.createChar(4, heart);

         lcd.home ();                   // go home
         lcd.setCursor (0, 0);
         lcd.print(F("LiquidCrystal_SRLCD3"));
         lcd.setCursor (0, 1);
         lcd.print(F("he.."));
         lcd.setCursor (0, 2);
         lcd.print(F("..lo"));
         lcd.setCursor (0, 3);
         lcd.print(F("World "));
         lcd.print(char(4));
         lcd.print(char(2));
         lcd.print(char(3));
         delay(2000);
     }

    void loop()
     {
         for (int i = 5; i <= 15; i++){
           lcd.setCursor ( i, 1 );
           lcd.print(char(random(0,2)));
           delay(100);
           lcd.setCursor ( i, 1 );
           lcd.print(F(" "));
         }

         for (int i = 15; i >= 5; i--){
           lcd.setCursor ( i, 1 );
           lcd.print(char(random(0,2)));
           delay(100);
           lcd.setCursor ( i, 1 );
      lcd.print(F(" "));
         }

         // Turn the display on/off
         lcd.setCursor ( 5, 2 );
         lcd.print(F("Turn screen off"));
         delay(1000);
         lcd.noDisplay();
         delay(1000);
         lcd.display();

         lcd.setCursor ( 5, 2 );
         lcd.print(F("Toggle Cursor  "));
         delay(1000);
         lcd.setCursor ( 19, 2 );
         lcd.cursor();
         delay(2000);
         lcd.noCursor();

         lcd.setCursor ( 5, 2 );
         lcd.print(F("Toggle Blink   "));
         lcd.setCursor ( 19, 2 );
         lcd.blink();
         delay(2000);
         lcd.noBlink();

         lcd.setCursor ( 5, 2 );
         lcd.print(F("Scroll screen  "));
         delay(1000);
     // This is an autoscroll demo, not super useful but here just in case.
     //    lcd.setCursor(16,0);
     //     lcd.autoscroll();
     //     // print from 0 to 9:
     //     for (uint8_t thisChar = 0; thisChar < 10; thisChar++) {
     //   lcd.print(char(2));
     //  delay(250);
     //  lcd.print(char(3));
     //  delay(250);
     //     }
     //     // turn off automatic scro
     //     lcd.noAutoscroll();

         for (uint8_t positionCounter = 0; positionCounter < 10; positionCounter++) {
           // scroll one position left:
           lcd.scrollDisplayLeft();
           // wait a bit:
           delay(50);
         }

         // scroll 29 positions (string length + display length) to the right
         // to move it offscreen right:
         for (uint8_t positionCounter = 0; positionCounter < 20; positionCounter++) {
           // scroll one position right:
           lcd.scrollDisplayRight();
           // wait a bit:
           delay(50);
        }

           // scroll 16 positions (display length + string length) to the left
           // to move it back to center:
         for (uint8_t positionCounter = 0; positionCounter < 10; positionCounter++) {
           // scroll one position left:
           lcd.scrollDisplayLeft();
           // wait a bit:
           delay(50);
         }
         lcd.setCursor ( 5, 2 );
         lcd.print(F("               "));
     }

title: Compiling Error 3 Wire LCD

Answers: 0


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

title: While loop not breaking

Answers: 4

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;
        }
      }


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

title: Simulator for AD8232 Chip

Answers: 1

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


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

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

Answers: 3

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