body:
OK, I'm working on a remote controlled robot. Both the robot and the remote use Arduino with a Bluetooth shield. The Bluetooth is working and I need to send something similar to this over Bluetooth:

`X:1026,Y:1026,Button:1`

There may be more buttons added and `X,Y` can be between `1026` and `0`. How can I build that string from:

```xPosition = 1026;
 yPosition = 1026;
 buttonState = 0;```

I also need to be able to separate that string back into variables on the 2nd Arduino.

EDIT: I have seen other questions similar to this but they involved Serial. I am using Bluetooth.

EDIT AGAIN: I am sending the data over Bluetooth with the `BlueToothSerial.print` command from the `SoftwareSerial.h` library. (`BlueToothSerial` is `SoftwareSerial BlueToothSerial(RxD,TxD);`)

title: Arduino join multiple strings and numbers and then seperate them

Answers: 1

body:
To make the string you can:

    char outstring[30];
    sprintf(outstring, "X:%d,Y:%d,Button:%d", xPosition, yPosition, buttonState);

Be sure to make the `outstring` big enough to store it all.

That is, of course, if you actually *need* to have the whole thing in one string all the time.  You haven't said how you are sending it (yes, I know, bluetooth, but there is bluetooth and there is bluetooth, and there are different ways of it working.)

Splitting a string like that can be done with `strtok()` then looking for the location of the colon in each returned token. Or, depending on how the string data actually arrives, could be parsed on a character-by-character basis, which would be better. Again, because you haven't told us how the data is actually being transferred it's impossible to elaborate on that.


body:
I have a quick question regarding this code below in Arduino:

    Serial.print("0");
    Serial.print(5);
    Serial.print("0");
    Serial.print(1);
    Serial.print("0");
    Serial.print(5);
    Serial.print("0");
    Serial.print(1);
    Serial.print("0");
    Serial.println(5);

In C code, currently I'm receiving the message using this method below:

    int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
    {
        char b[1];  // read expects an array, so we give it a 1-byte array
        int i=0;
        do {
            int n = read(fd, b, 1);  // read a char at a time
            if( n==-1) return -1;    // couldn't read
            if( n==0 ) {
                usleep( 1 * 1000 );  // wait 1 msec try again
                timeout--;
                if( timeout==0 ) return -2;
                continue;
            }
            buf[i] = b[0];
            i++;
        } while( b[0] != until && i+1 < buf_max && timeout>0 );

        buf[i] = 0;  // null terminate the string
        return 0;
    }

In C i defined:

    char message[13];
    uint32_t num;
    char until = '\n';

    serialport_read_until(fd, message, newLine, sizeof message, 20000);
    // the 20000 is timeout in millisec
    // this method stores the data in serial buffer into message array

    printf("message is %d\n", num);

I am expecting a raw value of **0501050105** first.
Then I convert this raw string into **501050105** using:

    sscanf(message, "%d", &num);

Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

In addition, when i use serialport_read_until() method above, even though i specify the char until as '\n', the method terminates after reading '\r' (leaving the \n in the serial buffer), and the '\n' is only captured in the next method call.

**Q1:** Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

**Q2:** Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

Thank you very much.

title: How to read long value sent by Arduino in C

Answers: 1

body:
> char b[1];  // read expects an array, so we give it a 1-byte array

No, it expects a *pointer* to a destination to store the data. You don't need a 1-entry array - you can simplify your code with:

    char b;
    ...
    int n = read(fd, &b, 1);  // read a char at a time
    ...
    buf[i] = b;
    ... etc ...

> Currently it works fine, but I strongly believe it is not the correct way to do it (or rather not the optimized way to do it).

C has the function `strtoul()` which is far more efficient that sscanf.

    uint32_t val = strtoul(buf, NULL, 10);

The `10` is the base to convert from, so you could convert hexadecimal (base 16), octal (base 8), etc using it.

> Q1: Am i reading the \r\n wrongly from the println (I saw in Arduino documentation that println prints \r\n)? What resulted in C 'cutting off' the message when it detected a \r from Arduino even though I specifically set to kill it only when \n is received?

You're defining the variable `until` to contain `\n`, yet passing the variable `newLine` to your function. Maybe that has something to do with it?

> Q2: Instead of printing a string to me and converting it back to integer in C, is there a way for Arduino to send me a long value directly instead? eg 501050105 or 51515. how should I rewrite the serial print or method? And how do i capture that integer correctly in C? If i'm not wrong if a raw integer is print out from Arduino, it converts it into ASCII code. I'm still very new to C and Arduino and hope some guidelines to be given so I can improve on the current coding.

You can send a 32-bit value using just 4 bytes. However it's not reliable without implementing a whole protocol around those 4 bytes which, for just 4 bytes, is a bit of a waste. Simplest just to stick to ASCII encoding your data.


body:
I'm using this [motor shield][1] for arduino from adafruit. It says it can drive 4 DC motors with it. However, two terminals M3 & M4 (as marked in the image) seem to be supplying lesser voltage.

[![motor shield][2]][2]

To avoid this becoming an XY problem, some more details:

The entire setup consists of an arduino, shield, raspberry Pi 3 & the motors being  powered with a 2200 mAh 12v supply. The raspberry pi is powered from the 5v supply of this shield.

Now the problem as mentioned is that even though M1 & M2 get the 12v, M3 & M4 don't. When I measured they give varying degree of voltage (3v - 6v). I tried disconnecting & connecting various combinations, with & without motors connected, pi removed, etc. All are giving same result. When I supplied 5v as external power, these pins in question dropped to 2v-3v.

As per [this documentation][3], there seems to be a difference in M3, M4 in that they run at 1KHZ, to save power. But my knowledge to make of this info seems to be limited. Can anyone point me to the right direction here?

The complete setup.[![The complete setup of hardware][4]][4]

  [1]: https://www.adafruit.com/products/81
  [2]: https://i.stack.imgur.com/mUB9G.jpg
  [3]: https://learn.adafruit.com/adafruit-motor-shield/using-dc-motors
  [4]: https://i.stack.imgur.com/YOB5m.jpg

title: Debugging arduino shield for varying voltage

Answers: 0


body:
I am using Neopixel Library and a Trinket Pro 5V Microcontroller to chase first three LEDs on a strip and then burst the last 2 (could be modified based on the number of LEDs).
The LEDs chase only once. See the code below. I am not sure why, even though the logic is inside the loop function, it only executes once. Any suggestions?

    #include <Adafruit_NeoPixel.h>
    #include "WS2812_Definitions.h"
    #ifdef __AVR__
      #include <avr/power.h>
    #endif

    // Which pin on the Arduino is connected to the NeoPixels?
    // On a Trinket or Gemma we suggest changing this to 1
    #define PIN            6

    // How many NeoPixels are attached to the Arduino? How many Neopixels do you want to chase (starting from the first in address 0. How many do you want to burst at the end?
    #define NUMPIXELS      5
    #define NUMPIXELSCHASE 3
    #define NUMPIXELSBURST 2

    // When we setup the NeoPixel library, we tell it how many pixels, and which pin to use to send signals.
    // Note that for older NeoPixel strips you might need to change the third parameter--see the strandtest
    // example for more information on possible values.
    Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
    #if defined (__AVR_ATtiny85__)
      if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
    #endif
      // End of trinket special code

      pixels.begin(); // This initializes the NeoPixel library.
      clearLEDs();
      pixels.show();
    }

    void loop() {

      // For a set of NeoPixels the first NeoPixel is 0, second is 1, all the way up to the count of pixels minus one.
      for(int i=0;i<NUMPIXELSCHASE;i++){

       pixels.setPixelColor(i, INDIGO);
       pixels.show(); // This sends the updated pixel color to the hardware.
       delay (200);
      }

      for(int i=NUMPIXELS-NUMPIXELSBURST;i<NUMPIXELS;i++){

       pixels.setPixelColor(i, AQUA);
       pixels.show(); // This sends the updated pixel color to the hardware.
       delay(0);
      }
    }

    // Sets all LEDs to off, but DOES NOT update the display;
    // call leds.show() to actually turn them off after this.
    void clearLEDs()
    {
      for (int i=0; i<NUMPIXELS; i++)
      {
        pixels.setPixelColor(i, 0);
      }
    }

Thank you.

title: LEDs instruction code does not loop

Answers: 1

body: Your 1st pixel should go indigo & stay there, & the other 2 very briefly show Aqua before going back to Indigo. Try a longer delay than 0 at the end, and then clear them down for the next loop.


body: Is it possible to determine at runtime whether a pointer points to `PROGMEM`'ed values or regular values? This would give some flexibility when writing code that handles both.

title: Possible to determine at runtime whether a pointer is declared PROGMEM?

Answers: 2

body:
Not really, if you are asking whether you can determine (simply from its value) whether 0x100 is in RAM or PROGMEM. Both are possible candidates for a memory location.

The `F()` macro works around this by changing the *type* of a variable at compile-time, so that the compiler can select a suitable method of printing. For example:

    Serial.println ("Hello, world");
    Serial.println (F("Hello, world"));

In this case the appropriate `println` function is chosen at compile-time by the compiler, based on the type (one would be a `const char *`, the other a `__FlashStringHelper` type).

You are best off designing a way (similar to the `F()` macro) where you can make the decision at compile time.

body:
> Is it possible to determine at runtime whether a pointer points to PROGMEM'ed values or regular values? This would give some flexibility when writing code that handles both.

The AVR MCUs are [Harvard Architectures][1]. Data and program memory spaces are separated. There are also several data memory spaces, e.g. SRAM, EEPROM, PROGMEM. Each of these have there own address space, and special instructions are used to access them.

In software anything is possible :) so it is possible to unify the address spaces and use a run-time mechanism to do the respective read and write. A simple method is to use the most significant bits to determine the address space. For instance,

    SRAM 0x0000..0x7fff
    EEPROM 0x8000..0x8fff
    PROGMEM 0x9000..0xffff

SRAM pointers are as usual, EEPROM pointers have an extra 0x8000, and PROGMEM pointers an extra 0x9000.

The next step is to write a simple mapping function from the unified address space to the separate memory address spaces. This can be wrapped into a C+++ smart pointer and/or a simple C++ class hierarchy.

An example of this technique can be found in 1) Forth Virtual Machine for Arduino, https://github.com/mikaelpatel/Arduino-FVM (see https://github.com/mikaelpatel/Arduino-FVM/blob/master/src/FVM.cpp#L85), 2) RPN Postscript/Forth Command Shell for Arduino, https://github.com/mikaelpatel/Arduino-Shell (see https://github.com/mikaelpatel/Arduino-Shell/blob/master/Shell.h#L1059).

Cheers!

PS: An interesting detail with the AVR architecture is that the registers 0..31, and the io-registers, are mapped to the SRAM address space.

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


body:
I'm using the Adafruit SIM808 breakout board to text a GPS link to Google Maps when pinged. My program is mostly working, but the GPS data that I get has no "N, S, E, W" indicators. In addition, I know that the longitude where I live is negative but it's coming out as positive. This is the output that I get:

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

This is the code that triggers that output:

    int8_t stat;
    // check GPS fix
    stat = fona.GPSstatus();
    if (stat < 0)  {
      Serial.println(F("Failed to query"));
    }
    if (stat == 0) {
      Serial.println(F("GPS off"));
    }
    if (stat == 1) {
      Serial.println(F("No fix"));
    }
    if (stat == 2) {
      Serial.println(F("2D fix"));
    }
    if (stat == 3) {
      Serial.println(F("3D fix"));
    }

    // check for GPS location
    char gpsdata[120];
    fona.getGPS(0, gpsdata, 120);
    Serial.println(gpsdata);

I'm already reading about how to fix the GPS data so that it can be used by Google Maps, but I don't know what to do about the issue of not having the directional information/sign.

Here is the full code, just for reference:

    #include "Adafruit_FONA.h"
    #include <SoftwareSerial.h>

    #define FONA_RX 2
    #define FONA_TX 3
    #define FONA_RST 4
    #define FONA_KEY 7
    #define FONA_PS 8

    // this is a large buffer for replies
    char replybuffer[255];

    SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
    SoftwareSerial *fonaSerial = &fonaSS;
    Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
    uint8_t readline(char *buff, uint8_t maxbuff, uint16_t timeout = 0);

    void setup() {
      Serial.begin(115200);
      pinMode(FONA_KEY, OUTPUT);
      pinMode(FONA_PS, INPUT);
      analogReference(INTERNAL);
      delay(2000);

      TurnOffFona();

      Serial.println(F("FONA SMS caller ID test"));
      Serial.println(F("Initializing....(May take 3 seconds)"));
      delay(1000);

      TurnOnFona();

      fonaSerial->begin(4800);
      if (! fona.begin(*fonaSerial)) {
        Serial.println(F("Couldn't find FONA"));
        while (1);
      }
      Serial.println(F("FONA is OK"));

      // Print SIM card IMEI number.
      char imei[15] = {0}; // MUST use a 16 character buffer for IMEI!
      uint8_t imeiLen = fona.getIMEI(imei);
      if (imeiLen > 0) {
        Serial.print("SIM card IMEI: "); Serial.println(imei);
      }

      // turn GPS on
      if (!fona.enableGPS(true)) {
        Serial.println(F("GPS failed to turn on"));
      }

      Serial.println("FONA Ready");
    }

    char fonaInBuffer[64]; //for notifications from the FONA

    void loop() {
      char* bufPtr = fonaInBuffer; //handy buffer pointer

      if (fona.available()) {
        //any data available from the FONA?
        int slot = 0; //this will be the slot number of the SMS
        int charCount = 0;
        //Read the notification into fonaInBuffer
        do  {
          *bufPtr = fona.read();
          Serial.write(*bufPtr);
          delay(1);
        } while ((*bufPtr++ != '\n') && (fona.available()) && (++charCount < (sizeof(fonaInBuffer) - 1)));

        //Add a terminal NULL to the notification string
        *bufPtr = 0;

        //Scan the notification string for an SMS received notification.
        //  If it's an SMS message, we'll get the slot number in 'slot'
        if (1 == sscanf(fonaInBuffer, "+CMTI: \"SM\",%d", &slot)) {
          Serial.print("slot: "); Serial.println(slot);
          char callerIDbuffer[32];  //we'll store the SMS sender number in here

          // Retrieve SMS sender address/phone number.
          if (! fona.getSMSSender(slot, callerIDbuffer, 31)) {
            Serial.println("Didn't find SMS message in slot!");
          }
          Serial.print(F("FROM: ")); Serial.println(callerIDbuffer);

          int8_t stat;
          // check GPS fix
          stat = fona.GPSstatus();
          if (stat < 0)  {
            Serial.println(F("Failed to query"));
          }
          if (stat == 0) {
            Serial.println(F("GPS off"));
          }
          if (stat == 1) {
            Serial.println(F("No fix"));
          }
          if (stat == 2) {
            Serial.println(F("2D fix"));
          }
          if (stat == 3) {
            Serial.println(F("3D fix"));
          }

          // check for GPS location
          char gpsdata[120];
          fona.getGPS(0, gpsdata, 120);
          Serial.println(gpsdata);
          String gpsString;

          gpsString = (String) gpsdata; //re-cast chr array as string.
          Serial.println(gpsString);
          int commaIndex = gpsString.indexOf(',');
          int secondCommaIndex = gpsString.indexOf(',', commaIndex + 1);
          int thirdCommaIndex = gpsString.indexOf(',', secondCommaIndex + 1);
          int fourthCommaIndex = gpsString.indexOf(',', thirdCommaIndex + 1);

          String firstValue = gpsString.substring(0, commaIndex);
          String rawLat = gpsString.substring(commaIndex + 1, secondCommaIndex);
          String rawLon = gpsString.substring(secondCommaIndex + 1, thirdCommaIndex);
          String rawAlt = gpsString.substring(thirdCommaIndex + 1, fourthCommaIndex);

          int decimalIndex = rawLat.indexOf('.');
          String lat1 = rawLat.substring(0, decimalIndex);
          String lat2 = rawLat.substring(decimalIndex + 1, rawLat.length());
          Serial.println(lat1);
          Serial.println(lat2);
          rawLat = lat1.substring(0, 2) + "." + lat1.substring(3, lat1.length()) + lat2;
          Serial.println(rawLat);

          int decimal2Index = rawLon.indexOf('.');
          String lon1 = rawLon.substring(0, decimal2Index);
          String lon2 = rawLon.substring(decimal2Index + 1, rawLon.length());
          Serial.println(lon1);
          Serial.println(lon2);
          rawLon = lon1.substring(0, 2) + "." + lon1.substring(3, lon1.length()) + lon2;
          Serial.println(rawLon);

          char txtmsgArray[80];
          String txmsg = "https://www.google.com/maps/@" + rawLat + "," +  rawLon + ",15z";
          txmsg.toCharArray(txtmsgArray, 80);
          Serial.println(txtmsgArray);

          Serial.println("Sending reponse...");
          if (!fona.sendSMS(callerIDbuffer, txtmsgArray)) {
            Serial.println(F("Failed"));
          } else {
            Serial.println(F("Sent!"));
          }
          delay(3000);
          // delete the original msg after it is processed
          //   otherwise, we will fill up all the slots
          //   and then we won't be able to receive SMS anymore
          if (fona.deleteSMS(slot)) {
            Serial.println(F("OK!"));
          } else {
            Serial.println(F("Couldn't delete"));
          }
        }
      }
    }

    void TurnOnFona() {
      Serial.println("Turning on Fona: ");
      while (digitalRead(FONA_PS) == LOW) {
        digitalWrite(FONA_KEY, LOW);
      }
      digitalWrite(FONA_KEY, HIGH);
      delay(4000);
    }

    void TurnOffFona() {
      Serial.println("Turning off Fona ");
      while (digitalRead(FONA_PS) == HIGH) {
        digitalWrite(FONA_KEY, LOW);
      }
      digitalWrite(FONA_KEY, HIGH);
      delay(4000);
    }

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

title: GPS North? South? East? West?

Answers: 2

body:
GPS is a positioning system: it doesn't do direction.  If your software has serial information coming in,  it can take the difference in readings and *generate* that data but GPS doesn't do it for you.

Some devices may add it to the standard,  but that's a per-device feature. .

body:
Send the command:<br>
`AT+CGPSOUT=1`

That should enable the output of the standard NMEA $GPGGA string which includes all the position information you should need in a format that either you can parse or use one of the many existing libraries to parse. It's not clear from the documentation if this will be a one time output or a 1 Hz output.

There are other NMEA messages available if you need them, see https://cdn-shop.adafruit.com/datasheets/SIM808_GPS_Application_Note_V1.00.pdf for details.


body: I would like to have a shield permanently attached that use the VIN (not 5v) for it's power - the problem comes in when I want to program the arduino (via the USB port), do I need to also have the barrel connector plugged in, or can I just expect the shield to not work (no, it won't be damaged from not getting enough/any power), but have the arduino itself be fine - or am I somehow damaging the power regulator by attempting to use it in reverse?

title: What happens if I try to draw power from the VIN port while under USB power on an Uno?

Answers: 1

body:
You do run the risk of damaging the 5V regulator, yes.

Power will attempt to flow from the 5V rail (USB port) through the voltage regulator (backwards) and into the shield to power it.

As your shield doesn't mind being under-powered from 5V while you're programming the Arduino you can add a diode between 5V (anode) and Vin (cathode). This will bypass the regulator when the voltage of the 5V rail is higher than the Vin rail, and your shield will be supplied with about 4.3V (slightly higher for a schottky diode).


body:
Recently I uploaded individual codes for relay's and Servo motor seperately, it all worked fine. But when I combined these two codes and dumped in to the loop there is a delay in functioning of the relay's but the Servo motor is working fine.

I have to control these devices through Bluetooth HC-05 module.
Could you please help me with the code?

<!-- language: c -->

    /*
    simple LED test
    */
    #include <Servo.h>
    char val;         // variable to receive data from the serial port
    int ledpin = 2; // LED connected to pin 2 (on-board LED)
    Servo myservo;
    int pos = 0;    // variable to store the servo position
    int motor = 0;

    void setup()
    {
      pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
      pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT
      myservo.attach(9);  // attaches the servo on pin 9 to the servo object
      Serial.print("Arduino control Servo Motor Connected OK");
      Serial.print('\n');
      Serial.begin(9600);       // start serial communication at 115200bps
      digitalWrite(ledpin = 2 ,HIGH);
      digitalWrite(ledpin = 3 ,HIGH);

    }

    void loop()
    {

          if( Serial.read() == 'a' )    // if 'a' was received led 2 is switched off
      {
        digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2

      }

      if( Serial.read() == 'A' )               // if 'A' was received led 2 on
      {
        digitalWrite(ledpin = 2, LOW);  // turn ON pin 2

      }

      if( Serial.read() == 'b' )        // if 'b' was received led 3 is switched off
      {
        digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3

      }

      if( Serial.read() == 'B' )               // if 'B' was received led 3 on
      {
        digitalWrite(ledpin = 3, LOW);  // turn ON pin 3

      }

      if (Serial.read() == '\n')
        {

       motor = Serial.parseInt();
        pos = Serial.parseInt();
          myservo.write(pos);
          delay(15);
          Serial.print("Data Response : ");
          Serial.print(motor, DEC);
          Serial.print(pos, DEC);

        }

        }

title: How to merge two arduino sketches, one for relay's and one for Servo motor?

Answers: 1

body:
A couple of things stand out in your code.

 1. Whenever you perform a digital write you assign a value to ledpin:

        digitalWrite(ledpin = 3, LOW);

  This is not necessary as you do not do anything with the ledpin variable. Instead, just have the digital I/O pin number:

        digitalWrite(3, LOW);

   Or simply have 2 variables, one for pin 2 and another for pin 3. Eg.

        redledpin = 2;
        greenledpin = 3;

   This also applies to the pinMode function calls in the setup function.

 2. Each one of your  `if( Serial.read() == xx)` statements will read a serial character off of the serial buffer. Instead store the read character in a local variable:

        readChar = Serial.read()
        if( readchar == 'a')
        ...
        if( readchar == 'A')
        ...
        if( readchar == 'b')
        ...
        if( readchar == 'B')
        ...

 3. I would encase all of the code inside `loop()` with:

        if ( Serial.available() )
        {
            ...
        }

 4. The delay function is blocking and this will cause issues. I suggest deleting the delay altogether.

 5. Due to the fact that you are sending commands to turn digital outputs on and off as well as sending an integer for motor and another for pos, I suggest that you define a packet structure and make your code follow that (with the necessary error handling). As the code currently stands you will miss information, depending on what character it sees first on the serial buffer.

  I suggest something like:

        A, B, 142, 090

  Starting the packet off with a know character is a good idea. So is having a timeout period - in case only a portion of your packet is received.


body:
For a project i need to extract some data from an external eeprom and then store it somewhere. Suddenly after some manipulations (not necessarly with Arduino board) i need to put them in an external eeprom.

What I would do is to convert the extracted data from the EEPROM in Intel Hex data and vice versa.
To do this I wanted to know if there is already a library for that purpose "ready to use" made for Arduino boards.

thanks

title: A library for manipulate Intel Hex data?

Answers: 3

body:
Why does it have to be in Intel Hex format? You could write out the EEPROM to the serial port one byte to a line, or something. Something like this:

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

    #include <EEPROM.h>

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

      for (int addr = 0x0000; addr < 0x0010; addr++)
        {
        Serial.print ("Address = ");
        Serial.print (addr, HEX);
        Serial.print (", value = ");
        Serial.println (EEPROM.read(addr), HEX);
        }

    }  // end of setup

    void loop ()
    {
    }  // end of loop

I'm not personally aware of a library that happens to write out/read in, Intel Hex format from/to the EEPROM.

---

I have [code that uploads and downloads files to the Arduino](http://www.gammon.com.au/uploader). Inside that is code to read/write Intel hex format. However it isn't a library.

Inside File_Utils.ino are some comments that show the format:

    /*
    Line format:

      :nnaaaatt(data)ss

      Where:
      :      = a colon

      (All of below in hex format)

      nn     = length of data part
      aaaa   = address (eg. where to write data)
      tt     = transaction type
               00 = data
               01 = end of file
               02 = extended segment address (changes high-order byte of the address)
               03 = start segment address *
               04 = linear address *
               05 = start linear address *
      (data) = variable length data
      ss     = sumcheck

                * We don't use these

    */

---

In that file is code to write Intel Hex format (reading from Flash, not EEPROM):

    void readFlashContents ()
      {
      if (!haveSDcard)
        {
        Serial.println (F("*** No SD card detected."));
        return;
        }

      progressBarCount = 0;
      pagesize = currentSignature.pageSize;
      pagemask = ~(pagesize - 1);
      oldPage = NO_PAGE;
      byte lastMSBwritten = 0;

      while (true)
        {

        Serial.println ();
        Serial.println (F("Choose file to save as: "));

        getline (name, sizeof name);
        int len = strlen (name);

        if (len < 5 || strcmp (&name [len - 4], ".HEX") != 0)
          {
          Serial.println (F("File name must end in .HEX"));
          return;
          }

        // if file doesn't exist, proceed
        if (!sd.vwd()->exists (name))
          break;

        Serial.print (F("File "));
        Serial.print (name);
        Serial.println (F(" exists. Overwrite? Type 'YES' to confirm ..."));

        if (getYesNo ())
          break;

        }  // end of checking if file exists

      // ensure back in programming mode
      if (!startProgramming ())
        return;

      SdFile myFile;

      // open the file for writing
      if (!myFile.open(name, O_WRITE | O_CREAT | O_TRUNC))
        {
        Serial.print (F("Could not open file "));
        Serial.print (name);
        Serial.println (F(" for writing."));
        return;
        }

      byte memBuf [16];
      bool allFF;
      unsigned int i;
      char linebuf [50];
      byte sumCheck;

      Serial.println (F("Copying flash memory to SD card (disk) ..."));

      for (unsigned long address = 0; address < currentSignature.flashSize; address += sizeof memBuf)
        {

        unsigned long thisPage = address & pagemask;
        // page changed? show progress
        if (thisPage != oldPage && oldPage != NO_PAGE)
          showProgress ();
        // now this is the current page
        oldPage = thisPage;

        // don't write lines that are all 0xFF
        allFF = true;

        for (i = 0; i < sizeof memBuf; i++)
          {
          memBuf [i] = readFlash (address + i);
          if (memBuf [i] != 0xFF)
            allFF = false;
          }  // end of reading 16 bytes
        if (allFF)
          continue;

        byte MSB = address >> 16;
        if (MSB != lastMSBwritten)
          {
          sumCheck = 2 + 2 + (MSB << 4);
          sumCheck = ~sumCheck + 1;
          // hexExtendedSegmentAddressRecord (02)
          sprintf (linebuf, ":02000002X00X\r\n", MSB << 4, sumCheck);
          myFile.print (linebuf);
          lastMSBwritten = MSB;
          }  // end if different MSB

        sumCheck = 16 + lowByte (address) + highByte (address);
        sprintf (linebuf, ":10X00", (unsigned int) address & 0xFFFF);
        for (i = 0; i < sizeof memBuf; i++)
          {
          sprintf (&linebuf [(i * 2) + 9] , "X",  memBuf [i]);
          sumCheck += memBuf [i];
          }  // end of reading 16 bytes

        // 2's complement
        sumCheck = ~sumCheck + 1;
        // append sumcheck
        sprintf (&linebuf [(sizeof memBuf * 2) + 9] , "X\r\n",  sumCheck);

        myFile.clearWriteError ();
        myFile.print (linebuf);
        if (myFile.getWriteError ())
           {
           Serial.println ();  // finish off progress bar
           Serial.println (F("Error writing file."));
           myFile.close ();
           return;
           }   // end of an error

        }  // end of reading flash

      Serial.println ();  // finish off progress bar
      myFile.print (":00000001FF\r\n");    // end of file record
      myFile.close ();
      // ensure written to disk
      sd.vwd()->sync ();
      Serial.print (F("File "));
      Serial.print (name);
      Serial.println (F(" saved."));
      }  // end of readFlashContents

---

That should give you some tips about how to write out the file. Look in my code to see the reading code as well. However as I said, you don't necessarily have to use that format if you just want to manipulate the data yourself.

body:
Nick's answer assumes you just want to read/process/write the data from one place to another.  If that's the case, there's no need to store the data into an Intel Hex Data formatted file – just keep it in a flat array, or a file that's formatted conveniently rather than in a form that requires parsing.

Of course, if you actually need the formatted file for some reason – such as an intermediate program only working with Hex files – you could edit the question and say so.

Note,  [Python Software Foundation's IntelHex](https://pypi.python.org/pypi/IntelHex) page provides a
> Python library to read, write, create from scratch and manipulate data from HEX (also known as Intel HEX) file format.

To use it, you would write a Python program that (on your host computer) reads serial-port data with values to be stored, and uses the IntelHex library to write a Hex file.  After the intermediate program fiddles with the Hex file, another Python program on your host computer uses IntelHex to read the modified Hex file and writes it to EEPROM or to serial for an Arduino to write it to an EEPROM.

body:
avrdude himself is very good at providing/inferring the various formats. We are ourselves manipulating output - EEPROMs, for example - in an external editor.

Of course, avrdude is neither *external* nor a *library*, but...


body:
I'm using a MCP3008 8ch 10bit ADC to expand the Analog Inputs for the project I'm working on. The only library I can find for it is [here][1] the library is ported from Adafruit's Raspberry Pi library [here][2]. From what I can tell the library uses bitbanging as opposed to hardware SPI in order to communicate. I would like to use hardware SPI, but don't have the skills to write a library to communicate with it myself. Are there any resources for how to write a library like that, or anything I can read about on how to convert a library from bitbanging to hardware SPI?

  [1]: https://github.com/nodesign/MCP3008
  [2]: https://learn.adafruit.com/reading-a-analog-in-and-controlling-audio-volume-with-the-raspberry-pi/script

title: Convert library from using bitbanging to hardware SPI

Answers: 2

body:
The standard AVR library has SPI handling. See, for example: <http://www.gammon.com.au/spi>

You don't have to write a library if you don't want, just communicate directly using SPI.

The datasheet for the MCP3008 has some tips for using an 8-bit SPI system to communicate with the device. In particular this chart:

[![MCP3008 timings][1]][1]

You can see from that, that you will need 3 x SPI.transfer. I don't have one here to test with, but the code would look like this:

    digitalWrite (SS, LOW);  // select device
    int result;
    SPI.transfer (0x01);  // start bit
    result = SPI.transfer (0b10000000);  // single, ch0
    result = (result & 0b11) << 8;  // move to high-order byte
    result |= SPI.transfer (0);   // lower order byte
    digitalWrite (SS, HIGH);  // deselect

Untested, but this should be roughly it.

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

body:
Turns out my google-fu needs work. I found [this][1] that works great using hardware SPI! Thanks everyone!

  [1]: https://rheingoldheavy.com/mcp3008-tutorial-02-sampling-dc-voltage/


body:
 I keep getting the error "Expected initializer" at different points in my code whenever I try to verify it. Currently, the error exists before "void setup." How can I fix this error and not allow it to happen in the future?

    int ledPins[] = {9, 8, 7, 6};
    int index;
    int currentLED

    void setup();
      {
      pinMode(Led1Pin, OUTPUT);
      pinMode(Led2Pin, OUTPUT);
      pinMode(Led3Pin, OUTPUT);
      pinMode(Led4Pin, OUTPUT);
      pinMode(Led5Pin, OUTPUT);
      pinMode(ButtonPin, INPUT);

      Serial.begin(9600);

      //Start a new game.

     for(index = 0; index <= 4; index++)
      {
        pinMode(ledPins[index],OUTPUT);
        // ledPins[index] is replaced by the value in the array.
        // For example, ledPins[0] is 2
      }
    }

    void loop()
    {

      oneAfterAnotherNoLoop();  // Light up all the LEDs in turn

    }

    void oneAfterAnotherNoLoop()
    {
      int delayTime = 200; // time (milliseconds) to pause between LEDs
                       // make this smaller for faster switching
      // turn all the LEDs on:
      int Index;

    for (Index = 0; Index <=3; Index++) {
      digitalWrite(ledPins[Index], HIGH);
      delay(delayTime);
      digitalWrite(ledPins[Index], LOW);
    }
    for (Index = 3; Index >= 0; Index--) {
        digitalWrite(ledPins[Index], HIGH);
      delay(delayTime);
      digitalWrite(ledPins[Index], LOW);
    }
    }

    void loop();
    {
        // Check if the button is pressed at the right moment

       if (digitalRead(10) == 0)
       {
        if (currentLED == 8)
        {
          // Blink the orrect (green) LED
          digitalWrite(8, HIGH);
          delay(200);
          digitalWrite(14, LOW);
          delay(200);
          digitalWrite(8, HIGH);
          delay(200);
          digitalWrite(14, LOW);
        }
        }
      }

title: Expected Initializer?

Answers: 1

body:
    int currentLED

You are missing a semicolon there.

---

    void setup();

There should *not* be a semicolon here.

---

Do some tutorials on the C or C++ language. They will help you.


body:
In trying to learn how to create a reasonably precise 3d model of my (very hilly) property, I stumbled across a product called Navspark, which appears to be a $22 arduino-compatible development board, with an RTK-capable (and RTKlib-compatible) GPS chip.

The idea with RTK is that a reference-position base-station transmits its positional error to a mobile unit, giving the mobile unit cm-level precision relative to the position of the base station. The error calculation is computationally intensive, but apparently within the capabilities of a Pi.

Is it actually possible to build an RTK-capable mobile/base pair using low-priced equipment like this?  Can you link a howto or project example?

title: Getting RTK-precision GPS with arduino devices like NavSpark?

Answers: 1

body:
How about the http://www.navspark.com.tw/tutorial-4 tutorial?  It seems to indicate you need a couple of the more capable $80 NS-RAW units with carrier-phase info rather than the less capable $22 NAV-SPARC plain GPS units.

The RTK system doesn't transmit only its positional error, (which it knows from external information) but also communicates the phase information for the particular channels, and then the RTK software re-calculates the positions of both using common sets of satellites and the phase info.  With the same framework, it knows the relative positions accurately, and with assumptions about the location of the base station, it can correct mobile station

This isn't an arduino problem, unless you are asking about porting RTKlib to something arduino.


body:
I want to send servo signal to ESC and Servo with my 3.3V Arduino Pro Mini.

Can the ESC/Servo read 3.3V signal from Arduino Pro Mini? Or do I need to make some level shifter to make 5V signal?

title: Arduino Pro Mini and Electronic Speed Controller (ESC)

Answers: 2

body: The ESC should have no problem with 3v3 signal.

body: Signal can be send easily from Arduino Pro mini to ESC, Simply either use .write() or .Microseconds() function.


body:
Hey guys need your help in verifying out this program about toggling the LED ON and OFF using 2 push buttons.What i actually want is to let my LED stay ON when i press and even leave the push button-1 , and on pressing and leaving the push button-2 i want the led to turn off and no matter how many times i press the push button-1 i want it to turn ON the LED and the push button-2 should only turn off the LED.but with my program i am only able to see the LED to be at HIGH state,It is not shifting to LOW state on clicking push button-2.

This is my sketch :-

<!-- language: c -->

        /* LED CONTROLLED WITH 2 PUSH BUTTON PROJECT
           BY ARSH BANSAL

     CIRCUIT :-
     i) LEDPIN CONNECTED PIN 13.
     ii) PUSHBUTTON1 CONNECTED TO PIN 8.
     iii) PUSHBUTTON2 CONNECTED TO PIN 7.
     iv) BOTH THE PUSH BUTTONS CONNECTED PARALLELY, EACH WITH A 1K PULLUP RESISTOR AND BOTH THE PUSH BUTTONS CONNECTED TO 5V SUPPLY.
       */

     int ledpin = 13;
     int pushbutton1 = 8;
     int pushbutton2 = 7;
     boolean lastbuttonstate1 = LOW;
     boolean lastbuttonstate2 = LOW;

     void setup()
     {
       pinMode(ledpin,OUTPUT);
       pinMode(pushbutton1,INPUT);
       pinMode(pushbutton2,INPUT);
     }

     void loop()
     {
       if ( digitalRead(pushbutton1)== HIGH && digitalRead(pushbutton2) == LOW && lastbuttonstate1 == LOW )
        { digitalWrite (ledpin,HIGH) ;}

       else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW && lastbuttonstate1 == HIGH)
        ; { digitalWrite (ledpin,HIGH) ; }

        if ( digitalRead(pushbutton1)== LOW && digitalRead(pushbutton2) == HIGH  && lastbuttonstate2 == LOW)
        { digitalWrite (ledpin,LOW) ;}

       else ( digitalRead(pushbutton1) == LOW && digitalRead(pushbutton2)== LOW  && lastbuttonstate2 == HIGH)
        ; { digitalWrite (ledpin,LOW) ; }
        }

title: Integrating 2 push buttons to toggle the LED ON and OFF

Answers: 1

body:
You are better off, in this case, remembering the state of the LED not the state of the buttons:

* If the LED is OFF and BUTTON1 is PRESSED then turn the LED on.
* If the LED is ON and BUTTON2 is PRESSED then turn the LED off.

For example:

    void loop() {
        static bool ledState = false; // LED is off by default
        if ((digitalRead(pushbutton1) == LOW) && !ledState) { // 1 pressed & led is off
            digitalWrite(ledpin, HIGH);
            ledState = true;
        }
        if ((digitalRead(pushbutton2) == LOW) && ledState) { // 2 pressed & led is on
            digitalWrite(ledpin, LOW);
            ledState = false;
        }
    }


body:
I am communicating with the esp8266 WiFi module using Arduino. The module returns GET requests from other clients. They will be of the form

    GET /101011 HTTP/1.1\r\nHost...

I wish to extract only the `101011` from the received serial data and discard the rest. I came up with this small chunk of code to test it by sending data from my laptop.

This is the code:

    String s;

    void setup() {

      Serial.begin(9600);
    }

    void loop() {

      if(Serial.available())
      {
        Serial.println("Inside");
        Serial.find("/");
        s = Serial.readStringUntil(' ');
        Serial.println(s);
        // Discard the rest of the data . Snippet from Jeremy Blum's Blog

        while(Serial.available()>0) Serial.read();

      }

    }

[Jeremy's Blog][1]

But when I run this using the input `GET /101011 HTTP/1.1\r\n` the output produced is

    Inside
    101011
    Inside
    1.1\r\n

Why is `Serial.available()` returning `true` even after reading everything? How to discard the rest of data from the serial input buffer?

  [1]: http://www.jeremyblum.com/2011/02/07/arduino-tutorial-6-serial-communication-and-processing/

title: How to flush the input serial buffer in Arduino?

Answers: 1

body:
One possible approach is to read and discard everything for a fixed time, like a second. For example:

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

    unsigned long now = millis ();
    while (millis () - now < 1000)
      Serial.read ();  // read and discard any input

I'm not a big fan of trying to "flush the input buffer". How do you know if a second is long enough? Or maybe it is too long? You are better off reading to some known delimiter.


body:
I have a college assignment where I need to get serial output, the Ethernet shield and SPI communication with other boards to work. We are not allowed to use any existing libraries, though we can use them as strong inspiration, as long as we are able to explain every line we have in our final code.

Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries but I am hopelessly overwhelmed by anything beyond getting a pure C blinky to run.

Do you have any idea how I should approach this? Are there C resources about the Ethernet shield and Arduino SPI?

title: How to approach an complex Arduino Uno project (Serial, SPI, Ethernet) in pure C, without libraries?

Answers: 2

body:
As Hans Neve wrote, you should really refer to the docs.

This is how it works in real life, when you want to write a driver for a new piece of HW.

You have to at least understand the block diagram, programming models and register sets of the device you want to control.

*Then* read whatever existing code you might find. In the practical case you have the driver for the version N-1 of the HW. Or maybe for something close enough.

As generic programming advice goes:

 - avoid any dynamic memory allocation, you will thank yourself later on, when you do not have to debug unexplained memory issues
 - if you want to write a driver, consider making it reentrant, should the same code be shared across multiple IP blocks
 - if you want to use OOP, avoid anything that requires runtime lookup. The compiler should have enough information to resolve everything statically.

WRT debugging: both device drivers might suffer from interference if you try to use the serial port. Consider using some ICD tools, like the AVR Dragon. Alternatively, you might find that debugging over I2C is less penalizing. But you have to define your debugging messages.

body:
SPI is pretty trivial (see the existing SPI library). Serial is easy enough. As for the Ethernet shield you would need to look at either the existing library or the manufacturer's datasheet. Some Ethernet chips are *much* easier to work with than others.

---

If you look at the datasheet for the Atmega328P (as used in the Uno) they have example code (in C) for SPI - along with comments. That should let you knock off the SPI part in an hour.

They also have example code for serial. Add in a ring buffer and you should be able to get serial going in half a day.

After all, the assignment doesn't tell you to not use the *datasheet*.

Depending on the Ethernet chip, you should be able to dig up (possibly in the chip datasheet) example code for that as well.

---

You could always use existing libraries (eg. Serial.print) for *debugging*, and then pull that code out once you are happy your own code works.


body:
I am trying to simulate an interrupt with an Arduino Uno in Proteus. This is the simple test code that I'm using:
<!-- language-all: lang-cpp -->

    void introutine()
    {
      digitalWrite(13,HIGH);
    }

    void setup()
    {
      pinMode(13,OUTPUT);
      attachInterrupt(2,introutine,LOW);
    }

    void loop()
    {
    }

Here's the circuit in Proteus:

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

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

When I hit the button, the LED is supposed to turn on. Well, nothing happens. I have read something about Proteus being bad at simulating interrupts, but I'm not sure about it because Timer1 interrupts did work well. Basically, the problem lies within EXTERNAL interrupts only. I hope you people can help me.

Thank you.

title: Does Proteus simulate external interrupts properly using Arduino? I can't get them to work

Answers: 0


body:
Last week I purchased a couple of [Trinkets from Adafruit (5v micro-USB)][1]. The first thing I did was solder the headers to one of them. I did the whole [setup process][2] w/ the Arduino IDE and didn't have any issues, until I actually tried uploading the "[Blink][3]" example.

When I plug in the Trinket, I get the pulsing red light, but when I try to upload during that, I get:

    avrdude: error: usbtiny_send: Input/output error (expected 64, got -5)
    avrdude: verification error, first mismatch at byte 0x0004
             0x1d != 0x36
    avrdude: verification error; content mismatch

    avrdude: error: usbtiny_transmit: Input/output error

Then, if I press the reset button, I can't get it to "pulse" again. The red light just dimly turns on and stays constant.

I tested the other Trinket I ordered (that has *not* been soldered yet) and it works perfectly fine.

So, did I somehow screw up something when soldering the headers? Or do I have a faulty Trinket?

For reference, here's the trinket in question...

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

  [1]: https://www.adafruit.com/product/1501
  [2]: https://learn.adafruit.com/introducing-trinket?view=all
  [3]: https://learn.adafruit.com/introducing-trinket?view=all#blink
  [4]: https://i.stack.imgur.com/2L6Ro.jpg

title: Soldering headers screwed up Trinket?

Answers: 2

body:
On this side it doesn't seem like there's a solder bridge, although it's possible there is one on the other side if you were heavy handed on the solder.

Since you did the verification with the other unit this can't be a software or usb cable issue.

So indeed it's coming from the trinket itself. I think your best bet is to desolder the pins and check the upload again. If it's failling, try flashing a new bootloader. And if it's still not working then I guess either it was faulty from the start or you did damaged a component during the soldering.

body:
There are what appear to be burn or melt marks on the 5 pin component labeled QTSO and on the diode near the USB pin. That could be a sign of damage due to soldering, reverse polarity, or excessive current draw through the voltage regulator (a short circuit).

Based on the fact that the light stays on solid when the reset button is pressed,  it sounds like it could also a different issue. First, turn on verbose output in the arduino IDE and post the full output when you try to upload.

Next, try disconnecting **everything** except the USB cable while uploading the program. If that does not fix it, it is most likely that the bootloader is corrupted. This has happened to me on multiple occasions for no apparent reason and it is pretty easy to fix.

If repairing the bootloader does not fix this, it is most likely that one or both of the components mentioned above are damaged.


body:
I have an Atmega328P that I have previously burned with a bootloader configured to use the 8MHz internal clock as described [here][1]. I would like to now burn the normal Duemilanove bootloader configured to use an external 16MHz clock onto the chip. However, when I try following the normal procedure, it says "Invalid device signature". I can still upload programs to the chip and they will run, but I would like it to use the 16MHz external clock. How do I do this?

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

title: Burn normal bootloader onto Atmega328P configured to use internal 8MHz clock

Answers: 1

body:
I have a [sketch that will upload the Optiboot bootloader](http://www.gammon.com.au/bootloader) - that will work perfectly well on the Duemilanove.

The latest version will be available on [GitHub](https://github.com/nickgammon/arduino_sketches).

This particular sketch is in the "Atmega_Board_Programmer" subdirectory.

You need to run this sketch on another Arduino (like a Uno) and connect it up like this:

[![Programming bootloader][1]][1]

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


body:
I am intending to write a code where a user will send lines through serial to affect timer interrupts. I am noticing a problem with serial where as soon as I enable the timer interrupts, the serial communication becomes garbled. More specifically, as soon as I enable the timer interrupts and I open the serial monitor, the monitor gets flooded with garbage. I haven't written too much code and this is already happening. Am I making a silly mistake? I am using an Arduino Mega 2560. My code is below:

    void setup() {
      Serial.begin(9600);
      Serial.println("Hello World!");
      timer_setup();
    }

    void loop() {
      // put your main code here, to run repeatedly:
    }

    void timer_setup() {
      // waveform generation = 0100 = CTC
      TCCR1B &= ~(1 << WGM13);
      TCCR1B |=  (1 << WGM12);
      TCCR1A &= ~(1 << WGM11);
      TCCR1A &= ~(1 << WGM10);
      // output mode = 00 (disconnected)
      TCCR1A &= ~(3 << COM1A0);
      TCCR1A &= ~(3 << COM1B0);
      // Set the timer pre-scaler
      TCCR1B = (TCCR1B & ~(0x07 << CS10)) | (2 << CS10);
      OCR1A = 0x4000;
      TCNT1 = 0;
      // Enable timer interrupt mask 1
      TIMSK1 |= (1<<OCIE1A);
    }

If I comment out the `TIMSK1 |= (1<<OCIE1A)` line, serial doesn't mess up.

title: Why does enabling TIMSK1 mess up serial?

Answers: 1

body:
You've enabled interrupts for Timer 1 Compare A interrupt. Where is the interrupt handler?

For example:

    ISR(TIMER1_COMPA_vect)
    {
      // whatever
    }  // end of TIMER1_COMPA_vect

Without that, the processor is just restarting. No wonder serial output is messed up.


body: Using a 'random' function in sketch gives same pattern of numbers every-time. But, I need to generate different numbers such that any number to repeat itself should have a very less probability.

title: How to generate true random numbers over Arduino Uno without any external hardware?

Answers: 2

body: The standard (but not very good) solution is to seed the random number generator from an `analogRead()` on an unconnected pin. For better options, see [this answer](https://arduino.stackexchange.com/a/22081) to a related question.

body:
Allocate 4 bytes in EEPROM to save a seed value.

Use the EEPROM library (#include <EEPROM.h>). Use EEPROM.put() and EEPROM.get() functions to write and read the seed value to EEPROM.

In setup(): Read the seed_value from EEPROM, increment it and write it back to EEPROM. Then call randomSeed(seed_value).

Now, after every run of setup(), random() will create a whole new random sequence. If you need a new sequence within your sketch, you can repeat the process, and don't forget to write the new seed to EEPROM for next time.

Note that I didn't bother with initialising the EEPROM value the first time we run. It'll probably be zero when you start a new Arduino board, but the only thing that matters is that you increment it each run. Incrementing by 1 will do the trick, but any increment value will probably do.


body:
I am using Arduino Uno, with **PID** library and [Jeff Rowberg library for MPU6050][1] i.e `I2Cdev.h`, `MPU6050_6Axis_MotionApps20.h`.

There is one PID for each axis i.e Pitch and Roll, I am getting output that wobbles and is unstable. I don't know whether my code is wrong or something else.

Errors which I feel are:

 - I am using `Esc.write()`, I know Microseconds should be used but it feels very light, even it doesn't wobble.
 - Kalman Filter not used, but I am getting the pitch, roll, yaw.
 - [PID library (By Brett Beauregard)][2] not suitable for Quadcopter.
 -

else if (mpuIntStatus & 0x02) // wait for correc available data length, should be a VERY short wait
             while (fifoCount < packetSize) fifoCount = mpu.getFIFOCount();

This statement in loop making loop slow, it's written in its comment and maybe it making pid compute upset

Please look at code.

    #ifdef OUTPUT_READABLE_YAWPITCHROLL
            // display Euler angles in degrees
            mpu.dmpGetQuaternion(&q, fifoBuffer);
            mpu.dmpGetGravity(&gravity, &q);
            mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);
            yaw = ypr[0] * 180/M_PI;
            pitch = ypr[1] * 180/M_PI;
            roll = ypr[2] * 180/M_PI;

            Input = pitch;
            RInput = roll;
            myPID.SetTunings(Kp,Ki,Kd);
            myPIDR.SetTunings(RKp,RKi,RKd);

            //Sample Time is 10 for both PID.

                 myPID.Compute();
                  myPIDR.Compute();

            if(armed == 1) {
              int m1 = throttle.toInt() + Output;
              int m2 = throttle.toInt() + ROutput;
              int m3 = throttle.toInt() - Output;
              int m4 = throttle.toInt() - ROutput;

     int angle1 = map(m1, 0, 100, 0, 180);
     ESC1.write(angle1); //FRONT PITCH+
     int angle2 = map(m2, 0, 100, 0, 180);
     ESC2.write(angle2); //LEFT ROLL+
     int angle3 = map(m3, 0, 100, 0, 180);
     ESC3.write(angle3); //BACK PITCH-
     int angle4 = map(m4, 0, 100, 0, 180);
     ESC4.write(angle4); //RIGHT ROLL-
            }
        #endif

*Kp = 0.25, Ki = 0.04, Kd = 0.05* |
*RKp = 0.25, RKi = 0.04, RKd = 0.05*

*From testing: if I shake my Quadcopter fast by hand it behaves like PID is activated and works as wanted, but suddenly after a couple of seconds again feel loose, may be PID compute become upset*

  [1]: http://www.i2cdevlib.com/devices/mpu6050#source
  [2]: http://playground.arduino.cc/Code/PIDLibrary

title: QuadCopter PID using MPU6050

Answers: 1

body:
Quadcopters usually use 2-PID loops per axis, a rate loop and an angle loop.

Your quadcopter needs to be very aggressive about its rate of rotation but relatively relaxed about how quickly it returns its angle to the center so it doesn't overshoot. With a single PID it will either be too slow to correct or overshoot and oscillate with no "usable" range of tunings in-between, because in order for its outputs to be strong enough to control the quad it will necessarily be too aggressive to smoothly align with the center position. There is a lot of math that explains why this cannot be achieved with a single loop more rigorously if you care to look into it.

So try setting it up with a PitchAngle PID whose output is the setpoint of a PitchRate PID loop whose output goes to the motors, and similarly with the Roll.

That is only one possible problem though, there is a huge number of things that could be wrong. Are your pitch and roll measurements angles to the horizon or euler angles? how fast is your loop running? Are oscillations induced by the motors causing your accelerometer reading/attitude filter combo to be unusable? Are the PID parameters correct? Is the accelerometer's bias calibrated? Is the gyro drift calibrated? Are all you ESC's calibrated the same way?


body:
I am using two XBee Series 2 modules (Zigbee), an Arduino Uno, and a HC-SR04 Ultrasonic sensor to send distance readings from the coordinator XBee on the Arduino to the XBee connected to my computer. I configured the ArduinoXBee as "Zigbee coordinator AT" and the ComputerXBee as "Zigbee end device AT" with the following networking settings:

Coordinator:
PanID: 1234
DH: 0
DL: FFFF

End Device:
PanID: 1234
DH: 0
DL: 0 (so it can only talk to the coordinator)

The problem I am facing is that when I open the End Device terminal on X-CTU, the distance readings I get are accurate yet very unstable. Like it receives the correct readings but the transmission is unsynchronized as it sometimes receives 5 numbers in one transmission and lags for 10 seconds then receives the next bunch and lags for another 10 seconds and so on...

The arduino code is:

    #include <SoftwareSerial.h>
    const int trigPin = 13;
    const int echoPin = 9;

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

    void setup()  {
       xbee.begin( 9600 );
       pinMode(trigPin, OUTPUT);
       pinMode(echoPin, INPUT);
    }
    void loop()  {
    long duration, distance;
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = (duration/2) / 29.1;
      xbee.println( distance );
      delay(500);
    }

Can anyone help me?

title: XBee unstable sensor data transmission

Answers: 1

body: Probably the end device is set into sleep mode. Check the Sleep Mode(SM) and the sleep period(SP) because what I can see is the XBee gives readings for every 10 seconds.


body:
So im just running a 328p at 8mhz with the internal oscillator. Datasheet says 1.8 to 5.5v is voltage range.

Will 3xAA in series (~4.5v) last longer than 2xAA in series (~3v), assuming all batteries have the same capacity, theoretically each option should have the same mAh but does the difference in voltage affect things ?

title: Barebones 328p, 2xAA vs 3xAA, which will last longer?

Answers: 2

body:
Yes, running at a higher voltage will consume more current.  In the datasheet you have this nice graph:

[![ATMega328P Voltage vs Current][1]][1]

I have highlighted the two voltages at 8MHz for you. At 4.5V you would typically be using about 4.7mA.  At 3V you would be using around 2.8mA.  That's not taking into account anything else in your circuit of course - just the ATMega itself.

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

body:
Majenko's answer is correct, however he (or both of you) are assuming that the processor clock is running. When it runs, a processor cycle at a higher voltage will use more current. However when in power-down sleep mode the clock stops, and consumption is much lower. If you don't need the watchdog timer (for example, a switch closure activates the processor) then the difference will be negligible. Indeed, the current consumption is around 100 nA.

[![Current usage - no watchdog timer][1]][1]

If you need the watchdog to periodically wake you, then the difference will be about 2 µA (that's a lot less than 2.8 mA).

[![Current usage - watchdog timer][2]][2]

These are quoted at room temperature - around 25°C.

---

I would be concerned about 2 x AA batteries. Their nominal voltage might be 3V, but their actual voltage (say, if they are NiMh batteries) might be closer to 2.4V, and that is the minimal amount for running at 8 MHz.

With 3 x AA batteries you are much more safely in range for the voltage requirements, particularly if you have some peripherals that might drain power, and thus lower the voltage.

---

Other discussions about low-power considerations at <http://www.gammon.com.au/power>.

  [1]: https://i.stack.imgur.com/JdOHg.png
  [2]: https://i.stack.imgur.com/yC6Je.png


body:
I'm using Arduino Uno R3 and the official Arduino WiFi Shield R3. I'm trying to update the Shield's firmware to 1.1.0 through [***this***][1] guide.

Everything goes fine until Step 9. When I execute the code in Step 10, I get an error (see attachment) as:

`AtLibUsbDfu: 3EB 2FF8 no device present`

`FAIL Could not open USB device.`

`ISP done.`

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

***EDIT:*** I re-installed the firmware on my shield and now the problem's gone.

  [1]: http://www.bustatech.com/upgrade-arduino-wifi-shield/
  [2]: https://i.stack.imgur.com/93FSy.png

title: Problem updating Arduino WiFi Shield's Firmware

Answers: 2

body: I cant comment because of reputation... You've already upgraded the firmware. Just when you try upgrading again your wifi device is rebooting itself because of upgrading before.

body: Many of the online instructions do not work. This one does - http://arduinotronics.blogspot.com/2015/06/upgrading-arduino-wifi-shield-firmware.html


body:
I'm planning on making my own Bluetooth mechanical keyboard using the Adafruit Feather 32u4 Bluetooth LE. Something that I haven't really figured out is the programming side of things. I was wondering if there is an easy to use library for this.

I know of the KeyPad library but I'm not sure how to handle modifier keys like Shift and CTRL with it. Any idea can help!

Edit: Like said before the project I'm working on is a Bluetooth mechanical keyboard. So this means there will be 85 (at least for my design) switches in a matrix.

In an ideal world the library I'm looking for can do the following: I specify the keys and their position in a matrix and what the modifier keys are. It can generate the appropriate ASCII character when the matching key(s) are pressed and return it or something, so that I can send it over Bluetooth in another piece of code.

In a less ideal world I use the KeyPad library but I don't really know how to take care of modifier keys like shift when doing that.

Have a nice day!

title: Library for DIY Keyboard

Answers: 2

body:
For shift (making an `a` into an `A`), simply program in some ands. Pseudo-code:

    if shift AND a:
        return A
    elif shift AND b:
        return B
and so on and so forth.

body:
https://github.com/tmk/tmk_keyboard is what you want.

Search in Adafruit's site for how to incorporate Bluefruit.


body:
I want to have a loop of 4 colours which runs constantly (i.e. red -> green -> blue -> white) each of the colours having their own LED and pin on the Arduino board. There is a 7 second delay between switching the colour and this cycle should run continuously. When I press a button, I want the cycle to immediately switch back to green and continue the cycle (i.e. -> blue -> white -> red) again.

How should I go about this? Can you have a listener for a button press going at the same time as a delay? How do you interrupt the timer and change the active LED?

title: How to interrupt a Timer to Change position along a Colour Cycle

Answers: 2

body:
You could start with the [attachInterrupt][1] example sketch and work from there. Here is a possible solution:

    enum { GREEN = 0, BLUE = 1, WHITE = 2, RED = 3};
    const int buttonPin = 2;
    const int ledPin[] = { 4, 5, 6, 7 };
    volatile bool reset = false;
    int state = GREEN;

    void setup() {
      pinMode(buttonPin, INPUT_PULLUP);
      for (int i = 0; i < 4; i++) pinMode(ledPin[i], OUTPUT);
      attachInterrupt(digitalPinToInterrupt(buttonPin), doResetState, FALLING);
    }

    void loop() {
       digitalWrite(ledPin[state], HIGH);
       delay(7000);
       digitalWrite(ledPin[state], LOW);
       if (state == RED || reset) {
         state = GREEN;
         reset = false;
       }
       else {
      state = state + 1;
       }
    }

    void doResetState () {
        reset = true;
    }

This will not immediately cycle back to GREEN when pressing the button but you can fix that by modifying the doResetState().

Cheers!

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt

body: The SimpleTimer library would be ideal for this. One timer callback function, the present contents of the loop() function, would advance the lighting state, called by a 7 second timer. Another, your present doResetState() with the modification noted by @MikaelPatel, would read (and debounce) the button on, say, a 100ms timer. The main loop would be reduced to `Timer.run();`


body:
I'm reading a code that uses Arduino as a webclient and when he tries to catch the info from the site, he uses a callback with the following parameters:

    static void response_callback (byte status, word off, word len)

Can anyone explain me how does each one of this parameters work exactly?

PS.: The example I got it from:

    #include <EtherCard.h>

    #define HTTP_HEADER_OFFSET 0
    static byte mymac[] = {0x12,0x34,0x56,0x78,0x90,0xAB};
    char website[] PROGMEM = "www.yourwebsite.com";

    byte Ethernet::buffer[700];
    static uint32_t timer = 0;

    static void response_callback (byte status, word off, word len) {
      Serial.print((const char*) Ethernet::buffer + off + HTTP_HEADER_OFFSET);
    }

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

      if (!ether.begin(sizeof Ethernet::buffer, mymac, 10))
      {
        Serial.println("Failed to access Ethernet controller");
        while(1);
      }
      else
        Serial.println("Ethernet controller initialized");
      Serial.println();

      if (!ether.dhcpSetup())
      {
        Serial.println("Failed to get configuration from DHCP");
        while(1);
      }
      else
        Serial.println("DHCP configuration done");

      if (!ether.dnsLookup(website))
      {
        Serial.println("DNS failed");
        while(1);
      }
      else
        Serial.println("DNS resolution done");

      ether.printIp("SRV IP:\t", ether.hisip);
      Serial.println();
    }

    void loop() {
      ether.packetLoop(ether.packetReceive());

      if (millis() > timer) {
        timer = millis() + 5000;
        ether.browseUrl("/", "yourpage.php", website, response_callback);
      }
    }

title: What are the parameters of the browseUrl() callback in the Ethercard library?

Answers: 1

body:
Apparently, the callback is executed on every packet which arrives by the browseUrl call.

"off" and "len" are pointers to the Ethernet buffer holding the data. "Off" are the initial value (offset) and "len" (length) is the amount of data received.

"byte status", I am not sure what it means, but it's very likely will be some kind of error code. It's not being used in any sample I am seeing, so I am really wondering what it means...

[Check this link for a fully working sample][1]

Callback here are called browseUrlCallback1 and browseUrlCallback2.

Can't figure out a link with the detailed documentation. If someone has it, please post it.

  [1]: http://www.rogerclark.net/aurduino-ethercard-multiple-browser-request-example/


body:
Is it possible to create an IP-to-USB HID (keyboard) using Arduino?

I'd like to connect an Arduino to my network using Ethernet, and then send it commands using TCP/IP and have those commands translated to USB HID and sent as keystrokes to the connected PC.

I've found a few articles discussing USB HID emulation using the Arduino Uno (see http://mitchtech.net/arduino-usb-hid-keyboard) but it refers to using GPIO pins as buttons.

Am I correct that this might work if I use an Arduino Uno and then purchase an Arduino Shield Ethernet?  (seems a bit expensive, but is this the cheapest option?)

Thanks in advance!

title: Possible to create IP-to-USB HID (keyboard) device using Arduino?

Answers: 1

body:
Yes, it is perfectly possible.

You ideally need an Arduino with a direct USB interface, such as the Leonardo. Then you can just access the `Keyboard` object to send the keystrokes to the PC.  How your receive the data through Ethernet is entirely up to you. A simple TCP interface may be easiest - open the connection with whatever telnet-like client and whatever you type gets sent through.  The trick will be getting it into character-at-a-time mode.


body:
I am working on a remote control car from an Arduino Esplora board and the Mega 2650 Board. My problem lies with the Esplora board as the nRF does not transmit like it is supposed to or does not even transmit at all.

I am using the [`pingpair_test.ino`][1] from the [RF24][2] library to make sure the transceiver is working, and when I try to transmit on the serial monitor, I get the following output:

    Configuration = t

    STATUS = 0x00 RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=0 TX_FULL=0

    RX_ADDR_P0-1 = 0x0000000000 0x0000000000

    RX_ADDR_P2-5 = 0x00 0x00 0x00 0x00

    TX_ADDR = 0x0000000000

    RX_PW_P0-6 = 0x00 0x00 0x00 0x00 0x00 0x00

    EN_AA = 0x00

    EN_RXADDR = 0x00

    RF_CH = 0x00

    RF_SETUP = 0x00

    CONFIG = 0x00

    DYNPD/FEATURE = 0x00 0x00

    Data Rate = 1MBPS

    Model = nRF24L01

    CRC Length = Disabled

    PA Power = PA_MIN

    Now sending length 4...No responses received. Are interrupts connected?

I have no idea what any of this means besides the interrupts part.

Even using `interrupts();` the Arduino Esplora still refuses to send data. I am sure my wiring is correct because the status light on the nRF is on and I triple checked all of the SPI pins.

On the Esplora:

 - CE = 0
 - CSN = 1

On the Mega:

 - CE = 51
 - CSN = 50

I have a fritzing sketch [here][3] for those who want to see my wiring.

  [1]: https://github.com/maniacbug/RF24/blob/master/tests/pingpair_test/pingpair_test.pde
  [2]: https://github.com/maniacbug/RF24 "RF24"
  [3]: https://onedrive.live.com/redir?resid=B54AEA44CB029F51!53123&authkey=!APUwJhmiNuUa6d8&ithint=file,zip "here"

title: Why is the nRF24L01 not working with Arduino Esplora?

Answers: 2

body: Looking at your output either you have a wrong wiring or, more probably, you need a capacitor between the nRF24 positive and negative pins: anything between 10uF and 100uF will do.

body:
Funny you should ask, I have been playing with nRF24 for a while, and was thinking of trying out my Esplora. There are however a few problems, which have postponed this (read: can't be arsed).

 1. Pins. You need access to the SPI pins + 2 other pins. On the code you linked to, it's 8 and 9. Which won't work on an Esplora: D9 is not broken out, and D8 is CARD_CS. Better leave that alone. Your best bet would be to use the ICSP header and the two orange TinkerKit pins, D11 & D3.

**[UPDATE]** Also, the RF24 library uses `D2` for IRQ, which is going to be slightly inconvenient on an Esplora, as this pin isn't broken out either. TMRh20 doesn't use an IRQ pin. Neither does Mirf.

[![ICSP Header][1]][1]

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

2. As you can see, the Esplora is on 5V, which could [give the nRF24 module a headache][3]. You'll have to step that down to 3.3. Way too much work for me, but then again I'm lazy.

3. If you're planning on using the screen, the ICSP header is kind of in an awkward place. I've tried fitting regular cables under the screen, and all I've got for my pains was a big dose of what the heck.

4. Stand-alone power. If you're planning to use the Esplora as a standalone, you'll need a battery and a voltage stepper. So in the end, you could use the voltage of the battery for the nRF24 module, and the 5V output from the stepper for the Esplora. More work, grrr.

  [1]: https://i.stack.imgur.com/oJZ1U.png
  [2]: https://i.stack.imgur.com/pbR3M.png
  [3]: https://www.google.com/search?q=nrf24 max voltage


body:
I'm trying to get consistent values from the LM335Z temperature sensor. But it behaves very strange.

I'm using an arduino nano and it's powered via USB from a Raspberry Pi. The circuit also has two little reed relays (SIP-1A05), a button and a potentiometer.
It's connected like this:
[![Sketch of circuit][1]][1]

Additionally I'm using `analogReference(EXTERNAL)` in an attempt to get consistent values, so I've connected the Arduinos 5V output to the reference voltage pin.
Here's the code for reading the thermometer:

    int getTemperature() {
      int rawvoltage = analogRead(0);
      float millivolts = (rawvoltage / 1024.0) * 5000;
      float kelvin = (millivolts / 10);
      float celsius = kelvin - 273.15;
      return round(celsius);
    }
Then it just waits for me to say "get" in the serial monitor and it replies with:

    void sendData(){
      String data = (String)getTemperature();
      data += ',';
      data += (String)map(getTablePos(), 0, 1023, 0, 100); //Potentiometer
      data += ',';
      data += (String)getTableActive(); //1 or 0
      Serial.println(data);
    }

I also read somewhere that the first couple of readings are unreliable, and that you should read a couple of times in startup, which I do:

    for(int i = 0; i < 10; i++){
        analogRead(0);
        delay(1);
      }

Yesterday the termometer reported 37 degrees. Today it started by reporting 49 degrees. After asking for the temperature a couple of times it said 56. Then now, about an hour later it says 52. And if one of they relays is active it says 77 degrees.
My two other (non Arduino) thermometers have ben on a steady 25 all this time.

What should I do to get reliable values from the LM335z?

----------

### Edit
Added dots to the intersections of the circuit diagram for better readability.

I've also found a way to get the thermometer to work, kind of. I removed the external analog reference and only have one 1kOhm resistor for the LM335Z.
Then I have this code instead:

    const float cal = 4.62; //Voltage between 5V and GND, measured with multimeter

    float getTemperature() {
        float input = (float) analogRead(0);
        input = (input*cal)/1024.0;
        return (input/0.01)-273.15;
    }

It worked perfectly standalone on an Arduino Uno powered via USB3.0. When I moved it over into my project with the Nano it gave a few degrees off, but that can be combated by just subtracting the difference I guess.
Then I tried switching to a USB2.0-port on my keyboard, and the values started jumping all over the place.
Here's a comparison using Arduinos rather spartan plotter:
[![enter image description here][2]][2]
Left: USB2.0 via keyboard hub. Right: Front panel USB3.0.

Also, the temperature dubbels when a relay is on.

How do I tackle this? I'd like keep powering it from my Raspberry pi 3, if possible.

  [1]: https://i.stack.imgur.com/bdpiA.png
  [2]: https://i.stack.imgur.com/MpC1v.png

title: LM335Z temperature sensor gives very varying values

Answers: 1

body:
According to your schematic, one of the LM335Z's leads is floating. The pins are meant to be Vcc, Gnd, and output; the output should go to an Analog input.

You wrote that Aref was tied to +5 but you've drawn it as going to one end of the pot with the other end of the pot grounded. The pot's wiper goes to A1 (assuming the pin hasn't been set to some other function).

In short, check your circuit. Try wiring up the sensor to +5, Gnd, and your DVM. Then replace the DVM with A0. At that point you'll have confirmed the sensor circuit, leaving only the code and the external analog circuitry. While I only skimmed the code I don't see anything that would give flaky results. I think you're seeing analog noise, probably due to one or more of the floating sensor pin, an inconsistent or noisy Aref, and pickup in the analog input from the sensor.

Update:
I based my connections description on this diagram

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

, from this [datasheet][2]. In all of those diagrams, the Resistor-Zener connection is shown as the output and no pins are shown floating. But I did see that pin labeled as adj, for what reason I don't know. That's really why I recommended getting the sensor working by itself first.

I see your +5V to Aref connection now. The usual convention for indicating a connection at such a crossing is to put a dot on the intersection, just as the output pin's connection is shown in the above diagram.

  [1]: https://i.stack.imgur.com/nJDBc.png
  [2]: http://www.futurlec.com/Linear/LM335Z.shtml


body:
## Problem description ##
I am trying to build a datalogger with an Arduino UNO. I have connected a SD card module to the Arduino. I have planned to catch the measurement data from the analog input pins. Everything works fine if connected to the usb port. But if I run the Arduino over an external power supply, the `SD.open`-method fails (It simply returns false).
The problem occurs even, if I connect the external power supply additional to the USB connection. So the problem can't be a missing serial connection.

Note that the problem only occurs, if `SD.open` is in WRITE-mode.
(`File dataFile = SD.open("datalog.txt", FILE_WRITE);`)

## What I've already tried: ##
 - running the SD-card example code, which is included in the SD card library.
 - trying different types of file-system formattings (FAT, FAT32, with different cluster-sizes)
 - powering the sd-card reader with 3.3V instead of 5V

## Arduino wiring ##
Look at the pictures to check if there are some mistakes with the wiring:
[![Digital inputs on the arduino][2]][2]
[![Wiring on the SD-card module and power connection][3]][3]

## Specifications of the power supply ##
And here are the specifications of the power supply:

 - **Manufacturer:** MyVolts
 - **Model:** DD282MU
 - **Input:** 100-240V (AC) - 50-60 Hz
 - **Output:** 9V, 1A (DC)

  [2]: https://i.stack.imgur.com/vubul.jpg "Digital inputs on the arduino"
  [3]: https://i.stack.imgur.com/UK4cz.jpg "Wiring on the SD-card module and power connection"

----------

I hope you can help me with my problem. And of course, I hope there is a solution for the problem at all. Thank you.

title: SD-Card-Module doesnt work with external power supply

Answers: 2

body:
Okay, thank you all for your efforts.

Finally, after changing the PSU and connecting the Arduino to another usb-port without operating system, I found the solution.

The problem was the SD-Card itself:
I swapped the SD-card with a newer (maybe more expensive(?)) one and it just works now. No matter if you connect the Arduino with the PSU or over an usb connection.
My assumption is, that there could be a different clock speed of the sd-card module on different voltages, which causes the problem. The old sd-card can't handle the fast speed and runs into an error (or just rejects it) on a write attempt...

Anyway, thank you again for your efforts!

body:
I had this problem too, SD card not initiliasing on external power.
Having read this I turned down my external power voltage to 5.1 V
(from 7.5V ish)  and suddenly my SD card initialises on external power.
So a 'solid' 5 V must have the SPI running at a higher speed ( I guess) make sense.  The drawback is TFT is not as bright as should be.
...  better get a more 'expensive' SD card module LOL.

Ps - After some testing I had found that the SD card would work up to 6.4V on the power jack, above that the card would not initialise.   BTW I am not convinced it is a speed issue only because the SPI speed is locked by a divider to the Mega clock, so the Mega clock needs to change first.

Hope this helps


body:
Im simply trying to pass my payload to another device that has the same architecture and struct. I'm using UART to transfer, and modeling the protocol from EasyTransfer.

When I call `Serial.print((char*)mydata.data);` in Transfer it prints Hello World as expected.

Calling that same line in Receive prints a '?' to console. This may be some background behavior with Arduino, or I'm just not casting/handling the pointers correctly. How can I get this print out to function properly?

Transfer Sketch

    #include <EasyTransfer.h>

    //create object
    EasyTransfer TransferObject;

    //Struct contents must be idential to struct from other board
    #define PAYLOAD_SIZE 255
    struct SEND_DATA_STRUCTURE
    {
      int blinks;
      int pause;

      uint8_t data[PAYLOAD_SIZE];
    };

    //give a name to the group of data
    SEND_DATA_STRUCTURE mydata;

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

      //#define details(name) (byte*)&name,sizeof(name)
      TransferObject.begin(details(mydata), &Serial);

      pinMode(13, OUTPUT);

      //initalize not so random number generator
      randomSeed(analogRead(0));

    }

    void loop()
    {
      //mydata.blinks = random(5);
      //mydata.pause = random(5);

      //Create payload to transfer
      char* payload = "Hello World!";

      //Fill array with data
      strncpy((char *)mydata.data, payload, PAYLOAD_SIZE);

      //Print sample
      Serial.print((char*)mydata.data);

      //send the entire struct
      TransferObject.sendData();

      delay(5000);
    }

Receive Sketch

        #include <EasyTransfer.h>

    //create object
    EasyTransfer TransferObject;

    //Struct contents must be idential to struct from other board
    #define PAYLOAD_SIZE 255
    struct RECEIVE_DATA_STRUCTURE
    {
      int blinks;
      int pause;

      uint8_t data[PAYLOAD_SIZE];
    };

    //give a name to the group of data
    RECEIVE_DATA_STRUCTURE mydata;

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

      //#define details(name) (byte*)&name,sizeof(name)
      TransferObject.begin(details(mydata), &Serial);

      pinMode(13, OUTPUT);

    }

    void loop()
    {
      //check and see if a data packet has come in.
      if(TransferObject.receiveData())
      {
        Serial.print("active");
        //print data payload
        Serial.print((char*)mydata.data);
        }

      //you should make this delay shorter then your transmit delay or else messages could be lost
      delay(250);

This is [an exerpt and variant from this library][1]

  [1]: https://github.com/madsci1016/Arduino-EasyTransfer/tree/master/EasyTransfer

title: Casting a struct member between uint8_t and char, with regard to serial transfer

Answers: 1

body:
You're actually falling into a common problem with pointers in structs.

This structure:

    struct SEND_DATA_STRUCTURE
    {
      int blinks;
      int pause;

      uint8_t *data;
    };

contains three values: blinks, pause and a pointer to the data.

    uint8_t *data;

That doesn't contain the data. That only contains the address that the data is stored at in memory.  When you transfer the struct it's that address that you are sending - then when the other end tries to print it all it can do is look at the address it's been told about and try and print whatever is in there - and that is complete garbage.

Instead of storing a pointer to the data you need to store the actual data itself. That means that you need to decide upon a maximum size for that data and pre-allocate the memory within the struct:

    #define DATA_SIZE 40

    struct SEND_DATA_STRUCTURE
    {
      int blinks;
      int pause;

      uint8_t data[DATA_SIZE];
    };

Now in order to get the data into that struct you need to fill that array with your payload. For strings the simplest way is:

    strncpy((char *)mydata.data, payload, DATA_SIZE);

That will copy *up to* `DATA_SIZE` characters from `payload` into `mydata.data`.

Note that if `payload` contains more than `DATA_SIZE-1` characters the data in `mydata.data` will not be NULL terminated. You can get round that by forcing NULL termination:

    mydata.data[DATA_SIZE-1] = 0;

----

In your revised code your payload size is too big. The way the EasyTransfer library works is it has a single byte for the size of the payload. Your total payload size is PAYLOAD_SIZE + 2 ints - that is 255 + 2 + 2 = 259 bytes.  Placed into a single byte that gets truncated to 3. That means you are actually transferring one and a half integers and nothing else.

You need to ensure that your entire struct never exceeds 255 bytes. So you can have a maximum size of data, once you have taken your two integers into account (assuming 16-bit integers on an 8-bit Arduino), of 251 bytes.


body:
I want to apply a Kalman Filter to the humidity data which I retrieve of the DHT11.

How can I do that?

title: Can I apply a Kalman filter to DHT11 data?

Answers: 1

body:
Learn about the kalman filter and what it does. It requires a certain understanding of what it is, what it is good for and why you would eventually use it. It seems to me, that at the moment this isn't your strongest topic.

Thereafter, figure out which !multiple! sensor values you have, since only with a "model" and an "observation" a filter of this kind makes sense in the first place.

To specifically adress your question: you can apply any filter to any data. The hidden question, if it makes sense in this case is not trivial to answer, since you didn't exactly provide the vast information. My guess is, you only have this one sensor, and it would be (at this state of knowledge) a reasonable idea to use a bandpass filter of sorts instead.


body:
I seek to call an ISR routine after a fixed time of 400us. This action needs to be done every now and then (in the range of 0.8-3.0ms). For that matter, I thought I'd set timer2 to CTC mode, use OCR2A to set some TOP value for 400us and let the timer call the ISR routine after 400us. Within the ISR I would then stop the timer from triggering interrupts, until I need to count to 400us again, where I would activate the timer interrupt again.

This works, as expected, except for the fact, that after activating the interrupt for OCR2A again, it instantly triggers. The code below, produces a 1ms alternating signal, instead of 1ms+400us.

My question is, am I on a good way with this, or should I use the overflow ISR and preload the timer? Or any other method? The problem is, that after the 1ms waiting time in the main loop, I'd expect the counter to count from 0 to 100, meaning 400us. However on an oscilloscope I see the pin toggle each 1ms.

    uint32_t timestamp;

    void setup() {
      Serial.begin(115200);
      pinMode(9, OUTPUT);
      cli();         // disable global interrupts
      // Timer2 for counting (to release the pin)
      TCCR2A |= (1 << WGM21); // CTC mode, clear timer on compare match
      TCCR2B |= (1 << CS22); // Prescalar 64

      OCR2A = 99; // ticks, before ISR is called
      TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
      TCNT2 = 0x00; // set the timer to 0
      // counting time[s] = (OCR+1)/(F_cpu/prescalar)
      // 99 = 400us | 124 = 500us
      sei(); // enable global interrups
      timestamp = micros();
    }

    void loop() {
      uint32_t now = micros();
      if (now - timestamp > 1000) {
        timestamp = now;
        cli();
        TIMSK2 |= (1 << OCIE2A); // enable timer compare interrupt
        sei();
        TCNT2 = 0x00;
      }
    }

    ISR(TIMER2_COMPA_vect) {
      // Serial.print(F("Here\n"));
      PORTB ^= 2; // set pin 9 high again
      // TCNT2 = 0x00; // reset timer for testing
      // deactivate the counter
       cli();
       TIMSK2 = 0x00; // unlink the ISR from timer
       sei();
    }

title: Irregularly triggering an ISR using timers

Answers: 1

body:
> However on an oscilloscope I see the pin toggle each 1ms.

That's what you expect. You set up the timer to fire every 1 ms. Since the ISR is called some time after that (and that is what toggles the pin) you will see the pin toggle every 1 ms.

I've reworked your example a bit to make it clearer, and to toggle the pin when we start the timer, and again when the ISR fires:

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

    uint32_t timestamp;

    void setup()
      {
      pinMode(9, OUTPUT);
      // Timer2 for counting
      TCCR2A = bit (WGM21); // CTC mode, clear timer on compare match
      OCR2A = 99;           // ticks, before ISR is called

      // counting time[s] = (OCR+1)/(F_cpu/prescalar)
      // 99 = 400us | 124 = 500us
      timestamp = micros();
      }  // end of seupt

    void loop()
    {
      uint32_t now = micros();
      if (now - timestamp >= 1000)
        {
        timestamp = now;
        TIFR2 = bit (OCF2A);   // clear any pending interrupt
        TCNT2 = 0;             // make sure counter is zero
        TIMSK2 = bit (OCIE2A); // enable timer compare interrupt
        TCCR2B = bit (CS22);   // start timer: Prescalar 64
        PINB = bit (1);        // toggle pin 9
        }  // end of if
    }  // end of loop

    ISR(TIMER2_COMPA_vect)
    {
      PINB = bit (1); // toggle pin 9
      TCCR2B = 0;     // stop timer
    }  // end of TIMER2_COMPA_vect

You can see from the scope output that the timer is started every 1 ms (as expected) because Cursor 1 is at -1 ms. The width of the pulse is 400 µs, as expected.

[![Timer 2 scope output][1]][1]

---

>  In my example I do not have to set so many settings each time I want to start the timer.

I took out the `cli` and `sei` so I saved you two lines. Don't forget to count them!

If you leave the timer running, it may well have reached the counter again (even though not generating an interrupt). Thus this line is important (even more so for you):

    TIFR2 = bit (OCF2A);   // clear any pending interrupt

Also, if you leave the timer running, you may have a race condition. Say the timer is just about to tick over and generate the interrupt. You clear the flag (as shown above), but one machine cycle later the timer reaches the counter and sets it again, just before you get a chance to zero it. With the timer running, there could be combinations of when you enable interrupts, zero the flag, and clear the pending interrupt flag, that could occasionally work against you. Having the timer stopped is much safer.

Now if you are worried about the number of lines you need to start it (I wouldn't be) then you can move this line into setup:

    TIMSK2 = bit (OCIE2A); // enable timer compare interrupt

Since you stop the timer in the ISR it doesn't matter if the interrupt is still enabled. Now you just have three lines to start the timer:

    TIFR2 = bit (OCF2A);  // clear any pending interrupt
    TCNT2 = 0;            // make sure timer is zeroed
    TCCR2B = bit (CS22);  // start timer: Prescalar 64

I think we've agreed that clearing the compare flag is important, so this isn't any lengthier.

---

> looking at your divisioning of the time axis, and from code, it is clear, that there is a 600us break, not 1ms!

Yes, there's a 600 µs break, because you start the timer every 1 ms, and it runs for 400 µs, thus there will be a 600 µs break.

---

> I seek to call an ISR routine after a fixed time of 400us.

That's exactly what my posted code does. The pin goes high at the time you desire, in loop, and it goes low 400 µs later. That's what you wanted: a 400 µs interval.

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


body:
I want to monitor the vibration from a motor running at 9.5Hz at 565rpm. I am using Arduino Uno and the ADXL345 as my condition monitoring equipment. How do I set the sampling frequency? I want to sample at at least 5x more than the operating frequency which is 50Hz, which will give a interval of 0.02 sec. However, to collect 2500 readings, I would need to take around 300 sec which is 0.12sec per reading different from the preset value at 0.02 sec.

Is my code wrong somewhere? Or what can I do to speed up the process?

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

    #include <Wire.h>
    #define DEVICE (0x53)    //ADXL345 device address
    #define TO_READ (6)        //num of bytes we are going to read each time    (two bytes for each axis)
    #define THRESH_ACT  (0x24)
    #define THRESH_INACT  (0x25)
    #include <SPI.h>
    #include <SD.h>
    File myFile;

    // Declare Variable
    byte runComplete; //setting the number of iteration
    int i; //delare i for count
    byte buff[TO_READ];//6 bytes buffer for saving data read from the device
    float x, y, z; //Acceleration variable
    float x1, y1, z1; //Acceleration variable

    void writeTo(int device, byte address, byte val) {
      Wire.beginTransmission(device); //start transmission to device
      Wire.write(address);        // send register address
      Wire.write(val);        // send value to write
      Wire.endTransmission(); //end transmission
    }

    void readFrom(int device, byte address, int num, byte buff[]) { //reads num bytes starting from address register on device in to buff array
      Wire.beginTransmission(device); //start transmission to device
      Wire.write(address);        //sends address to read from
      Wire.endTransmission(); //end transmission
      int n = Wire.requestFrom(device, num);    // request 6 bytes from device
      if( n == num)
      {
          Wire.readBytes(buff, n);
      }
        }
    void regAddress()
    {
        int regAddress = 0x32;    //first axis-acceleration-data register on the ADXL345
        readFrom(DEVICE, regAddress, TO_READ, buff); //read the acceleration data from the ADXL345

         //each axis reading comes in 10 bit resolution, ie 2 bytes.  Least Significat Byte first!!
         //thus we are converting both bytes in to one int
        x = (((int)buff[1]) << 8) | buff[0];
        y = (((int)buff[3])<< 8) | buff[2];
        z = (((int)buff[5]) << 8) | buff[4];

        x1 = (x/256);
        y1 = (y/256);
        z1 = (z/256);

     Serial.println(" ");
        Serial.print("X: ");Serial.print(x1); Serial.println(" mm/s2");
        Serial.print("Y: ");Serial.print(y1); Serial.println(" mm/s2");
        Serial.print("Z: ");Serial.print(z1); Serial.println(" mm/s2");
        Serial.println(" ");

        myFile = SD.open("x30.txt", FILE_WRITE); // if the file opened okay, write to it:
        if (myFile) {
          Serial.print("Writing to X.txt...");
          myFile.println(x1);
          myFile.close();// close the file:
          Serial.println("done.");
        } else {
          Serial.println(F("error opening x.txt")) ;// if the file didn't open, print an error:
        }

        myFile = SD.open("y30.txt", FILE_WRITE); // if the file opened okay, write to it:
        if (myFile) {
          Serial.print("Writing to Y.txt...");
          myFile.println(y1);
          myFile.close();// close the file:
          Serial.println("done.");
        } else {
          Serial.println(F("error opening Y.txt")) ; // if the file didn't open, print an error:
        }
          myFile = SD.open("z30.txt", FILE_WRITE);// if the file opened okay, write to it:
        if (myFile) {
          Serial.print("Writing to Z.txt...");
          myFile.println(z1);
          myFile.close();// close the file:
          Serial.println("done.");
          Serial.println("");
        } else {
          Serial.println(F("error opening Z.txt")); // if the file didn't open, print an error:
          Serial.println("");
        }
           }

    void setup()
    {
      Wire.begin();        // join i2c bus (address optional for master)
      Serial.begin(9600);  // start serial for output
      writeTo(DEVICE, 0x2D, 0);   //Turning on the ADXL345
      writeTo(DEVICE, 0x2D, 16);  //Turning on the ADXL345
      writeTo(DEVICE, 0x2D, 8);   //Turning on the ADXL345
      writeTo(DEVICE, 0x31, 8);
      Serial.println("Initializing Accelerometer...");
      Serial.print("Initializing SD card...");
      Serial.println("");
      if (!SD.begin(4)) {
        Serial.println("initialization failed!");
        Serial.println("");
        return;
      }
      delay(2000);
    }

     void loop() {
       if (runComplete == 0){
      for (i=0; i<2501; i=i+1){
     Serial.print("Number of iteration(seconds) = "); Serial.print(i);
     Serial.println("");
     regAddress();
         delay(200);
       }
      runComplete = 1;
      }
    }

title: How do I set my sampling rate?

Answers: 1

body:
0.02 seconds means 20 ms, not 200. Your delay time is too long. Try using millis or micros instead of delay for average deviation. Using delay will accumulate lags caused by process time.
Try to sacrifice memory to log the data first (using for()  & data array), and then write to serial later.