body:
I have the following errors trying to use a TFT library function inside my library. My library uses the pointer to an instance of the TFT library in the constructor, as well described there:

https://arduino.stackexchange.com/q/18974/19684

The errors are:

    error: invalid use of incomplete type 'class TFT'
    _TFTscreen->background(0, 0, 0);

    error: forward declaration of 'class TFT'
    class TFT;

_MESmenu.h:_

    #ifndef _MESMENU_H_
    #define _MESMENU_H_

    #include <SPI.h>
    #include <SD.h>

    class TFT;

    class MESmenu{
    public:
      MESmenu(TFT* pTFT) : _TFTscreen(pTFT) {};
      void start();
      void execute();
    private:
      TFT* _TFTscreen;
    };

    #endif

_MESmenu.cpp:_

    #include "Arduino.h"
    #include "MESmenu.h"

    void MESmenu::start(){
      _TFTscreen->background(0, 0, 0);
      _TFTscreen->text("starting menu...", 0, 0);
      //...
    }

    void MESmenu::execute(){
       //some code...
    }

The _Arduino sketch_ is:

    #include <SPI.h>
    #include <SD.h>
    #include <TFT.h>  // Arduino LCD library
    #include <MESmenu.h>  // my library

    // --------- TFT LCD ---------
    // pin definition for the due
    #define sd_cs  7
    #define lcd_cs 10
    #define dc     9
    #define rst    8
    TFT TFTscreen = TFT(lcd_cs, dc, rst);

    // MES menu class
    MESmenu *mainMenu = new MESmenu(&TFTscreen);

    void setup() {
      // initialize TFT
      TFTscreen.begin();
      TFTscreen.background(0, 0, 0);
      // set the stroke color to white
      TFTscreen.stroke(255,255,255);
      TFTscreen.fill(255,255,255);
      TFTscreen.setTextSize(2);
      TFTscreen.text("TEST", 0, 0);

      // Start menu
      mainMenu->start();
    }

    void loop () {
      mainMenu->execute();
    }

The problem is related to the function:

    _TFTscreen->background(0, 0, 0);

inside the MESmenu::start() in the .cpp file.

**UPDATE:**

As suggested by **frarugi87** I've updated the question with the details of .h and .cpp files.
Those file are in the Arduino\libraries\MESmenu folder.

I try to change

    class TFT;

with

    #include <TFT.h>

and removed the #include <TFT.h> from the main arduino sketch.

This leads to the following errors:

    libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
    D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)'
    sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: first defined here

    libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
    D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read16(SDLib::File)'
    sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

    libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
    D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::read32(SDLib::File)'
    sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

    libraries\MESmenu\MESmenu.cpp.o: In function `Adafruit_GFX::image(PImage&, unsigned int, unsigned int)':
    D:\Software\arduino-1.6.7\libraries\TFT\src/utility/Adafruit_GFX.h:231: multiple definition of `PImage::loadImage(char const*)'
    sketch\test_MESmenu_lib.ino.cpp.o:D:\Software\arduino-1.6.7\libraries\TFT\src/utility/PImage.h:17: first defined here

title: Error: "invalid use of incomplete type" and "forward declaration"

Answers: 1

body:
Try to change

    class TFT;

to

    #include <TFT.h>

Then you can remove the `#include <TFT.h>` from the main arduino sketch.

Moreover you should at least write a piece of code to make the compiler include your library just once; this is the usual way to do it:

    #ifndef _MESMENU_H_
    #define _MESMENU_H_

    #include <SPI.h>

    ...
    the rest of your library
    ...

      TFT* _TFTscreen;
    }

    #endif

`_MESMENU_H_` is any unique string (usually the filename is used, remembering that you can't put spaces or other punctuation marks except the underscore). And you should put it only in the header file (*.h or *.hpp), not in the source (*.c or *.cpp or *.ino)

EDIT:

The additional info lead me to analyze the library and.. there are problems with the library. Particularly the file `TFT/src/utility/Adafruit_GFX.h` has a big problem: it has the code for the functions.

To fix it, you have to modify the library.

Go into the folder `TFT/src/utility/` and make a copy of `Adafruit_GFX.h`, calling it `PImage.cpp`.

Open `Adafruit_GFX.h` and delete everything between line 227 and line 370. This means that from

    bool useFill;
    };

    #if defined(__SD_H__)  // Arduino SD library

    #define BUFFPIXEL 20

    void Adafruit_GFX::image(PImage & img, uint16_t x, uint16_t y) {

    ...

      return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
    }

    #endif

    #endif // _ADAFRUIT_GFX_H

it should become

    bool useFill;
    };

    #endif // _ADAFRUIT_GFX_H

Having done this, open `PImage.cpp` and delete everything above line 227, then delete the function `Adafruit_GFX::image` and the last `endif` and add, at the beginning, `#include Adafruit_GFX.h`. This means that the file should look like

    #include "Adafruit_GFX.h"

    #if defined(__SD_H__)  // Arduino SD library

    #define BUFFPIXEL 20

    // These read 16- and 32-bit types from the SD card file.
    // BMP data is stored little-endian, Arduino is little-endian too.
    // May need to reverse subscript order if porting elsewhere.

    uint16_t PImage::read16(File f) {

    ...

      return PImage(bmpFile, bmpWidth, bmpHeight, bmpDepth, bmpImageoffset, rowSize, flip);
    }

    #endif

Then try to compile again the program

BTW: the source I looked at is at [this page](http://bitsbytesnibble.com/indefero/p/builduinok5/source/tree/master/libraries/TFT/src/utility/Adafruit_GFX.h).


body:
 I modified the serial code in this way and I don't think the gap is produced by my edit even because it made it even before:

    //////////
    /////////  All Serial Handling Code,
    /////////  It's Changeable with the 'serialVisual' variable
    /////////  Set it to 'true' or 'false' when it's declared at start of code.
    /////////

    void serialOutput(){   // Decide How To Output Serial.
     if (serialVisual == true){
         arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
     } else{
          sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
     }
    }

    //  Decides How To OutPut BPM and IBI Data
    void serialOutputWhenBeatHappens(){
     if (serialVisual == true){            //  Code to Make the Serial Monitor Visualizer Work
        //ASCII Art Madness
        Serial.print(BPM);
        Serial.println("");

     } else{
            sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
            sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
     }
    }

    //  Sends Data to Pulse Sensor Processing App, Native Mac App, or Third-party Serial Readers.
    void sendDataToSerial(char symbol, int data ){
        Serial.print(symbol);

        Serial.println(data);
      }

    //  Code to Make the Serial Monitor Visualizer Work
    void arduinoSerialMonitorVisual(char symbol, int data ){
      const int sensorMin = 0;      // sensor minimum, discovered through experiment
    const int sensorMax = 1024;    // sensor maximum, discovered through experiment

      int sensorReading = data;
      // map the sensor range to a range of 12 options:
      int range = map(sensorReading, sensorMin, sensorMax, 0, 11);

      // do something different depending on the
      // range value:
      switch (range) {
      case 0:
        Serial.println("");

      }
    }

    63

    63
    63
    63
    63
    62
    62
    62
    62
    62
    62
    62
    63
    62
    63
    64
    63
    63
    64
    64
    65
    65

    65
    68
    74
    78
    86
    95
    105
    112
    123
    141
    167
    154
    136
    128
    123
    125
    123
    127
    132
    104
    93
    92
    92
    89
    83
    77
    73
    69
    65
    70
    70
    71

You can find all the code here:
https://github.com/WorldFamousElectronics/PulseSensor_Amped_Arduino

In the code I posted there is some code I don'f find useful but I can't delete it for reason linked to variables used for other functions I don't know I'm using.
You can also see huge changes in the heart rate that surely don't reflect the reality.

title: Why does pulse sensor shows gaps when I move it?

Answers: 1

body:
One of the possibilities is when you move your finger, the sensor grip loosened and doesn't count a "beat". So the sensor emits `data = 0`, and it will cause

    Serial.println("");

in your switch-case.


body:
One sensor has a baud rate of 115200, the other 9600. I think this will create problems in the serial because I can only choose one baud rate.

What do you think?
The first sensor is the pulse sensor, while the other is the gsr sensor by grove.
Link: http://pulsesensor.com/
Link 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor

title: Can I use two sensors with different baud rate without problems on arduino?

Answers: 2

body:
You can only have one sensor on one serial port, and the baud rate is set on the serial port.

So as long as you have two serial ports, or SoftwareSerial ports (I wouldn't, it causes more problems that it solves - get a board with multiple UART interfaces) then yes you can have two baud rates.

body:
> One sensor has a baud rate of 115200, the other 9600. I think this
> will create problems in the serial because I can only choose one baud
> rate.
>>Why do you think the sensor has a baudrate?

Both the sensors seem to use the "serial connection" of the Arduino to log their information.

> What do you think? The first sensor is the pulse sensor, while the
> other is the gsr sensor by grove. Link: http://pulsesensor.com/ Link
> 2: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor
>> I think it'll work fine.

Looking at the facts of your sensors, the pulse sensor does have some kind of weird low-level timing/ADC access. But your Grove GSR sensor can basically be read out through an analog input.

**So what to choose?**

You could choose 9,6k or 115k2 (9600 or 115200). It wouldn't make all that much difference. 9600 or 115200 will work fine. 115200 is a lot faster, but for debugging purpose 9600 is used, since it's often default and (often) more reliable.

**Wrapping up**

I don't think there is an issue with the two serials. You can easily log both messages to the same serial output.

Try using 115200 since timing is essential in your case, you want your sensor to be response/fast.

They do both use the same analog to digital converter on your board. An Arduino can't check both sensors at the same time. But by switching between them very fast, you will get a resolution that's good enough.


body:
I have a weird problem. I am currently building a BB-8. Therefore, I am using an Arduino Uno. On top, I have stacked an Adafruit Motor Shield v2.3 and, again, on top of this, I have stacked the Sparkfun USB Host Shield. The Arduino is powered by a 9V-Block battery, the motors are powered separately by two 18650 Li-Ion batteries. To control the two Pololu motors, which have a stall current of 1.6 amps each, I use a Xbox 360 wireless controller, where the receiver is connected to the USB Host Shield.

Now to my problem. Every seems to work fine, until i cover everything with a styrofoam hemisphere. Yes, you've read right. If that happens, the controller signals is lost and does not connect again, unless I restart the Arduino. I have uploaded a small video on [youtube][1], where you can see the problem.

I guess, this is a power problem, since this issue does not occur, when I connect the Xbox receiver to my Mac. Has anyone an idea, how to solve this problem?

I already tried another power source. And the USB host shield should give enough power, since the specs are saying, that 500 mA is no problem, and hit is exactly the USB 2.0 spec. The combination of the shield shouldn't be a problem, too. I carefully chose this shields, because the motor shield is just using the pins A4 and A5, the USB host shield is using some of the digital pins, so I think there is no interference.

Thank you for your help.

**EDIT**
I have tested it a bit more now and i think i can reduce the probable reasons. First, i tried some other power supplies, from AA batteries on the VIN pin to external power adaptors. Next, i tried other xbox receivers and controllers. I also tried a playstation 3 controller with a Bluetooth dongle. Nothing solved the problem. I also covered the Arduino with other things than styrofoam, like a garbage can, cardboard and some metal box. This worked, so the problem was only with styrofoam. Now i haven't covered the Arduino, but i slowly got closer. About 20 cm from the Arduino, it stopped working. My clue: static electricity. Do you think this can be a problem? And if yes, how can i solve this?

  [1]: https://youtu.be/kabobDlFX2s

title: Power problems stacked Arduino shields

Answers: 2

body: Those 9v batteries are not known for their ability to supply current. Their best uses are long-term powering of low-current standby devices like smoke detectors. I'd first try replacing it with 4 double- or triple-A cells, whatever you can scrounge up for a quick test. My guess is when you cover the robot the Xbox receiver's current demand increases just enough to crash or reset something. A-cells may supply enough more current without the voltage sagging.

body: So, I solved the problem. As is mentioned in my question, the problem was static electricity. I primed the styrofoam sphere with some special primer to make the styrofoam a little more stable and so on. That's it. Luckily I didn't touch the Arduino with the sphere. I think it would have damaged the Arduino.


body:
I'm looking for some reference material to start on a project I'd like to do.

I have an Open House at my school. My group project has been to create a little timesheet app using JavaEE. I just started looking for how to do this and if I can. But I would like to wow people a bit by setting this up using an Arduino Yun board. I know it has WiFi and I'm pretty sure I can run Linux on the little guy.

Any help would be greatly appreciated.

title: Setting Up a JavaEE app on an Arduino Yun Board

Answers: 1

body:
Sorry, forget it. 64Mb ram, 16Mb flash what the Yun has.
Java EE is magnitudes bigger (and bugger) than that.

You might try with Java SE embedded, the smallest profile might fit to 11Mb:
http://www.oracle.com/us/technologies/java/oracle-javase-embedded-ds-365290.pdf
and then you can roll your own web server.

(Personal comments: For little timesheets JavaEE is overkill, for anything modern JavaEE is obsolete - consider modern Java micro web frameworks, which offer magnitudes better performance than JavaEE).

What you can try is Raspberry PI, which works well with network, and Java (SE).
Not that well but also Java EE works: https://blogs.oracle.com/theaquarium/entry/glassfish_4_on_the_raspberry


body:
Probably I'm asking a nonsense question but I'm new at interfaces.

I want to connect an USB barcode scanner to an Arduino (Uno or Mega). I've read that I need a USB host shield to achieve this. But I don't have any. I have a FTDI, so I suppose I could plug the USB output of the scanner into the FTDI and connect the FTDI to the UART port of Arduino. Then, I would be passing the USB output to Serial.

Is it correct? Thanks and sorry if I said something stupid!

title: Connect a USB slave into Arduino using FTDI

Answers: 1

body:
No, that is completely wrong.

In USB you have *hosts* and *devices*. A *device* has to connect to a *host*. Your FT232 is a *device*. The barcode scanner is a *device*. Both of them need to be connected to a *host* for them to do anything.

So you need a USB *host* shield to act as that host.

However - check the manual for your barcode scanner: it may well have a RS-232 mode that it can be switched into (may need a different cable attached).


body:
I'm looking into working with an Arduino micro, and I'd like to be able to plug it into my computer directly(without a cable). I've been looking around, and the best thing that I found was [this](http://www.gearbest.com/usb-flash-drives/pp_241630.html?currency=USD&gclid=Cj0KEQjwz-i3BRDtn53Z5Z7t4PUBEiQA23q2ADLBLxSTh67ggFcvjZenuXTcFK6nriQfRnaFchLybM8aAuhx8P8HAQ). The reason I haven't bought the linked adapter is because I've seen a number of bad reviews of the seller with close to half of the reviews being 1-star. Anybody have an idea where I can find something similar?

EDIT: I'm going to be using this for security testing, emulating a rubber ducky usb, so I need the computer to recognize the Arduino as an HID, not an arduino, but I also (obviously) need to be able to load my code onto it

title: Micro USB to USB adapter m/m

Answers: 1

body:
That adapter is not suitable. Not only is it the wrong gender on the large end, but it is designed for a completely different purpose.

That is an "On The Go" adapter which is designed for connecting things with a USB A plug (such as a memory stick, etc) to a mobile phone's USB socket.  It is not suitable for connecting things to an Arduino.

I have never heard of an adapter like you want, but I have heard of Arduino-like boards that plug direct into a computer like you want. One example is the [Digispark from Digistump](http://digistump.com/products/1) which is an ATTiny85 on a USB plug.


body:
I want to read strings from `Serial.read()` to send them later.

To get the data from the Serial monitor I'm doing this:

<!-- language: c -->

    String stringOne  = "";
    int  incomingByte;

    if (Serial.available() > 0) {

      while(Serial.available() > 0)
      {
         incomingByte= Serial.read();
         stringOne = String(stringOne + String(incomingByte));
      }

      Serial.println(stringOne);
      stringOne = "";

The issue is that when I type:

    'a'

I got:

    '97'
for
    'abc'

I got

    '979899'

so on and so forth.

What should I do in order to get the same string I type?

title: Get strings from Serial.read()

Answers: 2

body:
You're adding the ASCII value of each char to your string, hence you get numbers. See the various String constructors at:
https://www.arduino.cc/en/Tutorial/StringConstructors

Either cast the read byte to a char:

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

or consider receiving characters as chars, instead of ints:

    char incomingByte;

There is a perfectly valid one-method call which does all of this hassle easier and more efficiently: https://www.arduino.cc/en/Serial/ReadStringUntil

Note that you'll sooner or later anyhow have to add a framing prototcol. For example, you're sending down text commands to Arduino, and each command is separated by a new line character. ReadStringUntil will handle that very nicely.

body:
Instead of using:

    while(Serial.available() > 0)
      {
         incomingByte= Serial.read();
         stringOne = String(stringOne + String(incomingByte));
      }

Use the following to cast them to character:

    while(Serial.available() > 0)
      {
         char incomingByte= Serial.read();
         stringOne.concat(incomingByte));
      }
    Serial.println(stringOne);
    stringOne="";


body:
Connected servo motor (180°) to Arduino Uno R3.

Currently I am using a servo motor which have rotation angle specified as 180°, but I have a requirement to rotate to certain angles greater that 180°.

So do I need to go for a *continuous rotation servo motor (360°)*, so that I can stop the motor at different angles greater than 180°, was my assumption true, will continuous rotation servo motor satisfy this requirement?

I am referring to [Servo - Generic High Torque Continuous Rotation (Standard Size)](https://www.sparkfun.com/products/9347)

Current code, which I am using 180° servo motor.

<!-- language: c -->

    Servo myservo;
    int pos = 0;
    void setup() {
      myservo.attach(9);
    }

    void loop() {
       {
        myservo.write(180);
        delay(15);
      }
    }

title: How to make servo rotate for angle bigger than 180°

Answers: 1

body:
No. The continuous rotation servo rotates _continuously_ and you can not control where to stop. You can control the rotation direction and the speed at a little.

What you need is either a special 270 degree servo, or you can use some mechanic, e.g. gears to transform the 0..180 rotation to 0..whateverrotation you prefer, depending on the gearbox ratio.

Alternatively, you can use stepper motors, where you can control steps in 1.8 degrees, and at the same time free to move as many turns as you prefer. Note though that steppers have two disadvantages compared to servos:

 * steppers require electrical current to hold their current position - for servo, the gearbox works ok for this
 * steppers don't know their initial position. So you need an optointerrupter or other means to learn the initial position first, then drive the steps to get to any position.
 * steppers require a more serious driving circuit, as well as a good power supply. Not for DIY robot running on batteries.

In industrial solutions, the stepper motor + some gearbox + an absolute rotation encoder is used to compose an industrial servo drive. (Similarly as a DC motor + some gearbox + an inexpensive potentiometer works in a model servo.)


body:
EDIT: upon further investigation: I found out that if I wired it Thermistor > resistor > GND values go one direction. If I wired it Thermistor > Resistor > 5v, it goes the other direction. So my new question: Which way is correct? One sketch assumes it works one way, and one the other.

I have some Thermistors from [here][1]. I have an Arduino Nano and an Arduino Uno, both set up identically with pictures of the wiring below. On the sketch below, when I heat up the thermistor the value increases on the Uno and decreases on the Nano.

    // which analog pin to connect
    #define THERMISTORPIN A0
    // resistance at 25 degrees C
    #define THERMISTORNOMINAL 10000
    // temp. for nominal resistance (almost always 25 C)
    #define TEMPERATURENOMINAL 25
    // how many samples to take and average, more takes longer
    // but is more 'smooth'
    #define NUMSAMPLES 5
    // The beta coefficient of the thermistor (usually 3000-4000)
    #define BCOEFFICIENT 3950
    // the value of the 'other' resistor
    #define SERIESRESISTOR 9800

    int samples[NUMSAMPLES];

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

    void loop(void) {
      uint8_t i;
      float average;

      // take N samples in a row, with a slight delay
      for (i=0; i< NUMSAMPLES; i++) {
           samples[i] = analogRead(THERMISTORPIN);
       delay(10);
      }

      // average all the samples out
      average = 0;
      for (i=0; i< NUMSAMPLES; i++) {
         average += samples[i];
      }
      average /= NUMSAMPLES;

      Serial.print("Average analog reading ");
      Serial.println(average);

      // convert the value to resistance
      average = 1023 / average - 1;
      average = SERIESRESISTOR / average;
      Serial.print("Thermistor resistance ");
      Serial.println(average);

      float steinhart;
      steinhart = average / THERMISTORNOMINAL;     // (R/Ro)
      steinhart = log(steinhart);                  // ln(R/Ro)
      steinhart /= BCOEFFICIENT;                   // 1/B * ln(R/Ro)
      steinhart += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)
      steinhart = 1.0 / steinhart;                 // Invert
      steinhart -= 273.15;                         // convert to C

      Serial.print("Temperature ");
      Serial.print(steinhart);
      Serial.println(" *C");
      Serial.println();

      delay(1000);
    }

On the sketch below, the Uno is backwards and the Nano is correct. I'm sure there's something simple I'm missing, but I sure can't find it. Any suggestions?

    #include <math.h>

    double Thermistor(int RawADC) {
     double Temp;
     Temp = log(10000.0*((1024.0/RawADC-1)));
     Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp );
     Temp = Temp - 273.15;
     Temp = (Temp * 9.0)/ 5.0 + 32.0;
     return Temp;
    }

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

    void loop() {
      int val;
      double temp;
      val=analogRead(7);
      temp=Thermistor(val);
      Serial.print("Temperature = ");
      Serial.print(temp);
      Serial.println(" F");
      delay(1000);
    }

[Nano Wiring][2]

[Uno Wiring][3]

  [1]: http://www.amazon.com/100-Temperature-Measurement-Thermistors-MF52-103/dp/B0087YI1KW/ref=sr_1_1?ie=UTF8&qid=1459212561&sr=8-1&keywords=thermistor
  [2]: https://i.stack.imgur.com/QQ8Fs.jpg
  [3]: https://i.stack.imgur.com/kIM29.jpg

title: Thermistor value correct on Uno backwards on Nano

Answers: 1

body:
There is no "correct" way. The thermistor and the resistor combine to make a voltage divider. Whether the thermistor is connected to +5V (AKA R1) or to GND (AKA R2) determines the formula to use to calculate the resistance.

The general form is:

              R2
    Vout = ------- x Vin
           R1 + R2

To solve for R2 (thermistor connected to GND) you re-arrange to:

                     1
    R2 = R1 x --------------
              (Vin/Vout) - 1

To solve for R1 (thermistor connected to +5V) it's:

         R2 x Vin
    R1 = -------- - R2
           Vout

Vin, of course, is 5V, and Vout is a voltage you calculate from the analog reading on the Arduino.

Once you have the resistance you can then calculate the temperature. That part doesn't change regardless of the orientation of the thermistor.


body:
I'm using the grove GSR sensor: http://www.seeedstudio.com/wiki/Grove_-_GSR_Sensor with this code:

    const int GSR=A0;
    int threshold=0;
    int sensorValue;
    const long interval = 1000;
    void setup(){
      long sum=0;
      Serial.begin(9600);
      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(){
      int temp;
      sensorValue=analogRead(GSR);
      Serial.println(sensorValue);
      temp = threshold - sensorValue;
      delay(250);
      }

There is the delay way to skip milliseconds or the `millis()` function. Do you have ideas on how can I implement it? The delay has the problem that doesn't consider the time the sensor uses to read the data.

Here's what I am trying

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

    void setup(){
      long sum=0;
      Serial.begin(9600);
      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() - startTime) % 250 == 0) {
       int temp;
      sensorValue=analogRead(GSR);
      Serial.println(sensorValue);
      temp = threshold - sensorValue;

      }
      }

title: How can I exactly put my sensor at 4 Hz readings?

Answers: 3

body:
Something like this should do it:

    const byte LED = 13;
    unsigned long lastReading;
    const unsigned long INTERVAL = 250;

    void setup()
      {
      pinMode (LED, OUTPUT);
      }  // end of setup

    void loop()
      {
      unsigned long now = millis ();
      if (now - lastReading >= INTERVAL)
        {
        lastReading = now;
        digitalWrite (LED, HIGH);
        delay (50);  // simulate reading delay
        digitalWrite (LED, LOW);
        }
      }  // end of loop

This code saves when we are *about to* do a reading, and uses that as the basis for when to do the next one. This eliminates the reading time from the equation. In my example code I throw in a 50 ms delay to prove the point.

The LED flashes exactly at 250 ms intervals.

body:
The difference between your first code and the second one is that the first one is blocking execution when it reaches the `delay` function, but the second code keeps running without being blocked.

Now your algorithm has a drawback, the loop may or may not reach the `if` condition exactly when the modulo is strictly equal to 0. So you may prefer to use something like :

 unsigned long T = millis();

 ...

 if( millis() - T >= 250 ) {
  ... // sensor stuff
  T = millis();
 }

This idea is also presented in this article <https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay>.

Another approach is to use Timers and Interrupts, but this is far more complicated (<http://playground.arduino.cc/Code/Timer1>).

body:
Both other answers are correct, but my usual way of dealing with this is

    unsigned long startTime = 0;
    #define MEASURE_PERIOD 250
    ...
    void loop()
    {
     if((millis() - startTime) >= MEASURE_PERIOD)
     {
      startTime += MEASURE_PERIOD;
      // Do your job, such as
      int temp;
      sensorValue=analogRead(GSR);
      Serial.println(sensorValue);
      temp = threshold - sensorValue;
     }
    }

The difference between this way and the other ones (Nick's way, i.e. saving `millis` and setting the `startTime` variable to it, or nico's one - which is worse - , to set it again), is that this way if there is some error (e.g. 260ms between two calls) it gets recovered by the next cycle (which will be of 240ms), while in their way it is not.


body:
So I'm doing a project that involves getting sensor data from several sensors, and then sending them to an external server when a tragic occurs. But I've been having trouble figuring out how to send this data, and I am welcome to advice (I'm still relatively new to Arduino coding).

I'm using an Arduino mega, with a sim900 GSM shield and an SD card. The sensors are just analog reads and a GPS.

I've looked into FTP, a Xively account and http requests to a web server but couldn't figure it out.

title: How to perform a data transfer to an external server

Answers: 1

body:
There is a good example of using the **SubmitHttpRequest()** in this article:
[GPRS Shield SIM900 Arduino][1]

You could easily modify:
**mySerial.println("AT+HTTPPARA=\"URL\",\"www.yourwebsite.com/testing.php\"");**

to include a string of the sensor value, and then using a PHP script to MySQL on your webserver. Maybe something like:
http://**yourwebsite.com**/testing.php?**sensor1**=5&**sensor2**=10

  [1]: https://roysoala.wordpress.com/2012/11/20/gprs-shield-sim900-arduino-get-data-application/


body:
I'm making a device for the visually disabled that makes a sound when the water in a bowl reach certain levels.

I've already made the sensors for three levels of water and if statements to make the sound, but I need the sound to be played just once for every level change and it loops over and over.
How can I make it to sound just one time?

Here is my code:

    #include <PCM.h>
    const unsigned char sample[] PROGMEM = { //Here goes the sample
    };
    int low = 0;
    int mid = 0;
    int high = 0;

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

    }

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (high > 50){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
      }
      else if (mid >50){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
      }
      else if (low > 50){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
      }
      delay(100);

title: Need to make an action just once when condition is reached

Answers: 2

body:
A possible solution to your problem can be the following:

    #include <PCM.h>
    const unsigned char sample[] PROGMEM = { //Here goes the sample
    };
    int low = 0;
    int mid = 0;
    int high = 0;
    bool first = true;
    bool second = true;
    bool third = true;

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

    }

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (high > 50 && first){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
        first = false;
      }
      else if (mid >50 && second){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
        second = false;
      }
      else if (low > 50 && third){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
        third = false;
      }
      delay(100);

In this way the sound for each level will be played only once. I hope this is what you were looking for.

body:
As an addition to the answer of Mattia.

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

I suspect you have something like:

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (resetVariables){
         first = true;
         second = true;
         third = true;
         resetVariables = false;
      }

      if (high > 50 && first){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
        first = false;
      }
      else if (mid >50 && second){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
        second = false;
      }
      else if (low > 50 && third){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
        third = false;
      }

      if(buttonPressed){
        resetVariables = true;
      }
      delay(100);
    }

A better practice would be to use another function

    void resetFlags() {
      first = true;
      second = true;
      third = true;
    }

And the main code would be:

    void loop() {
      // put your main code here, to run repeatedly:
      low = analogRead(A0);
      mid = analogRead(A1);
      high = analogRead(A2);
      Serial.print("nivel agua: ");

      if (high > 50 && first){
        Serial.print("Alto");
        startPlayback(sample, sizeof(sample));
        first = false;
      }
      else if (mid >50 && second){
        Serial.print("Medio");
        startPlayback(sample, sizeof(sample));
        second = false;
      }
      else if (low > 50 && third){
        Serial.print("Bajo");
        startPlayback(sample, sizeof(sample));
        third = false;
      }

      if(buttonPressed){
        resetFlags();
      }
      delay(100);
    }

Would this be faster?

 - It would at least make your loop code more readable, instead of juggling flags around.
 - `resetFlags()`; would act immediately and independent from the flag checking etc.
 - It saves checking unnecessary if's (which equals a very little speed increase).
 - It saves 1 boolean (byte maximal in memory) which equals a very little memory/speed increase.

But why mind speed if you have a 100msec delay?
You could make it only output the water level when it changes. Then you can run the water checking extremely fast!
(It wouldn't spam your console, plus, writing to console takes considerable amount of time, compared to checking if's.)


body:
I recently bought a brand new Arduino pro micro from [Amazon][1], I set it up according to the instructions on [sparkfun][2], except that when I plug it in, Windows doesn't even show that it tried to install device driver software. I figured it might just be a windows 10 thing because the tutorial was written on windows 7, so I forged ahead, and updated the device driver for COM3 in device manager, and attempted to upload a simple test for HID emulation:

    #include <Keyboard.h>

    void setup() {
      Keyboard.write('z');
    }

    void loop() {
      Keyboard.write('a');
      delay(5000);
    }

It compiled just fine, and the IDE said it started uploading to the device, However, as it was uploading (or so I thought) I read a little farther and realized that the IDE wasn't set to use the right voltage (3.3V instead of 5V) I closed the IDE and reopened my sketch, changed the voltage to match up, and tried uploading it again. Here, it got stuck on the `Uploading...` text and so again, I closed the IDE.

Only the LED closest to the USB port is on, and it's solid green. I've connected to my computer using a Micro USB to USB adapter, and I initially plugged the board into a USB 3.0, but then switched to 2.0 to see if it made a difference. I have also tried it on Ubuntu 14.04 with no luck. I don't think it's bricked because if it was, my computer would still recognize it, but not know what it was (according to sparkfun), and as a result, I have yet to try the debricking method they suggest. Any thoughts?

  [1]: http://www.amazon.com/OSOYOO-ATmega32U4-arduino-Leonardo-ATmega328/dp/B012FOV17O?ie=UTF8&psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00
  [2]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#installing-windows

title: Arduino Pro Micro troubles

Answers: 2

body:
The Pro Micro, like the Leonardo, cannot automatically reboot into the bootloader like boards such as the Uno and Mega.  Instead it relies on the sketch running on it listening for a special combination of events (open the serial port, set the baud rate to 1200 baud, close the serial port) to activate the bootloader.

If, for whatever reason, you don't have a working sketch installed on the board (such as you aborted the upload part way through) then there will be nothing there to listen for the "reboot into bootloader" instructions.

So you need to manually enter the bootloader. Fortunately it should be easy enough, but timing is all important.

When you first plug the board in, or when you press the reset button, you get a few seconds where the board is in the bootloader.  On the Leonardo that is signified by the LED glowing and pulsating - I don't know off hand what is shown on the Pro Micro.

As long as you press the reset button just before you compile and upload your sketch, and as long as the upload portion doesn't take too long to start (tip: compile it before uploading, it makes it faster) it should then install the sketch into the board and from then on the auto-reboot should start working.

(Note: I haven't used a Pro Micro - this is all from my experience with the Leonardo which I believe uses the same bootloader.)

body:
You have to retrieve the VID/PID numbers your board actually has and change your boards.txt accordingly. On my Linux computer I made a USB connection with my corrupted pro micro clone, "lsusb" does not show it, but if I pull rst-pin down (pulse) "lsusb" does show it for a few seconds. Now I know the vid:pid numbers. I edited boards.txt (~/.arduino15/packages/Sparkfun/hardware/avr/1/1/5/:

promicro.build.vid=0x1b4f      (edited 1b4f with vid outcome of "lsusb")

promicro.menu.cpu.16MHzatmega32U4.build.pid.0=0x9205  (9205 edited)

Then in Arduino IDE I gave a reset pulse, the port showed up. I loaded the sample blinky script from sparkfun (https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#faq-change-pid), clicked "upload" and once again gave a reset pulse. The upload succeeded and my pro micro clone is back to normal.


body:
So I have 7 different sensor I’d like to send to Processing, then use each of their values as variables inside different webcam filters.

I’m going off of [this tutorial][1] which has been helpful, but it doesn’t give linear steps – more like different techniques depending on what you’re trying to use it for.
In that tutorial, it shows two ways to initialize connection between Serial and Arduino – the Punctuation method and the Call-and-response method. I used the Punctuation method.

To sum up the Punctuation method, you put the sensor values into one string, separated with commas. Once the values are sent over, you split the string and put all of the values into an array. Once in an array, you can individually take out each of the values and turn them into variables that are usable in the draw loop.

My Processing sketch runs perfectly fine sometimes. Otherwise it will give either this error :

      Error, disabling serialEvent() for /dev/cu.usbmodem1421
      null

Or this one :

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

Does anyone see anything fishy with the syntax or structure I’m setting up?
(I took out all filter functions except the temp -> blur to make debugging easier.)

    // get the serial lib :
    import processing.serial.*;

    // give port a variable :
    Serial port;

    // get the webcam lib :
    import processing.video.*;

    // give webcam a variable :
    Capture webcam;

    // sensors
    int cap1, cap2, piezo, temp, axisX, axisY, axisZ;

    void setup() {
      size(480, 360, P2D);
      smooth();

      webcam = new Capture(this, width, height, 24);
      webcam.start();

      String portName = "/dev/cu.usbmodem1421";
      port = new Serial(this, portName, 9600);
      //port.bufferUntil('\n');
    }

    void captureEvent(Capture webcam) {
      webcam.read();
    }

    void serialEvent(Serial port) {

      String reading = port.readStringUntil('\n');
      if (reading != null) {
        reading = trim(reading);

        int values[] = int(split(reading, ','));

        for (int valNum = 0; valNum < values.length; valNum++) {
          print(values[valNum] + "|");
        }
        println();

        if (values.length > 1) {
          cap1 = values[0];
          cap2 = values[1];
          piezo = values[2];
          temp = values[3];
          axisX = values[4];
          axisY = values[5];
          axisZ = values[6];
        }
      }
    }

    void draw() {

      // temp
      float t;
      if (temp >= 100) { //when analog pin unplugged
        t = 6;
      } else {
        t = 0;
      }

      image(webcam, 0, 0);
      filter(BLUR, t);
    }

    //if down key pressed, saveImage();
    void saveImage()
    {
      saveFrame("images/captured-####.jpg");
    }

    void keyPressed() {
      if (key == CODED) {
        if (keyCode == DOWN) {
          saveImage();
        }
      }
    }

I’m thinking it’s an issue with memory, or maybe the way I’m sending/receiving the data is shoddy.

Apparently one of the disadvantages to using Punctuation rather than Call-and-response is that it can slow down the program if it contains a lot of graphic work… but why would it work in perfect time sometimes and then not work at all?

Any insight would be amazing!!

  [1]: https://itp.nyu.edu/physcomp/labs/labs-serial-communication/two-way-duplex-serial-communication-using-an-arduino/
  [2]: https://i.stack.imgur.com/WT6Eg.png

title: Arduino Uno to Processing, using Serial

Answers: 0


body:
I just bought my first Arduino compatible device, and I am greatly enjoying it. I finally could not resist the urge after going to an Arduino meetup, where someone showed me their `Teensy` connected to their laptop and reacting to MIDI signals over USB.

Not knowing anything, I bought my clone and soon learned about the whole `CH340G` limitation where it doesn't "just work" (I cannot simply use the USBMIDI Arduino library), and instead I need to run a software MIDI-serial converter command (`ttymidi`) in order to send the signals to my Arduino clone.

I've been reading up a bit (the amount of information out there is perhaps too vast and often outdated or simply doesn't exactly solve my problem) and have learned of [V-USB][1] and the project [V-USB-MIDI][2] but I am really out of my element here and do not know how to approach this to get it all working (since it is not just an Arduino sketch and `.h` header). Or even if this is a solution to my problem. I've read about some solutions which require using an AVR via some of the pins (as opposed to over USB) since you have to reprogram the chip in such a way that it no longer is programmable over USB once the sketch is uploaded, but if I understood it correctly, you can't do even this on the `CH340G`.

In any case, are there any examples of getting this working? A sketch or something? I downloaded the latest V-USB release, but I really don't want to make a mistake that will brick or otherwise ruin my device.

Basically: I want to just upload my MIDI sketch (with whatever necessary modifications or code) such that I do not need `ttymidi` to have the device recognized as a MIDI device (over USB) that I can just "plug 'n' play".

  [1]: https://www.obdev.at/products/vusb/index.html
  [2]: http://cryptomys.de/horo/V-USB-MIDI/index.html

title: Arduino clone CH340G (ATmega328P), MIDI over USB

Answers: 1

body:
V-USB [bit bangs](https://en.wikipedia.org/wiki/Bit_banging) some GPIO pins so that they speak the low-speed USB protocol.
This does not use the 'normal' USB connection through the CH340; you would have to solder a separate USB cable to those GPIO pins.

Programming would be no problem; the V-USB code is just normal code that runs on the MCU. (Programming through ISP pins would be required on hardware where USB communication and programming is handled with a *second* AVR MCU; in that case, the USB/MIDI code would run on that second MCU.)

Low-speed USB is not supposed to be used for MIDI, and as a software emulation, V-USB does not work very well, or efficiently.
If you want to create a USB device, you should use an MCU that actually supports USB in hardware, such as the ATmega32U4 or AT90USB646 used on some Teensies.


body:
I'm trying to connect a HC-05 to AB Shutter3 module. However, when I try to search AB Shutter3 address via AT commands (`AT+INQ`) I could not find AB Shutter3.

I want to integrate both, so that I can send commands from an AB Shutter button click to HC-05.

I also want to know whether the HC-05 needs to be in master or in slave mode.

title: HC-05 to low cost AB shutter 3

Answers: 1

body:
I rather suspect the AB Shutter 3 is a Bluetooth HID device (like a keyboard or a mouse). The HC-05 can only communicate with Bluetooth Serial devices, such as the HC-06 or systems that can emulate a serial device (such as a computer or a smartphone).

You won't get them to communicate no matter how hard you hit them.


body:
EDIT :

I have plenty of weird bugs. I will open another thread, and come back to this one when I have better understanding, rather than completely modify this one halway through. Sorry to every answerer for my electronic incompetence which led me to ask the wrong questions; I hope the other thread makes more sense.

I have recently exhumed an arduino from a cupboard, and can't seem to make even a blinking LED circuit work correctly.

Here's the sketch :

    void setup() {
      pinMode(9, OUTPUT);
    }

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

This has been tried without the circuit, on pin 13, using the onboard LED, and it worked.

However, using the following circuit, it did not result in a blinking LED, using several pins (8, 9, 12, 13) and LEDS.

May I assume the arduino is fried?

Here is a thumbnail of the circuit : [![circuit picture][1]][1]

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

title: Arduino fried? Onboard blink ok; offboard blink not ok

Answers: 5

body: Try lighting up the LED without using any resistance in the middle, if that doesn't work try with a LED which consumes less current even if that doesn't work put the pin to HIGH state in code and measure the voltage of the given pin using a multimeter it should read above 3.3V. If neither of these work then you can be sure that your arduino is fried

body:
Here's a guide posted by Nick Gammon for checking if your Arduino is bricked [Is My Arduino Bricked ?][1]

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293

body:
It it possible the non-working LED got wired backward (it wouldn't be the first time!)? If the LED is clear enough, hold it up to the light and look inside the plastic bubble. There will be two bits of metal, one attached to each lead. One of them is significantly larger than the other; that's the cathode and it needs to be connected to the more negative side of the circuit. Here's a [picture][1].

  [1]: http://www.instructables.com/id/IDENTIFY-THE-ANODECATHODE-of-LEDs/

body:
You haven't exactly got the LED connected to pin 9, as in the code, have you?

I find it hard to believe that you can upload new sketches, but none of the pins work. Try pins 0 or 1, in the sketch, for example. Or the whole lot:

    void setup() {
      for (int i = 0; i < 20; i++)
        pinMode (i, OUTPUT);
    }

    void loop() {
      for (int i = 0; i < 20; i++)
      {
        digitalWrite(i, HIGH);
        delay(1000);
        digitalWrite(i, LOW);
        delay(1000);
      }
    }

Now methodically test every pin.

---

> What happens if you plug the white jumper into 5V rather than the current digital pin 12

<!-- -->

> The LED doesn't light.

Something's wrong with your testing. The processor cannot be powering up, and accepting new sketches, yet not have power to the +5V pin.

body: My arduino is not bricked, I just don't know how many things I don't understand about electronics, and make every single mistake I can make, especially while cabling.


body:
I have bought a SIM900 shield for an ordinary Arduino Uno board. The problem is that it doesn't have long pins on the bottom side, making it impossible to click on mu Arduino Uno.
The shield I have is this:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/ZOqzp.jpg
As you can see, there are identical pin spaces next to the red and yellow plastic female pin things. Can I just solder new pins in the free spaces and will it work like that?
I notice that the yellow and red plastic female pin holders on my board are on the free spaces in this picture. I supposed I can just use the adjacent foles to solder long pins so I can use it for my Arduino?

title: Arduino GPRS (GSM) shield (SIM900) no long pins

Answers: 1

body:
Yes, you can.

There is two methods of making shields stackable:

1. Use the quite hard to source extra long pinned headers to go right through and down (such as these https://www.adafruit.com/products/85) , or

2. Use separate headers and pins and (if you are using through hole) offsetting them.

Your shield uses the second method, but the descending pins haven't been populated.  By populating those pins you are just completing the build.


body:
HI I am a newbie and need some suggestions
Is there a possibility to do this?? I am trying to send MIDI data through a button using Arduino and bluetooth module HM10. Can someone help me write the loop part or am going the right way.

    #include <MIDI.h>
    #include <SoftwareSerial.h>
    SoftwareSerial mySerial (2, 3);
    char c = ' ';
    int pushButton7 = 7;
    int buttonState7 = 0;
    int note7 = 0;
    void setup() {
      MIDI.begin(4);
      // 115200 hairless MIDI
      Serial.begin(9600);
      mySerial.begin(9600);
      pinMode(pushButton7, INPUT);
    }

      void loop() {

       int buttonState7 = digitalRead(pushButton7);

     // Button 7

      // when button pressed:
      if (buttonState7 == HIGH) {
        // if note not playing
        if (note7 == 0) {
          // play note (note number, velocity, channel)
          // more info: http://arduinomidilib.sourceforge.net/a00001.html
          // MIDI notes chart http://www.phys.unsw.edu.au/jw/notes.html
          // 55 = G3, 127 = trigger note with max volume
          MIDI.sendNoteOn(55,127,1);
          // note is playing
          note7 = 1;
        }
      // when button released
      } else {
        // if note playing
        if (note7 == 1) {
          // if playing - stop
          MIDI.sendNoteOff(55,0,1);
        }
        // if button released note is off
        note7 = 0;
      }

      delay(1);

      }

title: Arduino with Bluetooth

Answers: 0


body:
I have an Arduino Uno connected to a motor controller over I2C. The Arduino accepts commands from a Raspberry Pi via the USB serial line.

I'm trying to diagnose a problem where the Arduino will become completely unresponsive. It's programmed to respond to a "ping" request every N seconds, and for some reason I can't identify, it seems to crash and no longer respond to any commands. However, the motor controller continues powering the motors.

Everything is powered from a 12V Li-Po battery, but everything is located behind 5V regulators. When this problem happens, the battery is fully charged and the motors aren't sourcing much current, and neither the motor controller or Raspberry Pi are effected, so I've ruled out a brownout.

My theory is there's some subtle programming error in my Arduino code that's causing an "exception", but I don't know how to identify it. I've tried adding special code to allow me to trigger one of these, by indexing an array outside of its limits or calling a null function pointer, but the Arduino stubbornly refuses to crash when I try to explicitly make it.

How do I diagnose an Arduino becoming unresponsive?

title: Diagnosing crashed Arduino Uno

Answers: 3

body:
Assuming you don't have access to a debugger, the most common way is to add debug logging. The ususal algorithm to solve those problems is more or less like this:

    do {
        add_logs_in_suspicious_places();
        wait_until_it_crashes();
        analyze_logs();
    } while( ! i_know_why_it_crashes() );

If you cannot add any debug logging because of a flawed system design (lack of I/O, etc) you've commited a captial engineering crime and this is your punishment. :)

body:
There is an excellent [post][1] by Nick Gammon that covers a wide array of possible problems. Look into this, as might be useful.

  [1]: https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board/13293#13293

body:
If you have spare pins, add debugging LEDs. For example, toggle one at the start of `loop`, another at the start of another function, and so on. When the Arduino "crashes" the state of the LEDs should provide a hint as to where in the code it is.

>  but the Arduino stubbornly refuses to crash when I try to explicitly make it.

Typically you are indexing outside an array or using uninitialized memory. Your debugging code has moved the problem around enough to stop it happening (or appearing to happen).

If you amend your question and post your code we might spot something.


body:
I am making a basic 2WD robot using Arduino Uno with motor shield.
I am getting no compile errors - but something in my logic flow is not working as expected.

Expected Operation:

 1. Ping sensor does distance check.
 2. If distance is less than 5cm.
 3. Turn both Channel A & B motors half-speed for 1 second.
 4. Stop motors.
 5. Take new distance reading ping, start again.

What however is happening, is that channel A works as expected, but channel B motor keeps running??
Where is my code / logic mistake?

Later date I will add to `else` statement to turn one wheel to change direction.

    /*
     HC-SR04 Ping distance sensor:
     VCC to arduino 5v
     GND to arduino GND
     Echo to Arduino pin 7
     Trig to Arduino pin 8
     */

    #define echoPin 7 // Echo Pin
    #define trigPin 8 // Trigger Pin
    #define LEDPin 13 // Onboard LED

    int maximumRange = 1000; // Maximum range needed
    int minimumRange = 1; // Minimum range needed
    long duration, distance; // Duration used to calculate distance

    void setup() {
      // put your setup code here, to run once:

    Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)

      pinMode(12, OUTPUT); /* Motor Channel A RIGHT SIDE*/
      pinMode(9, OUTPUT); /* Motor Channel A */

      pinMode(13, OUTPUT); /* Motor Channel B LEFT SIDE */
      pinMode(8, OUTPUT);

      }

    void loop() {

      /* Distance check begins */

      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);

      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);

      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH);

     //Calculate the distance (in cm) based on the speed of sound.
     distance = duration/58.2;

     /* End distance check */

     if (distance >= 5){
     /* Distance great enough to provide room to move */
      Serial.println("Move!");

      digitalWrite(LEDPin, HIGH); /* LED show movement */

      digitalWrite(12, LOW); /*move channel A motor half-speed */
      digitalWrite(9, LOW);
      analogWrite(3, 123);

      digitalWrite(13, HIGH); /*move channel B motor half-speed */
      digitalWrite(8, LOW);
      analogWrite(11, 123);

      delay(1000);

      digitalWrite(9, HIGH);
      digitalWrite(8, HIGH);
     }

     else {
     /* Send the distance to the computer using Serial protocol, and
     turn LED OFF to indicate successful reading. */
     Serial.println(distance);
     digitalWrite(LEDPin, LOW);
     }

     //Delay 50ms before next reading.
     delay(500);

    }

title: 2WD robot - logic error

Answers: 1

body:
I believe that your error is in that you declare `LEDpin` as pin 13 and then your motor B as pin 13 as well, that to me would result in errors when you write to the led in the else statement at the end of your code. I would recommend that you clean this up, don't use pins for different things. Try this first.

Your logic is ok in terms of functionality.

Also why is there inconsistency at this part on your code:

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

    digitalWrite(12, LOW); /*move channel A motor half-speed */
      digitalWrite(9, LOW);
      analogWrite(3, 123);

      digitalWrite(13, HIGH); /*move channel B motor half-speed */
     digitalWrite(8, LOW);
      analogWrite(11, 123);

Why do you say pin `12` must be` LOW` and `13 HIGH` when moving forward? Is this the way your un-mentioned circuit setup works, if possible could you add this info?


body:
I am trying to create a stable communication channel without any mis-synchronization. In the SoftwareSerial library, the write function transmits one byte at a time. The mis-synchronization occurs when the receiver misjudges which bit is the start bit. Why is this a problem? Because the internal delay between the start bit and the first message bit is different from the internal delay between each message bit.

One of the really good suggestions I have heard is to use [Manchester encoding][1] on the Arduino. While I am testing out this option, I also wanted advice on altering the software serial library in the following way. If I modify the write function to transmit 128 bytes instead of 1, then this can avoid the problem I explained above, I *assume.*

Here is how I have altered the write function of SoftwareSerial. I haven't thought of any issues with this approach, but does anyone else see any problems?
Here is the whole altered function. (I changed the parameter, and added 2 new loops - one to invert all the bytes if(inv) and another loop outside the loop that transmits each bit of a byte. I have attached the original function, further below.

    size_t SoftwareSerial::write(byte* b)
    {
      if (_tx_delay == 0) {
        setWriteError();
        return 0;
      }

    // By declaring these as local variables, the compiler will put them
    // in registers _before_ disabling interrupts and entering the
    // critical timing sections below, which makes it a lot easier to
    // verify the cycle timings
    volatile uint8_t *reg = _transmitPortRegister;
    uint8_t reg_mask = _transmitBitMask;
    uint8_t inv_mask = ~_transmitBitMask;
    uint8_t oldSREG = SREG;
    bool inv = _inverse_logic;
    uint16_t delay = _tx_delay;

    //Doubtful of this loop ------------------
    for(int i = 0; i < 128; i++)
    {
      if (inv)
        b[i] = ~(b[i]);
    }

    cli();  // turn off interrupts for a clean txmit

    // Write the start bit
    if (inv)
      *reg |= reg_mask;
    else
      *reg &= inv_mask;

    tunedDelay(delay);
    for(int j = 0; j < 128; j++)
    {
      // Write each of the 8 bits
      for (long i = 8; i > 0; --i)
      {
        if (b[j] & 1) // choose bit
          *reg |= reg_mask; // send 1
        else
          *reg &= inv_mask; // send 0

        tunedDelay(delay);
        b[j] >>= 1;
      }
    }
    // restore pin to natural state
    if (inv)
      *reg &= inv_mask;
    else
      *reg |= reg_mask;

    SREG = oldSREG; // turn interrupts back on
    tunedDelay(_tx_delay);

    return 1;
    }

Here is the original function.

    size_t SoftwareSerial::write(uint8_t b)
    {
    if (_tx_delay == 0) {
      setWriteError();
      return 0;
    }

    // By declaring these as local variables, the compiler will put them
    // in registers _before_ disabling interrupts and entering the
    // critical timing sections below, which makes it a lot easier to
    // verify the cycle timings
    volatile uint8_t *reg = _transmitPortRegister;
    uint8_t reg_mask = _transmitBitMask;
    uint8_t inv_mask = ~_transmitBitMask;
    uint8_t oldSREG = SREG;
    bool inv = _inverse_logic;
    uint16_t delay = _tx_delay;

    if (inv)
      b = ~b;

    cli();  // turn off interrupts for a clean txmit

    // Write the start bit
    if (inv)
      *reg |= reg_mask;
    else
      *reg &= inv_mask;

    tunedDelay(delay);

    // Write each of the 8 bits
    for (uint8_t i = 8; i > 0; --i)
    {
      if (b & 1) // choose bit
        *reg |= reg_mask; // send 1
      else
        *reg &= inv_mask; // send 0

      tunedDelay(delay);
      b >>= 1;
    }

    // restore pin to natural state
    if (inv)
      *reg &= inv_mask;
    else
      *reg |= reg_mask;

    SREG = oldSREG; // turn interrupts back on
    tunedDelay(_tx_delay);

    return 1;
    }

The serial buffer can only hold 64 bytes at a time, but I am using the following [code][2], courtesy of Nick Gammon to read the data from serial buffer without blocking. So it shouldn't be a problem on the receiving end either, I hope.

  [1]: http://forum.arduino.cc/index.php?topic=63755.0
  [2]: http://www.gammon.com.au/serial

title: Altering SoftwareSerial to transmit more than 1 byte at a time

Answers: 2

body:
Basically your code has changed the size of the RS-232 packet from 10 bits to 1026 bits. There is nothing "wrong" with that, but it doesn't really solve the problem of a missed start bit - if anything it makes it worse since instead of losing 8 bits you lose 1024 bits.

Synchronisation is best done separately to the transmission of packets, and for that you need your packet to be nice and short.

A packet consists of 10 bits - the first is a LOW and the last is a HIGH; everything else in between is data.  The trick is to provide a forced idle period before sending of *at least* the amount of time it takes to transfer one packet.  That way if the receiver is mistakenly in a receive loop for whatever reason the 10 (or more) bits worth of HIGH will effectively cause the receiver to finish whatever it is doing and get ready to receive your real byte.

If you have a hugely long packet (1024 + 2 bits) flushing the receiver before transmitting will take a very long time - rather than just one byte's worth of time it will be your entire packet's transmit time.

On top of that you then have the problem of byte order and data integrity checking.  Just sending two bytes (or 128 bytes) is not reliable. You need to wrap those bytes in a protocol including a start-of-packet indicator (0x55 0xAA is common, as is the special ASCII character 0x01: SOH), packet or payload length, and checksums.  Options for things like sequence numbers, acknowledgements, packet retransmission, etc can also be built in to increase the reliability of the protocol.

Rather than trying to reinvent the wheel by changing the underlying data layer transmission you should learn the OSI 7 layer model and implement your protocol at a higher level than the data layer.

body:
So far you have asked a *lot* of questions about your project which uses SoftwareSerial to send a lot of bits:

* https://arduino.stackexchange.com/questions/17864/how-to-transmit-more-than-1-byte-continually
* https://arduino.stackexchange.com/questions/16390/basic-serial-transmission-protocol
* https://arduino.stackexchange.com/questions/17326/synchronization-and-implementing-hamming-code-on-software-serial
* https://arduino.stackexchange.com/questions/22274/encoding-clock-signal-into-linear-block-codes
* https://arduino.stackexchange.com/questions/16393/how-to-fix-baud-rate-when-hardware-capacity-has-a-low-limit
* https://arduino.stackexchange.com/questions/17021/unable-to-tell-if-error-is-from-receiving-or-transmitting-end
* https://arduino.stackexchange.com/questions/17309/read-function-in-software-serial

And now we have another one (this question).

I think you are flogging a dead horse with this. For one thing, what are you trying to achieve, that can't be achieved by just sending the bytes "normally" as 8-bit bytes? The only thing I can think of is a slight speed increase. By trying to make a 1024-bit packet, you are saving some start and stop bits in the middle, that's all.

In some of your other questions you mention 9600 baud, so let's run with that. At 9600 baud one bit is 1/9600 of a second, that is 104.17 µs.

To transmit 1024 bits "normally" you would need 128 bytes, each of which needs a start and stop bit, so the total is `128 * 10 * 104.17 µs = 133.338 ms.`

To use your system you need 1024 bits plus one start and stop bit, so that is `1026 * 104.17 µs = 106.878 ms.`

So far you have only saved 26.46 ms.

You could save a lot more by simply doubling the baud rate. Or quadrupling it. However SoftwareSerial is less reliable at higher baud rates. Why not use HardwareSerial?

Your next problem is that SoftwareSerial turns interrupts off during reception of one byte, so that it gets the timing right. For an 8-bit byte this means they are off for `10 * 104.17 µs = 1.0417 ms`. That's about the limit for turning interrupts off if you want the internal timer to work, the one which gives you `millis` and `micros`. If you turn them off for 128 times as long, you can say "goodbye" to knowing how much time has elapsed.

As I mentioned in a comment, too, since serial comms relies on external clocks (that is, both ends have to get the clocking right) you can only afford around a ±2% error in the receiving clock to ensure that we are sampling at the correct place (see the datasheet) for an *8-bit byte*. The error tolerance will drop to 1/128th of that if you try to send 128 bytes in a single stream. The crystal/resonator in the Arduino just won't be that good.

Finally, to avoid false detection of the start bit (which you have asked about elsewhere) you need a much longer gap between packets, to ensure that we get the correct start bit. Effectively you need a one-byte length (ie. the incoming data is continually HIGH) for 8-bit bytes. For 1024-bit packets you will need to introduce a gap of `1024 * 104.17 µs = 106.670 ms` between packets. This required gap totally wipes out any saving by not sending those extra start and stop bits.


body:
Looks like I'm overshooting the storage of my Adafruit Trinket:

    Sketch uses 5,600 bytes (105%) of program storage space. Maximum is 5,310 bytes.
    Global variables use 109 bytes of dynamic memory.

Any tips for reducing the footprint of my code?

<!-- language: c -->

    #include <Adafruit_NeoPixel.h>
    #include <Wire.h>
    #include <RTClib.h>

    #define LEDPIN 1
    #define TONE 4
    #define BTNPIN 3

    RTC_DS1307 rtc;
    Adafruit_NeoPixel strip = Adafruit_NeoPixel(4, LEDPIN, NEO_RGB);

    long fadeTime = 1 * 10000L; // X minutes
    int colorStops = 256;
    int delaySpeed = fadeTime / colorStops;
    int notes[] = {262,294,330,349};
    int timeHour = 14;
    int timeMinute = 43;
    uint32_t alarmLength = 5 * 60000L; // 5 minutes

    void setup() {
      rtc.begin();
      if(!rtc.isrunning()) {
        rtc.adjust(DateTime(__DATE__, __TIME__));
      }

      pinMode(TONE,OUTPUT);
      pinMode(BTNPIN, INPUT);
      digitalWrite(BTNPIN, HIGH);

      strip.begin();
      strip.show();
    }

    void loop() {
      DateTime now = rtc.now();

      if (now.hour() == timeHour && now.minute() == timeMinute && now.second() == 0){
        // Fade in light
        for(int i = 1; i<colorStops; i++){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
            strip.setPixelColor(np, strip.Color(i,i,0));
          }
          strip.show();
          delay(delaySpeed);
        }

        // Play tone after light fully bright
        for( uint32_t tStart = millis();  (millis()-tStart) < alarmLength; ){
          if (kill() == true){ break; }

          for(int np = 0;np<strip.numPixels(); np++){
            strip.setPixelColor(np, strip.Color(random(100,255),random(100,255),random(100,255)));
          }
          strip.show();

          beep(TONE, notes[random(0,3)], 50);
          delay(100);
        }

        for(int np = 0;np<strip.numPixels(); np++){
          strip.setPixelColor(np, strip.Color(0,0,0));
        }
        strip.show();
      }
    }

    void beep (unsigned char speakerPin, int frequencyInHertz, long timeInMilliseconds)
    {   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
      int x;
      long delayAmount = (long)(1000000/frequencyInHertz);
      long loopTime = (long)((timeInMilliseconds*1000)/(delayAmount*2));
      for (x=0;x<loopTime;x++)
      {
        digitalWrite(speakerPin,HIGH);
        delayMicroseconds(delayAmount);
        digitalWrite(speakerPin,LOW);
        delayMicroseconds(delayAmount);
      }
    }

    bool kill() {
      if (! digitalRead(BTNPIN)) {
        for(int np = 0;np<strip.numPixels(); np++){
          strip.setPixelColor(np, strip.Color(0,0,0));
        }
        strip.show();
        return true;
      }
      else {
        return false;
      }
    }

title: How can I reduce the size of my sketch?

Answers: 3

body:
The AdaFruit Trinket just doesn't have a lot of memory - 8kb, of which 3kb is used by the bootloader.

The order I look for things to reduce the footprint of an Arduino program are:

* data (e.g. large strings)
* libraries
* your code (especially doing the same things several times, which might be combined into loops or functions).

In this case, you don't have much data. Most of your resulting program size is in the libraries you use.

It seems like you use the clock solely to detect the year - that seems like a lot of overhead just to figure out what year it is. It then does nothing for subsequent years (or prior years), if I read your code correctly. Maybe you would consider dropping this code? Then you can skip the entire RTC library. At least try it to see how much you save. I suspect that the RTC library will use another library to do the underlying work.

You use the <Wire.h> library, but don't reference it in your code. It should be optimized out (unless used elsewhere), but there's no reason to have it there.

You may also save a little space by replacing initialized variables which don't change to constants. Storing `25` in a variable takes 1 byte, plus 2 bytes every time you reference it; `25` in a constant gets optimized away, and will take up 1 byte every time you reference it.

As mentioned in the comments, you can also save a few bytes by specifying the size of your int's, especially initialized ones.

Another option would be to use a larger chip - the AtMega328p used in (for example) the Arduino has 32kb of flash - 6 times the (available) size.

You can also save some bytes by removing the clause `  if(!rtc.isrunning()) {
`, once you have set it up once.

**Additional**: I have had some success reducing footprints by reimplementing a subset of a library. Usually, libraries are very well implemented, but if your needs are substantially different/simpler than what the library was designed for, or you are willing to forgo parts of it (e.g. error checking), then SOMETIMES this can help. WARNING! There is a HIGH price to pay (coding, debugging, loss of error checking, undetected bugs etc), and it may *not* save you anything in the end.

You can also (sometimes) move data (e.g. large strings) to eeprom. The Trinket has 512 bytes of eeprom. You may need one sketch to load the data into eeprom, to run before loading your main sketch. eeprom has it's own overhead, so may not be worthwhile for 512 bytes, it is slower (which probably won't matter for this), and you have a limited number of writes.

Another few bytes may be saved by doing all the maths for the tone frequency/time beforehand, and sacrificing something. For example, you beep for 50ms. If, instead of passing the frequency (between 262 and 349 hertz) and instead pre-calculate the delayAmount (for 262 hz, this would be 1,000,000/262 = 3817ms); your looptime for this is ((timeInMilliseconds*1000)/(delayAmount*2)) = (50*1000)/(3817*2) = 6.55 cycles. 7 cycles is probably "close enough" for all the tones you want to produce. So you can hardcode 7 cycles (using a constant of 7 for looptime), and get rid of that formula to calculate looptime.

In a similar way, if you don't care too much about the exact frequency (which varies between 3817ms and 2865ms depending on your random number), you might specify the delayamount as 2865+random(0,3)*238 (make sure you store at least the random number, you don't want it to change during the loop!).

You now have:

    #define random_beep_length 7
    void random_beep (unsigned char speakerPin)
    {   // http://web.media.mit.edu/~leah/LilyPad/07_sound_code.html
        // Heavily modified!
      int x;
      unsigned char pitch = 2865+random(0,3)*238;
      for (x=0;x<random_beep_length;x++)
      {
        digitalWrite(speakerPin,HIGH);
        delayMicroseconds(delayAmount);
        digitalWrite(speakerPin,LOW);
        delayMicroseconds(delayAmount);
      }
    }

body: An option not already mentioned, but may be worth mentioning, would be to remove the bootloader and program the chip directly with a hardware programmer (or another Arduino). That will increase the available sketch memory from 5kiB to the full 8kiB on the chip.

body:
As already mentioned by AMADANON Inc. in his answer, you should qualify
as `const` all the constant variables at the beginning of the program.
This is probably the biggest space saver.

You can gain something like 100 bytes by using [direct port
access](https://www.arduino.cc/en/Reference/PortManipulation) instead of
pinMode/digitalRead/digitalWrite. In the case of the ATtiny85, you only
have port B, and the Arduino pin numbers are the same as the Atmel bit
numbers. So you would for example use `PINB & _BV(BTNPIN)` instead of
`digitalRead(BTNPIN)`.

There are a few optimization opportunities in `beep()`:

* pass only one parameter, as `speakerPin` and `timeInMilliseconds` are
  constants in your program
* have this parameter be `delayAmount` instead of `frequencyInHertz`,
  and store these delays, instead of the frequencies, in the `notes[]`
  constant array
* do not compute the number of iterations (the misnamed `loopTime`)
  beforehand, instead compute the elapsed time and loop until you reach
  the required time

Here is my version of `beep()` with these optimizations:

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

    void beep(int delayAmount)
    {
      for (uint16_t t = 0; t < BEEP_TIME*1000/2; t += delayAmount)
      {
        PORTB |= _BV(TONE);  // digitalWrite(TONE,HIGH);
        delayMicroseconds(delayAmount);
        PORTB &= ~_BV(TONE);  // digitalWrite(TONE,LOW);
        delayMicroseconds(delayAmount);
      }
    }

Notice that the loop variable is actually _half_ the elapsed time. This
saves a few bytes. Making the number of iterations constant, as proposed
by AMADANON Inc., also saves a few bytes (6 bytes in my test).

You should also remove all the calls to `strip.Color()`: replace every
instance of `strip.setPixelColor(np, strip.Color(r, g, b))` by
`strip.setPixelColor(np, r, g, b)`.

With all these optimizations combined, I am quite confident you will
gain more than the 290 bytes you need to fit your program in the
Trinket.


body:
I'm trying to get GPS data transmitted from one Arduino UNO to a second unit to eventually be displayed on an LCD and stored in an SD card.  I am using Xbees S2C's on Xbee Shield's to do this.  The GPS information is coming from an Adafruit ultimate GPS breakout.

First I wanted so send two NMEA sentences as strings, but have since found that the EasyTransfer library does not like that.  I was getting information but it was just random characters, sort of.  The pattern was repeated, so it was consistent.

After doing some searching I thought the best way to do it was to convert my strings to character arrays and send those.  I managed to successfully convert them to character arrays, but I can't seem to get them over to the other Arduino.  I do get the FIX int as well as the Length int that I sent over just to make sure it is working.  Any ideas on what I am doing wrong?

Sender code:
<!-- language-all: lang-cpp -->

    #include <EasyTransfer.h>
    #include <Adafruit_GPS.h>
    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(3, 2); //Initialize SoftwareSerial, and tell it you will be connecting through pins 2 and 3
    Adafruit_GPS GPS(&mySerial); //Create GPS object

    String NMEA1;  //We will use this variable to hold our first NMEA sentence
    String NMEA2;  //We will use this variable to hold our second NMEA sentence
    char c;       //Used to read the characters spewing from the GPS module
    int fix = 0;
    long GPStime = 0;
    int val = 0;

    EasyTransfer ET;

    //Declare Data Structure for the EasyTransfer Library
    //Note: Data Structure must be same on TX and RX...

    struct DATA_STRUCTURE{
     int fixed;
     int length1;
     int length2;
     char* nmea1;
     char* nmea2;
    };

    DATA_STRUCTURE myData;

    void setup()
    {
      //Initalizing EasyTransfer Serial Ports
      Serial.begin(115200);
      ET.begin(details(myData), &Serial);
      GPS.begin(9600);       //Turn GPS on at baud rate of 9600
      pinMode(13, OUTPUT);
      digitalWrite(13, LOW);
      //Serial.println("Two GPS Sentences From GPS");
      GPS.sendCommand("$PGCMD,33,0*6D"); // Turn Off GPS Antenna Update
      GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); //Tell GPS we want only $GPRMC and $GPGGA NMEA sentences
      GPS.sendCommand(PMTK_SET_NMEA_UPDATE_10HZ);   // 10 Hz update rate
      delay(1000);  //Pause
    }

    void loop()
    {
      readGPS();  //This is a function we define below which reads two NMEA sentences from GPS
      //Sending Data
      ET.sendData();
    }

    void readGPS()    //This function will read and remember two NMEA sentences from GPS
    {
      clearGPS();    //Serial port probably has old or corrupt data, so begin by clearing it all out
      while(!GPS.newNMEAreceived())   //Keep reading characters in this loop until a good NMEA sentence is received
      {
        c=GPS.read(); //read a character from the GPS
      }
      GPS.parse(GPS.lastNMEA());  //Once you get a good NMEA, parse it
      NMEA1=GPS.lastNMEA();      //Once parsed, save NMEA sentence into NMEA1
      while(!GPS.newNMEAreceived()) //Go out and get the second NMEA sentence, should be different type than the first one read above.
      {
        c=GPS.read();
      }
      GPS.parse(GPS.lastNMEA());
      NMEA2=GPS.lastNMEA();

      fix = GPS.fix;
      if (fix == 1)
      {
        //Serial.print("FIXED");
        digitalWrite(13, HIGH);
        //Serial.print(NMEA1);
        myData.fixed = 1;
        int str_len1 = NMEA1.length();
        char char_array1[str_len1];
        NMEA1.toCharArray(char_array1, str_len1);
        myData.length1 = str_len1;

        //Serial.print(char_array1);
        //Serial.println("");
        //Serial.println("");
        myData.nmea1 = char_array1;

      }
      else
      {
        //Serial.println("No fix");
        digitalWrite(13, LOW);
        myData.fixed = 0;

      }
    }

    void clearGPS() //Since between GPS reads, we still have data streaming in, we need to clear the old data by reading a few sentences, and discarding these
    {
      while(!GPS.newNMEAreceived())
      {
        c=GPS.read();
      }
      GPS.parse(GPS.lastNMEA());
      while(!GPS.newNMEAreceived())
      {
        c=GPS.read();
      }
      GPS.parse(GPS.lastNMEA());
    }

Receiver Code:

    #include <EasyTransfer.h>
    #include "Wire.h"
    #include "Adafruit_LiquidCrystal.h"

    EasyTransfer ET;

    Adafruit_LiquidCrystal lcd(0);

    //Declare Data Structure for the EasyTransfer Library
    //Note: Data Structure must be same on TX and RX...

    struct DATA_STRUCTURE{
     int fixed;
     int length1;
     int length2;
     char* nmea1;
     char* nmea2;
     //int pause;
    };

    DATA_STRUCTURE myData;

    char* NMEA1[100] = {0};

    void setup()
    {
     //Initalizing EasyTransfer Serial Ports
     Serial.begin(115200);
     ET.begin(details(myData), &Serial);

     lcd.begin(20, 4);
     lcd.clear();
     lcd.setBacklight(HIGH);

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

    }

    void loop()
    {
      //check and see if a data packet has come in.
      if(ET.receiveData()){
        //this is how you access the variables. [name of the group].[variable name]
        int FIX = myData.fixed;
        int LENGTH1 = myData.length1;
        char* NMEA1 = myData.nmea1;
        Serial.println(FIX);
        Serial.println(LENGTH1);
        Serial.print(NMEA1);
        Serial.println("");
        if (myData.fixed == 1)
        {
          digitalWrite(13, HIGH);
          lcd.setCursor(10, 3);
          lcd.print(" GPS Fixed");
        }
        else
        {
          digitalWrite(13, LOW);
          lcd.setCursor(10, 3);
          lcd.print("No GPS Fix");
        }
      }

      delay(1000);
    }

Any help would be appreciated.

Thanks!
K-Bert

title: Sending GPS data between two Arduinos using Easy Transfer

Answers: 0


body:
I have a servo motor on one end which can be turned ON and OFF with web service sending SOAP request. In the other end I have my Arduino UNO with ESP8266. Currently, I am able to send HIGH or LOW status from my Arduino to ESP8266.

My query is: After receiving the status "HIGH" from Arduino to ESP8266, I need to POST the status via SOAP request so that my motor would be "turned ON" . After turning ON the motor in the other end I would like to GET a simple SOAP response.

I am not sure if the above explains to you clearly but I am tired of thinking "how to do this".

title: Sending data from Arduino UNO as a SOAP request

Answers: 0


body:
**I was wondering if it was possible to work, in the same Arduino board, both Transmitter and Receiver RF 433 MHz modules. Is it feasible?**

Here is the schematics I tried:

1) a pushbutton toggles a state value (0 or 1) and triggers the RF transmitter to send it as a message to the receiver module

2) the RF receiver, whenever reading the message, turns on or off a LED according to the corresponding value (0 or 1)

[![RF 433 Modules with the same Arduino board][1]][1]

Here is the source code I wrote:

    #include <VirtualWire.h>

    #define BTN_PIN A0    // pushbutton que aciona a transmissao
    #define LED_PIN 13    // LED aceso ao receber o sinal
    #define TX_PIN   4    // ligado ao pino DATA do transmissor RF
    #define RX_PIN   7    // ligado ao pino DATA do receptor RF

    #define SPEED  5000   // velocidade de comunicacao (bits por segundo)

    int estado = 0;

    void setup() {
      pinMode(BTN_PIN, INPUT);
      pinMode(LED_PIN, OUTPUT);

      vw_set_tx_pin(TX_PIN);  // transmissor
      vw_set_rx_pin(RX_PIN);  // receptor
      vw_setup(SPEED);
      vw_rx_start();

      Serial.begin(9600);
    }

    void loop() {
      int pressionado = !digitalRead(BTN_PIN);
      char msg[4];

      if (pressionado) {
        estado = !estado;
        itoa(estado, msg, 10);

        vw_send((uint8_t *) msg, strlen(msg));
        vw_wait_tx();

        Serial.print("Mensagem enviada: [");
        Serial.print(msg);
        Serial.println("]");

        delay(500);
      }

      uint8_t buf[VW_MAX_MESSAGE_LEN];
      uint8_t buflen = VW_MAX_MESSAGE_LEN;
      int recebido = 0;

      memset(msg, 0, 4);
      if (vw_get_message(buf, &buflen)) {

        for (int i = 0; i < buflen; i++)
          msg[i] = char(buf[i]);
        msg[buflen] = '\0';

        Serial.print("Mensagem recebida: [");
        Serial.print(msg);
        Serial.println("]");

        recebido = atoi(msg);

        Serial.print("recebido = ");
        Serial.println(recebido);

        digitalWrite(LED_PIN, recebido);
      }
    }

When I run it, according to Serial Monitor it sends the message. The problem is no message comes to the RF receiver.

**Does anyone have an idea of what could be wrong?**

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

title: RF 433 Module with VirtualWire: transmit and receive using the same Arduino board

Answers: 2

body:
As said in the comment you definitely need an antenna on both modules.

It is also possible that you are not supplying enough power to the 433 Mhz modules. The Arduino is not capable of outputting much current and RF transmitters generally have large current spikes.

So I would recommend that you use a seperate power supply to power the modules (do not forget to keep common ground between the Arduino and the Transmitter.)

I have also heard that it is preferred to not maintain common ground between the transmitter and the receiver. So if all else fails then use two separate power supplies.

body:
These lines in the ISR in VirtualWire.cpp

        if (vw_rx_enabled && !vw_tx_enabled)
         vw_rx_sample = vw_digitalRead_rx() ^ vw_rx_inverted;
and

        if (vw_rx_enabled && !vw_tx_enabled)
         vw_pll();

mean that the receive path code is just not executed while the transmitter is enabled.

It kind of seems from the comment as that might not have been true at some point in the past, though I'm not seeing a version history for an "official" version to check.

You could try to modify the code to implement both, but it is worth noting that VirtualWire has been deprecated in favor of the more versatile RadioHead, so you might want to evaluate that and perhaps make modifications there instead.


body:
The arduino IDE can't seem to find the wire.h file when i'm using the [new liquid crystal library][1]. Does anyone know how to solve this? here is the code i'm using and the error message:

    /*-----( Import needed libraries )-----*/
    #include <Wire.h>  // Comes with Arduino IDE
    #include <LiquidCrystal_I2C.h>

    /*-----( Declare Constants )-----*/ /*-----( Declare objects )-----*/ // set the LCD address to 0x27 for a 16 chars 2 line display // A FEW use address 0x3F // Set the pins on the I2C chip used for LCD connections: //                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    /*-----( Declare Variables )-----*/ //NONE

    void setup()   /*----( SETUP: RUNS ONCE )----*/ {   Serial.begin(9600);  // Used to type in characters

      lcd.begin(16,2);   // initialize the lcd for 16 chars 2 lines, turn on backlight

    // ------- Quick 3 blinks of backlight  -------------   for(int i = 0; i< 3; i++)   {
        lcd.backlight();
        delay(250);
        lcd.noBacklight();
        delay(250);   }   lcd.backlight(); // finish with backlight on

    //-------- Write characters on the display ------------------ // NOTE: Cursor Position: (CHAR, LINE) start at 0     lcd.setCursor(0,0); //Start at character 4 on line 0   lcd.print("Hello, world!");   delay(1000);   lcd.setCursor(0,1);   lcd.print("HI!YourDuino.com");   delay(8000);

    // Wait and then tell user they can start the Serial Monitor and type in characters to // Display. (Set Serial Monitor option to "No Line Ending")   lcd.clear();   lcd.setCursor(0,0); //Start at character 0 on line 0   lcd.print("Use Serial Mon");   lcd.setCursor(0,1);   lcd.print("Type to display");

    }/*--(end setup )---*/

    void loop()   /*----( LOOP: RUNS CONSTANTLY )----*/ {   {
        // when characters arrive over the serial port...
        if (Serial.available()) {
          // wait a bit for the entire message to arrive
          delay(100);
          // clear the screen
          lcd.clear();
          // read all the available characters
          while (Serial.available() > 0) {
            // display each character to the LCD
            lcd.write(Serial.read());
          }
        }   }

    }/* --(end main loop )-- */

Here is the compiler output

> Arduino: 1.6.7 (Windows 10), Board: "Arduino Nano, ATmega328"
>
> C:\Users\martin\Documents\Arduino\libraries\LiquidCrystal\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.
>
>   This report would have more information with   "Show verbose output
> during compilation"   enabled in File > Preferences.

[1]: https://bitbucket.org/fmalpartida/new-liquidcrystal/wiki/Home

title: Wire.h not found newliquidcrystal

Answers: 1

body:
The liquid crystal library has to be installed in the same folder as the wire library:

    libraries/Wire/Wire.h (etc)
    libraries/LiquidCrystal/LiquidCrystal_I2C.h (etc)

There is a hard-coded path in the liquid crystal library pointing to the wire library that is relative to where the liquid crystal library is, which is done to get around the problem that the Arduino library doesn't recurse libraries. It's not actually needed since including the Wire library in the IDE is enough to tell it where to find it for the liquid crystal library, so I don't really know why they did it that way.


body:
I'm trying to use Analog Devices' isolated ADC [ADE7912](http://www.analog.com/en/products/analog-to-digital-converters/integrated-special-purpose-converters/energy-metering-ics/ade7912.html#product-overview) to build a native product for voltage and current sensing, using an Arduino as a microcontroller. The IC communicates with the Arduino using SPI (and SCK frequencies of 8,4,2 and 1 MHz), and I have followed the datasheet and written down some basic code using SPI-transactions and all, which seems to be giving correct results when I apply a positive voltage to the inputs of the ADC. I have two problems here:

1. When I try to display the SCLK, MISO and MOSI signals on an oscilloscope, the clock seems to have trouble maintaining its value (it becomes erratic and hence the SPI communication also misses some values etc.) Why is this happening?

2. When I apply a negative voltage to the ADC inputs, the IC does not really show any response to that even though it clearly supports negative voltage inputs to the ADC, as mentioned in the datasheet. This might be an IC related problem, but I am not sure.

Also, is there anyone who has built a library for this IC? Would be greatly obliged if they could share it.

title: Using a SPI based ADC (ADE7912) with Arduino

Answers: 1

body:
I have not written a full library, but I have recently been using the ADE7913 (same as ADE7912 but with an extra voltage channel) with an Arduino MEGA.

The basic sketch located [here][1] talks to the ADE7913 over SPI, and then prints the results of the measurement registers over serial (so you can see them using a serial monitor).

I have not yet done much measurement testing, so can't comment on the negative voltage issue you have seen, but the sketch sets up the ADE7913 to use the V2WV register for monitoring temperature, and converts the result into degrees C, so you should be able to tell if its working properly.

In terms of the issues you have been having with the SPI comms, I can offer the following suggestions based on my troubleshooting experience (I also had glitchy comms initially):

1. I'm pretty new to SPI, but my interpretation of the data-sheet is that the ADE791X chips use `SPI_MODE3` (i.e. SCLK is normally high, and samples are read on the trailing clock edge). I have found `SPI_MODE1` also works, but unless others can correct me would suggest using 3.
2. I found having physically long jumper wires (my prototyping is still on a bread-board) caused issues. I have read elsewhere that at frequencies in the ones of MHz, distances less than tens of meters shouldn't be an issue; but I shortened / tidied my wiring and it seemed to help.
3. I would run everything at lowest possible speeds to troubleshoot, i.e. set the ADC sampling rate to 1kHz (set `CONFIG` bits `5:4` to `11`), and set the SCLK at 250kHz.
4. In the attached sketch, I am reading the register values based on an interrupt from the `CLKOUT\!DREADY` pin. You have to be careful that this reading routine takes less than one ADC sampling time to read all the registers. There is a good explanation of this timing constraint in Figure 8 of [this application note][2]. The attached sketch also reports some timing information over serial to help with this.

Hope that helps,

- Khalid.

  [1]: https://github.com/khalida/ade7913/blob/master/ADE7913_VI_sense_board.ino.ino
  [2]: http://www.analog.com/media/en/technical-documentation/application-notes/AN-1332.pdf


body:
I'm trying to transmit using mode 5 with the rc switch library, but my reciever tells me that the data is using protocol 2. I'm using the RecieveDemo_simple example as a sniffer for 433 MHz and I'm recieving data with protocol 5 from a wireless electric plug that I want to replicate.

I am able to send the data, but it is using the wrong protocol most of the time.

Here's some output from the reciever:

    Received 15766156 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 5
    Received 15885740 / 24bit Protocol: 2
    Received 15885740 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 2
    Received 15766156 / 24bit Protocol: 5
    Received 15885740 / 24bit Protocol: 2
    Received 15885740 / 24bit Protocol: 2
    Received 15885740 / 24bit Protocol: 5

The code:

    /*
      Example for different sending methods

      https://github.com/sui77/rc-switch/

    */

    #include <RCSwitch.h>

    RCSwitch mySwitch = RCSwitch();

    void setup() {

      Serial.begin(9600);

      // Transmitter is connected to Arduino Pin #10
      mySwitch.enableTransmit(10);

      // Optional set pulse length.
      // mySwitch.setPulseLength(320);

      // Optional set protocol (default is 1, will work for most outlets)
      mySwitch.setProtocol(5);

      // Optional set number of transmission repetitions.
      // mySwitch.setRepeatTransmit(15);

    }

    void loop() {

      /* Same switch as above, but using decimal code */
      mySwitch.send(15885740, 24);
      delay(1000);
      mySwitch.send(15766156, 24);
      delay(1000);

    }

title: Rc switch library transmit using protocol 5

Answers: 1

body:
I would expect your sending protocol 5 just fine.

But because protocol 2 and 5 are very similar, your receiver gets confused about which protocol it sees when there's noise or other interference.

This is the definition of the two protocols from the code:

    { 650, {  1, 10 }, {  1,  2 }, {  2,  1 }, false },    // protocol 2
    { 500, {  6, 14 }, {  1,  2 }, {  2,  1 }, false },    // protocol 5

Note the last three parts are the same, which are the pulses for 0, 1, and whether or not the high/lows are inverted.
The first part is also very similar, which is the pulse length. It's so similar that the difference probably falls within the margin for error the receiver software uses.
Only the second parts differs a bit more, which is the sync bit, it's a short high pulse followed by a longer low pulse. It's easy to mistake the one for the other though when there's noise and such.


body:
I'm dealing with an application in which I need to upload sketches remotely to an arduino UNO board. I successufully managed to upload sketches using an HC-06 bluetooth adapter. The only problem is that I am forced to manually press the reset button once the bluetooth link is established. Is there a way to automatically reset the arduino, in a software or hardware way,  so that it will be able to accept and install the incoming and sketch?
Would it be enough to activate a digital pin connected to the reset at the right timing prior the upload process starts?

title: Upload sketch via Bluetooth using HC-06 module

Answers: 2

body:
Here's a instructable on how to reset the arduino with software

[Instructables link][1]

  [1]: http://www.instructables.com/id/two-ways-to-reset-arduino-in-software/

body:
Use a BJT/FET.

For a NPN, connect RST to COLLECTOR, a digital pin in series with a 220 ohm (or whatever’s appropriate) resistor to BASE, and EMITTER to GND.

Just bring the digital pin HIGH to reset your arduino.